openai.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 StreamingStdOutCallbackHandler
  31. callbacks = config.callbacks if config.callbacks else [StreamingStdOutCallbackHandler()]
  32. chat = ChatOpenAI(**kwargs, streaming=config.stream, callbacks=callbacks)
  33. else:
  34. chat = ChatOpenAI(**kwargs)
  35. if self.functions is not None:
  36. from langchain.chains.openai_functions import create_openai_fn_runnable
  37. from langchain.prompts import ChatPromptTemplate
  38. structured_prompt = ChatPromptTemplate.from_messages(messages)
  39. runnable = create_openai_fn_runnable(functions=self.functions, prompt=structured_prompt, llm=chat)
  40. fn_res = runnable.invoke(
  41. {
  42. "input": prompt,
  43. }
  44. )
  45. messages.append(AIMessage(content=json.dumps(fn_res)))
  46. return chat(messages).content