embedchain.py 14 KB

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