utils.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import os
  2. import re
  3. import logging
  4. from typing import List
  5. import requests
  6. from huggingface_hub import snapshot_download
  7. from config import SRC_LOG_LEVELS, CHROMA_CLIENT
  8. log = logging.getLogger(__name__)
  9. log.setLevel(SRC_LOG_LEVELS["RAG"])
  10. def query_doc(collection_name: str, query: str, k: int, embedding_function):
  11. try:
  12. # if you use docker use the model from the environment variable
  13. collection = CHROMA_CLIENT.get_collection(
  14. name=collection_name,
  15. embedding_function=embedding_function,
  16. )
  17. result = collection.query(
  18. query_texts=[query],
  19. n_results=k,
  20. )
  21. return result
  22. except Exception as e:
  23. raise e
  24. def query_embeddings_doc(collection_name: str, query_embeddings, k: int):
  25. try:
  26. # if you use docker use the model from the environment variable
  27. log.info("query_embeddings_doc", query_embeddings)
  28. collection = CHROMA_CLIENT.get_collection(
  29. name=collection_name,
  30. )
  31. result = collection.query(
  32. query_embeddings=[query_embeddings],
  33. n_results=k,
  34. )
  35. return result
  36. except Exception as e:
  37. raise e
  38. def merge_and_sort_query_results(query_results, k):
  39. # Initialize lists to store combined data
  40. combined_ids = []
  41. combined_distances = []
  42. combined_metadatas = []
  43. combined_documents = []
  44. # Combine data from each dictionary
  45. for data in query_results:
  46. combined_ids.extend(data["ids"][0])
  47. combined_distances.extend(data["distances"][0])
  48. combined_metadatas.extend(data["metadatas"][0])
  49. combined_documents.extend(data["documents"][0])
  50. # Create a list of tuples (distance, id, metadata, document)
  51. combined = list(
  52. zip(combined_distances, combined_ids, combined_metadatas, combined_documents)
  53. )
  54. # Sort the list based on distances
  55. combined.sort(key=lambda x: x[0])
  56. # Unzip the sorted list
  57. sorted_distances, sorted_ids, sorted_metadatas, sorted_documents = zip(*combined)
  58. # Slicing the lists to include only k elements
  59. sorted_distances = list(sorted_distances)[:k]
  60. sorted_ids = list(sorted_ids)[:k]
  61. sorted_metadatas = list(sorted_metadatas)[:k]
  62. sorted_documents = list(sorted_documents)[:k]
  63. # Create the output dictionary
  64. merged_query_results = {
  65. "ids": [sorted_ids],
  66. "distances": [sorted_distances],
  67. "metadatas": [sorted_metadatas],
  68. "documents": [sorted_documents],
  69. "embeddings": None,
  70. "uris": None,
  71. "data": None,
  72. }
  73. return merged_query_results
  74. def query_collection(
  75. collection_names: List[str], query: str, k: int, embedding_function
  76. ):
  77. results = []
  78. for collection_name in collection_names:
  79. try:
  80. # if you use docker use the model from the environment variable
  81. collection = CHROMA_CLIENT.get_collection(
  82. name=collection_name,
  83. embedding_function=embedding_function,
  84. )
  85. result = collection.query(
  86. query_texts=[query],
  87. n_results=k,
  88. )
  89. results.append(result)
  90. except:
  91. pass
  92. return merge_and_sort_query_results(results, k)
  93. def query_embeddings_collection(collection_names: List[str], query_embeddings, k: int):
  94. results = []
  95. log.info("query_embeddings_collection", query_embeddings)
  96. for collection_name in collection_names:
  97. try:
  98. collection = CHROMA_CLIENT.get_collection(name=collection_name)
  99. result = collection.query(
  100. query_embeddings=[query_embeddings],
  101. n_results=k,
  102. )
  103. results.append(result)
  104. except:
  105. pass
  106. return merge_and_sort_query_results(results, k)
  107. def rag_template(template: str, context: str, query: str):
  108. template = template.replace("[context]", context)
  109. template = template.replace("[query]", query)
  110. return template
  111. def rag_messages(docs, messages, template, k, embedding_function):
  112. log.debug(f"docs: {docs}")
  113. last_user_message_idx = None
  114. for i in range(len(messages) - 1, -1, -1):
  115. if messages[i]["role"] == "user":
  116. last_user_message_idx = i
  117. break
  118. user_message = messages[last_user_message_idx]
  119. if isinstance(user_message["content"], list):
  120. # Handle list content input
  121. content_type = "list"
  122. query = ""
  123. for content_item in user_message["content"]:
  124. if content_item["type"] == "text":
  125. query = content_item["text"]
  126. break
  127. elif isinstance(user_message["content"], str):
  128. # Handle text content input
  129. content_type = "text"
  130. query = user_message["content"]
  131. else:
  132. # Fallback in case the input does not match expected types
  133. content_type = None
  134. query = ""
  135. relevant_contexts = []
  136. for doc in docs:
  137. context = None
  138. try:
  139. if doc["type"] == "collection":
  140. context = query_collection(
  141. collection_names=doc["collection_names"],
  142. query=query,
  143. k=k,
  144. embedding_function=embedding_function,
  145. )
  146. elif doc["type"] == "text":
  147. context = doc["content"]
  148. else:
  149. context = query_doc(
  150. collection_name=doc["collection_name"],
  151. query=query,
  152. k=k,
  153. embedding_function=embedding_function,
  154. )
  155. except Exception as e:
  156. log.exception(e)
  157. context = None
  158. relevant_contexts.append(context)
  159. log.debug(f"relevant_contexts: {relevant_contexts}")
  160. context_string = ""
  161. for context in relevant_contexts:
  162. if context:
  163. context_string += " ".join(context["documents"][0]) + "\n"
  164. ra_content = rag_template(
  165. template=template,
  166. context=context_string,
  167. query=query,
  168. )
  169. if content_type == "list":
  170. new_content = []
  171. for content_item in user_message["content"]:
  172. if content_item["type"] == "text":
  173. # Update the text item's content with ra_content
  174. new_content.append({"type": "text", "text": ra_content})
  175. else:
  176. # Keep other types of content as they are
  177. new_content.append(content_item)
  178. new_user_message = {**user_message, "content": new_content}
  179. else:
  180. new_user_message = {
  181. **user_message,
  182. "content": ra_content,
  183. }
  184. messages[last_user_message_idx] = new_user_message
  185. return messages
  186. def get_embedding_model_path(
  187. embedding_model: str, update_embedding_model: bool = False
  188. ):
  189. # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
  190. cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
  191. local_files_only = not update_embedding_model
  192. snapshot_kwargs = {
  193. "cache_dir": cache_dir,
  194. "local_files_only": local_files_only,
  195. }
  196. log.debug(f"embedding_model: {embedding_model}")
  197. log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
  198. # Inspiration from upstream sentence_transformers
  199. if (
  200. os.path.exists(embedding_model)
  201. or ("\\" in embedding_model or embedding_model.count("/") > 1)
  202. and local_files_only
  203. ):
  204. # If fully qualified path exists, return input, else set repo_id
  205. return embedding_model
  206. elif "/" not in embedding_model:
  207. # Set valid repo_id for model short-name
  208. embedding_model = "sentence-transformers" + "/" + embedding_model
  209. snapshot_kwargs["repo_id"] = embedding_model
  210. # Attempt to query the huggingface_hub library to determine the local path and/or to update
  211. try:
  212. embedding_model_repo_path = snapshot_download(**snapshot_kwargs)
  213. log.debug(f"embedding_model_repo_path: {embedding_model_repo_path}")
  214. return embedding_model_repo_path
  215. except Exception as e:
  216. log.exception(f"Cannot determine embedding model snapshot path: {e}")
  217. return embedding_model
  218. def generate_openai_embeddings(
  219. model: str, text: str, key: str, url: str = "https://api.openai.com"
  220. ):
  221. try:
  222. r = requests.post(
  223. f"{url}/v1/embeddings",
  224. headers={
  225. "Content-Type": "application/json",
  226. "Authorization": f"Bearer {key}",
  227. },
  228. json={"input": text, "model": model},
  229. )
  230. r.raise_for_status()
  231. data = r.json()
  232. if "data" in data:
  233. return data["data"][0]["embedding"]
  234. else:
  235. raise "Something went wrong :/"
  236. except Exception as e:
  237. print(e)
  238. return None