llm.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import copy
  2. import time
  3. import warnings
  4. from functools import partial
  5. from typing import Any
  6. from openhands.core.config import LLMConfig
  7. with warnings.catch_warnings():
  8. warnings.simplefilter('ignore')
  9. import litellm
  10. from litellm import ModelInfo
  11. from litellm import completion as litellm_completion
  12. from litellm import completion_cost as litellm_completion_cost
  13. from litellm.exceptions import (
  14. APIConnectionError,
  15. InternalServerError,
  16. RateLimitError,
  17. ServiceUnavailableError,
  18. )
  19. from litellm.types.utils import CostPerToken, ModelResponse, Usage
  20. from openhands.core.logger import openhands_logger as logger
  21. from openhands.core.message import Message
  22. from openhands.core.metrics import Metrics
  23. from openhands.llm.debug_mixin import DebugMixin
  24. from openhands.llm.retry_mixin import RetryMixin
  25. __all__ = ['LLM']
  26. # tuple of exceptions to retry on
  27. LLM_RETRY_EXCEPTIONS: tuple[type[Exception], ...] = (
  28. APIConnectionError,
  29. InternalServerError,
  30. RateLimitError,
  31. ServiceUnavailableError,
  32. )
  33. # cache prompt supporting models
  34. # remove this when we gemini and deepseek are supported
  35. CACHE_PROMPT_SUPPORTED_MODELS = [
  36. 'claude-3-5-sonnet-20240620',
  37. 'claude-3-haiku-20240307',
  38. 'claude-3-opus-20240229',
  39. 'anthropic/claude-3-opus-20240229',
  40. 'anthropic/claude-3-haiku-20240307',
  41. 'anthropic/claude-3-5-sonnet-20240620',
  42. ]
  43. class LLM(RetryMixin, DebugMixin):
  44. """The LLM class represents a Language Model instance.
  45. Attributes:
  46. config: an LLMConfig object specifying the configuration of the LLM.
  47. """
  48. def __init__(
  49. self,
  50. config: LLMConfig,
  51. metrics: Metrics | None = None,
  52. ):
  53. """Initializes the LLM. If LLMConfig is passed, its values will be the fallback.
  54. Passing simple parameters always overrides config.
  55. Args:
  56. config: The LLM configuration.
  57. metrics: The metrics to use.
  58. """
  59. self.metrics: Metrics = metrics if metrics is not None else Metrics()
  60. self.cost_metric_supported: bool = True
  61. self.config: LLMConfig = copy.deepcopy(config)
  62. # list of LLM completions (for logging purposes). Each completion is a dict with the following keys:
  63. # - 'messages': list of messages
  64. # - 'response': response from the LLM
  65. self.llm_completions: list[dict[str, Any]] = []
  66. # litellm actually uses base Exception here for unknown model
  67. self.model_info: ModelInfo | None = None
  68. try:
  69. if self.config.model.startswith('openrouter'):
  70. self.model_info = litellm.get_model_info(self.config.model)
  71. else:
  72. self.model_info = litellm.get_model_info(
  73. self.config.model.split(':')[0]
  74. )
  75. # noinspection PyBroadException
  76. except Exception as e:
  77. logger.warning(f'Could not get model info for {config.model}:\n{e}')
  78. # Set the max tokens in an LM-specific way if not set
  79. if self.config.max_input_tokens is None:
  80. if (
  81. self.model_info is not None
  82. and 'max_input_tokens' in self.model_info
  83. and isinstance(self.model_info['max_input_tokens'], int)
  84. ):
  85. self.config.max_input_tokens = self.model_info['max_input_tokens']
  86. else:
  87. # Safe fallback for any potentially viable model
  88. self.config.max_input_tokens = 4096
  89. if self.config.max_output_tokens is None:
  90. # Safe default for any potentially viable model
  91. self.config.max_output_tokens = 4096
  92. if self.model_info is not None:
  93. # max_output_tokens has precedence over max_tokens, if either exists.
  94. # litellm has models with both, one or none of these 2 parameters!
  95. if 'max_output_tokens' in self.model_info and isinstance(
  96. self.model_info['max_output_tokens'], int
  97. ):
  98. self.config.max_output_tokens = self.model_info['max_output_tokens']
  99. elif 'max_tokens' in self.model_info and isinstance(
  100. self.model_info['max_tokens'], int
  101. ):
  102. self.config.max_output_tokens = self.model_info['max_tokens']
  103. self._completion = partial(
  104. litellm_completion,
  105. model=self.config.model,
  106. api_key=self.config.api_key,
  107. base_url=self.config.base_url,
  108. api_version=self.config.api_version,
  109. custom_llm_provider=self.config.custom_llm_provider,
  110. max_tokens=self.config.max_output_tokens,
  111. timeout=self.config.timeout,
  112. temperature=self.config.temperature,
  113. top_p=self.config.top_p,
  114. drop_params=self.config.drop_params,
  115. )
  116. if self.vision_is_active():
  117. logger.debug('LLM: model has vision enabled')
  118. if self.is_caching_prompt_active():
  119. logger.debug('LLM: caching prompt enabled')
  120. completion_unwrapped = self._completion
  121. @self.retry_decorator(
  122. num_retries=self.config.num_retries,
  123. retry_exceptions=LLM_RETRY_EXCEPTIONS,
  124. retry_min_wait=self.config.retry_min_wait,
  125. retry_max_wait=self.config.retry_max_wait,
  126. retry_multiplier=self.config.retry_multiplier,
  127. )
  128. def wrapper(*args, **kwargs):
  129. """Wrapper for the litellm completion function. Logs the input and output of the completion function."""
  130. messages: list[dict[str, Any]] | dict[str, Any] = []
  131. # some callers might send the model and messages directly
  132. # litellm allows positional args, like completion(model, messages, **kwargs)
  133. if len(args) > 1:
  134. # ignore the first argument if it's provided (it would be the model)
  135. # design wise: we don't allow overriding the configured values
  136. # implementation wise: the partial function set the model as a kwarg already
  137. # as well as other kwargs
  138. messages = args[1] if len(args) > 1 else args[0]
  139. kwargs['messages'] = messages
  140. # remove the first args, they're sent in kwargs
  141. args = args[2:]
  142. elif 'messages' in kwargs:
  143. messages = kwargs['messages']
  144. # ensure we work with a list of messages
  145. messages = messages if isinstance(messages, list) else [messages]
  146. # if we have no messages, something went very wrong
  147. if not messages:
  148. raise ValueError(
  149. 'The messages list is empty. At least one message is required.'
  150. )
  151. # log the entire LLM prompt
  152. self.log_prompt(messages)
  153. if self.is_caching_prompt_active():
  154. # Anthropic-specific prompt caching
  155. if 'claude-3' in self.config.model:
  156. kwargs['extra_headers'] = {
  157. 'anthropic-beta': 'prompt-caching-2024-07-31',
  158. }
  159. # we don't support streaming here, thus we get a ModelResponse
  160. resp: ModelResponse = completion_unwrapped(*args, **kwargs)
  161. # log for evals or other scripts that need the raw completion
  162. if self.config.log_completions:
  163. self.llm_completions.append(
  164. {
  165. 'messages': messages,
  166. 'response': resp,
  167. 'timestamp': time.time(),
  168. 'cost': self._completion_cost(resp),
  169. }
  170. )
  171. message_back: str = resp['choices'][0]['message']['content']
  172. # log the LLM response
  173. self.log_response(message_back)
  174. # post-process the response
  175. self._post_completion(resp)
  176. return resp
  177. self._completion = wrapper
  178. @property
  179. def completion(self):
  180. """Decorator for the litellm completion function.
  181. Check the complete documentation at https://litellm.vercel.app/docs/completion
  182. """
  183. return self._completion
  184. def vision_is_active(self):
  185. return not self.config.disable_vision and self._supports_vision()
  186. def _supports_vision(self):
  187. """Acquire from litellm if model is vision capable.
  188. Returns:
  189. bool: True if model is vision capable. If model is not supported by litellm, it will return False.
  190. """
  191. # litellm.supports_vision currently returns False for 'openai/gpt-...' or 'anthropic/claude-...' (with prefixes)
  192. # but model_info will have the correct value for some reason.
  193. # we can go with it, but we will need to keep an eye if model_info is correct for Vertex or other providers
  194. # remove when litellm is updated to fix https://github.com/BerriAI/litellm/issues/5608
  195. return litellm.supports_vision(self.config.model) or (
  196. self.model_info is not None
  197. and self.model_info.get('supports_vision', False)
  198. )
  199. def is_caching_prompt_active(self) -> bool:
  200. """Check if prompt caching is supported and enabled for current model.
  201. Returns:
  202. boolean: True if prompt caching is supported and enabled for the given model.
  203. """
  204. return (
  205. self.config.caching_prompt is True
  206. and self.model_info is not None
  207. and self.model_info.get('supports_prompt_caching', False)
  208. and self.config.model in CACHE_PROMPT_SUPPORTED_MODELS
  209. )
  210. def _post_completion(self, response: ModelResponse) -> None:
  211. """Post-process the completion response.
  212. Logs the cost and usage stats of the completion call.
  213. """
  214. try:
  215. cur_cost = self._completion_cost(response)
  216. except Exception:
  217. cur_cost = 0
  218. stats = ''
  219. if self.cost_metric_supported:
  220. # keep track of the cost
  221. stats = 'Cost: %.2f USD | Accumulated Cost: %.2f USD\n' % (
  222. cur_cost,
  223. self.metrics.accumulated_cost,
  224. )
  225. usage: Usage | None = response.get('usage')
  226. if usage:
  227. # keep track of the input and output tokens
  228. input_tokens = usage.get('prompt_tokens')
  229. output_tokens = usage.get('completion_tokens')
  230. if input_tokens:
  231. stats += 'Input tokens: ' + str(input_tokens)
  232. if output_tokens:
  233. stats += (
  234. (' | ' if input_tokens else '')
  235. + 'Output tokens: '
  236. + str(output_tokens)
  237. + '\n'
  238. )
  239. # read the prompt caching status as received from the provider
  240. model_extra = usage.get('model_extra', {})
  241. cache_creation_input_tokens = model_extra.get('cache_creation_input_tokens')
  242. if cache_creation_input_tokens:
  243. stats += (
  244. 'Input tokens (cache write): '
  245. + str(cache_creation_input_tokens)
  246. + '\n'
  247. )
  248. cache_read_input_tokens = model_extra.get('cache_read_input_tokens')
  249. if cache_read_input_tokens:
  250. stats += (
  251. 'Input tokens (cache read): ' + str(cache_read_input_tokens) + '\n'
  252. )
  253. # log the stats
  254. if stats:
  255. logger.info(stats)
  256. def get_token_count(self, messages):
  257. """Get the number of tokens in a list of messages.
  258. Args:
  259. messages (list): A list of messages.
  260. Returns:
  261. int: The number of tokens.
  262. """
  263. try:
  264. return litellm.token_counter(model=self.config.model, messages=messages)
  265. except Exception:
  266. # TODO: this is to limit logspam in case token count is not supported
  267. return 0
  268. def _is_local(self):
  269. """Determines if the system is using a locally running LLM.
  270. Returns:
  271. boolean: True if executing a local model.
  272. """
  273. if self.config.base_url is not None:
  274. for substring in ['localhost', '127.0.0.1' '0.0.0.0']:
  275. if substring in self.config.base_url:
  276. return True
  277. elif self.config.model is not None:
  278. if self.config.model.startswith('ollama'):
  279. return True
  280. return False
  281. def _completion_cost(self, response):
  282. """Calculate the cost of a completion response based on the model. Local models are treated as free.
  283. Add the current cost into total cost in metrics.
  284. Args:
  285. response: A response from a model invocation.
  286. Returns:
  287. number: The cost of the response.
  288. """
  289. if not self.cost_metric_supported:
  290. return 0.0
  291. extra_kwargs = {}
  292. if (
  293. self.config.input_cost_per_token is not None
  294. and self.config.output_cost_per_token is not None
  295. ):
  296. cost_per_token = CostPerToken(
  297. input_cost_per_token=self.config.input_cost_per_token,
  298. output_cost_per_token=self.config.output_cost_per_token,
  299. )
  300. logger.info(f'Using custom cost per token: {cost_per_token}')
  301. extra_kwargs['custom_cost_per_token'] = cost_per_token
  302. if not self._is_local():
  303. try:
  304. cost = litellm_completion_cost(
  305. completion_response=response, **extra_kwargs
  306. )
  307. self.metrics.add_cost(cost)
  308. return cost
  309. except Exception:
  310. self.cost_metric_supported = False
  311. logger.warning('Cost calculation not supported for this model.')
  312. return 0.0
  313. def __str__(self):
  314. if self.config.api_version:
  315. return f'LLM(model={self.config.model}, api_version={self.config.api_version}, base_url={self.config.base_url})'
  316. elif self.config.base_url:
  317. return f'LLM(model={self.config.model}, base_url={self.config.base_url})'
  318. return f'LLM(model={self.config.model})'
  319. def __repr__(self):
  320. return str(self)
  321. def reset(self):
  322. self.metrics = Metrics()
  323. self.llm_completions = []
  324. def format_messages_for_llm(self, messages: Message | list[Message]) -> list[dict]:
  325. if isinstance(messages, Message):
  326. messages = [messages]
  327. # set flags to know how to serialize the messages
  328. for message in messages:
  329. message.cache_enabled = self.is_caching_prompt_active()
  330. message.vision_enabled = self.vision_is_active()
  331. # let pydantic handle the serialization
  332. return [message.model_dump() for message in messages]