llm.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import asyncio
  2. import copy
  3. import warnings
  4. from functools import partial
  5. from typing import Union
  6. from openhands.core.config import LLMConfig
  7. with warnings.catch_warnings():
  8. warnings.simplefilter('ignore')
  9. import litellm
  10. from litellm import completion as litellm_completion
  11. from litellm import completion_cost as litellm_completion_cost
  12. from litellm.exceptions import (
  13. APIConnectionError,
  14. ContentPolicyViolationError,
  15. InternalServerError,
  16. NotFoundError,
  17. OpenAIError,
  18. RateLimitError,
  19. ServiceUnavailableError,
  20. )
  21. from litellm.types.utils import CostPerToken
  22. from tenacity import (
  23. retry,
  24. retry_if_exception_type,
  25. stop_after_attempt,
  26. wait_exponential,
  27. )
  28. from openhands.core.exceptions import LLMResponseError, UserCancelledError
  29. from openhands.core.logger import llm_prompt_logger, llm_response_logger
  30. from openhands.core.logger import openhands_logger as logger
  31. from openhands.core.message import Message, format_messages
  32. from openhands.core.metrics import Metrics
  33. __all__ = ['LLM']
  34. message_separator = '\n\n----------\n\n'
  35. cache_prompting_supported_models = [
  36. 'claude-3-5-sonnet-20240620',
  37. 'claude-3-haiku-20240307',
  38. ]
  39. class LLM:
  40. """The LLM class represents a Language Model instance.
  41. Attributes:
  42. config: an LLMConfig object specifying the configuration of the LLM.
  43. """
  44. def __init__(
  45. self,
  46. config: LLMConfig,
  47. metrics: Metrics | None = None,
  48. ):
  49. """Initializes the LLM. If LLMConfig is passed, its values will be the fallback.
  50. Passing simple parameters always overrides config.
  51. Args:
  52. config: The LLM configuration
  53. """
  54. self.metrics = metrics if metrics is not None else Metrics()
  55. self.cost_metric_supported = True
  56. self.config = copy.deepcopy(config)
  57. # Set up config attributes with default values to prevent AttributeError
  58. LLMConfig.set_missing_attributes(self.config)
  59. # litellm actually uses base Exception here for unknown model
  60. self.model_info = None
  61. try:
  62. if self.config.model.startswith('openrouter'):
  63. self.model_info = litellm.get_model_info(self.config.model)
  64. else:
  65. self.model_info = litellm.get_model_info(
  66. self.config.model.split(':')[0]
  67. )
  68. # noinspection PyBroadException
  69. except Exception as e:
  70. logger.warning(f'Could not get model info for {config.model}:\n{e}')
  71. # Tuple of exceptions to retry on
  72. self.retry_exceptions = (
  73. APIConnectionError,
  74. ContentPolicyViolationError,
  75. InternalServerError,
  76. OpenAIError,
  77. RateLimitError,
  78. )
  79. # Set the max tokens in an LM-specific way if not set
  80. if self.config.max_input_tokens is None:
  81. if (
  82. self.model_info is not None
  83. and 'max_input_tokens' in self.model_info
  84. and isinstance(self.model_info['max_input_tokens'], int)
  85. ):
  86. self.config.max_input_tokens = self.model_info['max_input_tokens']
  87. else:
  88. # Max input tokens for gpt3.5, so this is a safe fallback for any potentially viable model
  89. self.config.max_input_tokens = 4096
  90. if self.config.max_output_tokens is None:
  91. if (
  92. self.model_info is not None
  93. and 'max_output_tokens' in self.model_info
  94. and isinstance(self.model_info['max_output_tokens'], int)
  95. ):
  96. self.config.max_output_tokens = self.model_info['max_output_tokens']
  97. else:
  98. # Max output tokens for gpt3.5, so this is a safe fallback for any potentially viable model
  99. self.config.max_output_tokens = 1024
  100. if self.config.drop_params:
  101. litellm.drop_params = self.config.drop_params
  102. self._completion = partial(
  103. litellm_completion,
  104. model=self.config.model,
  105. api_key=self.config.api_key,
  106. base_url=self.config.base_url,
  107. api_version=self.config.api_version,
  108. custom_llm_provider=self.config.custom_llm_provider,
  109. max_tokens=self.config.max_output_tokens,
  110. timeout=self.config.timeout,
  111. temperature=self.config.temperature,
  112. top_p=self.config.top_p,
  113. )
  114. if self.vision_is_active():
  115. logger.debug('LLM: model has vision enabled')
  116. completion_unwrapped = self._completion
  117. def attempt_on_error(retry_state):
  118. """Custom attempt function for litellm completion."""
  119. logger.error(
  120. f'{retry_state.outcome.exception()}. Attempt #{retry_state.attempt_number} | You can customize retry values in the configuration.',
  121. exc_info=False,
  122. )
  123. return None
  124. def custom_completion_wait(retry_state):
  125. """Custom wait function for litellm completion."""
  126. if not retry_state:
  127. return 0
  128. exception = retry_state.outcome.exception() if retry_state.outcome else None
  129. if exception is None:
  130. return 0
  131. min_wait_time = self.config.retry_min_wait
  132. max_wait_time = self.config.retry_max_wait
  133. # for rate limit errors, wait 1 minute by default, max 4 minutes between retries
  134. exception_type = type(exception).__name__
  135. logger.error(f'\nexception_type: {exception_type}\n')
  136. if exception_type == 'RateLimitError':
  137. min_wait_time = 60
  138. max_wait_time = 240
  139. elif exception_type == 'BadRequestError' and exception.response:
  140. # this should give us the burried, actual error message from
  141. # the LLM model.
  142. logger.error(f'\n\nBadRequestError: {exception.response}\n\n')
  143. # Return the wait time using exponential backoff
  144. exponential_wait = wait_exponential(
  145. multiplier=self.config.retry_multiplier,
  146. min=min_wait_time,
  147. max=max_wait_time,
  148. )
  149. # Call the exponential wait function with retry_state to get the actual wait time
  150. return exponential_wait(retry_state)
  151. @retry(
  152. after=attempt_on_error,
  153. stop=stop_after_attempt(self.config.num_retries),
  154. reraise=True,
  155. retry=retry_if_exception_type(self.retry_exceptions),
  156. wait=custom_completion_wait,
  157. )
  158. def wrapper(*args, **kwargs):
  159. """Wrapper for the litellm completion function. Logs the input and output of the completion function."""
  160. # some callers might just send the messages directly
  161. if 'messages' in kwargs:
  162. messages = kwargs['messages']
  163. else:
  164. messages = args[1] if len(args) > 1 else []
  165. # this serves to prevent empty messages and logging the messages
  166. debug_message = self._get_debug_message(messages)
  167. if self.is_caching_prompt_active():
  168. # Anthropic-specific prompt caching
  169. if 'claude-3' in self.config.model:
  170. kwargs['extra_headers'] = {
  171. 'anthropic-beta': 'prompt-caching-2024-07-31',
  172. }
  173. # skip if messages is empty (thus debug_message is empty)
  174. if debug_message:
  175. llm_prompt_logger.debug(debug_message)
  176. resp = completion_unwrapped(*args, **kwargs)
  177. else:
  178. logger.debug('No completion messages!')
  179. resp = {'choices': [{'message': {'content': ''}}]}
  180. # log the response
  181. message_back = resp['choices'][0]['message']['content']
  182. if message_back:
  183. llm_response_logger.debug(message_back)
  184. # post-process to log costs
  185. self._post_completion(resp)
  186. return resp
  187. self._completion = wrapper # type: ignore
  188. # Async version
  189. self._async_completion = partial(
  190. self._call_acompletion,
  191. model=self.config.model,
  192. api_key=self.config.api_key,
  193. base_url=self.config.base_url,
  194. api_version=self.config.api_version,
  195. custom_llm_provider=self.config.custom_llm_provider,
  196. max_tokens=self.config.max_output_tokens,
  197. timeout=self.config.timeout,
  198. temperature=self.config.temperature,
  199. top_p=self.config.top_p,
  200. drop_params=True,
  201. )
  202. async_completion_unwrapped = self._async_completion
  203. @retry(
  204. after=attempt_on_error,
  205. stop=stop_after_attempt(self.config.num_retries),
  206. reraise=True,
  207. retry=retry_if_exception_type(self.retry_exceptions),
  208. wait=custom_completion_wait,
  209. )
  210. async def async_completion_wrapper(*args, **kwargs):
  211. """Async wrapper for the litellm acompletion function."""
  212. # some callers might just send the messages directly
  213. if 'messages' in kwargs:
  214. messages = kwargs['messages']
  215. else:
  216. messages = args[1] if len(args) > 1 else []
  217. # this serves to prevent empty messages and logging the messages
  218. debug_message = self._get_debug_message(messages)
  219. async def check_stopped():
  220. while True:
  221. if (
  222. hasattr(self.config, 'on_cancel_requested_fn')
  223. and self.config.on_cancel_requested_fn is not None
  224. and await self.config.on_cancel_requested_fn()
  225. ):
  226. raise UserCancelledError('LLM request cancelled by user')
  227. await asyncio.sleep(0.1)
  228. stop_check_task = asyncio.create_task(check_stopped())
  229. try:
  230. # Directly call and await litellm_acompletion
  231. if debug_message:
  232. llm_prompt_logger.debug(debug_message)
  233. resp = await async_completion_unwrapped(*args, **kwargs)
  234. else:
  235. logger.debug('No completion messages!')
  236. resp = {'choices': [{'message': {'content': ''}}]}
  237. # skip if messages is empty (thus debug_message is empty)
  238. if debug_message:
  239. message_back = resp['choices'][0]['message']['content']
  240. llm_response_logger.debug(message_back)
  241. else:
  242. resp = {'choices': [{'message': {'content': ''}}]}
  243. self._post_completion(resp)
  244. # We do not support streaming in this method, thus return resp
  245. return resp
  246. except UserCancelledError:
  247. logger.info('LLM request cancelled by user.')
  248. raise
  249. except (
  250. APIConnectionError,
  251. ContentPolicyViolationError,
  252. InternalServerError,
  253. NotFoundError,
  254. OpenAIError,
  255. RateLimitError,
  256. ServiceUnavailableError,
  257. ) as e:
  258. logger.error(f'Completion Error occurred:\n{e}')
  259. raise
  260. finally:
  261. await asyncio.sleep(0.1)
  262. stop_check_task.cancel()
  263. try:
  264. await stop_check_task
  265. except asyncio.CancelledError:
  266. pass
  267. @retry(
  268. after=attempt_on_error,
  269. stop=stop_after_attempt(self.config.num_retries),
  270. reraise=True,
  271. retry=retry_if_exception_type(self.retry_exceptions),
  272. wait=custom_completion_wait,
  273. )
  274. async def async_acompletion_stream_wrapper(*args, **kwargs):
  275. """Async wrapper for the litellm acompletion with streaming function."""
  276. # some callers might just send the messages directly
  277. if 'messages' in kwargs:
  278. messages = kwargs['messages']
  279. else:
  280. messages = args[1] if len(args) > 1 else []
  281. # log the prompt
  282. debug_message = ''
  283. for message in messages:
  284. debug_message += message_separator + message['content']
  285. llm_prompt_logger.debug(debug_message)
  286. try:
  287. # Directly call and await litellm_acompletion
  288. resp = await async_completion_unwrapped(*args, **kwargs)
  289. # For streaming we iterate over the chunks
  290. async for chunk in resp:
  291. # Check for cancellation before yielding the chunk
  292. if (
  293. hasattr(self.config, 'on_cancel_requested_fn')
  294. and self.config.on_cancel_requested_fn is not None
  295. and await self.config.on_cancel_requested_fn()
  296. ):
  297. raise UserCancelledError(
  298. 'LLM request cancelled due to CANCELLED state'
  299. )
  300. # with streaming, it is "delta", not "message"!
  301. message_back = chunk['choices'][0]['delta']['content']
  302. llm_response_logger.debug(message_back)
  303. self._post_completion(chunk)
  304. yield chunk
  305. except UserCancelledError:
  306. logger.info('LLM request cancelled by user.')
  307. raise
  308. except (
  309. APIConnectionError,
  310. ContentPolicyViolationError,
  311. InternalServerError,
  312. NotFoundError,
  313. OpenAIError,
  314. RateLimitError,
  315. ServiceUnavailableError,
  316. ) as e:
  317. logger.error(f'Completion Error occurred:\n{e}')
  318. raise
  319. finally:
  320. if kwargs.get('stream', False):
  321. await asyncio.sleep(0.1)
  322. self._async_completion = async_completion_wrapper # type: ignore
  323. self._async_streaming_completion = async_acompletion_stream_wrapper # type: ignore
  324. def _get_debug_message(self, messages):
  325. if not messages:
  326. return ''
  327. messages = messages if isinstance(messages, list) else [messages]
  328. return message_separator.join(
  329. self._format_message_content(msg) for msg in messages if msg['content']
  330. )
  331. def _format_message_content(self, message):
  332. content = message['content']
  333. if isinstance(content, list):
  334. return self._format_list_content(content)
  335. return str(content)
  336. def _format_list_content(self, content_list):
  337. return '\n'.join(
  338. self._format_content_element(element) for element in content_list
  339. )
  340. def _format_content_element(self, element):
  341. if isinstance(element, dict):
  342. if 'text' in element:
  343. return element['text']
  344. if (
  345. self.vision_is_active()
  346. and 'image_url' in element
  347. and 'url' in element['image_url']
  348. ):
  349. return element['image_url']['url']
  350. return str(element)
  351. async def _call_acompletion(self, *args, **kwargs):
  352. return await litellm.acompletion(*args, **kwargs)
  353. @property
  354. def completion(self):
  355. """Decorator for the litellm completion function.
  356. Check the complete documentation at https://litellm.vercel.app/docs/completion
  357. """
  358. try:
  359. return self._completion
  360. except Exception as e:
  361. raise LLMResponseError(e)
  362. @property
  363. def async_completion(self):
  364. """Decorator for the async litellm acompletion function.
  365. Check the complete documentation at https://litellm.vercel.app/docs/providers/ollama#example-usage---streaming--acompletion
  366. """
  367. try:
  368. return self._async_completion
  369. except Exception as e:
  370. raise LLMResponseError(e)
  371. @property
  372. def async_streaming_completion(self):
  373. """Decorator for the async litellm acompletion function with streaming.
  374. Check the complete documentation at https://litellm.vercel.app/docs/providers/ollama#example-usage---streaming--acompletion
  375. """
  376. try:
  377. return self._async_streaming_completion
  378. except Exception as e:
  379. raise LLMResponseError(e)
  380. def vision_is_active(self):
  381. return not self.config.disable_vision and self._supports_vision()
  382. def _supports_vision(self):
  383. """Acquire from litellm if model is vision capable.
  384. Returns:
  385. bool: True if model is vision capable. If model is not supported by litellm, it will return False.
  386. """
  387. try:
  388. return litellm.supports_vision(self.config.model)
  389. except Exception:
  390. return False
  391. def is_caching_prompt_active(self) -> bool:
  392. """Check if prompt caching is enabled and supported for current model.
  393. Returns:
  394. boolean: True if prompt caching is active for the given model.
  395. """
  396. return self.config.caching_prompt is True and any(
  397. model in self.config.model for model in cache_prompting_supported_models
  398. )
  399. def _post_completion(self, response) -> None:
  400. """Post-process the completion response."""
  401. try:
  402. cur_cost = self.completion_cost(response)
  403. except Exception:
  404. cur_cost = 0
  405. stats = ''
  406. if self.cost_metric_supported:
  407. stats = 'Cost: %.2f USD | Accumulated Cost: %.2f USD\n' % (
  408. cur_cost,
  409. self.metrics.accumulated_cost,
  410. )
  411. usage = response.get('usage')
  412. if usage:
  413. input_tokens = usage.get('prompt_tokens')
  414. output_tokens = usage.get('completion_tokens')
  415. if input_tokens:
  416. stats += 'Input tokens: ' + str(input_tokens) + '\n'
  417. if output_tokens:
  418. stats += 'Output tokens: ' + str(output_tokens) + '\n'
  419. model_extra = usage.get('model_extra', {})
  420. cache_creation_input_tokens = model_extra.get('cache_creation_input_tokens')
  421. if cache_creation_input_tokens:
  422. stats += (
  423. 'Input tokens (cache write): '
  424. + str(cache_creation_input_tokens)
  425. + '\n'
  426. )
  427. cache_read_input_tokens = model_extra.get('cache_read_input_tokens')
  428. if cache_read_input_tokens:
  429. stats += (
  430. 'Input tokens (cache read): ' + str(cache_read_input_tokens) + '\n'
  431. )
  432. if stats:
  433. logger.info(stats)
  434. def get_token_count(self, messages):
  435. """Get the number of tokens in a list of messages.
  436. Args:
  437. messages (list): A list of messages.
  438. Returns:
  439. int: The number of tokens.
  440. """
  441. try:
  442. return litellm.token_counter(model=self.config.model, messages=messages)
  443. except Exception:
  444. # TODO: this is to limit logspam in case token count is not supported
  445. return 0
  446. def is_local(self):
  447. """Determines if the system is using a locally running LLM.
  448. Returns:
  449. boolean: True if executing a local model.
  450. """
  451. if self.config.base_url is not None:
  452. for substring in ['localhost', '127.0.0.1' '0.0.0.0']:
  453. if substring in self.config.base_url:
  454. return True
  455. elif self.config.model is not None:
  456. if self.config.model.startswith('ollama'):
  457. return True
  458. return False
  459. def completion_cost(self, response):
  460. """Calculate the cost of a completion response based on the model. Local models are treated as free.
  461. Add the current cost into total cost in metrics.
  462. Args:
  463. response: A response from a model invocation.
  464. Returns:
  465. number: The cost of the response.
  466. """
  467. if not self.cost_metric_supported:
  468. return 0.0
  469. extra_kwargs = {}
  470. if (
  471. self.config.input_cost_per_token is not None
  472. and self.config.output_cost_per_token is not None
  473. ):
  474. cost_per_token = CostPerToken(
  475. input_cost_per_token=self.config.input_cost_per_token,
  476. output_cost_per_token=self.config.output_cost_per_token,
  477. )
  478. logger.info(f'Using custom cost per token: {cost_per_token}')
  479. extra_kwargs['custom_cost_per_token'] = cost_per_token
  480. if not self.is_local():
  481. try:
  482. cost = litellm_completion_cost(
  483. completion_response=response, **extra_kwargs
  484. )
  485. self.metrics.add_cost(cost)
  486. return cost
  487. except Exception:
  488. self.cost_metric_supported = False
  489. logger.warning('Cost calculation not supported for this model.')
  490. return 0.0
  491. def __str__(self):
  492. if self.config.api_version:
  493. return f'LLM(model={self.config.model}, api_version={self.config.api_version}, base_url={self.config.base_url})'
  494. elif self.config.base_url:
  495. return f'LLM(model={self.config.model}, base_url={self.config.base_url})'
  496. return f'LLM(model={self.config.model})'
  497. def __repr__(self):
  498. return str(self)
  499. def reset(self):
  500. self.metrics = Metrics()
  501. def format_messages_for_llm(
  502. self, messages: Union[Message, list[Message]]
  503. ) -> list[dict]:
  504. return format_messages(
  505. messages, self.vision_is_active(), self.is_caching_prompt_active()
  506. )