llm.py 15 KB

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