utils.py 7.0 KB

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