llm.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. message_back: str = resp['choices'][0]['message']['content'] or ''
  192. tool_calls = resp['choices'][0]['message'].get('tool_calls', [])
  193. if tool_calls:
  194. for tool_call in tool_calls:
  195. fn_name = tool_call.function.name
  196. fn_args = tool_call.function.arguments
  197. message_back += f'\nFunction call: {fn_name}({fn_args})'
  198. # log the LLM response
  199. self.log_response(message_back)
  200. # post-process the response first to calculate cost
  201. cost = self._post_completion(resp)
  202. # log for evals or other scripts that need the raw completion
  203. if self.config.log_completions:
  204. assert self.config.log_completions_folder is not None
  205. log_file = os.path.join(
  206. self.config.log_completions_folder,
  207. # use the metric model name (for draft editor)
  208. f'{self.metrics.model_name.replace("/", "__")}-{time.time()}.json',
  209. )
  210. # set up the dict to be logged
  211. _d = {
  212. 'messages': messages,
  213. 'response': resp,
  214. 'args': args,
  215. 'kwargs': {k: v for k, v in kwargs.items() if k != 'messages'},
  216. 'timestamp': time.time(),
  217. 'cost': cost,
  218. }
  219. # if non-native function calling, save messages/response separately
  220. if mock_function_calling:
  221. # Overwrite response as non-fncall to be consistent with messages
  222. _d['response'] = non_fncall_response
  223. # Save fncall_messages/response separately
  224. _d['fncall_messages'] = original_fncall_messages
  225. _d['fncall_response'] = resp
  226. with open(log_file, 'w') as f:
  227. f.write(json.dumps(_d))
  228. return resp
  229. except APIError as e:
  230. if 'Attention Required! | Cloudflare' in str(e):
  231. raise CloudFlareBlockageError(
  232. 'Request blocked by CloudFlare'
  233. ) from e
  234. raise
  235. self._completion = wrapper
  236. @property
  237. def completion(self):
  238. """Decorator for the litellm completion function.
  239. Check the complete documentation at https://litellm.vercel.app/docs/completion
  240. """
  241. return self._completion
  242. def init_model_info(self):
  243. if self._tried_model_info:
  244. return
  245. self._tried_model_info = True
  246. try:
  247. if self.config.model.startswith('openrouter'):
  248. self.model_info = litellm.get_model_info(self.config.model)
  249. except Exception as e:
  250. logger.debug(f'Error getting model info: {e}')
  251. if self.config.model.startswith('litellm_proxy/'):
  252. # IF we are using LiteLLM proxy, get model info from LiteLLM proxy
  253. # GET {base_url}/v1/model/info with litellm_model_id as path param
  254. response = requests.get(
  255. f'{self.config.base_url}/v1/model/info',
  256. headers={'Authorization': f'Bearer {self.config.api_key}'},
  257. )
  258. resp_json = response.json()
  259. if 'data' not in resp_json:
  260. logger.error(
  261. f'Error getting model info from LiteLLM proxy: {resp_json}'
  262. )
  263. all_model_info = resp_json.get('data', [])
  264. current_model_info = next(
  265. (
  266. info
  267. for info in all_model_info
  268. if info['model_name']
  269. == self.config.model.removeprefix('litellm_proxy/')
  270. ),
  271. None,
  272. )
  273. if current_model_info:
  274. self.model_info = current_model_info['model_info']
  275. # Last two attempts to get model info from NAME
  276. if not self.model_info:
  277. try:
  278. self.model_info = litellm.get_model_info(
  279. self.config.model.split(':')[0]
  280. )
  281. # noinspection PyBroadException
  282. except Exception:
  283. pass
  284. if not self.model_info:
  285. try:
  286. self.model_info = litellm.get_model_info(
  287. self.config.model.split('/')[-1]
  288. )
  289. # noinspection PyBroadException
  290. except Exception:
  291. pass
  292. logger.debug(f'Model info: {self.model_info}')
  293. if self.config.model.startswith('huggingface'):
  294. # HF doesn't support the OpenAI default value for top_p (1)
  295. logger.debug(
  296. f'Setting top_p to 0.9 for Hugging Face model: {self.config.model}'
  297. )
  298. self.config.top_p = 0.9 if self.config.top_p == 1 else self.config.top_p
  299. # Set the max tokens in an LM-specific way if not set
  300. if self.config.max_input_tokens is None:
  301. if (
  302. self.model_info is not None
  303. and 'max_input_tokens' in self.model_info
  304. and isinstance(self.model_info['max_input_tokens'], int)
  305. ):
  306. self.config.max_input_tokens = self.model_info['max_input_tokens']
  307. else:
  308. # Safe fallback for any potentially viable model
  309. self.config.max_input_tokens = 4096
  310. if self.config.max_output_tokens is None:
  311. # Safe default for any potentially viable model
  312. self.config.max_output_tokens = 4096
  313. if self.model_info is not None:
  314. # max_output_tokens has precedence over max_tokens, if either exists.
  315. # litellm has models with both, one or none of these 2 parameters!
  316. if 'max_output_tokens' in self.model_info and isinstance(
  317. self.model_info['max_output_tokens'], int
  318. ):
  319. self.config.max_output_tokens = self.model_info['max_output_tokens']
  320. elif 'max_tokens' in self.model_info and isinstance(
  321. self.model_info['max_tokens'], int
  322. ):
  323. self.config.max_output_tokens = self.model_info['max_tokens']
  324. def vision_is_active(self) -> bool:
  325. with warnings.catch_warnings():
  326. warnings.simplefilter('ignore')
  327. return not self.config.disable_vision and self._supports_vision()
  328. def _supports_vision(self) -> bool:
  329. """Acquire from litellm if model is vision capable.
  330. Returns:
  331. bool: True if model is vision capable. Return False if model not supported by litellm.
  332. """
  333. # litellm.supports_vision currently returns False for 'openai/gpt-...' or 'anthropic/claude-...' (with prefixes)
  334. # but model_info will have the correct value for some reason.
  335. # we can go with it, but we will need to keep an eye if model_info is correct for Vertex or other providers
  336. # remove when litellm is updated to fix https://github.com/BerriAI/litellm/issues/5608
  337. # Check both the full model name and the name after proxy prefix for vision support
  338. return (
  339. litellm.supports_vision(self.config.model)
  340. or litellm.supports_vision(self.config.model.split('/')[-1])
  341. or (
  342. self.model_info is not None
  343. and self.model_info.get('supports_vision', False)
  344. )
  345. )
  346. def is_caching_prompt_active(self) -> bool:
  347. """Check if prompt caching is supported and enabled for current model.
  348. Returns:
  349. boolean: True if prompt caching is supported and enabled for the given model.
  350. """
  351. return (
  352. self.config.caching_prompt is True
  353. and (
  354. self.config.model in CACHE_PROMPT_SUPPORTED_MODELS
  355. or self.config.model.split('/')[-1] in CACHE_PROMPT_SUPPORTED_MODELS
  356. )
  357. # We don't need to look-up model_info, because only Anthropic models needs the explicit caching breakpoint
  358. )
  359. def is_function_calling_active(self) -> bool:
  360. # Check if model name is in supported list before checking model_info
  361. model_name_supported = (
  362. self.config.model in FUNCTION_CALLING_SUPPORTED_MODELS
  363. or self.config.model.split('/')[-1] in FUNCTION_CALLING_SUPPORTED_MODELS
  364. or any(m in self.config.model for m in FUNCTION_CALLING_SUPPORTED_MODELS)
  365. )
  366. return model_name_supported
  367. def _post_completion(self, response: ModelResponse) -> float:
  368. """Post-process the completion response.
  369. Logs the cost and usage stats of the completion call.
  370. """
  371. try:
  372. cur_cost = self._completion_cost(response)
  373. except Exception:
  374. cur_cost = 0
  375. stats = ''
  376. if self.cost_metric_supported:
  377. # keep track of the cost
  378. stats = 'Cost: %.2f USD | Accumulated Cost: %.2f USD\n' % (
  379. cur_cost,
  380. self.metrics.accumulated_cost,
  381. )
  382. usage: Usage | None = response.get('usage')
  383. if usage:
  384. # keep track of the input and output tokens
  385. input_tokens = usage.get('prompt_tokens')
  386. output_tokens = usage.get('completion_tokens')
  387. if input_tokens:
  388. stats += 'Input tokens: ' + str(input_tokens)
  389. if output_tokens:
  390. stats += (
  391. (' | ' if input_tokens else '')
  392. + 'Output tokens: '
  393. + str(output_tokens)
  394. + '\n'
  395. )
  396. # read the prompt cache hit, if any
  397. prompt_tokens_details: PromptTokensDetails = usage.get(
  398. 'prompt_tokens_details'
  399. )
  400. cache_hit_tokens = (
  401. prompt_tokens_details.cached_tokens if prompt_tokens_details else None
  402. )
  403. if cache_hit_tokens:
  404. stats += 'Input tokens (cache hit): ' + str(cache_hit_tokens) + '\n'
  405. # For Anthropic, the cache writes have a different cost than regular input tokens
  406. # but litellm doesn't separate them in the usage stats
  407. # so we can read it from the provider-specific extra field
  408. model_extra = usage.get('model_extra', {})
  409. cache_write_tokens = model_extra.get('cache_creation_input_tokens')
  410. if cache_write_tokens:
  411. stats += 'Input tokens (cache write): ' + str(cache_write_tokens) + '\n'
  412. # log the stats
  413. if stats:
  414. logger.debug(stats)
  415. return cur_cost
  416. def get_token_count(self, messages) -> int:
  417. """Get the number of tokens in a list of messages.
  418. Args:
  419. messages (list): A list of messages.
  420. Returns:
  421. int: The number of tokens.
  422. """
  423. try:
  424. return litellm.token_counter(model=self.config.model, messages=messages)
  425. except Exception:
  426. # TODO: this is to limit logspam in case token count is not supported
  427. return 0
  428. def _is_local(self) -> bool:
  429. """Determines if the system is using a locally running LLM.
  430. Returns:
  431. boolean: True if executing a local model.
  432. """
  433. if self.config.base_url is not None:
  434. for substring in ['localhost', '127.0.0.1' '0.0.0.0']:
  435. if substring in self.config.base_url:
  436. return True
  437. elif self.config.model is not None:
  438. if self.config.model.startswith('ollama'):
  439. return True
  440. return False
  441. def _completion_cost(self, response) -> float:
  442. """Calculate the cost of a completion response based on the model. Local models are treated as free.
  443. Add the current cost into total cost in metrics.
  444. Args:
  445. response: A response from a model invocation.
  446. Returns:
  447. number: The cost of the response.
  448. """
  449. if not self.cost_metric_supported:
  450. return 0.0
  451. extra_kwargs = {}
  452. if (
  453. self.config.input_cost_per_token is not None
  454. and self.config.output_cost_per_token is not None
  455. ):
  456. cost_per_token = CostPerToken(
  457. input_cost_per_token=self.config.input_cost_per_token,
  458. output_cost_per_token=self.config.output_cost_per_token,
  459. )
  460. logger.debug(f'Using custom cost per token: {cost_per_token}')
  461. extra_kwargs['custom_cost_per_token'] = cost_per_token
  462. try:
  463. # try directly get response_cost from response
  464. cost = getattr(response, '_hidden_params', {}).get('response_cost', None)
  465. if cost is None:
  466. cost = litellm_completion_cost(
  467. completion_response=response, **extra_kwargs
  468. )
  469. self.metrics.add_cost(cost)
  470. return cost
  471. except Exception:
  472. self.cost_metric_supported = False
  473. logger.debug('Cost calculation not supported for this model.')
  474. return 0.0
  475. def __str__(self):
  476. if self.config.api_version:
  477. return f'LLM(model={self.config.model}, api_version={self.config.api_version}, base_url={self.config.base_url})'
  478. elif self.config.base_url:
  479. return f'LLM(model={self.config.model}, base_url={self.config.base_url})'
  480. return f'LLM(model={self.config.model})'
  481. def __repr__(self):
  482. return str(self)
  483. def reset(self) -> None:
  484. self.metrics.reset()
  485. def format_messages_for_llm(self, messages: Message | list[Message]) -> list[dict]:
  486. if isinstance(messages, Message):
  487. messages = [messages]
  488. # set flags to know how to serialize the messages
  489. for message in messages:
  490. message.cache_enabled = self.is_caching_prompt_active()
  491. message.vision_enabled = self.vision_is_active()
  492. message.function_calling_enabled = self.is_function_calling_active()
  493. # let pydantic handle the serialization
  494. return [message.model_dump() for message in messages]