llm.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import copy
  2. import os
  3. import time
  4. import warnings
  5. from functools import partial
  6. from typing import Any
  7. import requests
  8. from openhands.core.config import LLMConfig
  9. with warnings.catch_warnings():
  10. warnings.simplefilter('ignore')
  11. import litellm
  12. from litellm import ModelInfo, PromptTokensDetails
  13. from litellm import completion as litellm_completion
  14. from litellm import completion_cost as litellm_completion_cost
  15. from litellm.exceptions import (
  16. APIConnectionError,
  17. APIError,
  18. InternalServerError,
  19. RateLimitError,
  20. ServiceUnavailableError,
  21. )
  22. from litellm.types.utils import CostPerToken, ModelResponse, Usage
  23. from openhands.core.exceptions import CloudFlareBlockageError
  24. from openhands.core.logger import openhands_logger as logger
  25. from openhands.core.message import Message
  26. from openhands.llm.debug_mixin import DebugMixin
  27. from openhands.llm.metrics import Metrics
  28. from openhands.llm.retry_mixin import RetryMixin
  29. __all__ = ['LLM']
  30. # tuple of exceptions to retry on
  31. LLM_RETRY_EXCEPTIONS: tuple[type[Exception], ...] = (
  32. APIConnectionError,
  33. # FIXME: APIError is useful on 502 from a proxy for example,
  34. # but it also retries on other errors that are permanent
  35. APIError,
  36. InternalServerError,
  37. RateLimitError,
  38. ServiceUnavailableError,
  39. )
  40. # cache prompt supporting models
  41. # remove this when we gemini and deepseek are supported
  42. CACHE_PROMPT_SUPPORTED_MODELS = [
  43. 'claude-3-5-sonnet-20241022',
  44. 'claude-3-5-sonnet-20240620',
  45. 'claude-3-5-haiku-20241022',
  46. 'claude-3-haiku-20240307',
  47. 'claude-3-opus-20240229',
  48. ]
  49. # function calling supporting models
  50. FUNCTION_CALLING_SUPPORTED_MODELS = [
  51. 'claude-3-5-sonnet-20240620',
  52. 'claude-3-5-sonnet-20241022',
  53. 'claude-3-5-haiku-20241022',
  54. 'gpt-4o',
  55. 'gpt-4o-mini',
  56. ]
  57. class LLM(RetryMixin, DebugMixin):
  58. """The LLM class represents a Language Model instance.
  59. Attributes:
  60. config: an LLMConfig object specifying the configuration of the LLM.
  61. """
  62. def __init__(
  63. self,
  64. config: LLMConfig,
  65. metrics: Metrics | None = None,
  66. ):
  67. """Initializes the LLM. If LLMConfig is passed, its values will be the fallback.
  68. Passing simple parameters always overrides config.
  69. Args:
  70. config: The LLM configuration.
  71. metrics: The metrics to use.
  72. """
  73. self._tried_model_info = False
  74. self.metrics: Metrics = (
  75. metrics if metrics is not None else Metrics(model_name=config.model)
  76. )
  77. self.cost_metric_supported: bool = True
  78. self.config: LLMConfig = copy.deepcopy(config)
  79. # litellm actually uses base Exception here for unknown model
  80. self.model_info: ModelInfo | None = None
  81. if self.config.log_completions:
  82. if self.config.log_completions_folder is None:
  83. raise RuntimeError(
  84. 'log_completions_folder is required when log_completions is enabled'
  85. )
  86. os.makedirs(self.config.log_completions_folder, exist_ok=True)
  87. self._completion = partial(
  88. litellm_completion,
  89. model=self.config.model,
  90. api_key=self.config.api_key,
  91. base_url=self.config.base_url,
  92. api_version=self.config.api_version,
  93. custom_llm_provider=self.config.custom_llm_provider,
  94. max_tokens=self.config.max_output_tokens,
  95. timeout=self.config.timeout,
  96. temperature=self.config.temperature,
  97. top_p=self.config.top_p,
  98. drop_params=self.config.drop_params,
  99. )
  100. if self.vision_is_active():
  101. logger.debug('LLM: model has vision enabled')
  102. if self.is_caching_prompt_active():
  103. logger.debug('LLM: caching prompt enabled')
  104. if self.is_function_calling_active():
  105. logger.debug('LLM: model supports function calling')
  106. self._completion = partial(
  107. litellm_completion,
  108. model=self.config.model,
  109. api_key=self.config.api_key,
  110. base_url=self.config.base_url,
  111. api_version=self.config.api_version,
  112. custom_llm_provider=self.config.custom_llm_provider,
  113. max_tokens=self.config.max_output_tokens,
  114. timeout=self.config.timeout,
  115. temperature=self.config.temperature,
  116. top_p=self.config.top_p,
  117. drop_params=self.config.drop_params,
  118. )
  119. if self.vision_is_active():
  120. logger.debug('LLM: model has vision enabled')
  121. if self.is_caching_prompt_active():
  122. logger.debug('LLM: caching prompt enabled')
  123. if self.is_function_calling_active():
  124. logger.debug('LLM: model supports function calling')
  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. self.init_model_info()
  136. messages: list[dict[str, Any]] | dict[str, Any] = []
  137. # some callers might send the model and messages directly
  138. # litellm allows positional args, like completion(model, messages, **kwargs)
  139. if len(args) > 1:
  140. # ignore the first argument if it's provided (it would be the model)
  141. # design wise: we don't allow overriding the configured values
  142. # implementation wise: the partial function set the model as a kwarg already
  143. # as well as other kwargs
  144. messages = args[1] if len(args) > 1 else args[0]
  145. kwargs['messages'] = messages
  146. # remove the first args, they're sent in kwargs
  147. args = args[2:]
  148. elif 'messages' in kwargs:
  149. messages = kwargs['messages']
  150. # ensure we work with a list of messages
  151. messages = messages if isinstance(messages, list) else [messages]
  152. # if we have no messages, something went very wrong
  153. if not messages:
  154. raise ValueError(
  155. 'The messages list is empty. At least one message is required.'
  156. )
  157. # log the entire LLM prompt
  158. self.log_prompt(messages)
  159. if self.is_caching_prompt_active():
  160. # Anthropic-specific prompt caching
  161. if 'claude-3' in self.config.model:
  162. kwargs['extra_headers'] = {
  163. 'anthropic-beta': 'prompt-caching-2024-07-31',
  164. }
  165. try:
  166. # we don't support streaming here, thus we get a ModelResponse
  167. resp: ModelResponse = completion_unwrapped(*args, **kwargs)
  168. # log for evals or other scripts that need the raw completion
  169. if self.config.log_completions:
  170. assert self.config.log_completions_folder is not None
  171. log_file = os.path.join(
  172. self.config.log_completions_folder,
  173. # use the metric model name (for draft editor)
  174. f'{self.metrics.model_name.replace("/", "__")}-{time.time()}.json',
  175. )
  176. from openhands.core.utils import json
  177. with open(log_file, 'w') as f:
  178. f.write(
  179. json.dumps(
  180. {
  181. 'messages': messages,
  182. 'response': resp,
  183. 'args': args,
  184. 'kwargs': {
  185. k: v
  186. for k, v in kwargs.items()
  187. if k != 'messages'
  188. },
  189. 'timestamp': time.time(),
  190. 'cost': self._completion_cost(resp),
  191. },
  192. )
  193. )
  194. message_back: str = resp['choices'][0]['message']['content']
  195. # log the LLM response
  196. self.log_response(message_back)
  197. # post-process the response
  198. self._post_completion(resp)
  199. return resp
  200. except APIError as e:
  201. if 'Attention Required! | Cloudflare' in str(e):
  202. raise CloudFlareBlockageError(
  203. 'Request blocked by CloudFlare'
  204. ) from e
  205. raise
  206. self._completion = wrapper
  207. @property
  208. def completion(self):
  209. """Decorator for the litellm completion function.
  210. Check the complete documentation at https://litellm.vercel.app/docs/completion
  211. """
  212. return self._completion
  213. def init_model_info(self):
  214. if self._tried_model_info:
  215. return
  216. self._tried_model_info = True
  217. try:
  218. if self.config.model.startswith('openrouter'):
  219. self.model_info = litellm.get_model_info(self.config.model)
  220. except Exception as e:
  221. logger.debug(f'Error getting model info: {e}')
  222. if self.config.model.startswith('litellm_proxy/'):
  223. # IF we are using LiteLLM proxy, get model info from LiteLLM proxy
  224. # GET {base_url}/v1/model/info with litellm_model_id as path param
  225. response = requests.get(
  226. f'{self.config.base_url}/v1/model/info',
  227. headers={'Authorization': f'Bearer {self.config.api_key}'},
  228. )
  229. resp_json = response.json()
  230. if 'data' not in resp_json:
  231. logger.error(
  232. f'Error getting model info from LiteLLM proxy: {resp_json}'
  233. )
  234. all_model_info = resp_json.get('data', [])
  235. current_model_info = next(
  236. (
  237. info
  238. for info in all_model_info
  239. if info['model_name']
  240. == self.config.model.removeprefix('litellm_proxy/')
  241. ),
  242. None,
  243. )
  244. if current_model_info:
  245. self.model_info = current_model_info['model_info']
  246. # Last two attempts to get model info from NAME
  247. if not self.model_info:
  248. try:
  249. self.model_info = litellm.get_model_info(
  250. self.config.model.split(':')[0]
  251. )
  252. # noinspection PyBroadException
  253. except Exception:
  254. pass
  255. if not self.model_info:
  256. try:
  257. self.model_info = litellm.get_model_info(
  258. self.config.model.split('/')[-1]
  259. )
  260. # noinspection PyBroadException
  261. except Exception:
  262. pass
  263. logger.debug(f'Model info: {self.model_info}')
  264. # Set the max tokens in an LM-specific way if not set
  265. if self.config.max_input_tokens is None:
  266. if (
  267. self.model_info is not None
  268. and 'max_input_tokens' in self.model_info
  269. and isinstance(self.model_info['max_input_tokens'], int)
  270. ):
  271. self.config.max_input_tokens = self.model_info['max_input_tokens']
  272. else:
  273. # Safe fallback for any potentially viable model
  274. self.config.max_input_tokens = 4096
  275. if self.config.max_output_tokens is None:
  276. # Safe default for any potentially viable model
  277. self.config.max_output_tokens = 4096
  278. if self.model_info is not None:
  279. # max_output_tokens has precedence over max_tokens, if either exists.
  280. # litellm has models with both, one or none of these 2 parameters!
  281. if 'max_output_tokens' in self.model_info and isinstance(
  282. self.model_info['max_output_tokens'], int
  283. ):
  284. self.config.max_output_tokens = self.model_info['max_output_tokens']
  285. elif 'max_tokens' in self.model_info and isinstance(
  286. self.model_info['max_tokens'], int
  287. ):
  288. self.config.max_output_tokens = self.model_info['max_tokens']
  289. def vision_is_active(self):
  290. return not self.config.disable_vision and self._supports_vision()
  291. def _supports_vision(self):
  292. """Acquire from litellm if model is vision capable.
  293. Returns:
  294. bool: True if model is vision capable. If model is not supported by litellm, it will return False.
  295. """
  296. # litellm.supports_vision currently returns False for 'openai/gpt-...' or 'anthropic/claude-...' (with prefixes)
  297. # but model_info will have the correct value for some reason.
  298. # we can go with it, but we will need to keep an eye if model_info is correct for Vertex or other providers
  299. # remove when litellm is updated to fix https://github.com/BerriAI/litellm/issues/5608
  300. return litellm.supports_vision(self.config.model) or (
  301. self.model_info is not None
  302. and self.model_info.get('supports_vision', False)
  303. )
  304. def is_caching_prompt_active(self) -> bool:
  305. """Check if prompt caching is supported and enabled for current model.
  306. Returns:
  307. boolean: True if prompt caching is supported and enabled for the given model.
  308. """
  309. return self.config.caching_prompt is True and (
  310. (
  311. self.config.model in CACHE_PROMPT_SUPPORTED_MODELS
  312. or self.config.model.split('/')[-1] in CACHE_PROMPT_SUPPORTED_MODELS
  313. )
  314. or (
  315. self.model_info is not None
  316. and self.model_info.get('supports_prompt_caching', False)
  317. )
  318. )
  319. def is_function_calling_active(self) -> bool:
  320. # Check if model name is in supported list before checking model_info
  321. model_name_supported = (
  322. self.config.model in FUNCTION_CALLING_SUPPORTED_MODELS
  323. or self.config.model.split('/')[-1] in FUNCTION_CALLING_SUPPORTED_MODELS
  324. or any(m in self.config.model for m in FUNCTION_CALLING_SUPPORTED_MODELS)
  325. )
  326. return model_name_supported or (
  327. self.model_info is not None
  328. and self.model_info.get('supports_function_calling', False)
  329. )
  330. def _post_completion(self, response: ModelResponse) -> None:
  331. """Post-process the completion response.
  332. Logs the cost and usage stats of the completion call.
  333. """
  334. try:
  335. cur_cost = self._completion_cost(response)
  336. except Exception:
  337. cur_cost = 0
  338. stats = ''
  339. if self.cost_metric_supported:
  340. # keep track of the cost
  341. stats = 'Cost: %.2f USD | Accumulated Cost: %.2f USD\n' % (
  342. cur_cost,
  343. self.metrics.accumulated_cost,
  344. )
  345. usage: Usage | None = response.get('usage')
  346. if usage:
  347. # keep track of the input and output tokens
  348. input_tokens = usage.get('prompt_tokens')
  349. output_tokens = usage.get('completion_tokens')
  350. if input_tokens:
  351. stats += 'Input tokens: ' + str(input_tokens)
  352. if output_tokens:
  353. stats += (
  354. (' | ' if input_tokens else '')
  355. + 'Output tokens: '
  356. + str(output_tokens)
  357. + '\n'
  358. )
  359. # read the prompt cache hit, if any
  360. prompt_tokens_details: PromptTokensDetails = usage.get(
  361. 'prompt_tokens_details'
  362. )
  363. cache_hit_tokens = (
  364. prompt_tokens_details.cached_tokens if prompt_tokens_details else None
  365. )
  366. if cache_hit_tokens:
  367. stats += 'Input tokens (cache hit): ' + str(cache_hit_tokens) + '\n'
  368. # For Anthropic, the cache writes have a different cost than regular input tokens
  369. # but litellm doesn't separate them in the usage stats
  370. # so we can read it from the provider-specific extra field
  371. model_extra = usage.get('model_extra', {})
  372. cache_write_tokens = model_extra.get('cache_creation_input_tokens')
  373. if cache_write_tokens:
  374. stats += 'Input tokens (cache write): ' + str(cache_write_tokens) + '\n'
  375. # log the stats
  376. if stats:
  377. logger.debug(stats)
  378. def get_token_count(self, messages):
  379. """Get the number of tokens in a list of messages.
  380. Args:
  381. messages (list): A list of messages.
  382. Returns:
  383. int: The number of tokens.
  384. """
  385. try:
  386. return litellm.token_counter(model=self.config.model, messages=messages)
  387. except Exception:
  388. # TODO: this is to limit logspam in case token count is not supported
  389. return 0
  390. def _is_local(self):
  391. """Determines if the system is using a locally running LLM.
  392. Returns:
  393. boolean: True if executing a local model.
  394. """
  395. if self.config.base_url is not None:
  396. for substring in ['localhost', '127.0.0.1' '0.0.0.0']:
  397. if substring in self.config.base_url:
  398. return True
  399. elif self.config.model is not None:
  400. if self.config.model.startswith('ollama'):
  401. return True
  402. return False
  403. def _completion_cost(self, response):
  404. """Calculate the cost of a completion response based on the model. Local models are treated as free.
  405. Add the current cost into total cost in metrics.
  406. Args:
  407. response: A response from a model invocation.
  408. Returns:
  409. number: The cost of the response.
  410. """
  411. if not self.cost_metric_supported:
  412. return 0.0
  413. extra_kwargs = {}
  414. if (
  415. self.config.input_cost_per_token is not None
  416. and self.config.output_cost_per_token is not None
  417. ):
  418. cost_per_token = CostPerToken(
  419. input_cost_per_token=self.config.input_cost_per_token,
  420. output_cost_per_token=self.config.output_cost_per_token,
  421. )
  422. logger.debug(f'Using custom cost per token: {cost_per_token}')
  423. extra_kwargs['custom_cost_per_token'] = cost_per_token
  424. try:
  425. # try directly get response_cost from response
  426. cost = getattr(response, '_hidden_params', {}).get('response_cost', None)
  427. if cost is None:
  428. cost = litellm_completion_cost(
  429. completion_response=response, **extra_kwargs
  430. )
  431. self.metrics.add_cost(cost)
  432. return cost
  433. except Exception:
  434. self.cost_metric_supported = False
  435. logger.debug('Cost calculation not supported for this model.')
  436. return 0.0
  437. def __str__(self):
  438. if self.config.api_version:
  439. return f'LLM(model={self.config.model}, api_version={self.config.api_version}, base_url={self.config.base_url})'
  440. elif self.config.base_url:
  441. return f'LLM(model={self.config.model}, base_url={self.config.base_url})'
  442. return f'LLM(model={self.config.model})'
  443. def __repr__(self):
  444. return str(self)
  445. def reset(self):
  446. self.metrics.reset()
  447. def format_messages_for_llm(self, messages: Message | list[Message]) -> list[dict]:
  448. if isinstance(messages, Message):
  449. messages = [messages]
  450. # set flags to know how to serialize the messages
  451. for message in messages:
  452. message.cache_enabled = self.is_caching_prompt_active()
  453. message.vision_enabled = self.vision_is_active()
  454. # let pydantic handle the serialization
  455. return [message.model_dump() for message in messages]