embedchain.py 16 KB

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