anthropic.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import logging
  2. import os
  3. from typing import Any, Optional
  4. try:
  5. from langchain_anthropic import ChatAnthropic
  6. except ImportError:
  7. raise ImportError("Please install the langchain-anthropic package by running `pip install langchain-anthropic`.")
  8. from embedchain.config import BaseLlmConfig
  9. from embedchain.helpers.json_serializable import register_deserializable
  10. from embedchain.llm.base import BaseLlm
  11. logger = logging.getLogger(__name__)
  12. @register_deserializable
  13. class AnthropicLlm(BaseLlm):
  14. def __init__(self, config: Optional[BaseLlmConfig] = None):
  15. super().__init__(config=config)
  16. if not self.config.api_key and "ANTHROPIC_API_KEY" not in os.environ:
  17. raise ValueError("Please set the ANTHROPIC_API_KEY environment variable or pass it in the config.")
  18. def get_llm_model_answer(self, prompt) -> tuple[str, Optional[dict[str, Any]]]:
  19. if self.config.token_usage:
  20. response, token_info = self._get_answer(prompt, self.config)
  21. model_name = "anthropic/" + self.config.model
  22. if model_name not in self.config.model_pricing_map:
  23. raise ValueError(
  24. f"Model {model_name} not found in `model_prices_and_context_window.json`. \
  25. You can disable token usage by setting `token_usage` to False."
  26. )
  27. total_cost = (
  28. self.config.model_pricing_map[model_name]["input_cost_per_token"] * token_info["input_tokens"]
  29. ) + self.config.model_pricing_map[model_name]["output_cost_per_token"] * token_info["output_tokens"]
  30. response_token_info = {
  31. "prompt_tokens": token_info["input_tokens"],
  32. "completion_tokens": token_info["output_tokens"],
  33. "total_tokens": token_info["input_tokens"] + token_info["output_tokens"],
  34. "total_cost": round(total_cost, 10),
  35. "cost_currency": "USD",
  36. }
  37. return response, response_token_info
  38. return self._get_answer(prompt, self.config)
  39. @staticmethod
  40. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  41. api_key = config.api_key or os.getenv("ANTHROPIC_API_KEY")
  42. chat = ChatAnthropic(anthropic_api_key=api_key, temperature=config.temperature, model_name=config.model)
  43. if config.max_tokens and config.max_tokens != 1000:
  44. logger.warning("Config option `max_tokens` is not supported by this model.")
  45. messages = BaseLlm._get_messages(prompt, system_prompt=config.system_prompt)
  46. chat_response = chat.invoke(messages)
  47. if config.token_usage:
  48. return chat_response.content, chat_response.response_metadata["token_usage"]
  49. return chat_response.content