anthropic.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. if "ANTHROPIC_API_KEY" not in os.environ:
  16. raise ValueError("Please set the ANTHROPIC_API_KEY environment variable.")
  17. super().__init__(config=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. chat = ChatAnthropic(
  23. anthropic_api_key=os.environ["ANTHROPIC_API_KEY"], temperature=config.temperature, model_name=config.model
  24. )
  25. if config.max_tokens and config.max_tokens != 1000:
  26. logger.warning("Config option `max_tokens` is not supported by this model.")
  27. messages = BaseLlm._get_messages(prompt, system_prompt=config.system_prompt)
  28. return chat(messages).content