llm.py 11 KB

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