embedchain.py 15 KB

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