embedchain.py 6.5 KB

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