utils.py 12.2 KB
Newer Older
1
import logging
2
3
import requests

4
from typing import List
5

6
7
8
9
from apps.ollama.main import (
    generate_ollama_embeddings,
    GenerateEmbeddingsForm,
)
Timothy J. Baek's avatar
Timothy J. Baek committed
10

11
12
from langchain_core.documents import Document
from langchain_community.retrievers import BM25Retriever
Steven Kreitzer's avatar
Steven Kreitzer committed
13
from langchain.retrievers import (
14
    ContextualCompressionRetriever,
Steven Kreitzer's avatar
Steven Kreitzer committed
15
16
17
    EnsembleRetriever,
)

18
19
from config import SRC_LOG_LEVELS, CHROMA_CLIENT

20

21
22
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["RAG"])
Timothy J. Baek's avatar
Timothy J. Baek committed
23
24


Steven Kreitzer's avatar
Steven Kreitzer committed
25
26
27
28
def query_embeddings_doc(
    collection_name: str,
    query: str,
    k: int,
29
    r: float,
Steven Kreitzer's avatar
Steven Kreitzer committed
30
31
32
    embeddings_function,
    reranking_function,
):
33
34
    try:
        # if you use docker use the model from the environment variable
35
36
        collection = CHROMA_CLIENT.get_collection(name=collection_name)

37
        documents = collection.get()  # get all documents
Steven Kreitzer's avatar
Steven Kreitzer committed
38
39
40
41
42
43
44
45
46
        bm25_retriever = BM25Retriever.from_texts(
            texts=documents.get("documents"),
            metadatas=documents.get("metadatas"),
        )
        bm25_retriever.k = k

        chroma_retriever = ChromaRetriever(
            collection=collection,
            embeddings_function=embeddings_function,
47
            top_n=k,
Steven Kreitzer's avatar
Steven Kreitzer committed
48
49
50
        )

        ensemble_retriever = EnsembleRetriever(
51
            retrievers=[bm25_retriever, chroma_retriever], weights=[0.5, 0.5]
52
        )
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
53

54
55
        compressor = RerankCompressor(
            embeddings_function=embeddings_function,
Steven Kreitzer's avatar
Steven Kreitzer committed
56
            reranking_function=reranking_function,
57
58
            r_score=r,
            top_n=k,
Steven Kreitzer's avatar
Steven Kreitzer committed
59
        )
60
61
62
63
64
65

        compression_retriever = ContextualCompressionRetriever(
            base_compressor=compressor, base_retriever=ensemble_retriever
        )

        result = compression_retriever.invoke(query)
Steven Kreitzer's avatar
Steven Kreitzer committed
66
        result = {
67
68
69
            "distances": [[d.metadata.get("score") for d in result]],
            "documents": [[d.page_content for d in result]],
            "metadatas": [[d.metadata for d in result]],
Steven Kreitzer's avatar
Steven Kreitzer committed
70
71
        }

72
73
74
75
76
        return result
    except Exception as e:
        raise e


Timothy J. Baek's avatar
Timothy J. Baek committed
77
78
79
80
def merge_and_sort_query_results(query_results, k):
    # Initialize lists to store combined data
    combined_distances = []
    combined_documents = []
Steven Kreitzer's avatar
Steven Kreitzer committed
81
    combined_metadatas = []
Timothy J. Baek's avatar
Timothy J. Baek committed
82
83
84
85

    for data in query_results:
        combined_distances.extend(data["distances"][0])
        combined_documents.extend(data["documents"][0])
Steven Kreitzer's avatar
Steven Kreitzer committed
86
        combined_metadatas.extend(data["metadatas"][0])
Timothy J. Baek's avatar
Timothy J. Baek committed
87

Steven Kreitzer's avatar
Steven Kreitzer committed
88
    # Create a list of tuples (distance, document, metadata)
89
    combined = list(zip(combined_distances, combined_documents, combined_metadatas))
Timothy J. Baek's avatar
Timothy J. Baek committed
90
91
92
93

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

94
95
96
97
98
99
100
101
    # We don't have anything :-(
    if not combined:
        sorted_distances = []
        sorted_documents = []
        sorted_metadatas = []
    else:
        # Unzip the sorted list
        sorted_distances, sorted_documents, sorted_metadatas = zip(*combined)
Timothy J. Baek's avatar
Timothy J. Baek committed
102

103
104
105
106
        # Slicing the lists to include only k elements
        sorted_distances = list(sorted_distances)[:k]
        sorted_documents = list(sorted_documents)[:k]
        sorted_metadatas = list(sorted_metadatas)[:k]
Timothy J. Baek's avatar
Timothy J. Baek committed
107
108

    # Create the output dictionary
