embedchain.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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.loaders.youtube_video import YoutubeVideoLoader
  9. from embedchain.loaders.pdf_file import PdfFileLoader
  10. from embedchain.loaders.web_page import WebPageLoader
  11. from embedchain.loaders.local_qna_pair import LocalQnaPairLoader
  12. from embedchain.loaders.local_text import LocalTextLoader
  13. from embedchain.loaders.doc_file import DocFileLoader
  14. from embedchain.chunkers.youtube_video import YoutubeVideoChunker
  15. from embedchain.chunkers.pdf_file import PdfFileChunker
  16. from embedchain.chunkers.web_page import WebPageChunker
  17. from embedchain.chunkers.qna_pair import QnaPairChunker
  18. from embedchain.chunkers.text import TextChunker
  19. from embedchain.chunkers.doc_file import DocFileChunker
  20. from embedchain.vectordb.chroma_db import ChromaDB
  21. gpt4all_model = None
  22. load_dotenv()
  23. ABS_PATH = os.getcwd()
  24. DB_DIR = os.path.join(ABS_PATH, "db")
  25. memory = ConversationBufferMemory()
  26. class EmbedChain:
  27. def __init__(self, db=None, ef=None):
  28. """
  29. Initializes the EmbedChain instance, sets up a vector DB client and
  30. creates a collection.
  31. :param db: The instance of the VectorDB subclass.
  32. """
  33. if db is None:
  34. db = ChromaDB(ef=ef)
  35. self.db_client = db.client
  36. self.collection = 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):
  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. """
  82. loader = self._get_loader(data_type)
  83. chunker = self._get_chunker(data_type)
  84. self.user_asks.append([data_type, url])
  85. self.load_and_embed(loader, chunker, url)
  86. def add_local(self, data_type, content):
  87. """
  88. Adds the data you supply to the vector db.
  89. Loads the data, chunks it, create embedding for each chunk
  90. and then stores the embedding to vector database.
  91. :param data_type: The type of the data to add.
  92. :param content: The local data. Refer to the `README` for formatting.
  93. """
  94. loader = self._get_loader(data_type)
  95. chunker = self._get_chunker(data_type)
  96. self.user_asks.append([data_type, content])
  97. self.load_and_embed(loader, chunker, content)
  98. def load_and_embed(self, loader, chunker, url):
  99. """
  100. Loads the data from the given URL, chunks it, and adds it to the database.
  101. :param loader: The loader to use to load the data.
  102. :param chunker: The chunker to use to chunk the data.
  103. :param url: The URL where the data is located.
  104. """
  105. embeddings_data = chunker.create_chunks(loader, url)
  106. documents = embeddings_data["documents"]
  107. metadatas = embeddings_data["metadatas"]
  108. ids = embeddings_data["ids"]
  109. # get existing ids, and discard doc if any common id exist.
  110. existing_docs = self.collection.get(
  111. ids=ids,
  112. # where={"url": url}
  113. )
  114. existing_ids = set(existing_docs["ids"])
  115. if len(existing_ids):
  116. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  117. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  118. if not data_dict:
  119. print(f"All data from {url} already exists in the database.")
  120. return
  121. ids = list(data_dict.keys())
  122. documents, metadatas = zip(*data_dict.values())
  123. self.collection.add(
  124. documents=documents,
  125. metadatas=metadatas,
  126. ids=ids
  127. )
  128. print(f"Successfully saved {url}. Total chunks count: {self.collection.count()}")
  129. def _format_result(self, results):
  130. return [
  131. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  132. for result in zip(
  133. results["documents"][0],
  134. results["metadatas"][0],
  135. results["distances"][0],
  136. )
  137. ]
  138. def get_llm_model_answer(self, prompt):
  139. raise NotImplementedError
  140. def retrieve_from_database(self, input_query):
  141. """
  142. Queries the vector database based on the given input query.
  143. Gets relevant doc based on the query
  144. :param input_query: The query to use.
  145. :return: The content of the document that matched your query.
  146. """
  147. result = self.collection.query(
  148. query_texts=[input_query,],
  149. n_results=1,
  150. )
  151. result_formatted = self._format_result(result)
  152. if result_formatted:
  153. content = result_formatted[0][0].page_content
  154. else:
  155. content = ""
  156. return content
  157. def generate_prompt(self, input_query, context):
  158. """
  159. Generates a prompt based on the given query and context, ready to be passed to an LLM
  160. :param input_query: The query to use.
  161. :param context: Similar documents to the query used as context.
  162. :return: The prompt
  163. """
  164. 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.
  165. {context}
  166. Query: {input_query}
  167. Helpful Answer:
  168. """
  169. return prompt
  170. def get_answer_from_llm(self, prompt):
  171. """
  172. Gets an answer based on the given query and context by passing it
  173. to an LLM.
  174. :param query: The query to use.
  175. :param context: Similar documents to the query used as context.
  176. :return: The answer.
  177. """
  178. answer = self.get_llm_model_answer(prompt)
  179. return answer
  180. def query(self, input_query):
  181. """
  182. Queries the vector database based on the given input query.
  183. Gets relevant doc based on the query and then passes it to an
  184. LLM as context to get the answer.
  185. :param input_query: The query to use.
  186. :return: The answer to the query.
  187. """
  188. context = self.retrieve_from_database(input_query)
  189. prompt = self.generate_prompt(input_query, context)
  190. answer = self.get_answer_from_llm(prompt)
  191. return answer
  192. def generate_chat_prompt(self, input_query, context, chat_history=''):
  193. """
  194. Generates a prompt based on the given query, context and chat history
  195. for chat interface. This is then passed to an LLM.
  196. :param input_query: The query to use.
  197. :param context: Similar documents to the query used as context.
  198. :param chat_history: User and bot conversation that happened before.
  199. :return: The prompt
  200. """
  201. 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"."""
  202. chat_history_prompt = f"""\n----\nChat History: {chat_history}\n----"""
  203. suffix_prompt = f"""\n####\nContext: {context}\n####\nQuery: {input_query}\nHelpful Answer:"""
  204. prompt = prefix_prompt
  205. if chat_history:
  206. prompt += chat_history_prompt
  207. prompt += suffix_prompt
  208. return prompt
  209. def chat(self, input_query):
  210. """
  211. Queries the vector database on the given input query.
  212. Gets relevant doc based on the query and then passes it to an
  213. LLM as context to get the answer.
  214. Maintains last 5 conversations in memory.
  215. """
  216. context = self.retrieve_from_database(input_query)
  217. global memory
  218. chat_history = memory.load_memory_variables({})["history"]
  219. prompt = self.generate_chat_prompt(
  220. input_query,
  221. context,
  222. chat_history=chat_history,
  223. )
  224. answer = self.get_answer_from_llm(prompt)
  225. memory.chat_memory.add_user_message(input_query)
  226. memory.chat_memory.add_ai_message(answer)
  227. return answer
  228. def dry_run(self, input_query):
  229. """
  230. A dry run does everything except send the resulting prompt to
  231. the LLM. The purpose is to test the prompt, not the response.
  232. You can use it to test your prompt, including the context provided
  233. by the vector database's doc retrieval.
  234. The only thing the dry run does not consider is the cut-off due to
  235. the `max_tokens` parameter.
  236. :param input_query: The query to use.
  237. :return: The prompt that would be sent to the LLM
  238. """
  239. context = self.retrieve_from_database(input_query)
  240. prompt = self.generate_prompt(input_query, context)
  241. return prompt
  242. class App(EmbedChain):
  243. """
  244. The EmbedChain app.
  245. Has two functions: add and query.
  246. adds(data_type, url): adds the data from the given URL to the vector db.
  247. query(query): finds answer to the given query using vector database and LLM.
  248. dry_run(query): test your prompt without consuming tokens.
  249. """
  250. def __int__(self, db=None, ef=None):
  251. if ef is None:
  252. ef = embedding_functions.OpenAIEmbeddingFunction(
  253. api_key=os.getenv("OPENAI_API_KEY"),
  254. organization_id=os.getenv("OPENAI_ORGANIZATION"),
  255. model_name="text-embedding-ada-002"
  256. )
  257. super().__init__(db, ef)
  258. def get_llm_model_answer(self, prompt):
  259. messages = []
  260. messages.append({
  261. "role": "user", "content": prompt
  262. })
  263. response = openai.ChatCompletion.create(
  264. model="gpt-3.5-turbo-0613",
  265. messages=messages,
  266. temperature=0,
  267. max_tokens=1000,
  268. top_p=1,
  269. )
  270. return response["choices"][0]["message"]["content"]
  271. class OpenSourceApp(EmbedChain):
  272. """
  273. The OpenSource app.
  274. Same as App, but uses an open source embedding model and LLM.
  275. Has two function: add and query.
  276. adds(data_type, url): adds the data from the given URL to the vector db.
  277. query(query): finds answer to the given query using vector database and LLM.
  278. """
  279. def __init__(self, db=None, ef=None):
  280. print("Loading open source embedding model. This may take some time...")
  281. if ef is None:
  282. ef = embedding_functions.SentenceTransformerEmbeddingFunction(
  283. model_name="all-MiniLM-L6-v2"
  284. )
  285. print("Successfully loaded open source embedding model.")
  286. super().__init__(db, ef)
  287. def get_llm_model_answer(self, prompt):
  288. from gpt4all import GPT4All
  289. global gpt4all_model
  290. if gpt4all_model is None:
  291. gpt4all_model = GPT4All("orca-mini-3b.ggmlv3.q4_0.bin")
  292. response = gpt4all_model.generate(
  293. prompt=prompt,
  294. )
  295. return response