llm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import warnings
  2. from functools import partial
  3. with warnings.catch_warnings():
  4. warnings.simplefilter('ignore')
  5. import litellm
  6. from litellm import completion as litellm_completion
  7. from litellm import completion_cost as litellm_completion_cost
  8. from litellm.exceptions import (
  9. APIConnectionError,
  10. RateLimitError,
  11. ServiceUnavailableError,
  12. )
  13. from litellm.types.utils import CostPerToken
  14. from tenacity import (
  15. retry,
  16. retry_if_exception_type,
  17. stop_after_attempt,
  18. wait_random_exponential,
  19. )
  20. from opendevin.core.config import config
  21. from opendevin.core.logger import llm_prompt_logger, llm_response_logger
  22. from opendevin.core.logger import opendevin_logger as logger
  23. from opendevin.core.metrics import Metrics
  24. __all__ = ['LLM']
  25. message_separator = '\n\n----------\n\n'
  26. class LLM:
  27. """
  28. The LLM class represents a Language Model instance.
  29. Attributes:
  30. model_name (str): The name of the language model.
  31. api_key (str): The API key for accessing the language model.
  32. base_url (str): The base URL for the language model API.
  33. api_version (str): The version of the API to use.
  34. max_input_tokens (int): The maximum number of tokens to send to the LLM per task.
  35. max_output_tokens (int): The maximum number of tokens to receive from the LLM per task.
  36. llm_timeout (int): The maximum time to wait for a response in seconds.
  37. custom_llm_provider (str): A custom LLM provider.
  38. """
  39. def __init__(
  40. self,
  41. model=None,
  42. api_key=None,
  43. base_url=None,
  44. api_version=None,
  45. num_retries=None,
  46. retry_min_wait=None,
  47. retry_max_wait=None,
  48. llm_timeout=None,
  49. llm_temperature=None,
  50. llm_top_p=None,
  51. custom_llm_provider=None,
  52. max_input_tokens=None,
  53. max_output_tokens=None,
  54. llm_config=None,
  55. metrics=None,
  56. ):
  57. """
  58. Initializes the LLM. If LLMConfig is passed, its values will be the fallback.
  59. Passing simple parameters always overrides config.
  60. Args:
  61. model (str, optional): The name of the language model. Defaults to LLM_MODEL.
  62. api_key (str, optional): The API key for accessing the language model. Defaults to LLM_API_KEY.
  63. base_url (str, optional): The base URL for the language model API. Defaults to LLM_BASE_URL. Not necessary for OpenAI.
  64. api_version (str, optional): The version of the API to use. Defaults to LLM_API_VERSION. Not necessary for OpenAI.
  65. num_retries (int, optional): The number of retries for API calls. Defaults to LLM_NUM_RETRIES.
  66. retry_min_wait (int, optional): The minimum time to wait between retries in seconds. Defaults to LLM_RETRY_MIN_TIME.
  67. retry_max_wait (int, optional): The maximum time to wait between retries in seconds. Defaults to LLM_RETRY_MAX_TIME.
  68. max_input_tokens (int, optional): The maximum number of tokens to send to the LLM per task. Defaults to LLM_MAX_INPUT_TOKENS.
  69. max_output_tokens (int, optional): The maximum number of tokens to receive from the LLM per task. Defaults to LLM_MAX_OUTPUT_TOKENS.
  70. custom_llm_provider (str, optional): A custom LLM provider. Defaults to LLM_CUSTOM_LLM_PROVIDER.
  71. llm_timeout (int, optional): The maximum time to wait for a response in seconds. Defaults to LLM_TIMEOUT.
  72. llm_temperature (float, optional): The temperature for LLM sampling. Defaults to LLM_TEMPERATURE.
  73. metrics (Metrics, optional): The metrics object to use. Defaults to None.
  74. """
  75. if llm_config is None:
  76. llm_config = config.llm
  77. model = model if model is not None else llm_config.model
  78. api_key = api_key if api_key is not None else llm_config.api_key
  79. base_url = base_url if base_url is not None else llm_config.base_url
  80. api_version = api_version if api_version is not None else llm_config.api_version
  81. num_retries = num_retries if num_retries is not None else llm_config.num_retries
  82. retry_min_wait = (
  83. retry_min_wait if retry_min_wait is not None else llm_config.retry_min_wait
  84. )
  85. retry_max_wait = (
  86. retry_max_wait if retry_max_wait is not None else llm_config.retry_max_wait
  87. )
  88. llm_timeout = llm_timeout if llm_timeout is not None else llm_config.timeout
  89. llm_temperature = (
  90. llm_temperature if llm_temperature is not None else llm_config.temperature
  91. )
  92. llm_top_p = llm_top_p if llm_top_p is not None else llm_config.top_p
  93. custom_llm_provider = (
  94. custom_llm_provider
  95. if custom_llm_provider is not None
  96. else llm_config.custom_llm_provider
  97. )
  98. max_input_tokens = (
  99. max_input_tokens
  100. if max_input_tokens is not None
  101. else llm_config.max_input_tokens
  102. )
  103. max_output_tokens = (
  104. max_output_tokens
  105. if max_output_tokens is not None
  106. else llm_config.max_output_tokens
  107. )
  108. metrics = metrics if metrics is not None else Metrics()
  109. logger.info(f'Initializing LLM with model: {model}')
  110. self.model_name = model
  111. self.api_key = api_key
  112. self.base_url = base_url
  113. self.api_version = api_version
  114. self.max_input_tokens = max_input_tokens
  115. self.max_output_tokens = max_output_tokens
  116. self.llm_timeout = llm_timeout
  117. self.custom_llm_provider = custom_llm_provider
  118. self.metrics = metrics
  119. # litellm actually uses base Exception here for unknown model
  120. self.model_info = None
  121. try:
  122. if not self.model_name.startswith('openrouter'):
  123. self.model_info = litellm.get_model_info(self.model_name.split(':')[0])
  124. else:
  125. self.model_info = litellm.get_model_info(self.model_name)
  126. # noinspection PyBroadException
  127. except Exception:
  128. logger.warning(f'Could not get model info for {self.model_name}')
  129. if self.max_input_tokens is None:
  130. if self.model_info is not None and 'max_input_tokens' in self.model_info:
  131. self.max_input_tokens = self.model_info['max_input_tokens']
  132. else:
  133. # Max input tokens for gpt3.5, so this is a safe fallback for any potentially viable model
  134. self.max_input_tokens = 4096
  135. if self.max_output_tokens is None:
  136. if self.model_info is not None and 'max_output_tokens' in self.model_info:
  137. self.max_output_tokens = self.model_info['max_output_tokens']
  138. else:
  139. # Enough tokens for most output actions, and not too many for a bad llm to get carried away responding
  140. # with thousands of unwanted tokens
  141. self.max_output_tokens = 1024
  142. self._completion = partial(
  143. litellm_completion,
  144. model=self.model_name,
  145. api_key=self.api_key,
  146. base_url=self.base_url,
  147. api_version=self.api_version,
  148. custom_llm_provider=custom_llm_provider,
  149. max_tokens=self.max_output_tokens,
  150. timeout=self.llm_timeout,
  151. temperature=llm_temperature,
  152. top_p=llm_top_p,
  153. )
  154. completion_unwrapped = self._completion
  155. def attempt_on_error(retry_state):
  156. logger.error(
  157. f'{retry_state.outcome.exception()}. Attempt #{retry_state.attempt_number} | You can customize these settings in the configuration.',
  158. exc_info=False,
  159. )
  160. return True
  161. @retry(
  162. reraise=True,
  163. stop=stop_after_attempt(num_retries),
  164. wait=wait_random_exponential(min=retry_min_wait, max=retry_max_wait),
  165. retry=retry_if_exception_type(
  166. (RateLimitError, APIConnectionError, ServiceUnavailableError)
  167. ),
  168. after=attempt_on_error,
  169. )
  170. def wrapper(*args, **kwargs):
  171. if 'messages' in kwargs:
  172. messages = kwargs['messages']
  173. else:
  174. messages = args[1]
  175. debug_message = ''
  176. for message in messages:
  177. debug_message += message_separator + message['content']
  178. llm_prompt_logger.debug(debug_message)
  179. resp = completion_unwrapped(*args, **kwargs)
  180. message_back = resp['choices'][0]['message']['content']
  181. llm_response_logger.debug(message_back)
  182. return resp
  183. self._completion = wrapper # type: ignore
  184. @property
  185. def completion(self):
  186. """
  187. Decorator for the litellm completion function.
  188. """
  189. return self._completion
  190. def do_completion(self, *args, **kwargs):
  191. """
  192. Wrapper for the litellm completion function.
  193. Check the complete documentation at https://litellm.vercel.app/docs/completion
  194. """
  195. resp = self._completion(*args, **kwargs)
  196. self.post_completion(resp)
  197. return resp
  198. def post_completion(self, response: str) -> None:
  199. """
  200. Post-process the completion response.
  201. """
  202. try:
  203. cur_cost = self.completion_cost(response)
  204. except Exception:
  205. cur_cost = 0
  206. logger.info(
  207. 'Cost: %.2f USD | Accumulated Cost: %.2f USD',
  208. cur_cost,
  209. self.metrics.accumulated_cost,
  210. )
  211. def get_token_count(self, messages):
  212. """
  213. Get the number of tokens in a list of messages.
  214. Args:
  215. messages (list): A list of messages.
  216. Returns:
  217. int: The number of tokens.
  218. """
  219. return litellm.token_counter(model=self.model_name, messages=messages)
  220. def is_local(self):
  221. """
  222. Determines if the system is using a locally running LLM.
  223. Returns:
  224. boolean: True if executing a local model.
  225. """
  226. if self.base_url is not None:
  227. for substring in ['localhost', '127.0.0.1' '0.0.0.0']:
  228. if substring in self.base_url:
  229. return True
  230. elif self.model_name is not None:
  231. if self.model_name.startswith('ollama'):
  232. return True
  233. return False
  234. def completion_cost(self, response):
  235. """
  236. Calculate the cost of a completion response based on the model. Local models are treated as free.
  237. Add the current cost into total cost in metrics.
  238. Args:
  239. response (list): A response from a model invocation.
  240. Returns:
  241. number: The cost of the response.
  242. """
  243. extra_kwargs = {}
  244. if (
  245. config.llm.input_cost_per_token is not None
  246. and config.llm.output_cost_per_token is not None
  247. ):
  248. cost_per_token = CostPerToken(
  249. input_cost_per_token=config.llm.input_cost_per_token,
  250. output_cost_per_token=config.llm.output_cost_per_token,
  251. )
  252. logger.info(f'Using custom cost per token: {cost_per_token}')
  253. extra_kwargs['custom_cost_per_token'] = cost_per_token
  254. if not self.is_local():
  255. try:
  256. cost = litellm_completion_cost(
  257. completion_response=response, **extra_kwargs
  258. )
  259. self.metrics.add_cost(cost)
  260. return cost
  261. except Exception:
  262. logger.warning('Cost calculation not supported for this model.')
  263. return 0.0
  264. def __str__(self):
  265. if self.api_version:
  266. return f'LLM(model={self.model_name}, api_version={self.api_version}, base_url={self.base_url})'
  267. elif self.base_url:
  268. return f'LLM(model={self.model_name}, base_url={self.base_url})'
  269. return f'LLM(model={self.model_name})'
  270. def __repr__(self):
  271. return str(self)