embedchain.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import logging
  2. import os
  3. from string import Template
  4. import openai
  5. from chromadb.utils import embedding_functions
  6. from dotenv import load_dotenv
  7. from langchain.docstore.document import Document
  8. from langchain.memory import ConversationBufferMemory
  9. from embedchain.config import AddConfig, ChatConfig, InitConfig, QueryConfig
  10. from embedchain.config.QueryConfig import CODE_DOCS_PAGE_PROMPT_TEMPLATE, DEFAULT_PROMPT, DEFAULT_PROMPT_WITH_HISTORY
  11. from embedchain.data_formatter import DataFormatter
  12. gpt4all_model = None
  13. load_dotenv()
  14. ABS_PATH = os.getcwd()
  15. DB_DIR = os.path.join(ABS_PATH, "db")
  16. memory = ConversationBufferMemory()
  17. class EmbedChain:
  18. def __init__(self, config: InitConfig):
  19. """
  20. Initializes the EmbedChain instance, sets up a vector DB client and
  21. creates a collection.
  22. :param config: InitConfig instance to load as configuration.
  23. """
  24. self.config = config
  25. self.db_client = self.config.db.client
  26. self.collection = self.config.db.collection
  27. self.user_asks = []
  28. self.is_code_docs_instance = False
  29. self.online = False
  30. def add(self, data_type, url, metadata=None, config: AddConfig = None):
  31. """
  32. Adds the data from the given URL to the vector db.
  33. Loads the data, chunks it, create embedding for each chunk
  34. and then stores the embedding to vector database.
  35. :param data_type: The type of the data to add.
  36. :param url: The URL where the data is located.
  37. :param metadata: Optional. Metadata associated with the data source.
  38. :param config: Optional. The `AddConfig` instance to use as configuration
  39. options.
  40. """
  41. if config is None:
  42. config = AddConfig()
  43. data_formatter = DataFormatter(data_type, config)
  44. self.user_asks.append([data_type, url, metadata])
  45. self.load_and_embed(data_formatter.loader, data_formatter.chunker, url, metadata)
  46. if data_type in ("code_docs_page",):
  47. self.is_code_docs_instance = True
  48. def add_local(self, data_type, content, metadata=None, config: AddConfig = None):
  49. """
  50. Adds the data you supply to the vector db.
  51. Loads the data, chunks it, create embedding for each chunk
  52. and then stores the embedding to vector database.
  53. :param data_type: The type of the data to add.
  54. :param content: The local data. Refer to the `README` for formatting.
  55. :param metadata: Optional. Metadata associated with the data source.
  56. :param config: Optional. The `AddConfig` instance to use as
  57. configuration options.
  58. """
  59. if config is None:
  60. config = AddConfig()
  61. data_formatter = DataFormatter(data_type, config)
  62. self.user_asks.append([data_type, content])
  63. self.load_and_embed(
  64. data_formatter.loader,
  65. data_formatter.chunker,
  66. content,
  67. metadata,
  68. )
  69. def load_and_embed(self, loader, chunker, src, metadata=None):
  70. """
  71. Loads the data from the given URL, chunks it, and adds it to database.
  72. :param loader: The loader to use to load the data.
  73. :param chunker: The chunker to use to chunk the data.
  74. :param src: The data to be handled by the loader. Can be a URL for
  75. remote sources or local content for local loaders.
  76. :param metadata: Optional. Metadata associated with the data source.
  77. """
  78. embeddings_data = chunker.create_chunks(loader, src)
  79. documents = embeddings_data["documents"]
  80. metadatas = embeddings_data["metadatas"]
  81. ids = embeddings_data["ids"]
  82. # get existing ids, and discard doc if any common id exist.
  83. where = {"app_id": self.config.id} if self.config.id is not None else {}
  84. # where={"url": src}
  85. existing_docs = self.collection.get(
  86. ids=ids,
  87. where=where, # optional filter
  88. )
  89. existing_ids = set(existing_docs["ids"])
  90. if len(existing_ids):
  91. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  92. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  93. if not data_dict:
  94. print(f"All data from {src} already exists in the database.")
  95. return
  96. ids = list(data_dict.keys())
  97. documents, metadatas = zip(*data_dict.values())
  98. # Add app id in metadatas so that they can be queried on later
  99. if self.config.id is not None:
  100. metadatas = [{**m, "app_id": self.config.id} for m in metadatas]
  101. chunks_before_addition = self.count()
  102. # Add metadata to each document
  103. metadatas_with_metadata = [meta or metadata for meta in metadatas]
  104. self.collection.add(documents=documents, metadatas=list(metadatas_with_metadata), ids=ids)
  105. print((f"Successfully saved {src}. New chunks count: " f"{self.count() - chunks_before_addition}"))
  106. def _format_result(self, results):
  107. return [
  108. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  109. for result in zip(
  110. results["documents"][0],
  111. results["metadatas"][0],
  112. results["distances"][0],
  113. )
  114. ]
  115. def get_llm_model_answer(self, prompt):
  116. raise NotImplementedError
  117. def retrieve_from_database(self, input_query, config: QueryConfig):
  118. """
  119. Queries the vector database based on the given input query.
  120. Gets relevant doc based on the query
  121. :param input_query: The query to use.
  122. :param config: The query configuration.
  123. :return: The content of the document that matched your query.
  124. """
  125. where = {"app_id": self.config.id} if self.config.id is not None else {} # optional filter
  126. result = self.collection.query(
  127. query_texts=[
  128. input_query,
  129. ],
  130. n_results=config.number_documents,
  131. where=where,
  132. )
  133. results_formatted = self._format_result(result)
  134. contents = [result[0].page_content for result in results_formatted]
  135. return contents
  136. def _append_search_and_context(self, context, web_search_result):
  137. return f"{context}\nWeb Search Result: {web_search_result}"
  138. def generate_prompt(self, input_query, contexts, config: QueryConfig, **kwargs):
  139. """
  140. Generates a prompt based on the given query and context, ready to be
  141. passed to an LLM
  142. :param input_query: The query to use.
  143. :param contexts: List of similar documents to the query used as context.
  144. :param config: Optional. The `QueryConfig` instance to use as
  145. configuration options.
  146. :return: The prompt
  147. """
  148. context_string = (" | ").join(contexts)
  149. web_search_result = kwargs.get("web_search_result", "")
  150. if web_search_result:
  151. context_string = self._append_search_and_context(context_string, web_search_result)
  152. if not config.history:
  153. prompt = config.template.substitute(context=context_string, query=input_query)
  154. else:
  155. prompt = config.template.substitute(context=context_string, query=input_query, history=config.history)
  156. return prompt
  157. def get_answer_from_llm(self, prompt, config: ChatConfig):
  158. """
  159. Gets an answer based on the given query and context by passing it
  160. to an LLM.
  161. :param query: The query to use.
  162. :param context: Similar documents to the query used as context.
  163. :return: The answer.
  164. """
  165. return self.get_llm_model_answer(prompt, config)
  166. def access_search_and_get_results(self, input_query):
  167. from langchain.tools import DuckDuckGoSearchRun
  168. search = DuckDuckGoSearchRun()
  169. logging.info(f"Access search to get answers for {input_query}")
  170. return search.run(input_query)
  171. def query(self, input_query, config: QueryConfig = None):
  172. """
  173. Queries the vector database based on the given input query.
  174. Gets relevant doc based on the query and then passes it to an
  175. LLM as context to get the answer.
  176. :param input_query: The query to use.
  177. :param config: Optional. The `QueryConfig` instance to use as
  178. configuration options.
  179. :return: The answer to the query.
  180. """
  181. if config is None:
  182. config = QueryConfig()
  183. if self.is_code_docs_instance:
  184. config.template = CODE_DOCS_PAGE_PROMPT_TEMPLATE
  185. config.number_documents = 5
  186. k = {}
  187. if self.online:
  188. k["web_search_result"] = self.access_search_and_get_results(input_query)
  189. contexts = self.retrieve_from_database(input_query, config)
  190. prompt = self.generate_prompt(input_query, contexts, config, **k)
  191. logging.info(f"Prompt: {prompt}")
  192. answer = self.get_answer_from_llm(prompt, config)
  193. if isinstance(answer, str):
  194. logging.info(f"Answer: {answer}")
  195. return answer
  196. else:
  197. return self._stream_query_response(answer)
  198. def _stream_query_response(self, answer):
  199. streamed_answer = ""
  200. for chunk in answer:
  201. streamed_answer = streamed_answer + chunk
  202. yield chunk
  203. logging.info(f"Answer: {streamed_answer}")
  204. def chat(self, input_query, config: ChatConfig = None):
  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. :param config: Optional. The `ChatConfig` instance to use as
  212. configuration options.
  213. :return: The answer to the query.
  214. """
  215. if config is None:
  216. config = ChatConfig()
  217. if self.is_code_docs_instance:
  218. config.template = CODE_DOCS_PAGE_PROMPT_TEMPLATE
  219. config.number_documents = 5
  220. k = {}
  221. if self.online:
  222. k["web_search_result"] = self.access_search_and_get_results(input_query)
  223. contexts = self.retrieve_from_database(input_query, config, **k)
  224. global memory
  225. chat_history = memory.load_memory_variables({})["history"]
  226. if chat_history:
  227. config.set_history(chat_history)
  228. prompt = self.generate_prompt(input_query, contexts, config, **k)
  229. logging.info(f"Prompt: {prompt}")
  230. answer = self.get_answer_from_llm(prompt, config)
  231. memory.chat_memory.add_user_message(input_query)
  232. if isinstance(answer, str):
  233. memory.chat_memory.add_ai_message(answer)
  234. logging.info(f"Answer: {answer}")
  235. return answer
  236. else:
  237. # this is a streamed response and needs to be handled differently.
  238. return self._stream_chat_response(answer)
  239. def _stream_chat_response(self, answer):
  240. streamed_answer = ""
  241. for chunk in answer:
  242. streamed_answer = streamed_answer + chunk
  243. yield chunk
  244. memory.chat_memory.add_ai_message(streamed_answer)
  245. logging.info(f"Answer: {streamed_answer}")
  246. def dry_run(self, input_query, config: QueryConfig = None):
  247. """
  248. A dry run does everything except send the resulting prompt to
  249. the LLM. The purpose is to test the prompt, not the response.
  250. You can use it to test your prompt, including the context provided
  251. by the vector database's doc retrieval.
  252. The only thing the dry run does not consider is the cut-off due to
  253. the `max_tokens` parameter.
  254. :param input_query: The query to use.
  255. :param config: Optional. The `QueryConfig` instance to use as
  256. configuration options.
  257. :return: The prompt that would be sent to the LLM
  258. """
  259. if config is None:
  260. config = QueryConfig()
  261. contexts = self.retrieve_from_database(input_query, config)
  262. prompt = self.generate_prompt(input_query, contexts, config)
  263. logging.info(f"Prompt: {prompt}")
  264. return prompt
  265. def count(self):
  266. """
  267. Count the number of embeddings.
  268. :return: The number of embeddings.
  269. """
  270. return self.collection.count()
  271. def reset(self):
  272. """
  273. Resets the database. Deletes all embeddings irreversibly.
  274. `App` has to be reinitialized after using this method.
  275. """
  276. self.db_client.reset()
  277. class App(EmbedChain):
  278. """
  279. The EmbedChain app.
  280. Has two functions: add and query.
  281. adds(data_type, url): adds the data from the given URL to the vector db.
  282. query(query): finds answer to the given query using vector database and LLM.
  283. dry_run(query): test your prompt without consuming tokens.
  284. """
  285. def __init__(self, config: InitConfig = None):
  286. """
  287. :param config: InitConfig instance to load as configuration. Optional.
  288. """
  289. if config is None:
  290. config = InitConfig()
  291. if not config.ef:
  292. config._set_embedding_function_to_default()
  293. if not config.db:
  294. config._set_db_to_default()
  295. super().__init__(config)
  296. def get_llm_model_answer(self, prompt, config: ChatConfig):
  297. messages = []
  298. messages.append({"role": "user", "content": prompt})
  299. response = openai.ChatCompletion.create(
  300. model=config.model,
  301. messages=messages,
  302. temperature=config.temperature,
  303. max_tokens=config.max_tokens,
  304. top_p=config.top_p,
  305. stream=config.stream,
  306. )
  307. if config.stream:
  308. return self._stream_llm_model_response(response)
  309. else:
  310. return response["choices"][0]["message"]["content"]
  311. def _stream_llm_model_response(self, response):
  312. """
  313. This is a generator for streaming response from the OpenAI completions API
  314. """
  315. for line in response:
  316. chunk = line["choices"][0].get("delta", {}).get("content", "")
  317. yield chunk
  318. class OpenSourceApp(EmbedChain):
  319. """
  320. The OpenSource app.
  321. Same as App, but uses an open source embedding model and LLM.
  322. Has two function: add and query.
  323. adds(data_type, url): adds the data from the given URL to the vector db.
  324. query(query): finds answer to the given query using vector database and LLM.
  325. """
  326. def __init__(self, config: InitConfig = None):
  327. """
  328. :param config: InitConfig instance to load as configuration. Optional.
  329. `ef` defaults to open source.
  330. """
  331. print("Loading open source embedding model. This may take some time...") # noqa:E501
  332. if not config:
  333. config = InitConfig()
  334. if not config.ef:
  335. config._set_embedding_function(
  336. embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
  337. )
  338. if not config.db:
  339. config._set_db_to_default()
  340. print("Successfully loaded open source embedding model.")
  341. super().__init__(config)
  342. def get_llm_model_answer(self, prompt, config: ChatConfig):
  343. from gpt4all import GPT4All
  344. global gpt4all_model
  345. if gpt4all_model is None:
  346. gpt4all_model = GPT4All("orca-mini-3b.ggmlv3.q4_0.bin")
  347. response = gpt4all_model.generate(prompt=prompt, streaming=config.stream)
  348. return response
  349. class EmbedChainPersonApp:
  350. """
  351. Base class to create a person bot.
  352. This bot behaves and speaks like a person.
  353. :param person: name of the person, better if its a well known person.
  354. :param config: InitConfig instance to load as configuration.
  355. """
  356. def __init__(self, person, config: InitConfig = None):
  357. self.person = person
  358. self.person_prompt = f"You are {person}. Whatever you say, you will always say in {person} style." # noqa:E501
  359. if config is None:
  360. config = InitConfig()
  361. super().__init__(config)
  362. class PersonApp(EmbedChainPersonApp, App):
  363. """
  364. The Person app.
  365. Extends functionality from EmbedChainPersonApp and App
  366. """
  367. def query(self, input_query, config: QueryConfig = None):
  368. self.template = Template(self.person_prompt + " " + DEFAULT_PROMPT)
  369. query_config = QueryConfig(
  370. template=self.template,
  371. )
  372. return super().query(input_query, query_config)
  373. def chat(self, input_query, config: ChatConfig = None):
  374. self.template = Template(self.person_prompt + " " + DEFAULT_PROMPT_WITH_HISTORY)
  375. chat_config = ChatConfig(
  376. template=self.template,
  377. )
  378. return super().chat(input_query, chat_config)
  379. class PersonOpenSourceApp(EmbedChainPersonApp, OpenSourceApp):
  380. """
  381. The Person app.
  382. Extends functionality from EmbedChainPersonApp and OpenSourceApp
  383. """
  384. def query(self, input_query, config: QueryConfig = None):
  385. query_config = QueryConfig(
  386. template=self.template,
  387. )
  388. return super().query(input_query, query_config)
  389. def chat(self, input_query, config: ChatConfig = None):
  390. chat_config = ChatConfig(
  391. template=self.template,
  392. )
  393. return super().chat(input_query, chat_config)