embedchain.py 12 KB

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