embedchain.py 16 KB

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