embedchain.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import openai
  2. import os
  3. from string import Template
  4. from chromadb.utils import embedding_functions
  5. from dotenv import load_dotenv
  6. from langchain.docstore.document import Document
  7. from langchain.embeddings.openai import OpenAIEmbeddings
  8. from langchain.memory import ConversationBufferMemory
  9. from embedchain.config import InitConfig, AddConfig, QueryConfig, ChatConfig
  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 options.
  36. """
  37. if config is None:
  38. config = AddConfig()
  39. data_formatter = DataFormatter(data_type)
  40. self.user_asks.append([data_type, url])
  41. self.load_and_embed(data_formatter.loader, data_formatter.chunker, url)
  42. def add_local(self, data_type, content, config: AddConfig = None):
  43. """
  44. Adds the data you supply to the vector db.
  45. Loads the data, chunks it, create embedding for each chunk
  46. and then stores the embedding to vector database.
  47. :param data_type: The type of the data to add.
  48. :param content: The local data. Refer to the `README` for formatting.
  49. :param config: Optional. The `AddConfig` instance to use as configuration options.
  50. """
  51. if config is None:
  52. config = AddConfig()
  53. data_formatter = DataFormatter(data_type)
  54. self.user_asks.append([data_type, content])
  55. self.load_and_embed(data_formatter.loader, data_formatter.chunker, content)
  56. def load_and_embed(self, loader, chunker, src):
  57. """
  58. Loads the data from the given URL, chunks it, and adds it to the database.
  59. :param loader: The loader to use to load the data.
  60. :param chunker: The chunker to use to chunk the data.
  61. :param src: The data to be handled by the loader. Can be a URL for remote sources or local content for local loaders.
  62. """
  63. embeddings_data = chunker.create_chunks(loader, src)
  64. documents = embeddings_data["documents"]
  65. metadatas = embeddings_data["metadatas"]
  66. ids = embeddings_data["ids"]
  67. # get existing ids, and discard doc if any common id exist.
  68. existing_docs = self.collection.get(
  69. ids=ids,
  70. # where={"url": src}
  71. )
  72. existing_ids = set(existing_docs["ids"])
  73. if len(existing_ids):
  74. data_dict = {id: (doc, meta) for id, doc, meta in zip(ids, documents, metadatas)}
  75. data_dict = {id: value for id, value in data_dict.items() if id not in existing_ids}
  76. if not data_dict:
  77. print(f"All data from {src} already exists in the database.")
  78. return
  79. ids = list(data_dict.keys())
  80. documents, metadatas = zip(*data_dict.values())
  81. chunks_before_addition = self.count()
  82. self.collection.add(
  83. documents=documents,
  84. metadatas=list(metadatas),
  85. ids=ids
  86. )
  87. print(f"Successfully saved {src}. New chunks count: {self.count() - chunks_before_addition}")
  88. def _format_result(self, results):
  89. return [
  90. (Document(page_content=result[0], metadata=result[1] or {}), result[2])
  91. for result in zip(
  92. results["documents"][0],
  93. results["metadatas"][0],
  94. results["distances"][0],
  95. )
  96. ]
  97. def get_llm_model_answer(self, prompt):
  98. raise NotImplementedError
  99. def retrieve_from_database(self, input_query):
  100. """
  101. Queries the vector database based on the given input query.
  102. Gets relevant doc based on the query
  103. :param input_query: The query to use.
  104. :return: The content of the document that matched your query.
  105. """
  106. result = self.collection.query(
  107. query_texts=[input_query,],
  108. n_results=1,
  109. )
  110. result_formatted = self._format_result(result)
  111. if result_formatted:
  112. content = result_formatted[0][0].page_content
  113. else:
  114. content = ""
  115. return content
  116. def generate_prompt(self, input_query, context, template: Template = None):
  117. """
  118. Generates a prompt based on the given query and context, ready to be passed to an LLM
  119. :param input_query: The query to use.
  120. :param context: Similar documents to the query used as context.
  121. :param template: Optional. The `Template` instance to use as a template for prompt.
  122. :return: The prompt
  123. """
  124. prompt = template.substitute(context = context, query = input_query)
  125. return prompt
  126. def get_answer_from_llm(self, prompt):
  127. """
  128. Gets an answer based on the given query and context by passing it
  129. to an LLM.
  130. :param query: The query to use.
  131. :param context: Similar documents to the query used as context.
  132. :return: The answer.
  133. """
  134. answer = self.get_llm_model_answer(prompt)
  135. return answer
  136. def query(self, input_query, config: QueryConfig = None):
  137. """
  138. Queries the vector database based on the given input query.
  139. Gets relevant doc based on the query and then passes it to an
  140. LLM as context to get the answer.
  141. :param input_query: The query to use.
  142. :param config: Optional. The `QueryConfig` instance to use as configuration options.
  143. :return: The answer to the query.
  144. """
  145. if config is None:
  146. config = QueryConfig()
  147. context = self.retrieve_from_database(input_query)
  148. prompt = self.generate_prompt(input_query, context, config.template)
  149. answer = self.get_answer_from_llm(prompt)
  150. return answer
  151. def generate_chat_prompt(self, input_query, context, chat_history=''):
  152. """
  153. Generates a prompt based on the given query, context and chat history
  154. for chat interface. This is then passed to an LLM.
  155. :param input_query: The query to use.
  156. :param context: Similar documents to the query used as context.
  157. :param chat_history: User and bot conversation that happened before.
  158. :return: The prompt
  159. """
  160. prefix_prompt = f"""You are a chatbot having a conversation with a human. You are given chat history and context. You need to answer the query considering context, chat history and your knowledge base. If you don't know the answer or the answer is neither contained in the context nor in history, then simply say "I don't know"."""
  161. chat_history_prompt = f"""\n----\nChat History: {chat_history}\n----"""
  162. suffix_prompt = f"""\n####\nContext: {context}\n####\nQuery: {input_query}\nHelpful Answer:"""
  163. prompt = prefix_prompt
  164. if chat_history:
  165. prompt += chat_history_prompt
  166. prompt += suffix_prompt
  167. return prompt
  168. def chat(self, input_query, config: ChatConfig = None):
  169. """
  170. Queries the vector database on the given input query.
  171. Gets relevant doc based on the query and then passes it to an
  172. LLM as context to get the answer.
  173. Maintains last 5 conversations in memory.
  174. :param input_query: The query to use.
  175. :param config: Optional. The `ChatConfig` instance to use as configuration options.
  176. :return: The answer to the query.
  177. """
  178. if config is None:
  179. config = ChatConfig()
  180. context = self.retrieve_from_database(input_query)
  181. global memory
  182. chat_history = memory.load_memory_variables({})["history"]
  183. prompt = self.generate_chat_prompt(
  184. input_query,
  185. context,
  186. chat_history=chat_history,
  187. )
  188. answer = self.get_answer_from_llm(prompt)
  189. memory.chat_memory.add_user_message(input_query)
  190. memory.chat_memory.add_ai_message(answer)
  191. return 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.template)
  208. return prompt
  209. def count(self):
  210. """
  211. Count the number of embeddings.
  212. :return: The number of embeddings.
  213. """
  214. return self.collection.count()
  215. def reset(self):
  216. """
  217. Resets the database. Deletes all embeddings irreversibly.
  218. `App` has to be reinitialized after using this method.
  219. """
  220. self.db_client.reset()
  221. class App(EmbedChain):
  222. """
  223. The EmbedChain app.
  224. Has two functions: add and query.
  225. adds(data_type, url): adds the data from the given URL to the vector db.
  226. query(query): finds answer to the given query using vector database and LLM.
  227. dry_run(query): test your prompt without consuming tokens.
  228. """
  229. def __init__(self, config: InitConfig = None):
  230. """
  231. :param config: InitConfig instance to load as configuration. Optional.
  232. """
  233. if config is None:
  234. config = InitConfig()
  235. super().__init__(config)
  236. def get_llm_model_answer(self, prompt):
  237. messages = []
  238. messages.append({
  239. "role": "user", "content": prompt
  240. })
  241. response = openai.ChatCompletion.create(
  242. model="gpt-3.5-turbo-0613",
  243. messages=messages,
  244. temperature=0,
  245. max_tokens=1000,
  246. top_p=1,
  247. )
  248. return response["choices"][0]["message"]["content"]
  249. class OpenSourceApp(EmbedChain):
  250. """
  251. The OpenSource app.
  252. Same as App, but uses an open source embedding model and LLM.
  253. Has two function: add and query.
  254. adds(data_type, url): adds the data from the given URL to the vector db.
  255. query(query): finds answer to the given query using vector database and LLM.
  256. """
  257. def __init__(self, config: InitConfig = None):
  258. """
  259. :param config: InitConfig instance to load as configuration. Optional. `ef` defaults to open source.
  260. """
  261. print("Loading open source embedding model. This may take some time...")
  262. if not config:
  263. config = InitConfig(
  264. ef = embedding_functions.SentenceTransformerEmbeddingFunction(
  265. model_name="all-MiniLM-L6-v2"
  266. )
  267. )
  268. elif not config.ef:
  269. config._set_embedding_function(
  270. embedding_functions.SentenceTransformerEmbeddingFunction(
  271. model_name="all-MiniLM-L6-v2"
  272. ))
  273. print("Successfully loaded open source embedding model.")
  274. super().__init__(config)
  275. def get_llm_model_answer(self, prompt):
  276. from gpt4all import GPT4All
  277. global gpt4all_model
  278. if gpt4all_model is None:
  279. gpt4all_model = GPT4All("orca-mini-3b.ggmlv3.q4_0.bin")
  280. response = gpt4all_model.generate(
  281. prompt=prompt,
  282. )
  283. return response
  284. class EmbedChainPersonApp:
  285. """
  286. Base class to create a person bot.
  287. This bot behaves and speaks like a person.
  288. :param person: name of the person, better if its a well known person.
  289. :param config: InitConfig instance to load as configuration.
  290. """
  291. def __init__(self, person, config: InitConfig = None):
  292. self.person = person
  293. self.person_prompt = f"You are {person}. Whatever you say, you will always say in {person} style."
  294. self.template = Template(
  295. self.person_prompt + " " + DEFAULT_PROMPT
  296. )
  297. if config is None:
  298. config = InitConfig()
  299. super().__init__(config)
  300. class PersonApp(EmbedChainPersonApp, App):
  301. """
  302. The Person app.
  303. Extends functionality from EmbedChainPersonApp and App
  304. """
  305. def query(self, input_query, config: QueryConfig = None):
  306. query_config = QueryConfig(
  307. template=self.template,
  308. )
  309. return super().query(input_query, query_config)
  310. def chat(self, input_query, config: ChatConfig = None):
  311. chat_config = ChatConfig(
  312. template = self.template,
  313. )
  314. return super().chat(input_query, chat_config)
  315. class PersonOpenSourceApp(EmbedChainPersonApp, OpenSourceApp):
  316. """
  317. The Person app.
  318. Extends functionality from EmbedChainPersonApp and OpenSourceApp
  319. """
  320. def query(self, input_query, config: QueryConfig = None):
  321. query_config = QueryConfig(
  322. template=self.template,
  323. )
  324. return super().query(input_query, query_config)
  325. def chat(self, input_query, config: ChatConfig = None):
  326. chat_config = ChatConfig(
  327. template = self.template,
  328. )
  329. return super().chat(input_query, chat_config)