llm.py 22 KB

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