llm.py 22 KB

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