llm.py 22 KB

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