groq.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. from typing import Optional
  3. from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
  4. from langchain.schema import HumanMessage, SystemMessage
  5. try:
  6. from langchain_groq import ChatGroq
  7. except ImportError:
  8. raise ImportError("Groq requires extra dependencies. Install with `pip install langchain-groq`") from None
  9. from embedchain.config import BaseLlmConfig
  10. from embedchain.helpers.json_serializable import register_deserializable
  11. from embedchain.llm.base import BaseLlm
  12. @register_deserializable
  13. class GroqLlm(BaseLlm):
  14. def __init__(self, config: Optional[BaseLlmConfig] = None):
  15. super().__init__(config=config)
  16. if not self.config.api_key and "GROQ_API_KEY" not in os.environ:
  17. raise ValueError("Please set the GROQ_API_KEY environment variable or pass it in the config.")
  18. def get_llm_model_answer(self, prompt) -> str:
  19. response = self._get_answer(prompt, self.config)
  20. return response
  21. def _get_answer(self, prompt: str, config: BaseLlmConfig) -> str:
  22. messages = []
  23. if config.system_prompt:
  24. messages.append(SystemMessage(content=config.system_prompt))
  25. messages.append(HumanMessage(content=prompt))
  26. api_key = config.api_key or os.environ["GROQ_API_KEY"]
  27. kwargs = {
  28. "model_name": config.model or "mixtral-8x7b-32768",
  29. "temperature": config.temperature,
  30. "groq_api_key": api_key,
  31. }
  32. if config.stream:
  33. callbacks = config.callbacks if config.callbacks else [StreamingStdOutCallbackHandler()]
  34. chat = ChatGroq(**kwargs, streaming=config.stream, callbacks=callbacks, api_key=api_key)
  35. else:
  36. chat = ChatGroq(**kwargs)
  37. return chat.invoke(messages).content