llm.py 25 KB

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