llm.py 22 KB

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