File size: 12,710 Bytes
1286e81
eebeb78
a1f037d
20e3edd
1286e81
 
b374298
1286e81
 
 
 
2ce5e93
a1f037d
 
 
 
2ce5e93
588b95c
1286e81
 
 
 
91028c0
1286e81
a1f037d
 
 
 
2ce5e93
0eba73c
1286e81
20e3edd
1286e81
a1f037d
 
 
 
 
 
0eba73c
 
a1f037d
 
 
 
 
 
 
1286e81
 
a1f037d
1286e81
d07865c
 
de78af1
3d09051
2ce5e93
 
 
 
0eba73c
 
 
 
 
 
de78af1
6876423
 
e70ffc1
 
c5586ab
 
 
6876423
0cb12f9
78209bc
de78af1
6876423
2ce5e93
a1f037d
0eba73c
6876423
 
 
903083d
78209bc
6876423
0cb12f9
0eba73c
78209bc
6876423
 
c5586ab
78209bc
 
0cb12f9
 
 
0eba73c
6876423
0eba73c
 
 
 
 
0cb12f9
0eba73c
 
 
 
e70ffc1
 
f490f11
e70ffc1
0eba73c
2ce5e93
 
 
 
d07865c
0eba73c
 
e70ffc1
3d09051
2ce5e93
e70ffc1
 
f8e2c8b
3d09051
 
2213315
 
 
 
 
 
 
 
 
 
 
d07865c
3d09051
 
0cb12f9
3d09051
12d3e1a
d07865c
b374298
d07865c
 
 
 
2ce5e93
d07865c
 
b374298
0eba73c
 
 
 
 
 
d07865c
3d09051
 
 
 
 
 
 
 
 
d07865c
0eba73c
d07865c
 
b374298
3d09051
d07865c
 
b374298
0cb12f9
 
 
d07865c
12d3e1a
 
0eba73c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6876423
 
 
 
0eba73c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6876423
0eba73c
 
b909baa
 
 
 
0eba73c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b909baa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0eba73c
 
 
e70ffc1
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import os
from _utils.langchain_utils.LLM_class import LLM
from typing import Any, List, Dict, Tuple, Optional, Union, cast
from anthropic import Anthropic, AsyncAnthropic
import logging
from langchain.schema import Document
from llama_index import Document as Llama_Index_Document
import asyncio
from typing import List
from dataclasses import dataclass

from _utils.gerar_documento_utils.llm_calls import (
    aclaude_answer,
    agemini_answer,
    agpt_answer,
)
from _utils.gerar_documento_utils.prompts import contextual_prompt
from _utils.models.gerar_documento import (
    ContextualizedChunk,
    DocumentChunk,
    RetrievalConfig,
)
from langchain_core.messages import HumanMessage

from gerar_documento.serializer import (
    GerarDocumentoComPDFProprioSerializerData,
    GerarDocumentoSerializerData,
)
from setup.logging import Axiom
import re


