utils.py 7.96 KB
Newer Older
1
import os
Timothy J. Baek's avatar
Timothy J. Baek committed
2
import re
3
import logging
Timothy J. Baek's avatar
Timothy J. Baek committed
4
from typing import List
5
6
7
import requests


8
from huggingface_hub import snapshot_download
Timothy J. Baek's avatar
Timothy J. Baek committed
9

10
11
12
13
from config import SRC_LOG_LEVELS, CHROMA_CLIENT

log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["RAG"])
Timothy J. Baek's avatar
Timothy J. Baek committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


def query_doc(collection_name: str, query: str, k: int, embedding_function):
    try:
        # if you use docker use the model from the environment variable
        collection = CHROMA_CLIENT.get_collection(
            name=collection_name,
            embedding_function=embedding_function,
        )
        result = collection.query(
            query_texts=[query],
            n_results=k,
        )
        return result
    except Exception as e:
        raise e


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def query_embeddings_doc(collection_name: str, query_embeddings, k: int):
    try:
        # if you use docker use the model from the environment variable
        collection = CHROMA_CLIENT.get_collection(
            name=collection_name,
        )
        result = collection.query(
            query_embeddings=[query_embeddings],
            n_results=k,
        )
        return result
    except Exception as e:
        raise e


Timothy J. Baek's avatar
Timothy J. Baek committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def merge_and_sort_query_results(query_results, k):
    # Initialize lists to store combined data
    combined_ids = []
    combined_distances = []
    combined_metadatas = []
    combined_documents = []

    # Combine data from each dictionary
    for data in query_results:
        combined_ids.extend(data["ids"][0])
        combined_distances.extend(data["distances"][0])
        combined_metadatas.extend(data["metadatas"][0])
        combined_documents.extend(data["documents"][0])

    # Create a list of tuples (distance, id, metadata, document)
    combined = list(
        zip(combined_distances, combined_ids, combined_metadatas, combined_documents)
    )

    # Sort the list based on distances
    combined.sort(key=lambda x: x[0])

    # Unzip the sorted list
    sorted_distances, sorted_ids, sorted_metadatas, sorted_documents = zip(*combined)

    # Slicing the lists to include only k elements
    sorted_distances = list(sorted_distances)[:k]
    sorted_ids = list(sorted_ids)[:k]
    sorted_metadatas = list(sorted_metadatas)[:k]
    sorted_documents = list(sorted_documents)[:k]

    # Create the output dictionary
    merged_query_results = {
        "ids": [sorted_ids],
        "distances": [sorted_distances],
        "metadatas": [sorted_metadatas],
        "documents": [sorted_documents],
        "embeddings": None,
        "uris": None,
        "data": None,
    }

    return merged_query_results


def query_collection(
    collection_names: List[str], query: str, k: int, embedding_function
):

    results = []

    for collection_name in collection_names:
        try:
            # if you use docker use the model from the environment variable
            collection = CHROMA_CLIENT.get_collection(
                name=collection_name,
                embedding_function=embedding_function,
            )

            result = collection.query(
                query_texts=[query],
                n_results=k,
            )
            results.append(result)
        except:
            pass

    return merge_and_sort_query_results(results, k)
Timothy J. Baek's avatar
Timothy J. Baek committed
115
116


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def query_embeddings_collection(collection_names: List[str], query_embeddings, k: int):

    results = []
    for collection_name in collection_names:
        try:
            collection = CHROMA_CLIENT.get_collection(name=collection_name)

            result = collection.query(
                query_embeddings=[query_embeddings],
                n_results=k,
            )
            results.append(result)
        except:
            pass

    return merge_and_sort_query_results(results, k)


Timothy J. Baek's avatar
Timothy J. Baek committed
135
def rag_template(template: str, context: str, query: str):
136
137
    template = template.replace("[context]", context)
    template = template.replace("[query]", query)
Timothy J. Baek's avatar
Timothy J. Baek committed
138
    return template
Timothy J. Baek's avatar
Timothy J. Baek committed
139
140
141


