base.py 12 KB

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