class ContextualRetriever:
    def __init__(
        self,
        serializer: Union[
            GerarDocumentoSerializerData, GerarDocumentoComPDFProprioSerializerData, Any
        ],
    ):
        self.lista_contador = []
        self.contextual_retriever_utils = ContextualRetrieverUtils()
        self.config = RetrievalConfig(
            num_chunks=serializer.num_chunks_retrieval,
            embedding_weight=serializer.embedding_weight,
            bm25_weight=serializer.bm25_weight,
            context_window=serializer.context_window,
            chunk_overlap=serializer.chunk_overlap,
        )
        self.logger = logging.getLogger(__name__)
        self.bm25 = None
        self.claude_context_model = serializer.claude_context_model

        self.claude_api_key = os.environ.get("CLAUDE_API_KEY", "")
        self.claude_client = AsyncAnthropic(api_key=self.claude_api_key)

    async def llm_call_uma_lista_de_20_chunks(
        self,
        lista_com_20_chunks: List[DocumentChunk],
        resumo_auxiliar,
        axiom_instance: Axiom,
    ) -> List[List[str]]:

        all_chunks_contents, all_document_ids = (
            self.contextual_retriever_utils.get_all_document_ids_and_contents(
                lista_com_20_chunks
            )
        )
        send_axiom = axiom_instance.send_axiom
        utils = self.contextual_retriever_utils

        try:
            prompt = contextual_prompt(
                resumo_auxiliar, all_chunks_contents, len(lista_com_20_chunks)
            )
            result = None

            for attempt in range(4):
                if attempt != 0:
                    send_axiom(
                        f"------------- FORMATAÇÃO DO CONTEXTUAL INCORRETA - TENTANDO NOVAMENTE (TENTATIVA: {attempt + 1}) -------------"
                    )

                send_axiom(
                    f"COMEÇANDO UMA REQUISIÇÃO DO CONTEXTUAL - TENTATIVA {attempt + 1}"
                )
                raw_response = await agemini_answer(prompt, "gemini-2.0-flash-lite")
                response = cast(str, raw_response)
                send_axiom(
                    f"TERMINOU UMA REQUISIÇÃO DO CONTEXTUAL - TENTATIVA {attempt + 1}"
                )

                matches = utils.validate_many_chunks_in_one_request(
                    response, all_document_ids
                )

                if matches:
                    send_axiom(
                        f"VALIDAÇÃO DO CONTEXTUAL FUNCIONOU NA TENTATIVA {attempt + 1} (ou seja, a função validate_many_chunks_in_one_request)"
                    )

                    result = utils.get_info_from_validated_chunks(matches)

                    break

            if result is None:
                axiom_instance.send_axiom(
                    f"-------------- UMA LISTA DE 20 CHUNKS FALHOU AS 4x NA FORMATAÇÃO ------------- ÚLTIMO RETORNO ERRADO: {response}"
                )
                result = [[""]]  # default value if no iteration succeeded

            return result
        except Exception as e:
            self.logger.error(f"Context generation failed for chunks .... : {str(e)}")
            return [[""]]

    async def contextualize_uma_lista_de_20_chunks(
        self,
        lista_com_20_chunks: List[DocumentChunk],
        response_auxiliar_summary,
        axiom_instance: Axiom,
    ):
        self.lista_contador.append(0)
        print("contador: ", len(self.lista_contador))

        result = await self.llm_call_uma_lista_de_20_chunks(
            lista_com_20_chunks, response_auxiliar_summary, axiom_instance
        )

        lista_chunks: List[ContextualizedChunk] = []
        try:
            for index, chunk in enumerate(lista_com_20_chunks):
                lista_chunks.append(
                    ContextualizedChunk(
                        contextual_summary=result[index][2],
                        content=chunk.content,
                        page_number=chunk.page_number,
                        id_do_processo=int(result[index][0]),
                        chunk_id=chunk.chunk_id,
                        start_char=chunk.start_char,
                        end_char=chunk.end_char,
                        context=result[index][1],
                    )
                )
        except BaseException as e:
            axiom_instance.send_axiom(
                f"ERRO EM UMA LISTA COM 20 CHUNKS CONTEXTUALS --------- lista: {lista_com_20_chunks} ------------ ERRO: {e}"
            )

        return lista_chunks

    async def contextualize_all_chunks(
        self,
        all_PDFs_chunks: List[DocumentChunk],
        response_auxiliar_summary,
        axiom_instance: Axiom,
    ) -> List[ContextualizedChunk]:
        """Add context to all chunks"""

        lista_de_listas_cada_com_20_chunks = (
            self.contextual_retriever_utils.get_lista_de_listas_cada_com_20_chunks(
                all_PDFs_chunks
            )
        )

        async with asyncio.TaskGroup() as tg:

            def processa_uma_lista_de_20_chunks(
                lista_com_20_chunks: List[DocumentChunk],
            ):
                coroutine = self.contextualize_uma_lista_de_20_chunks(
                    lista_com_20_chunks, response_auxiliar_summary, axiom_instance
                )
                return tg.create_task(coroutine)

            tasks = [
                processa_uma_lista_de_20_chunks(lista_com_20_chunks)
                for lista_com_20_chunks in lista_de_listas_cada_com_20_chunks
            ]

        contextualized_chunks: List[ContextualizedChunk] = []
        for task in tasks:
            contextualized_chunks = contextualized_chunks + task.result()

        axiom_instance.send_axiom(
            "TERMINOU COM SUCESSO DE PROCESSAR TUDO DOS CONTEXTUALS"
        )
        return contextualized_chunks


