cohere.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import importlib
  2. import os
  3. from typing import Optional
  4. from langchain_community.llms.cohere import Cohere
  5. from embedchain.config import BaseLlmConfig
  6. from embedchain.helpers.json_serializable import register_deserializable
  7. from embedchain.llm.base import BaseLlm
  8. @register_deserializable
  9. class CohereLlm(BaseLlm):
  10. def __init__(self, config: Optional[BaseLlmConfig] = None):
  11. try:
  12. importlib.import_module("cohere")
  13. except ModuleNotFoundError:
  14. raise ModuleNotFoundError(
  15. "The required dependencies for Cohere are not installed."
  16. 'Please install with `pip install --upgrade "embedchain[cohere]"`'
  17. ) from None
  18. super().__init__(config=config)
  19. if not self.config.api_key and "COHERE_API_KEY" not in os.environ:
  20. raise ValueError("Please set the COHERE_API_KEY environment variable or pass it in the config.")
  21. def get_llm_model_answer(self, prompt):
  22. if self.config.system_prompt:
  23. raise ValueError("CohereLlm does not support `system_prompt`")
  24. return CohereLlm._get_answer(prompt=prompt, config=self.config)
  25. @staticmethod
  26. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  27. api_key = config.api_key or os.getenv("COHERE_API_KEY")
  28. llm = Cohere(
  29. cohere_api_key=api_key,
  30. model=config.model,
  31. max_tokens=config.max_tokens,
  32. temperature=config.temperature,
  33. p=config.top_p,
  34. )
  35. return llm.invoke(prompt)