embedchain.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import openai
  2. import os
  3. import logging
  4. from string import Template
  5. from chromadb.utils import embedding_functions
  6. from dotenv import load_dotenv
  7. from langchain.docstore.document import Document
  8. from langchain.embeddings.openai import OpenAIEmbeddings
  9. from langchain.memory import ConversationBufferMemory
  10. from embedchain.config import InitConfig, AddConfig, QueryConfig, ChatConfig
  11. from embedchain.config.QueryConfig import DEFAULT_PROMPT
  12. from embedchain.data_formatter import DataFormatter
  13. gpt4all_model = None
  14. load_dotenv()
  15. ABS_PATH = os.getcwd()
  16. DB_DIR = os.path.join(ABS_PATH, "db")
  17. memory = ConversationBufferMemory()
  18. class EmbedChain:
  19. def __init__(self, config: InitConfig):
  20. """
  21. Initializes the EmbedChain instance, sets up a vector DB client and
  22. creates a collection.
  23. :param config: InitConfig instance to load as configuration.
  24. """
  25. self.config = config
  26. self.db_client = self.config.db.client
  27. self.collection = self.config.db.collection
  28. self.user_asks = []
  29. def add(self, data_type, url, config: AddConfig = None):
  30. """
  31. Adds the data from the given URL to the vector db.
  32. Loads the data, chunks it, create embedding for each chunk
  33. and then stores the embedding to vector database.
  34. :param data_type: The type of the data to add.
  35. :param url: The URL where the data is located.
  36. :param config: Optional. The `AddConfig` instance to use as configuration options.
  37. """
  38. if config is None:
  39. config = AddConfig()
  40. data_formatter = DataFormatter(data_type)
  41. self.user_asks.append([data_type, url])
  42. self.load_and_embed(data_formatter.loader, data_formatter.chunker, url)
  43. def add_local(self, data_type, content, config: AddConfig = None):
  44. """
  45. Adds the data you supply to the vector db.
  46. Loads the data, chunks it, create embedding for each chunk
  47. and then stores the embedding to vector database.
  48. :param data_type: The type of the data to add.
  49. :param content: The local data. Refer to the `README` for formatting.
  50. :param config: Optional. The `AddConfig` instance to use as configuration options.
  51. """
  52. if config is None:
  53. config = AddConfig()
  54. data_formatter = DataFormatter(data_type)
  55. self.user_asks.append([data_type, content])
  56. self.load_and_embed(data_formatter.loader, data_formatter.chunker, content)
  57. def load_and_embed(self, loader, chunker, src):
  58. """
  59. Loads the data from the given URL, chunks it, and adds it to the database.
  60. :param loader: The loader to use to load the data.
  61. :param chunker: The chunker to use to chunk the data.
  62. :param src: The data to be handled by the loader. Can be a URL for remote sources or local content for local loaders.
  63. """
  64. embeddings_data = chunker.create_chunks(loader, src)
  65. documents = embeddings_data["documents"]
  66. metadatas = embeddings_data["metadatas"]
  67. ids = embeddings_data["ids"]
  68. # get existing ids, and discard doc if any common id exist.
  69. existing_docs = self.collection.get(
  70. ids=ids,
  71. # where={"url": src}
  72. )
  73. existing_ids = set(existing_docs["ids"])
  74. if len(existing_ids):
  75. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  76. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  77. if not data_dict:
  78. print(f"All data from {src} already exists in the database.")
  79. return
  80. ids = list(data_dict.keys())
  81. documents, metadatas = zip(*data_dict.values())
  82. chunks_before_addition = self.count()
  83. self.collection.add(
  84. documents=documents,
  85. metadatas=list(metadatas),
  86. ids=ids
  87. )
  88. print(f"Successfully saved {src}. New chunks count: {self.count() - chunks_before_addition}")
  89. def _format_result(self, results):
  90. return [
  91. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  92. for result in zip(
  93. results["documents"][0],
  94. results["metadatas"][0],
  95. results["distances"][0],
  96. )
  97. ]
  98. def get_llm_model_answer(self, prompt):
  99. raise NotImplementedError
  100. def retrieve_from_database(self, input_query):
  101. """
  102. Queries the vector database based on the given input query.
  103. Gets relevant doc based on the query
  104. :param input_query: The query to use.
  105. :return: The content of the document that matched your query.
  106. """
  107. result = self.collection.query(
  108. query_texts=[input_query,],
  109. n_results=1,
  110. )
  111. result_formatted = self._format_result(result)
  112. if result_formatted:
  113. content = result_formatted[0][0].page_content
  114. else:
  115. content = ""
  116. return content
  117. def generate_prompt(self, input_query, context, template: Template = None):
  118. """
  119. Generates a prompt based on the given query and context, ready to be passed to an LLM
  120. :param input_query: The query to use.
  121. :param context: Similar documents to the query used as context.
  122. :param template: Optional. The `Template` instance to use as a template for prompt.
  123. :return: The prompt
  124. """
  125. prompt = template.substitute(context = context, query = input_query)
  126. return prompt
  127. def get_answer_from_llm(self, prompt, config: ChatConfig):
  128. """
  129. Gets an answer based on the given query and context by passing it
  130. to an LLM.
  131. :param query: The query to use.
  132. :param context: Similar documents to the query used as context.
  133. :return: The answer.
  134. """
  135. return self.get_llm_model_answer(prompt, config)
  136. def query(self, input_query, config: QueryConfig = None):
  137. """
  138. Queries the vector database based on the given input query.
  139. Gets relevant doc based on the query and then passes it to an
  140. LLM as context to get the answer.
  141. :param input_query: The query to use.
  142. :param config: Optional. The `QueryConfig` instance to use as configuration options.
  143. :return: The answer to the query.
  144. """
  145. if config is None:
  146. config = QueryConfig()
  147. context = self.retrieve_from_database(input_query)
  148. prompt = self.generate_prompt(input_query, context, config.template)
  149. logging.info(f"Prompt: {prompt}")
  150. answer = self.get_answer_from_llm(prompt, config)
  151. logging.info(f"Answer: {answer}")
  152. return answer
  153. def generate_chat_prompt(self, input_query, context, chat_history=''):
  154. """
  155. Generates a prompt based on the given query, context and chat history
  156. for chat interface. This is then passed to an LLM.
  157. :param input_query: The query to use.
  158. :param context: Similar documents to the query used as context.
  159. :param chat_history: User and bot conversation that happened before.
  160. :return: The prompt
  161. """
  162. 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"."""
  163. chat_history_prompt = f"""\n----\nChat History: {chat_history}\n----"""
  164. suffix_prompt = f"""\n####\nContext: {context}\n####\nQuery: {input_query}\nHelpful Answer:"""
  165. prompt = prefix_prompt
  166. if chat_history:
  167. prompt += chat_history_prompt
  168. prompt += suffix_prompt
  169. return prompt
  170. def chat(self, input_query, config: ChatConfig = None):
  171. """
  172. Queries the vector database on the given input query.
  173. Gets relevant doc based on the query and then passes it to an
  174. LLM as context to get the answer.
  175. Maintains last 5 conversations in memory.
  176. :param input_query: The query to use.
  177. :param config: Optional. The `ChatConfig` instance to use as configuration options.
  178. :return: The answer to the query.
  179. """
  180. if config is None:
  181. config = ChatConfig()
  182. context = self.retrieve_from_database(input_query)
  183. global memory
  184. chat_history = memory.load_memory_variables({})["history"]
  185. prompt = self.generate_chat_prompt(
  186. input_query,
  187. context,
  188. chat_history=chat_history,
  189. )
  190. logging.info(f"Prompt: {prompt}")
  191. answer = self.get_answer_from_llm(prompt, config)
  192. memory.chat_memory.add_user_message(input_query)
  193. if isinstance(answer, str):
  194. memory.chat_memory.add_ai_message(answer)
  195. logging.info(f"Answer: {answer}")
  196. return answer
  197. else:
  198. #this is a streamed response and needs to be handled differently.
  199. return self._stream_chat_response(answer)
  200. def _stream_chat_response(self, answer):
  201. streamed_answer = ""
  202. for chunk in answer:
  203. streamed_answer.join(chunk)
  204. yield chunk
  205. memory.chat_memory.add_ai_message(streamed_answer)
  206. logging.info(f"Answer: {streamed_answer}")
  207. def dry_run(self, input_query, config: QueryConfig = None):
  208. """
  209. A dry run does everything except send the resulting prompt to
  210. the LLM. The purpose is to test the prompt, not the response.
  211. You can use it to test your prompt, including the context provided
  212. by the vector database's doc retrieval.
  213. The only thing the dry run does not consider is the cut-off due to
  214. the `max_tokens` parameter.
  215. :param input_query: The query to use.
  216. :param config: Optional. The `QueryConfig` instance to use as configuration options.
  217. :return: The prompt that would be sent to the LLM
  218. """
  219. if config is None:
  220. config = QueryConfig()
  221. context = self.retrieve_from_database(input_query)
  222. prompt = self.generate_prompt(input_query, context, config.template)
  223. logging.info(f"Prompt: {prompt}")
  224. return prompt
  225. def count(self):
  226. """
  227. Count the number of embeddings.
  228. :return: The number of embeddings.
  229. """
  230. return self.collection.count()
  231. def reset(self):
  232. """
  233. Resets the database. Deletes all embeddings irreversibly.
  234. `App` has to be reinitialized after using this method.
  235. """
  236. self.db_client.reset()
  237. class App(EmbedChain):
  238. """
  239. The EmbedChain app.
  240. Has two functions: add and query.
  241. adds(data_type, url): adds the data from the given URL to the vector db.
  242. query(query): finds answer to the given query using vector database and LLM.
  243. dry_run(query): test your prompt without consuming tokens.
  244. """
  245. def __init__(self, config: InitConfig = None):
  246. """
  247. :param config: InitConfig instance to load as configuration. Optional.
  248. """
  249. if config is None:
  250. config = InitConfig()
  251. super().__init__(config)
  252. def get_llm_model_answer(self, prompt, config: ChatConfig):
  253. messages = []
  254. messages.append({
  255. "role": "user", "content": prompt
  256. })
  257. response = openai.ChatCompletion.create(
  258. model="gpt-3.5-turbo-0613",
  259. messages=messages,
  260. temperature=0,
  261. max_tokens=1000,
  262. top_p=1,
  263. stream=config.stream
  264. )
  265. if config.stream:
  266. return self._stream_llm_model_response(response)
  267. else:
  268. return response["choices"][0]["message"]["content"]
  269. def _stream_llm_model_response(self, response):
  270. """
  271. This is a generator for streaming response from the OpenAI completions API
  272. """
  273. for line in response:
  274. chunk = line['choices'][0].get('delta', {}).get('content', '')
  275. yield chunk
  276. class OpenSourceApp(EmbedChain):
  277. """
  278. The OpenSource app.
  279. Same as App, but uses an open source embedding model and LLM.
  280. Has two function: add and query.
  281. adds(data_type, url): adds the data from the given URL to the vector db.
  282. query(query): finds answer to the given query using vector database and LLM.
  283. """
  284. def __init__(self, config: InitConfig = None):
  285. """
  286. :param config: InitConfig instance to load as configuration. Optional. `ef` defaults to open source.
  287. """
  288. print("Loading open source embedding model. This may take some time...")
  289. if not config:
  290. config = InitConfig(
  291. ef = embedding_functions.SentenceTransformerEmbeddingFunction(
  292. model_name="all-MiniLM-L6-v2"
  293. )
  294. )
  295. elif not config.ef:
  296. config._set_embedding_function(
  297. embedding_functions.SentenceTransformerEmbeddingFunction(
  298. model_name="all-MiniLM-L6-v2"
  299. ))
  300. print("Successfully loaded open source embedding model.")
  301. super().__init__(config)
  302. def get_llm_model_answer(self, prompt):
  303. from gpt4all import GPT4All
  304. global gpt4all_model
  305. if gpt4all_model is None:
  306. gpt4all_model = GPT4All("orca-mini-3b.ggmlv3.q4_0.bin")
  307. response = gpt4all_model.generate(
  308. prompt=prompt,
  309. )
  310. return response
  311. class EmbedChainPersonApp:
  312. """
  313. Base class to create a person bot.
  314. This bot behaves and speaks like a person.
  315. :param person: name of the person, better if its a well known person.
  316. :param config: InitConfig instance to load as configuration.
  317. """
  318. def __init__(self, person, config: InitConfig = None):
  319. self.person = person
  320. self.person_prompt = f"You are {person}. Whatever you say, you will always say in {person} style."
  321. self.template = Template(
  322. self.person_prompt + " " + DEFAULT_PROMPT
  323. )
  324. if config is None:
  325. config = InitConfig()
  326. super().__init__(config)
  327. class PersonApp(EmbedChainPersonApp, App):
  328. """
  329. The Person app.
  330. Extends functionality from EmbedChainPersonApp and App
  331. """
  332. def query(self, input_query, config: QueryConfig = None):
  333. query_config = QueryConfig(
  334. template=self.template,
  335. )
  336. return super().query(input_query, query_config)
  337. def chat(self, input_query, config: ChatConfig = None):
  338. chat_config = ChatConfig(
  339. template = self.template,
  340. )
  341. return super().chat(input_query, chat_config)
  342. class PersonOpenSourceApp(EmbedChainPersonApp, OpenSourceApp):
  343. """
  344. The Person app.
  345. Extends functionality from EmbedChainPersonApp and OpenSourceApp
  346. """
  347. def query(self, input_query, config: QueryConfig = None):
  348. query_config = QueryConfig(
  349. template=self.template,
  350. )
  351. return super().query(input_query, query_config)
  352. def chat(self, input_query, config: ChatConfig = None):
  353. chat_config = ChatConfig(
  354. template = self.template,
  355. )
  356. return super().chat(input_query, chat_config)