@dataclass
class ContextualRetrieverUtils:
    def get_all_document_ids_and_contents(
        self, lista_com_20_chunks: List[DocumentChunk]
    ):
        contador = 1
        all_chunks_contents = ""
        all_document_ids = []
        for chunk in lista_com_20_chunks:
            all_chunks_contents += f"\n\nCHUNK {contador}:\n"
            all_chunks_contents += chunk.content

            pattern = r"Num\. (\d+)"
            import re

            match = re.search(pattern, chunk.content)
            if match:
                number = match.group(1)  # Extract the number
            else:
                number = 0

            all_document_ids.append(int(number))
            contador += 1
        return all_chunks_contents, all_document_ids

    def get_info_from_validated_chunks(self, matches):
        result = [
            [int(doc_id), title.strip(), content.strip()]
            for doc_id, title, content in matches
        ]
        return result

    def get_lista_de_listas_cada_com_20_chunks(
        self, all_PDFs_chunks: List[DocumentChunk]
    ):
        return [all_PDFs_chunks[i : i + 20] for i in range(0, len(all_PDFs_chunks), 20)]

    def validate_many_chunks_in_one_request(
        self, response: str, lista_de_document_ids: List[int]
    ):
        context = (
            response.replace("document_id: ", "")
            .replace("document_id:", "")
            .replace("DOCUMENT_ID: ", "")
            .replace("DOCUMENT_ID: ", "")
        )

        # pattern = r"\[(\d+|[-.]+)\] --- (.+?) --- (.+?)</chunk_context>"  # Funciona para quando a resposta do LLM não vem com "document_id" escrito
        matches = self.check_regex_patterns(context, lista_de_document_ids)
        if not matches or len(matches) == 0:
            print(
                "----------- ERROU NA TENTATIVA ATUAL DE FORMATAR O CONTEXTUAL -----------"
            )
            return False

        matches_as_list = []

        for index, match in enumerate(list(matches)):
            if index >= 20:
                break
            resultado = match[0].replace(".", "").replace("-", "")

            resultado = lista_de_document_ids[index]

            matches_as_list.append((resultado, match[1], match[2]))

        return matches_as_list

    def check_regex_patterns(self, context: str, lista_de_document_ids: List[int]):
        patterns = [
            r"\[(.*?)\] --- \[(.*?)\] --- \[(.*?)\](?=\n|\s*$)",
            r"\[([^\[\]]+?)\]\s*---\s*\[([^\[\]]+?)\]\s*---\s*(.*?)</chunk_context>",
            r"<chunk_context>\s*(\d+)(?:\s*-\s*Pág\.\s*\d+)?\s*---\s*([^-\n]+)\s*---\s*([^<]+)</chunk_context>",
            r"<chunk_context>\s*(?:\[*([\d]+)\]*\s*[-–]*\s*(?:Pág\.\s*\d+\s*[-–]*)?)?\s*\[*([^\]]+)\]*\s*[-–]*\s*\[*([^\]]+)\]*\s*[-–]*\s*\[*([^\]]+)\]*\s*</chunk_context>",
            r"<chunk_context>\s*(.*?)\s*---\s*(.*?)\s*---\s*(.*?)\s*</chunk_context>",
            # -------------- ABAIXO SÃO OS ANTIGOS
            # r"\[*([\d.\-]+)\]*\s*---\s*\[*([^]]+)\]*\s*---\s*\[*([^]]+)\]*\s*</chunk_context>", # PRIMEIRO DE TODOS
            # r"<chunk_context>\s*([\d.\-]+)\s*---\s*([^<]+)\s*---\s*([^<]+)\s*</chunk_context>",
            # r"\[([\d.\-]+)\]\s*---\s*\[([^]]+)\]\s*---\s*\[([^]]+)\]\s*</chunk_context>",
            # r"<chunk_context>\s*\[?([\d.\-]+)\]?\s*---\s*\[?([^\]\[]+?)\]?\s*---\s*\[?([^<]+?)\]?\s*</chunk_context>",
            # r"<chunk_context>\s*\[([\d.\-]+)\]\s*---\s*\[([^\]]+)\]\s*---\s*\[([^\]]+)\]\s*</chunk_context>"
            # r"<chunk_context>\s*\[?([\d.\-\s]+)\]?\s*---\s*\[?([^\]\[]+?)\]?\s*---\s*\[?([\s\S]+?)\]?\s*</chunk_context>",
        ]

        resultado = None
        for pattern in patterns:
            matches: List[str] = re.findall(pattern, context, re.DOTALL)
            condition_tuples_3_items = all(len(m) == 3 for m in matches)
            if len(matches) == len(lista_de_document_ids) and condition_tuples_3_items:
                print("\n--------------- REGEX DO CONTEXTUAL FUNCIONOU")
                resultado = []
                for m in matches:
                    regex = r"Num\.\s*(\d+)\s*-"
                    page_id = re.search(regex, m[0])
                    if page_id:
                        first_item = page_id.group(1)
                    else:
                        first_item = "0"
                    resultado.append((first_item, m[1], m[2]))
                break

        if not resultado:
            context = (
                context.replace("</final_output>", "")
                .replace("<final_output>", "")
                .strip()
            )
            raw_chunks = context.split("</chunk_context>")[0:20]

            resultado_temporario = []
            for r in raw_chunks:
                lista_3_itens = r.split("---")
                page_id = re.search(r"Num\.\s*(\d+)\s*-", lista_3_itens[0].strip())
                page_id_tentativa_2 = re.search(
                    r"\d+\.\s+(\d+)\s+-\s+Pág\.", lista_3_itens[0].strip()
                )
                if page_id:
                    first_item = page_id.group(1)
                elif page_id_tentativa_2:
                    first_item = page_id_tentativa_2.group(1)
                else:
                    first_item = "0"
                resultado_temporario.append(
                    (first_item, lista_3_itens[1], lista_3_itens[2])
                )

            condition_tuples_3_items = all(len(m) == 3 for m in resultado_temporario)
            if (
                len(resultado_temporario) == len(lista_de_document_ids)
                and condition_tuples_3_items
            ):
                resultado = resultado_temporario

        return resultado


# Código comentado abaixo é para ler as páginas ao redor da página atual do chunk
# page_content = ""
# for i in range(
#     max(0, chunk.page_number - 1),
#     min(len(single_page_text), chunk.page_number + 2),
# ):
#     page_content += single_page_text[i].page_content if single_page_text[i] else ""