109
    result = {
Timothy J. Baek's avatar
Timothy J. Baek committed
110
111
        "distances": [sorted_distances],
        "documents": [sorted_documents],
Steven Kreitzer's avatar
Steven Kreitzer committed
112
        "metadatas": [sorted_metadatas],
Timothy J. Baek's avatar
Timothy J. Baek committed
113
114
    }

115
    return result
Timothy J. Baek's avatar
Timothy J. Baek committed
116
117


118
def query_embeddings_collection(
Steven Kreitzer's avatar
Steven Kreitzer committed
119
120
121
    collection_names: List[str],
    query: str,
    k: int,
122
    r: float,
Steven Kreitzer's avatar
Steven Kreitzer committed
123
124
    embeddings_function,
    reranking_function,
Timothy J. Baek's avatar
Timothy J. Baek committed
125
126
):

127
    results = []
Timothy J. Baek's avatar
Timothy J. Baek committed
128

129
130
    for collection_name in collection_names:
        try:
131
132
133
134
            result = query_embeddings_doc(
                collection_name=collection_name,
                query=query,
                k=k,
135
                r=r,
Steven Kreitzer's avatar
Steven Kreitzer committed
136
137
                embeddings_function=embeddings_function,
                reranking_function=reranking_function,
138
139
140
141
142
143
144
145
            )
            results.append(result)
        except:
            pass

    return merge_and_sort_query_results(results, k)


Timothy J. Baek's avatar
Timothy J. Baek committed
146
def rag_template(template: str, context: str, query: str):
147
148
    template = template.replace("[context]", context)
    template = template.replace("[query]", query)
Timothy J. Baek's avatar
Timothy J. Baek committed
149
    return template
Timothy J. Baek's avatar
Timothy J. Baek committed
150
151


Steven Kreitzer's avatar
Steven Kreitzer committed
152
153
154
155
156
157
158
159
160
def query_embeddings_function(
    embedding_engine,
    embedding_model,
    embedding_function,
    openai_key,
    openai_url,
):
    if embedding_engine == "":
        return lambda query: embedding_function.encode(query).tolist()
161
162
163
164
165
166
167
168
169
    elif embedding_engine in ["ollama", "openai"]:
        if embedding_engine == "ollama":
            func = lambda query: generate_ollama_embeddings(
                GenerateEmbeddingsForm(
                    **{
                        "model": embedding_model,
                        "prompt": query,
                    }
                )
Steven Kreitzer's avatar
Steven Kreitzer committed
170
            )
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        elif embedding_engine == "openai":
            func = lambda query: generate_openai_embeddings(
                model=embedding_model,
                text=query,
                key=openai_key,
                url=openai_url,
            )

        def generate_multiple(query, f):
            if isinstance(query, list):
                return [f(q) for q in query]
            else:
                return f(query)

        return lambda query: generate_multiple(query, func)
Steven Kreitzer's avatar
Steven Kreitzer committed
186
187


188
189
190
191
192
def rag_messages(
    docs,
    messages,
    template,
    k,
193
    r,
194
195
196
    embedding_engine,
    embedding_model,
    embedding_function,
Steven Kreitzer's avatar
Steven Kreitzer committed
197
    reranking_function,
198
199
200
    openai_key,
    openai_url,
):
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
201
    log.debug(
Steven Kreitzer's avatar
Steven Kreitzer committed
202
        f"docs: {docs} {messages} {embedding_engine} {embedding_model} {embedding_function} {reranking_function} {openai_key} {openai_url}"
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
203
    )
Timothy J. Baek's avatar
Timothy J. Baek committed
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
229

    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 = ""

230
231
232
233
234
235
236
237
238
    embeddings_function = query_embeddings_function(
        embedding_engine,
        embedding_model,
        embedding_function,
        openai_key,
        openai_url,
    )

    extracted_collections = []
Timothy J. Baek's avatar
Timothy J. Baek committed
239
240
241
242
243
    relevant_contexts = []

    for doc in docs:
        context = None

244
245
246
247
248
249
250
251
252
253
        collection = doc.get("collection_name")
        if collection:
            collection = [collection]
        else:
            collection = doc.get("collection_names", [])

        collection = set(collection).difference(extracted_collections)
        if not collection:
            log.debug(f"skipping {doc} as it has already been extracted")
            continue
254

255
        try:
256
            if doc["type"] == "text":
257
                context = doc["content"]
258
259
260
261
262
263
264
265
266
            elif doc["type"] == "collection":
                context = query_embeddings_collection(
                    collection_names=doc["collection_names"],
                    query=query,
                    k=k,
                    r=r,
                    embeddings_function=embeddings_function,
                    reranking_function=reranking_function,
                )
