llm.py 24 KB

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