openai.py 2.3 KB

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