openai.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import json
  2. from typing import Any, Dict, Optional
  3. from langchain.chat_models import ChatOpenAI
  4. from langchain.schema import AIMessage, HumanMessage, SystemMessage
  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 OpenAILlm(BaseLlm):
  10. def __init__(self, config: Optional[BaseLlmConfig] = None, functions: Optional[Dict[str, Any]] = None):
  11. self.functions = functions
  12. super().__init__(config=config)
  13. def get_llm_model_answer(self, prompt) -> str:
  14. response = self._get_answer(prompt, self.config)
  15. return response
  16. def _get_answer(self, prompt: str, config: BaseLlmConfig) -> str:
  17. messages = []
  18. if config.system_prompt:
  19. messages.append(SystemMessage(content=config.system_prompt))
  20. messages.append(HumanMessage(content=prompt))
  21. kwargs = {
  22. "model": config.model or "gpt-3.5-turbo",
  23. "temperature": config.temperature,
  24. "max_tokens": config.max_tokens,
  25. "model_kwargs": {},
  26. }
  27. if config.top_p:
  28. kwargs["model_kwargs"]["top_p"] = config.top_p
  29. if config.stream:
  30. from langchain.callbacks.streaming_stdout import \
  31. StreamingStdOutCallbackHandler
  32. callbacks = config.callbacks if config.callbacks else [StreamingStdOutCallbackHandler()]
  33. chat = ChatOpenAI(**kwargs, streaming=config.stream, callbacks=callbacks)
  34. else:
  35. chat = ChatOpenAI(**kwargs)
  36. if self.functions is not None:
  37. from langchain.chains.openai_functions import \
  38. create_openai_fn_runnable
  39. from langchain.prompts import ChatPromptTemplate
  40. structured_prompt = ChatPromptTemplate.from_messages(messages)
  41. runnable = create_openai_fn_runnable(functions=self.functions, prompt=structured_prompt, llm=chat)
  42. fn_res = runnable.invoke(
  43. {
  44. "input": prompt,
  45. }
  46. )
  47. messages.append(AIMessage(content=json.dumps(fn_res)))
  48. return chat(messages).content