embedchain.py 14 KB

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