App.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from typing import Optional
  2. import openai
  3. from embedchain.config import AppConfig, ChatConfig
  4. from embedchain.embedchain import EmbedChain
  5. from embedchain.helper_classes.json_serializable import register_deserializable
  6. @register_deserializable
  7. class App(EmbedChain):
  8. """
  9. The EmbedChain app.
  10. Has two functions: add and query.
  11. adds(data_type, url): adds the data from the given URL to the vector db.
  12. query(query): finds answer to the given query using vector database and LLM.
  13. dry_run(query): test your prompt without consuming tokens.
  14. """
  15. def __init__(self, config: AppConfig = None, system_prompt: Optional[str] = None):
  16. """
  17. :param config: AppConfig instance to load as configuration. Optional.
  18. :param system_prompt: System prompt string. Optional.
  19. """
  20. if config is None:
  21. config = AppConfig()
  22. super().__init__(config, system_prompt)
  23. def get_llm_model_answer(self, prompt, config: ChatConfig):
  24. messages = []
  25. system_prompt = (
  26. self.system_prompt
  27. if self.system_prompt is not None
  28. else config.system_prompt
  29. if config.system_prompt is not None
  30. else None
  31. )
  32. if system_prompt:
  33. messages.append({"role": "system", "content": system_prompt})
  34. messages.append({"role": "user", "content": prompt})
  35. response = openai.ChatCompletion.create(
  36. model=config.model or "gpt-3.5-turbo-0613",
  37. messages=messages,
  38. temperature=config.temperature,
  39. max_tokens=config.max_tokens,
  40. top_p=config.top_p,
  41. stream=config.stream,
  42. )
  43. if config.stream:
  44. return self._stream_llm_model_response(response)
  45. else:
  46. return response["choices"][0]["message"]["content"]
  47. def _stream_llm_model_response(self, response):
  48. """
  49. This is a generator for streaming response from the OpenAI completions API
  50. """
  51. for line in response:
  52. chunk = line["choices"][0].get("delta", {}).get("content", "")
  53. yield chunk