embedchain.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import openai
  2. import os
  3. from dotenv import load_dotenv
  4. from langchain.docstore.document import Document
  5. from langchain.embeddings.openai import OpenAIEmbeddings
  6. from embedchain.loaders.youtube_video import YoutubeVideoLoader
  7. from embedchain.loaders.pdf_file import PdfFileLoader
  8. from embedchain.loaders.web_page import WebPageLoader
  9. from embedchain.chunkers.youtube_video import YoutubeVideoChunker
  10. from embedchain.chunkers.pdf_file import PdfFileChunker
  11. from embedchain.chunkers.web_page import WebPageChunker
  12. from embedchain.vectordb.chroma_db import ChromaDB
  13. load_dotenv()
  14. embeddings = OpenAIEmbeddings()
  15. ABS_PATH = os.getcwd()
  16. DB_DIR = os.path.join(ABS_PATH, "db")
  17. class EmbedChain:
  18. def __init__(self, db=None):
  19. """
  20. Initializes the EmbedChain instance, sets up a vector DB client and
  21. creates a collection.
  22. :param db: The instance of the VectorDB subclass.
  23. """
  24. if db is None:
  25. db = ChromaDB()
  26. self.db_client = db.client
  27. self.collection = db.collection
  28. self.user_asks = []
  29. def _get_loader(self, data_type):
  30. """
  31. Returns the appropriate data loader for the given data type.
  32. :param data_type: The type of the data to load.
  33. :return: The loader for the given data type.
  34. :raises ValueError: If an unsupported data type is provided.
  35. """
  36. loaders = {
  37. 'youtube_video': YoutubeVideoLoader(),
  38. 'pdf_file': PdfFileLoader(),
  39. 'web_page': WebPageLoader()
  40. }
  41. if data_type in loaders:
  42. return loaders[data_type]
  43. else:
  44. raise ValueError(f"Unsupported data type: {data_type}")
  45. def _get_chunker(self, data_type):
  46. """
  47. Returns the appropriate chunker for the given data type.
  48. :param data_type: The type of the data to chunk.
  49. :return: The chunker for the given data type.
  50. :raises ValueError: If an unsupported data type is provided.
  51. """
  52. chunkers = {
  53. 'youtube_video': YoutubeVideoChunker(),
  54. 'pdf_file': PdfFileChunker(),
  55. 'web_page': WebPageChunker()
  56. }
  57. if data_type in chunkers:
  58. return chunkers[data_type]
  59. else:
  60. raise ValueError(f"Unsupported data type: {data_type}")
  61. def add(self, data_type, url):
  62. """
  63. Adds the data from the given URL to the vector db.
  64. Loads the data, chunks it, create embedding for each chunk
  65. and then stores the embedding to vector database.
  66. :param data_type: The type of the data to add.
  67. :param url: The URL where the data is located.
  68. """
  69. loader = self._get_loader(data_type)
  70. chunker = self._get_chunker(data_type)
  71. self.user_asks.append([data_type, url])
  72. self.load_and_embed(loader, chunker, url)
  73. def load_and_embed(self, loader, chunker, url):
  74. """
  75. Loads the data from the given URL, chunks it, and adds it to the database.
  76. :param loader: The loader to use to load the data.
  77. :param chunker: The chunker to use to chunk the data.
  78. :param url: The URL where the data is located.
  79. """
  80. embeddings_data = chunker.create_chunks(loader, url)
  81. documents = embeddings_data["documents"]
  82. metadatas = embeddings_data["metadatas"]
  83. ids = embeddings_data["ids"]
  84. # get existing ids, and discard doc if any common id exist.
  85. existing_docs = self.collection.get(
  86. ids=ids,
  87. # where={"url": url}
  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 {url} already exists in the database.")
  95. return
  96. ids = list(data_dict.keys())
  97. documents, metadatas = zip(*data_dict.values())
  98. self.collection.add(
  99. documents=documents,
  100. metadatas=metadatas,
  101. ids=ids
  102. )
  103. print(f"Successfully saved {url}. Total chunks count: {self.collection.count()}")
  104. def _format_result(self, results):
  105. return [
  106. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  107. for result in zip(
  108. results["documents"][0],
  109. results["metadatas"][0],
  110. results["distances"][0],
  111. )
  112. ]
  113. def get_openai_answer(self, prompt):
  114. messages = []
  115. messages.append({
  116. "role": "user", "content": prompt
  117. })
  118. response = openai.ChatCompletion.create(
  119. model="gpt-3.5-turbo-0613",
  120. messages=messages,
  121. temperature=0,
  122. max_tokens=1000,
  123. top_p=1,
  124. )
  125. return response["choices"][0]["message"]["content"]
  126. def get_answer_from_llm(self, query, context):
  127. """
  128. Gets an answer based on the given query and context by passing it
  129. to an LLM.
  130. :param query: The query to use.
  131. :param context: Similar documents to the query used as context.
  132. :return: The answer.
  133. """
  134. 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.
  135. {context}
  136. Query: {query}
  137. Helpful Answer:
  138. """
  139. answer = self.get_openai_answer(prompt)
  140. return answer
  141. def query(self, input_query):
  142. """
  143. Queries the vector database based on the given input query.
  144. Gets relevant doc based on the query and then passes it to an
  145. LLM as context to get the answer.
  146. :param input_query: The query to use.
  147. :return: The answer to the query.
  148. """
  149. result = self.collection.query(
  150. query_texts=[input_query,],
  151. n_results=1,
  152. )
  153. result_formatted = self._format_result(result)
  154. answer = self.get_answer_from_llm(input_query, result_formatted[0][0].page_content)
  155. return answer
  156. class App(EmbedChain):
  157. """
  158. The EmbedChain app.
  159. Has two functions: add and query.
  160. adds(data_type, url): adds the data from the given URL to the vector db.
  161. query(query): finds answer to the given query using vector database and LLM.
  162. """
  163. pass