def rag_messages(docs, messages, template, k, embedding_function):
142
    log.debug(f"docs: {docs}")
Timothy J. Baek's avatar
Timothy J. Baek committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

    last_user_message_idx = None
    for i in range(len(messages) - 1, -1, -1):
        if messages[i]["role"] == "user":
            last_user_message_idx = i
            break

    user_message = messages[last_user_message_idx]

    if isinstance(user_message["content"], list):
        # Handle list content input
        content_type = "list"
        query = ""
        for content_item in user_message["content"]:
            if content_item["type"] == "text":
                query = content_item["text"]
                break
    elif isinstance(user_message["content"], str):
        # Handle text content input
        content_type = "text"
        query = user_message["content"]
    else:
        # Fallback in case the input does not match expected types
        content_type = None
        query = ""

    relevant_contexts = []

    for doc in docs:
        context = None

        try:
            if doc["type"] == "collection":
                context = query_collection(
                    collection_names=doc["collection_names"],
                    query=query,
                    k=k,
                    embedding_function=embedding_function,
                )
182
183
            elif doc["type"] == "text":
                context = doc["content"]
Timothy J. Baek's avatar
Timothy J. Baek committed
184
185
186
187
188
189
190
191
            else:
                context = query_doc(
                    collection_name=doc["collection_name"],
                    query=query,
                    k=k,
                    embedding_function=embedding_function,
                )
        except Exception as e:
192
            log.exception(e)
Timothy J. Baek's avatar
Timothy J. Baek committed
193
194
195
196
            context = None

        relevant_contexts.append(context)

Timothy J. Baek's avatar
Timothy J. Baek committed
197
198
    log.debug(f"relevant_contexts: {relevant_contexts}")

Timothy J. Baek's avatar
Timothy J. Baek committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
    context_string = ""
    for context in relevant_contexts:
        if context:
            context_string += " ".join(context["documents"][0]) + "\n"

    ra_content = rag_template(
        template=template,
        context=context_string,
        query=query,
    )

    if content_type == "list":
        new_content = []
        for content_item in user_message["content"]:
            if content_item["type"] == "text":
                # Update the text item's content with ra_content
                new_content.append({"type": "text", "text": ra_content})
            else:
                # Keep other types of content as they are
                new_content.append(content_item)
        new_user_message = {**user_message, "content": new_content}
    else:
        new_user_message = {
            **user_message,
            "content": ra_content,
        }

    messages[last_user_message_idx] = new_user_message

    return messages
229

Self Denial's avatar
Self Denial committed
230

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
231
def get_embedding_model_path(
Self Denial's avatar
Self Denial committed
232
233
    embedding_model: str, update_embedding_model: bool = False
):
234
235
    # Construct huggingface_hub kwargs with local_files_only to return the snapshot path
    cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
236

237
    local_files_only = not update_embedding_model
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
238

239
240
241
242
243
244
    snapshot_kwargs = {
        "cache_dir": cache_dir,
        "local_files_only": local_files_only,
    }

    log.debug(f"embedding_model: {embedding_model}")
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
245
    log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
246
247

    # Inspiration from upstream sentence_transformers
Self Denial's avatar
Self Denial committed
248
249
250
251
252
    if (
        os.path.exists(embedding_model)
        or ("\\" in embedding_model or embedding_model.count("/") > 1)
        and local_files_only
    ):
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        # If fully qualified path exists, return input, else set repo_id
        return embedding_model
    elif "/" not in embedding_model:
        # Set valid repo_id for model short-name
        embedding_model = "sentence-transformers" + "/" + embedding_model

    snapshot_kwargs["repo_id"] = embedding_model

    # Attempt to query the huggingface_hub library to determine the local path and/or to update
    try:
        embedding_model_repo_path = snapshot_download(**snapshot_kwargs)
        log.debug(f"embedding_model_repo_path: {embedding_model_repo_path}")
        return embedding_model_repo_path
    except Exception as e:
        log.exception(f"Cannot determine embedding model snapshot path: {e}")
        return embedding_model