llm.py 9.9 KB

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