base.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import logging
  2. from typing import Any, Dict, Generator, List, Optional
  3. from langchain.memory import ConversationBufferMemory
  4. from langchain.schema import BaseMessage
  5. from embedchain.config import BaseLlmConfig
  6. from embedchain.config.llm.base import (DEFAULT_PROMPT,
  7. DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE,
  8. DOCS_SITE_PROMPT_TEMPLATE)
  9. from embedchain.helper.json_serializable import JSONSerializable
  10. class BaseLlm(JSONSerializable):
  11. def __init__(self, config: Optional[BaseLlmConfig] = None):
  12. """Initialize a base LLM class
  13. :param config: LLM configuration option class, defaults to None
  14. :type config: Optional[BaseLlmConfig], optional
  15. """
  16. if config is None:
  17. self.config = BaseLlmConfig()
  18. else:
  19. self.config = config
  20. self.memory = ConversationBufferMemory()
  21. self.is_docs_site_instance = False
  22. self.online = False
  23. self.history: Any = None
  24. def get_llm_model_answer(self):
  25. """
  26. Usually implemented by child class
  27. """
  28. raise NotImplementedError
  29. def set_history(self, history: Any):
  30. """
  31. Provide your own history.
  32. Especially interesting for the query method, which does not internally manage conversation history.
  33. :param history: History to set
  34. :type history: Any
  35. """
  36. self.history = history
  37. def update_history(self):
  38. """Update class history attribute with history in memory (for chat method)"""
  39. chat_history = self.memory.load_memory_variables({})["history"]
  40. if chat_history:
  41. self.set_history(chat_history)
  42. def generate_prompt(self, input_query: str, contexts: List[str], **kwargs: Dict[str, Any]) -> str:
  43. """
  44. Generates a prompt based on the given query and context, ready to be
  45. passed to an LLM
  46. :param input_query: The query to use.
  47. :type input_query: str
  48. :param contexts: List of similar documents to the query used as context.
  49. :type contexts: List[str]
  50. :return: The prompt
  51. :rtype: str
  52. """
  53. context_string = (" | ").join(contexts)
  54. web_search_result = kwargs.get("web_search_result", "")
  55. if web_search_result:
  56. context_string = self._append_search_and_context(context_string, web_search_result)
  57. template_contains_history = self.config._validate_template_history(self.config.template)
  58. if template_contains_history:
  59. # Template contains history
  60. # If there is no history yet, we insert `- no history -`
  61. prompt = self.config.template.substitute(
  62. context=context_string, query=input_query, history=self.history or "- no history -"
  63. )
  64. elif self.history and not template_contains_history:
  65. # History is present, but not included in the template.
  66. # check if it's the default template without history
  67. if (
  68. not self.config._validate_template_history(self.config.template)
  69. and self.config.template.template == DEFAULT_PROMPT
  70. ):
  71. # swap in the template with history
  72. prompt = DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE.substitute(
  73. context=context_string, query=input_query, history=self.history
  74. )
  75. else:
  76. # If we can't swap in the default, we still proceed but tell users that the history is ignored.
  77. logging.warning(
  78. "Your bot contains a history, but template does not include `$history` key. History is ignored."
  79. )
  80. prompt = self.config.template.substitute(context=context_string, query=input_query)
  81. else:
  82. # basic use case, no history.
  83. prompt = self.config.template.substitute(context=context_string, query=input_query)
  84. return prompt
  85. def _append_search_and_context(self, context: str, web_search_result: str) -> str:
  86. """Append web search context to existing context
  87. :param context: Existing context
  88. :type context: str
  89. :param web_search_result: Web search result
  90. :type web_search_result: str
  91. :return: Concatenated web search result
  92. :rtype: str
  93. """
  94. return f"{context}\nWeb Search Result: {web_search_result}"
  95. def get_answer_from_llm(self, prompt: str):
  96. """
  97. Gets an answer based on the given query and context by passing it
  98. to an LLM.
  99. :param prompt: Gets an answer based on the given query and context by passing it to an LLM.
  100. :type prompt: str
  101. :return: The answer.
  102. :rtype: _type_
  103. """
  104. return self.get_llm_model_answer(prompt)
  105. def access_search_and_get_results(self, input_query: str):
  106. """
  107. Search the internet for additional context
  108. :param input_query: search query
  109. :type input_query: str
  110. :return: Search results
  111. :rtype: Unknown
  112. """
  113. try:
  114. from langchain.tools import DuckDuckGoSearchRun
  115. except ImportError:
  116. raise ImportError(
  117. 'Searching requires extra dependencies. Install with `pip install --upgrade "embedchain[dataloaders]"`'
  118. ) from None
  119. search = DuckDuckGoSearchRun()
  120. logging.info(f"Access search to get answers for {input_query}")
  121. return search.run(input_query)
  122. def _stream_query_response(self, answer: Any) -> Generator[Any, Any, None]:
  123. """Generator to be used as streaming response
  124. :param answer: Answer chunk from llm
  125. :type answer: Any
  126. :yield: Answer chunk from llm
  127. :rtype: Generator[Any, Any, None]
  128. """
  129. streamed_answer = ""
  130. for chunk in answer:
  131. streamed_answer = streamed_answer + chunk
  132. yield chunk
  133. logging.info(f"Answer: {streamed_answer}")
  134. def _stream_chat_response(self, answer: Any) -> Generator[Any, Any, None]:
  135. """Generator to be used as streaming response
  136. :param answer: Answer chunk from llm
  137. :type answer: Any
  138. :yield: Answer chunk from llm
  139. :rtype: Generator[Any, Any, None]
  140. """
  141. streamed_answer = ""
  142. for chunk in answer:
  143. streamed_answer = streamed_answer + chunk
  144. yield chunk
  145. self.memory.chat_memory.add_ai_message(streamed_answer)
  146. logging.info(f"Answer: {streamed_answer}")
  147. def query(self, input_query: str, contexts: List[str], config: BaseLlmConfig = None, dry_run=False):
  148. """
  149. Queries the vector database based on the given input query.
  150. Gets relevant doc based on the query and then passes it to an
  151. LLM as context to get the answer.
  152. :param input_query: The query to use.
  153. :type input_query: str
  154. :param contexts: Embeddings retrieved from the database to be used as context.
  155. :type contexts: List[str]
  156. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  157. To persistently use a config, declare it during app init., defaults to None
  158. :type config: Optional[BaseLlmConfig], optional
  159. :param dry_run: A dry run does everything except send the resulting prompt to
  160. the LLM. The purpose is to test the prompt, not the response., defaults to False
  161. :type dry_run: bool, optional
  162. :return: The answer to the query or the dry run result
  163. :rtype: str
  164. """
  165. try:
  166. if config:
  167. # A config instance passed to this method will only be applied temporarily, for one call.
  168. # So we will save the previous config and restore it at the end of the execution.
  169. # For this we use the serializer.
  170. prev_config = self.config.serialize()
  171. self.config = config
  172. if config is not None and config.query_type == "Images":
  173. return contexts
  174. if self.is_docs_site_instance:
  175. self.config.template = DOCS_SITE_PROMPT_TEMPLATE
  176. self.config.number_documents = 5
  177. k = {}
  178. if self.online:
  179. k["web_search_result"] = self.access_search_and_get_results(input_query)
  180. prompt = self.generate_prompt(input_query, contexts, **k)
  181. logging.info(f"Prompt: {prompt}")
  182. if dry_run:
  183. return prompt
  184. answer = self.get_answer_from_llm(prompt)
  185. if isinstance(answer, str):
  186. logging.info(f"Answer: {answer}")
  187. return answer
  188. else:
  189. return self._stream_query_response(answer)
  190. finally:
  191. if config:
  192. # Restore previous config
  193. self.config: BaseLlmConfig = BaseLlmConfig.deserialize(prev_config)
  194. def chat(self, input_query: str, contexts: List[str], config: BaseLlmConfig = None, dry_run=False):
  195. """
  196. Queries the vector database on the given input query.
  197. Gets relevant doc based on the query and then passes it to an
  198. LLM as context to get the answer.
  199. Maintains the whole conversation in memory.
  200. :param input_query: The query to use.
  201. :type input_query: str
  202. :param contexts: Embeddings retrieved from the database to be used as context.
  203. :type contexts: List[str]
  204. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  205. To persistently use a config, declare it during app init., defaults to None
  206. :type config: Optional[BaseLlmConfig], optional
  207. :param dry_run: A dry run does everything except send the resulting prompt to
  208. the LLM. The purpose is to test the prompt, not the response., defaults to False
  209. :type dry_run: bool, optional
  210. :return: The answer to the query or the dry run result
  211. :rtype: str
  212. """
  213. try:
  214. if config:
  215. # A config instance passed to this method will only be applied temporarily, for one call.
  216. # So we will save the previous config and restore it at the end of the execution.
  217. # For this we use the serializer.
  218. prev_config = self.config.serialize()
  219. self.config = config
  220. if self.is_docs_site_instance:
  221. self.config.template = DOCS_SITE_PROMPT_TEMPLATE
  222. self.config.number_documents = 5
  223. k = {}
  224. if self.online:
  225. k["web_search_result"] = self.access_search_and_get_results(input_query)
  226. self.update_history()
  227. prompt = self.generate_prompt(input_query, contexts, **k)
  228. logging.info(f"Prompt: {prompt}")
  229. if dry_run:
  230. return prompt
  231. answer = self.get_answer_from_llm(prompt)
  232. self.memory.chat_memory.add_user_message(input_query)
  233. if isinstance(answer, str):
  234. self.memory.chat_memory.add_ai_message(answer)
  235. logging.info(f"Answer: {answer}")
  236. # NOTE: Adding to history before and after. This could be seen as redundant.
  237. # If we change it, we have to change the tests (no big deal).
  238. self.update_history()
  239. return answer
  240. else:
  241. # this is a streamed response and needs to be handled differently.
  242. return self._stream_chat_response(answer)
  243. finally:
  244. if config:
  245. # Restore previous config
  246. self.config: BaseLlmConfig = BaseLlmConfig.deserialize(prev_config)
  247. @staticmethod
  248. def _get_messages(prompt: str, system_prompt: Optional[str] = None) -> List[BaseMessage]:
  249. """
  250. Construct a list of langchain messages
  251. :param prompt: User prompt
  252. :type prompt: str
  253. :param system_prompt: System prompt, defaults to None
  254. :type system_prompt: Optional[str], optional
  255. :return: List of messages
  256. :rtype: List[BaseMessage]
  257. """
  258. from langchain.schema import HumanMessage, SystemMessage
  259. messages = []
  260. if system_prompt:
  261. messages.append(SystemMessage(content=system_prompt))
  262. messages.append(HumanMessage(content=prompt))
  263. return messages