llm.py 15 KB

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