base.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. def _append_search_and_context(self, context: str, web_search_result: str) -> str:
  99. """Append web search context to existing context
  100. :param context: Existing context
  101. :type context: str
  102. :param web_search_result: Web search result
  103. :type web_search_result: str
  104. :return: Concatenated web search result
  105. :rtype: str
  106. """
  107. return f"{context}\nWeb Search Result: {web_search_result}"
  108. def get_answer_from_llm(self, prompt: str):
  109. """
  110. Gets an answer based on the given query and context by passing it
  111. to an LLM.
  112. :param prompt: Gets an answer based on the given query and context by passing it to an LLM.
  113. :type prompt: str
  114. :return: The answer.
  115. :rtype: _type_
  116. """
  117. return self.get_llm_model_answer(prompt)
  118. def access_search_and_get_results(self, input_query: str):
  119. """
  120. Search the internet for additional context
  121. :param input_query: search query
  122. :type input_query: str
  123. :return: Search results
  124. :rtype: Unknown
  125. """
  126. try:
  127. from langchain.tools import DuckDuckGoSearchRun
  128. except ImportError:
  129. raise ImportError(
  130. 'Searching requires extra dependencies. Install with `pip install --upgrade "embedchain[dataloaders]"`'
  131. ) from None
  132. search = DuckDuckGoSearchRun()
  133. logging.info(f"Access search to get answers for {input_query}")
  134. return search.run(input_query)
  135. def _stream_response(self, answer: Any) -> Generator[Any, Any, None]:
  136. """Generator to be used as streaming response
  137. :param answer: Answer chunk from llm
  138. :type answer: Any
  139. :yield: Answer chunk from llm
  140. :rtype: Generator[Any, Any, None]
  141. """
  142. streamed_answer = ""
  143. for chunk in answer:
  144. streamed_answer = streamed_answer + chunk
  145. yield chunk
  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.prompt = 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_response(answer)
  190. finally:
  191. if config:
  192. # Restore previous config
  193. self.config: BaseLlmConfig = BaseLlmConfig.deserialize(prev_config)
  194. def chat(
  195. self, input_query: str, contexts: List[str], config: BaseLlmConfig = None, dry_run=False, session_id: str = None
  196. ):
  197. """
  198. Queries the vector database on the given input query.
  199. Gets relevant doc based on the query and then passes it to an
  200. LLM as context to get the answer.
  201. Maintains the whole conversation in memory.
  202. :param input_query: The query to use.
  203. :type input_query: str
  204. :param contexts: Embeddings retrieved from the database to be used as context.
  205. :type contexts: List[str]
  206. :param config: The `BaseLlmConfig` instance to use as configuration options. This is used for one method call.
  207. To persistently use a config, declare it during app init., defaults to None
  208. :type config: Optional[BaseLlmConfig], optional
  209. :param dry_run: A dry run does everything except send the resulting prompt to
  210. the LLM. The purpose is to test the prompt, not the response., defaults to False
  211. :type dry_run: bool, optional
  212. :param session_id: Session ID to use for the conversation, defaults to None
  213. :type session_id: str, optional
  214. :return: The answer to the query or the dry run result
  215. :rtype: str
  216. """
  217. try:
  218. if config:
  219. # A config instance passed to this method will only be applied temporarily, for one call.
  220. # So we will save the previous config and restore it at the end of the execution.
  221. # For this we use the serializer.
  222. prev_config = self.config.serialize()
  223. self.config = config
  224. if self.is_docs_site_instance:
  225. self.config.prompt = DOCS_SITE_PROMPT_TEMPLATE
  226. self.config.number_documents = 5
  227. k = {}
  228. if self.online:
  229. k["web_search_result"] = self.access_search_and_get_results(input_query)
  230. prompt = self.generate_prompt(input_query, contexts, **k)
  231. logging.info(f"Prompt: {prompt}")
  232. if dry_run:
  233. return prompt
  234. answer = self.get_answer_from_llm(prompt)
  235. if isinstance(answer, str):
  236. logging.info(f"Answer: {answer}")
  237. return answer
  238. else:
  239. # this is a streamed response and needs to be handled differently.
  240. return self._stream_response(answer)
  241. finally:
  242. if config:
  243. # Restore previous config
  244. self.config: BaseLlmConfig = BaseLlmConfig.deserialize(prev_config)
  245. @staticmethod
  246. def _get_messages(prompt: str, system_prompt: Optional[str] = None) -> List[LCBaseMessage]:
  247. """
  248. Construct a list of langchain messages
  249. :param prompt: User prompt
  250. :type prompt: str
  251. :param system_prompt: System prompt, defaults to None
  252. :type system_prompt: Optional[str], optional
  253. :return: List of messages
  254. :rtype: List[BaseMessage]
  255. """
  256. from langchain.schema import HumanMessage, SystemMessage
  257. messages = []
  258. if system_prompt:
  259. messages.append(SystemMessage(content=system_prompt))
  260. messages.append(HumanMessage(content=prompt))
  261. return messages