base.py 12 KB

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