jina.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import os
  2. from typing import Optional
  3. from langchain.chat_models import JinaChat
  4. from langchain.schema import HumanMessage, SystemMessage
  5. from embedchain.config import BaseLlmConfig
  6. from embedchain.helper.json_serializable import register_deserializable
  7. from embedchain.llm.base import BaseLlm
  8. @register_deserializable
  9. class JinaLlm(BaseLlm):
  10. def __init__(self, config: Optional[BaseLlmConfig] = None):
  11. if "JINACHAT_API_KEY" not in os.environ:
  12. raise ValueError("Please set the JINACHAT_API_KEY environment variable.")
  13. super().__init__(config=config)
  14. def get_llm_model_answer(self, prompt):
  15. response = JinaLlm._get_answer(prompt, self.config)
  16. return response
  17. @staticmethod
  18. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  19. messages = []
  20. if config.system_prompt:
  21. messages.append(SystemMessage(content=config.system_prompt))
  22. messages.append(HumanMessage(content=prompt))
  23. kwargs = {
  24. "temperature": config.temperature,
  25. "max_tokens": config.max_tokens,
  26. "model_kwargs": {},
  27. }
  28. if config.top_p:
  29. kwargs["model_kwargs"]["top_p"] = config.top_p
  30. if config.stream:
  31. from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
  32. chat = JinaChat(**kwargs, streaming=config.stream, callbacks=[StreamingStdOutCallbackHandler()])
  33. else:
  34. chat = JinaChat(**kwargs)
  35. return chat(messages).content