Timothy J. Baek's avatar
Timothy J. Baek committed
267
            else:
268
269
270
271
272
273
274
                context = query_embeddings_doc(
                    collection_name=doc["collection_name"],
                    query=query,
                    k=k,
                    r=r,
                    embeddings_function=embeddings_function,
                    reranking_function=reranking_function,
Steven Kreitzer's avatar
Steven Kreitzer committed
275
                )
Timothy J. Baek's avatar
Timothy J. Baek committed
276
        except Exception as e:
277
            log.exception(e)
Timothy J. Baek's avatar
Timothy J. Baek committed
278
279
            context = None

280
281
282
283
        if context:
            relevant_contexts.append(context)

        extracted_collections.extend(collection)
Timothy J. Baek's avatar
Timothy J. Baek committed
284

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

Timothy J. Baek's avatar
Timothy J. Baek committed
287
288
    context_string = ""
    for context in relevant_contexts:
289
290
291
        items = context["documents"][0]
        context_string += "\n\n".join(items)
    context_string = context_string.strip()
Timothy J. Baek's avatar
Timothy J. Baek committed
292
293
294
295
296
297
298

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

299
300
    log.debug(f"ra_content: {ra_content}")

Timothy J. Baek's avatar
Timothy J. Baek committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    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
320

Self Denial's avatar
Self Denial committed
321

322
def generate_openai_embeddings(
Timothy J. Baek's avatar
Timothy J. Baek committed
323
    model: str, text: str, key: str, url: str = "https://api.openai.com/v1"
324
325
326
):
    try:
        r = requests.post(
Timothy J. Baek's avatar
Timothy J. Baek committed
327
            f"{url}/embeddings",
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {key}",
            },
            json={"input": text, "model": model},
        )
        r.raise_for_status()
        data = r.json()
        if "data" in data:
            return data["data"][0]["embedding"]
        else:
            raise "Something went wrong :/"
    except Exception as e:
        print(e)
        return None
Steven Kreitzer's avatar
Steven Kreitzer committed
343
344
345
346
347


from typing import Any

from langchain_core.retrievers import BaseRetriever
348
from langchain_core.callbacks import CallbackManagerForRetrieverRun
Steven Kreitzer's avatar
Steven Kreitzer committed
349
350
351
352
353


class ChromaRetriever(BaseRetriever):
    collection: Any
    embeddings_function: Any
354
    top_n: int
Steven Kreitzer's avatar
Steven Kreitzer committed
355
356
357
358
359
360
361
362
363
364
365

    def _get_relevant_documents(
        self,
        query: str,
        *,
        run_manager: CallbackManagerForRetrieverRun,
    ) -> List[Document]:
        query_embeddings = self.embeddings_function(query)

        results = self.collection.query(
            query_embeddings=[query_embeddings],
366
            n_results=self.top_n,
Steven Kreitzer's avatar
Steven Kreitzer committed
367
368
369
370
371
372
373
374
375
376
377
378
379
        )

        ids = results["ids"][0]
        metadatas = results["metadatas"][0]
        documents = results["documents"][0]

        return [
            Document(
                metadata=metadatas[idx],
                page_content=documents[idx],
            )
            for idx in range(len(ids))
        ]
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436


import operator

from typing import Optional, Sequence

from langchain_core.documents import BaseDocumentCompressor, Document
from langchain_core.callbacks import Callbacks
from langchain_core.pydantic_v1 import Extra

from sentence_transformers import util


class RerankCompressor(BaseDocumentCompressor):
    embeddings_function: Any
    reranking_function: Any
    r_score: float
    top_n: int

    class Config:
        extra = Extra.forbid
        arbitrary_types_allowed = True

    def compress_documents(
        self,
        documents: Sequence[Document],
        query: str,
        callbacks: Optional[Callbacks] = None,
    ) -> Sequence[Document]:
        if self.reranking_function:
            scores = self.reranking_function.predict(
                [(query, doc.page_content) for doc in documents]
            )
        else:
            query_embedding = self.embeddings_function(query)
            document_embedding = self.embeddings_function(
                [doc.page_content for doc in documents]
            )
            scores = util.cos_sim(query_embedding, document_embedding)[0]

        docs_with_scores = list(zip(documents, scores.tolist()))
        if self.r_score:
            docs_with_scores = [
                (d, s) for d, s in docs_with_scores if s >= self.r_score
            ]

        result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
        final_results = []
        for doc, doc_score in result[: self.top_n]:
            metadata = doc.metadata
            metadata["score"] = doc_score
            doc = Document(
                page_content=doc.page_content,
                metadata=metadata,
            )
            final_results.append(doc)
        return final_results