llm.py 15 KB

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