embedchain.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import openai
  2. import os
  3. from chromadb.utils import embedding_functions
  4. from dotenv import load_dotenv
  5. from langchain.docstore.document import Document
  6. from langchain.embeddings.openai import OpenAIEmbeddings
  7. from langchain.memory import ConversationBufferMemory
  8. from embedchain.config import InitConfig, AddConfig, QueryConfig, ChatConfig
  9. from embedchain.loaders.youtube_video import YoutubeVideoLoader
  10. from embedchain.loaders.pdf_file import PdfFileLoader
  11. from embedchain.loaders.web_page import WebPageLoader
  12. from embedchain.loaders.local_qna_pair import LocalQnaPairLoader
  13. from embedchain.loaders.local_text import LocalTextLoader
  14. from embedchain.loaders.doc_file import DocFileLoader
  15. from embedchain.chunkers.youtube_video import YoutubeVideoChunker
  16. from embedchain.chunkers.pdf_file import PdfFileChunker
  17. from embedchain.chunkers.web_page import WebPageChunker
  18. from embedchain.chunkers.qna_pair import QnaPairChunker
  19. from embedchain.chunkers.text import TextChunker
  20. from embedchain.chunkers.doc_file import DocFileChunker
  21. from embedchain.vectordb.chroma_db import ChromaDB
  22. gpt4all_model = None
  23. load_dotenv()
  24. ABS_PATH = os.getcwd()
  25. DB_DIR = os.path.join(ABS_PATH, "db")
  26. memory = ConversationBufferMemory()
  27. class EmbedChain:
  28. def __init__(self, config: InitConfig):
  29. """
  30. Initializes the EmbedChain instance, sets up a vector DB client and
  31. creates a collection.
  32. :param config: InitConfig instance to load as configuration.
  33. """
  34. self.config = config
  35. self.db_client = self.config.db.client
  36. self.collection = self.config.db.collection
  37. self.user_asks = []
  38. def _get_loader(self, data_type):
  39. """
  40. Returns the appropriate data loader for the given data type.
  41. :param data_type: The type of the data to load.
  42. :return: The loader for the given data type.
  43. :raises ValueError: If an unsupported data type is provided.
  44. """
  45. loaders = {
  46. 'youtube_video': YoutubeVideoLoader(),
  47. 'pdf_file': PdfFileLoader(),
  48. 'web_page': WebPageLoader(),
  49. 'qna_pair': LocalQnaPairLoader(),
  50. 'text': LocalTextLoader(),
  51. }
  52. if data_type in loaders:
  53. return loaders[data_type]
  54. else:
  55. raise ValueError(f"Unsupported data type: {data_type}")
  56. def _get_chunker(self, data_type):
  57. """
  58. Returns the appropriate chunker for the given data type.
  59. :param data_type: The type of the data to chunk.
  60. :return: The chunker for the given data type.
  61. :raises ValueError: If an unsupported data type is provided.
  62. """
  63. chunkers = {
  64. 'youtube_video': YoutubeVideoChunker(),
  65. 'pdf_file': PdfFileChunker(),
  66. 'web_page': WebPageChunker(),
  67. 'qna_pair': QnaPairChunker(),
  68. 'text': TextChunker(),
  69. }
  70. if data_type in chunkers:
  71. return chunkers[data_type]
  72. else:
  73. raise ValueError(f"Unsupported data type: {data_type}")
  74. def add(self, data_type, url, config: AddConfig = None):
  75. """
  76. Adds the data from the given URL to the vector db.
  77. Loads the data, chunks it, create embedding for each chunk
  78. and then stores the embedding to vector database.
  79. :param data_type: The type of the data to add.
  80. :param url: The URL where the data is located.
  81. :param config: Optional. The `AddConfig` instance to use as configuration options.
  82. """
  83. if config is None:
  84. config = AddConfig()
  85. loader = self._get_loader(data_type)
  86. chunker = self._get_chunker(data_type)
  87. self.user_asks.append([data_type, url])
  88. self.load_and_embed(loader, chunker, url)
  89. def add_local(self, data_type, content, config: AddConfig = None):
  90. """
  91. Adds the data you supply to the vector db.
  92. Loads the data, chunks it, create embedding for each chunk
  93. and then stores the embedding to vector database.
  94. :param data_type: The type of the data to add.
  95. :param content: The local data. Refer to the `README` for formatting.
  96. :param config: Optional. The `AddConfig` instance to use as configuration options.
  97. """
  98. if config is None:
  99. config = AddConfig()
  100. loader = self._get_loader(data_type)
  101. chunker = self._get_chunker(data_type)
  102. self.user_asks.append([data_type, content])
  103. self.load_and_embed(loader, chunker, content)
  104. def load_and_embed(self, loader, chunker, url):
  105. """
  106. Loads the data from the given URL, chunks it, and adds it to the database.
  107. :param loader: The loader to use to load the data.
  108. :param chunker: The chunker to use to chunk the data.
  109. :param url: The URL where the data is located.
  110. """
  111. embeddings_data = chunker.create_chunks(loader, url)
  112. documents = embeddings_data["documents"]
  113. metadatas = embeddings_data["metadatas"]
  114. ids = embeddings_data["ids"]
  115. # get existing ids, and discard doc if any common id exist.
  116. existing_docs = self.collection.get(
  117. ids=ids,
  118. # where={"url": url}
  119. )
  120. existing_ids = set(existing_docs["ids"])
  121. if len(existing_ids):
  122. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  123. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  124. if not data_dict:
  125. print(f"All data from {url} already exists in the database.")
  126. return
  127. ids = list(data_dict.keys())
  128. documents, metadatas = zip(*data_dict.values())
  129. self.collection.add(
  130. documents=documents,
  131. metadatas=metadatas,
  132. ids=ids
  133. )
  134. print(f"Successfully saved {url}. Total chunks count: {self.collection.count()}")
  135. def _format_result(self, results):
  136. return [
  137. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  138. for result in zip(
  139. results["documents"][0],
  140. results["metadatas"][0],
  141. results["distances"][0],
  142. )
  143. ]
  144. def get_llm_model_answer(self, prompt):
  145. raise NotImplementedError
  146. def retrieve_from_database(self, input_query):
  147. """
  148. Queries the vector database based on the given input query.
  149. Gets relevant doc based on the query
  150. :param input_query: The query to use.
  151. :return: The content of the document that matched your query.
  152. """
  153. result = self.collection.query(
  154. query_texts=[input_query,],
  155. n_results=1,
  156. )
  157. result_formatted = self._format_result(result)
  158. if result_formatted:
  159. content = result_formatted[0][0].page_content
  160. else:
  161. content = ""
  162. return content
  163. def generate_prompt(self, input_query, context):
  164. """
  165. Generates a prompt based on the given query and context, ready to be passed to an LLM
  166. :param input_query: The query to use.
  167. :param context: Similar documents to the query used as context.
  168. :return: The prompt
  169. """
  170. prompt = f"""Use the following pieces of context to answer the query at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
  171. {context}
  172. Query: {input_query}
  173. Helpful Answer:
  174. """
  175. return prompt
  176. def get_answer_from_llm(self, prompt):
  177. """
  178. Gets an answer based on the given query and context by passing it
  179. to an LLM.
  180. :param query: The query to use.
  181. :param context: Similar documents to the query used as context.
  182. :return: The answer.
  183. """
  184. answer = self.get_llm_model_answer(prompt)
  185. return answer
  186. def query(self, input_query, config: QueryConfig = None):
  187. """
  188. Queries the vector database based on the given input query.
  189. Gets relevant doc based on the query and then passes it to an
  190. LLM as context to get the answer.
  191. :param input_query: The query to use.
  192. :param config: Optional. The `QueryConfig` instance to use as configuration options.
  193. :return: The answer to the query.
  194. """
  195. if config is None:
  196. config = QueryConfig()
  197. context = self.retrieve_from_database(input_query)
  198. prompt = self.generate_prompt(input_query, context)
  199. answer = self.get_answer_from_llm(prompt)
  200. return answer
  201. def generate_chat_prompt(self, input_query, context, chat_history=''):
  202. """
  203. Generates a prompt based on the given query, context and chat history
  204. for chat interface. This is then passed to an LLM.
  205. :param input_query: The query to use.
  206. :param context: Similar documents to the query used as context.
  207. :param chat_history: User and bot conversation that happened before.
  208. :return: The prompt
  209. """
  210. prefix_prompt = f"""You are a chatbot having a conversation with a human. You are given chat history and context. You need to answer the query considering context, chat history and your knowledge base. If you don't know the answer or the answer is neither contained in the context nor in history, then simply say "I don't know"."""
  211. chat_history_prompt = f"""\n----\nChat History: {chat_history}\n----"""
  212. suffix_prompt = f"""\n####\nContext: {context}\n####\nQuery: {input_query}\nHelpful Answer:"""
  213. prompt = prefix_prompt
  214. if chat_history:
  215. prompt += chat_history_prompt
  216. prompt += suffix_prompt
  217. return prompt
  218. def chat(self, input_query, config: ChatConfig = None):
  219. """
  220. Queries the vector database on the given input query.
  221. Gets relevant doc based on the query and then passes it to an
  222. LLM as context to get the answer.
  223. Maintains last 5 conversations in memory.
  224. :param input_query: The query to use.
  225. :param config: Optional. The `ChatConfig` instance to use as configuration options.
  226. :return: The answer to the query.
  227. """
  228. if config is None:
  229. config = ChatConfig()
  230. context = self.retrieve_from_database(input_query)
  231. global memory
  232. chat_history = memory.load_memory_variables({})["history"]
  233. prompt = self.generate_chat_prompt(
  234. input_query,
  235. context,
  236. chat_history=chat_history,
  237. )
  238. answer = self.get_answer_from_llm(prompt)
  239. memory.chat_memory.add_user_message(input_query)
  240. memory.chat_memory.add_ai_message(answer)
  241. return answer
  242. def dry_run(self, input_query):
  243. """
  244. A dry run does everything except send the resulting prompt to
  245. the LLM. The purpose is to test the prompt, not the response.
  246. You can use it to test your prompt, including the context provided
  247. by the vector database's doc retrieval.
  248. The only thing the dry run does not consider is the cut-off due to
  249. the `max_tokens` parameter.
  250. :param input_query: The query to use.
  251. :param config: Optional. The `QueryConfig` instance to use as configuration options.
  252. :return: The prompt that would be sent to the LLM
  253. """
  254. if config is None:
  255. config = QueryConfig()
  256. context = self.retrieve_from_database(input_query)
  257. prompt = self.generate_prompt(input_query, context)
  258. return prompt
  259. def count(self):
  260. """
  261. Count the number of embeddings.
  262. :return: The number of embeddings.
  263. """
  264. return self.collection.count()
  265. def reset(self):
  266. """
  267. Resets the database. Deletes all embeddings irreversibly.
  268. `App` has to be reinitialized after using this method.
  269. """
  270. self.db_client.reset()
  271. class App(EmbedChain):
  272. """
  273. The EmbedChain app.
  274. Has two functions: add and query.
  275. adds(data_type, url): adds the data from the given URL to the vector db.
  276. query(query): finds answer to the given query using vector database and LLM.
  277. dry_run(query): test your prompt without consuming tokens.
  278. """
  279. def __init__(self, config: InitConfig = None):
  280. """
  281. :param config: InitConfig instance to load as configuration. Optional.
  282. """
  283. if config is None:
  284. config = InitConfig()
  285. super().__init__(config)
  286. def get_llm_model_answer(self, prompt):
  287. messages = []
  288. messages.append({
  289. "role": "user", "content": prompt
  290. })
  291. response = openai.ChatCompletion.create(
  292. model="gpt-3.5-turbo-0613",
  293. messages=messages,
  294. temperature=0,
  295. max_tokens=1000,
  296. top_p=1,
  297. )
  298. return response["choices"][0]["message"]["content"]
  299. class OpenSourceApp(EmbedChain):
  300. """
  301. The OpenSource app.
  302. Same as App, but uses an open source embedding model and LLM.
  303. Has two function: add and query.
  304. adds(data_type, url): adds the data from the given URL to the vector db.
  305. query(query): finds answer to the given query using vector database and LLM.
  306. """
  307. def __init__(self, config: InitConfig = None):
  308. """
  309. :param config: InitConfig instance to load as configuration. Optional. `ef` defaults to open source.
  310. """
  311. print("Loading open source embedding model. This may take some time...")
  312. if not config or not config.ef:
  313. if config is None:
  314. config = InitConfig(
  315. ef = embedding_functions.SentenceTransformerEmbeddingFunction(
  316. model_name="all-MiniLM-L6-v2"
  317. )
  318. )
  319. else:
  320. config._set_embedding_function(
  321. embedding_functions.SentenceTransformerEmbeddingFunction(
  322. model_name="all-MiniLM-L6-v2"
  323. ))
  324. print("Successfully loaded open source embedding model.")
  325. super().__init__(config)
  326. def get_llm_model_answer(self, prompt):
  327. from gpt4all import GPT4All
  328. global gpt4all_model
  329. if gpt4all_model is None:
  330. gpt4all_model = GPT4All("orca-mini-3b.ggmlv3.q4_0.bin")
  331. response = gpt4all_model.generate(
  332. prompt=prompt,
  333. )
  334. return response