anthropic.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import logging
  2. import os
  3. from typing import 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):
  19. return AnthropicLlm._get_answer(prompt=prompt, config=self.config)
  20. @staticmethod
  21. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  22. api_key = config.api_key or os.getenv("ANTHROPIC_API_KEY")
  23. chat = ChatAnthropic(anthropic_api_key=api_key, temperature=config.temperature, model_name=config.model)
  24. if config.max_tokens and config.max_tokens != 1000:
  25. logger.warning("Config option `max_tokens` is not supported by this model.")
  26. messages = BaseLlm._get_messages(prompt, system_prompt=config.system_prompt)
  27. return chat(messages).content