base.py 12 KB

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