embedchain.py 16 KB

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