embedchain.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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=[
  127. input_query,
  128. ],
  129. n_results=config.number_documents,
  130. where=where,
  131. )
  132. results_formatted = self._format_result(result)
  133. contents = [result[0].page_content for result in results_formatted]
  134. return contents
  135. def generate_prompt(self, input_query, contexts, config: QueryConfig):
  136. """
  137. Generates a prompt based on the given query and context, ready to be
  138. passed to an LLM
  139. :param input_query: The query to use.
  140. :param contexts: List of similar documents to the query used as context.
  141. :param config: Optional. The `QueryConfig` instance to use as
  142. configuration options.
  143. :return: The prompt
  144. """
  145. context_string = (" | ").join(contexts)
  146. if not config.history:
  147. prompt = config.template.substitute(context=context_string, query=input_query)
  148. else:
  149. prompt = config.template.substitute(context=context_string, query=input_query, history=config.history)
  150. return prompt
  151. def get_answer_from_llm(self, prompt, config: ChatConfig):
  152. """
  153. Gets an answer based on the given query and context by passing it
  154. to an LLM.
  155. :param query: The query to use.
  156. :param context: Similar documents to the query used as context.
  157. :return: The answer.
  158. """
  159. return self.get_llm_model_answer(prompt, config)
  160. def query(self, input_query, config: QueryConfig = None):
  161. """
  162. Queries the vector database based on the given input query.
  163. Gets relevant doc based on the query and then passes it to an
  164. LLM as context to get the answer.
  165. :param input_query: The query to use.
  166. :param config: Optional. The `QueryConfig` instance to use as
  167. configuration options.
  168. :return: The answer to the query.
  169. """
  170. if config is None:
  171. config = QueryConfig()
  172. if self.is_code_docs_instance:
  173. config.template = CODE_DOCS_PAGE_PROMPT_TEMPLATE
  174. config.number_documents = 5
  175. contexts = self.retrieve_from_database(input_query, config)
  176. prompt = self.generate_prompt(input_query, contexts, config)
  177. logging.info(f"Prompt: {prompt}")
  178. answer = self.get_answer_from_llm(prompt, config)
  179. if isinstance(answer, str):
  180. logging.info(f"Answer: {answer}")
  181. return answer
  182. else:
  183. return self._stream_query_response(answer)
  184. def _stream_query_response(self, answer):
  185. streamed_answer = ""
  186. for chunk in answer:
  187. streamed_answer = streamed_answer + chunk
  188. yield chunk
  189. logging.info(f"Answer: {streamed_answer}")
  190. def chat(self, input_query, config: ChatConfig = None):
  191. """
  192. Queries the vector database on the given input query.
  193. Gets relevant doc based on the query and then passes it to an
  194. LLM as context to get the answer.
  195. Maintains the whole conversation in memory.
  196. :param input_query: The query to use.
  197. :param config: Optional. The `ChatConfig` instance to use as
  198. configuration options.
  199. :return: The answer to the query.
  200. """
  201. if config is None:
  202. config = ChatConfig()
  203. if self.is_code_docs_instance:
  204. config.template = CODE_DOCS_PAGE_PROMPT_TEMPLATE
  205. config.number_documents = 5
  206. contexts = self.retrieve_from_database(input_query, config)
  207. global memory
  208. chat_history = memory.load_memory_variables({})["history"]
  209. if chat_history:
  210. config.set_history(chat_history)
  211. prompt = self.generate_prompt(input_query, contexts, config)
  212. logging.info(f"Prompt: {prompt}")
  213. answer = self.get_answer_from_llm(prompt, config)
  214. memory.chat_memory.add_user_message(input_query)
  215. if isinstance(answer, str):
  216. memory.chat_memory.add_ai_message(answer)
  217. logging.info(f"Answer: {answer}")
  218. return answer
  219. else:
  220. # this is a streamed response and needs to be handled differently.
  221. return self._stream_chat_response(answer)
  222. def _stream_chat_response(self, answer):
  223. streamed_answer = ""
  224. for chunk in answer:
  225. streamed_answer = streamed_answer + chunk
  226. yield chunk
  227. memory.chat_memory.add_ai_message(streamed_answer)
  228. logging.info(f"Answer: {streamed_answer}")
  229. def dry_run(self, input_query, config: QueryConfig = None):
  230. """
  231. A dry run does everything except send the resulting prompt to
  232. the LLM. The purpose is to test the prompt, not the response.
  233. You can use it to test your prompt, including the context provided
  234. by the vector database's doc retrieval.
  235. The only thing the dry run does not consider is the cut-off due to
  236. the `max_tokens` parameter.
  237. :param input_query: The query to use.
  238. :param config: Optional. The `QueryConfig` instance to use as
  239. configuration options.
  240. :return: The prompt that would be sent to the LLM
  241. """
  242. if config is None:
  243. config = QueryConfig()
  244. contexts = self.retrieve_from_database(input_query, config)
  245. prompt = self.generate_prompt(input_query, contexts, config)
  246. logging.info(f"Prompt: {prompt}")
  247. return prompt
  248. def count(self):
  249. """
  250. Count the number of embeddings.
  251. :return: The number of embeddings.
  252. """
  253. return self.collection.count()
  254. def reset(self):
  255. """
  256. Resets the database. Deletes all embeddings irreversibly.
  257. `App` has to be reinitialized after using this method.
  258. """
  259. self.db_client.reset()
  260. class App(EmbedChain):
  261. """
  262. The EmbedChain app.
  263. Has two functions: add and query.
  264. adds(data_type, url): adds the data from the given URL to the vector db.
  265. query(query): finds answer to the given query using vector database and LLM.
  266. dry_run(query): test your prompt without consuming tokens.
  267. """
  268. def __init__(self, config: InitConfig = None):
  269. """
  270. :param config: InitConfig instance to load as configuration. Optional.
  271. """
  272. if config is None:
  273. config = InitConfig()
  274. if not config.ef:
  275. config._set_embedding_function_to_default()
  276. if not config.db:
  277. config._set_db_to_default()
  278. super().__init__(config)
  279. def get_llm_model_answer(self, prompt, config: ChatConfig):
  280. messages = []
  281. messages.append({"role": "user", "content": prompt})
  282. response = openai.ChatCompletion.create(
  283. model=config.model,
  284. messages=messages,
  285. temperature=config.temperature,
  286. max_tokens=config.max_tokens,
  287. top_p=config.top_p,
  288. stream=config.stream,
  289. )
  290. if config.stream:
  291. return self._stream_llm_model_response(response)
  292. else:
  293. return response["choices"][0]["message"]["content"]
  294. def _stream_llm_model_response(self, response):
  295. """
  296. This is a generator for streaming response from the OpenAI completions API
  297. """
  298. for line in response:
  299. chunk = line["choices"][0].get("delta", {}).get("content", "")
  300. yield chunk
  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.
  312. `ef` defaults to open source.
  313. """
  314. print("Loading open source embedding model. This may take some time...") # noqa:E501
  315. if not config:
  316. config = InitConfig()
  317. if not config.ef:
  318. config._set_embedding_function(
  319. embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
  320. )
  321. if not config.db:
  322. config._set_db_to_default()
  323. print("Successfully loaded open source embedding model.")
  324. super().__init__(config)
  325. def get_llm_model_answer(self, prompt, config: ChatConfig):
  326. from gpt4all import GPT4All
  327. global gpt4all_model
  328. if gpt4all_model is None:
  329. gpt4all_model = GPT4All("orca-mini-3b.ggmlv3.q4_0.bin")
  330. response = gpt4all_model.generate(prompt=prompt, streaming=config.stream)
  331. return response
  332. class EmbedChainPersonApp:
  333. """
  334. Base class to create a person bot.
  335. This bot behaves and speaks like a person.
  336. :param person: name of the person, better if its a well known person.
  337. :param config: InitConfig instance to load as configuration.
  338. """
  339. def __init__(self, person, config: InitConfig = None):
  340. self.person = person
  341. self.person_prompt = f"You are {person}. Whatever you say, you will always say in {person} style." # noqa:E501
  342. self.template = Template(self.person_prompt + " " + DEFAULT_PROMPT)
  343. if config is None:
  344. config = InitConfig()
  345. super().__init__(config)
  346. class PersonApp(EmbedChainPersonApp, App):
  347. """
  348. The Person app.
  349. Extends functionality from EmbedChainPersonApp and App
  350. """
  351. def query(self, input_query, config: QueryConfig = None):
  352. query_config = QueryConfig(
  353. template=self.template,
  354. )
  355. return super().query(input_query, query_config)
  356. def chat(self, input_query, config: ChatConfig = None):
  357. chat_config = ChatConfig(
  358. template=self.template,
  359. )
  360. return super().chat(input_query, chat_config)
  361. class PersonOpenSourceApp(EmbedChainPersonApp, OpenSourceApp):
  362. """
  363. The Person app.
  364. Extends functionality from EmbedChainPersonApp and OpenSourceApp
  365. """
  366. def query(self, input_query, config: QueryConfig = None):
  367. query_config = QueryConfig(
  368. template=self.template,
  369. )
  370. return super().query(input_query, query_config)
  371. def chat(self, input_query, config: ChatConfig = None):
  372. chat_config = ChatConfig(
  373. template=self.template,
  374. )
  375. return super().chat(input_query, chat_config)