base.py 12 KB

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