Spaces:
Running
Running
luanpoppe
commited on
Commit
·
2ce5e93
1
Parent(s):
967a079
feat: refatoração nome de pastas
Browse files- _utils/gerar_documento.py +5 -6
- _utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/ContextualRetriever_original.py +0 -0
- _utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/DocumentSummarizer_simples.py +0 -0
- _utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/GerarDocumento.py +1 -1
- _utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/contextual_retriever.py +33 -22
- _utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/llm_calls.py +0 -0
- _utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/prompts.py +0 -40
- _utils/gerar_documento_utils/tests/conftest.py +3 -0
- _utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/utils.py +2 -2
- _utils/ragas.py +3 -1
- gerar_documento/serializer.py +2 -3
- gerar_documento/serializer_base.py +0 -7
- gerar_documento/views.py +2 -2
- tests/gerar_relatorio_modelo_usuario/test_contextual_retriever.py +10 -9
_utils/gerar_documento.py
CHANGED
@@ -4,16 +4,16 @@ from typing import Any, Union, cast
|
|
4 |
from _utils.langchain_utils.LLM_class import LLM
|
5 |
from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
|
6 |
from _utils.custom_exception_handler import custom_exception_handler_wihout_api_handler
|
7 |
-
from _utils.
|
8 |
prompt_gerar_query_dinamicamente,
|
9 |
)
|
10 |
-
from _utils.
|
11 |
GerarDocumento,
|
12 |
)
|
13 |
-
from _utils.
|
14 |
ContextualRetriever,
|
15 |
)
|
16 |
-
from _utils.
|
17 |
generate_document_title,
|
18 |
gerar_resposta_compilada,
|
19 |
get_full_text_and_all_PDFs_chunks,
|
@@ -48,7 +48,6 @@ async def gerar_documento(
|
|
48 |
axiom_instance: Axiom,
|
49 |
isBubble=False,
|
50 |
):
|
51 |
-
"""Parâmetro "contexto" só deve ser passado quando quiser utilizar o teste com ragas, e assim, não quiser passar PDFs"""
|
52 |
try:
|
53 |
contextual_retriever = ContextualRetriever(serializer)
|
54 |
|
@@ -77,7 +76,7 @@ async def gerar_documento(
|
|
77 |
|
78 |
axiom_instance.send_axiom("COMEÇANDO A FAZER AS REQUISIÇÕES DO CONTEXTUAL")
|
79 |
contextualized_chunks = await contextual_retriever.contextualize_all_chunks(
|
80 |
-
all_PDFs_chunks, response_auxiliar_summary
|
81 |
)
|
82 |
axiom_instance.send_axiom(
|
83 |
"TERMINOU DE FAZER TODAS AS REQUISIÇÕES DO CONTEXTUAL"
|
|
|
4 |
from _utils.langchain_utils.LLM_class import LLM
|
5 |
from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
|
6 |
from _utils.custom_exception_handler import custom_exception_handler_wihout_api_handler
|
7 |
+
from _utils.gerar_documento_utils.prompts import (
|
8 |
prompt_gerar_query_dinamicamente,
|
9 |
)
|
10 |
+
from _utils.gerar_documento_utils.GerarDocumento import (
|
11 |
GerarDocumento,
|
12 |
)
|
13 |
+
from _utils.gerar_documento_utils.contextual_retriever import (
|
14 |
ContextualRetriever,
|
15 |
)
|
16 |
+
from _utils.gerar_documento_utils.utils import (
|
17 |
generate_document_title,
|
18 |
gerar_resposta_compilada,
|
19 |
get_full_text_and_all_PDFs_chunks,
|
|
|
48 |
axiom_instance: Axiom,
|
49 |
isBubble=False,
|
50 |
):
|
|
|
51 |
try:
|
52 |
contextual_retriever = ContextualRetriever(serializer)
|
53 |
|
|
|
76 |
|
77 |
axiom_instance.send_axiom("COMEÇANDO A FAZER AS REQUISIÇÕES DO CONTEXTUAL")
|
78 |
contextualized_chunks = await contextual_retriever.contextualize_all_chunks(
|
79 |
+
all_PDFs_chunks, response_auxiliar_summary, axiom_instance
|
80 |
)
|
81 |
axiom_instance.send_axiom(
|
82 |
"TERMINOU DE FAZER TODAS AS REQUISIÇÕES DO CONTEXTUAL"
|
_utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/ContextualRetriever_original.py
RENAMED
File without changes
|
_utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/DocumentSummarizer_simples.py
RENAMED
File without changes
|
_utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/GerarDocumento.py
RENAMED
@@ -20,7 +20,7 @@ from setup.easy_imports import (
|
|
20 |
HuggingFaceEmbeddings,
|
21 |
)
|
22 |
import logging
|
23 |
-
from _utils.
|
24 |
DocumentSummarizer,
|
25 |
)
|
26 |
from _utils.models.gerar_relatorio import (
|
|
|
20 |
HuggingFaceEmbeddings,
|
21 |
)
|
22 |
import logging
|
23 |
+
from _utils.gerar_documento_utils.DocumentSummarizer_simples import (
|
24 |
DocumentSummarizer,
|
25 |
)
|
26 |
from _utils.models.gerar_relatorio import (
|
_utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/contextual_retriever.py
RENAMED
@@ -1,6 +1,6 @@
|
|
1 |
import os
|
2 |
from _utils.langchain_utils.LLM_class import LLM
|
3 |
-
from _utils.
|
4 |
get_response_from_auxiliar_contextual_prompt,
|
5 |
validate_many_chunks_in_one_request,
|
6 |
)
|
@@ -13,12 +13,12 @@ import asyncio
|
|
13 |
from typing import List
|
14 |
from dataclasses import dataclass
|
15 |
|
16 |
-
from _utils.
|
17 |
aclaude_answer,
|
18 |
agemini_answer,
|
19 |
agpt_answer,
|
20 |
)
|
21 |
-
from _utils.
|
22 |
from _utils.models.gerar_relatorio import (
|
23 |
ContextualizedChunk,
|
24 |
DocumentChunk,
|
@@ -30,6 +30,7 @@ from gerar_documento.serializer import (
|
|
30 |
GerarDocumentoComPDFProprioSerializerData,
|
31 |
GerarDocumentoSerializerData,
|
32 |
)
|
|
|
33 |
|
34 |
lista_contador = []
|
35 |
|
@@ -86,7 +87,10 @@ class ContextualRetriever:
|
|
86 |
return result
|
87 |
|
88 |
async def llm_call_uma_lista_de_chunks(
|
89 |
-
self,
|
|
|
|
|
|
|
90 |
) -> List[List[Any]]:
|
91 |
"""Generate contextual description using ChatOpenAI"""
|
92 |
all_chunks_contents, all_document_ids = self.getAllDocumentsIds(
|
@@ -101,44 +105,50 @@ class ContextualRetriever:
|
|
101 |
|
102 |
for attempt in range(4):
|
103 |
if attempt != 0:
|
104 |
-
|
105 |
-
"------------- FORMATAÇÃO DO CONTEXTUAL INCORRETA - TENTANDO NOVAMENTE -------------"
|
106 |
)
|
107 |
-
print(f"TENTATIVA FORMATAÇÃO CHUNKS NÚMERO {attempt + 1}")
|
108 |
print("COMEÇANDO UMA REQUISIÇÃO DO CONTEXTUAL")
|
109 |
-
# raw_response = await agpt_answer(prompt)
|
110 |
-
# raw_response = await agemini_answer(prompt, "gemini-2.0-flash-lite-preview-02-05")
|
111 |
raw_response = await agemini_answer(prompt, "gemini-2.0-flash-lite")
|
112 |
|
113 |
print("TERMINOU UMA REQUISIÇÃO DO CONTEXTUAL")
|
114 |
response = cast(str, raw_response)
|
115 |
-
# response = await llms.deepseek().ainvoke([HumanMessage(content=prompt)])
|
116 |
-
# return cast(str, response.content)
|
117 |
|
118 |
matches = validate_many_chunks_in_one_request(
|
119 |
response, all_document_ids
|
120 |
)
|
121 |
|
122 |
if matches:
|
|
|
|
|
|
|
123 |
return self.get_info_from_validated_chunks(matches)
|
124 |
-
|
|
|
|
|
|
|
|
|
|
|
125 |
except Exception as e:
|
126 |
self.logger.error(f"Context generation failed for chunks .... : {str(e)}")
|
127 |
return [[""]]
|
128 |
|
129 |
async def contextualize_uma_lista_de_chunks(
|
130 |
-
self,
|
|
|
|
|
|
|
131 |
):
|
132 |
lista_contador.append(0)
|
133 |
print("contador: ", len(lista_contador))
|
134 |
|
135 |
result = await self.llm_call_uma_lista_de_chunks(
|
136 |
-
lista_com_20_chunks, response_auxiliar_summary
|
137 |
)
|
138 |
|
139 |
lista_chunks: List[ContextualizedChunk] = []
|
140 |
-
|
141 |
-
|
142 |
lista_chunks.append(
|
143 |
ContextualizedChunk(
|
144 |
contextual_summary=result[index][2],
|
@@ -151,17 +161,19 @@ class ContextualRetriever:
|
|
151 |
context=result[index][1],
|
152 |
)
|
153 |
)
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
|
|
|
159 |
return lista_chunks
|
160 |
|
161 |
async def contextualize_all_chunks(
|
162 |
self,
|
163 |
all_PDFs_chunks: List[DocumentChunk],
|
164 |
response_auxiliar_summary,
|
|
|
165 |
) -> List[ContextualizedChunk]:
|
166 |
"""Add context to all chunks"""
|
167 |
|
@@ -173,8 +185,7 @@ class ContextualRetriever:
|
|
173 |
tasks = [
|
174 |
tg.create_task(
|
175 |
self.contextualize_uma_lista_de_chunks(
|
176 |
-
lista_com_20_chunks,
|
177 |
-
response_auxiliar_summary,
|
178 |
)
|
179 |
)
|
180 |
for lista_com_20_chunks in lista_de_listas_cada_com_20_chunks
|
|
|
1 |
import os
|
2 |
from _utils.langchain_utils.LLM_class import LLM
|
3 |
+
from _utils.gerar_documento_utils.utils import (
|
4 |
get_response_from_auxiliar_contextual_prompt,
|
5 |
validate_many_chunks_in_one_request,
|
6 |
)
|
|
|
13 |
from typing import List
|
14 |
from dataclasses import dataclass
|
15 |
|
16 |
+
from _utils.gerar_documento_utils.llm_calls import (
|
17 |
aclaude_answer,
|
18 |
agemini_answer,
|
19 |
agpt_answer,
|
20 |
)
|
21 |
+
from _utils.gerar_documento_utils.prompts import contextual_prompt
|
22 |
from _utils.models.gerar_relatorio import (
|
23 |
ContextualizedChunk,
|
24 |
DocumentChunk,
|
|
|
30 |
GerarDocumentoComPDFProprioSerializerData,
|
31 |
GerarDocumentoSerializerData,
|
32 |
)
|
33 |
+
from setup.logging import Axiom
|
34 |
|
35 |
lista_contador = []
|
36 |
|
|
|
87 |
return result
|
88 |
|
89 |
async def llm_call_uma_lista_de_chunks(
|
90 |
+
self,
|
91 |
+
lista_com_20_chunks: List[DocumentChunk],
|
92 |
+
resumo_auxiliar,
|
93 |
+
axiom_instance: Axiom,
|
94 |
) -> List[List[Any]]:
|
95 |
"""Generate contextual description using ChatOpenAI"""
|
96 |
all_chunks_contents, all_document_ids = self.getAllDocumentsIds(
|
|
|
105 |
|
106 |
for attempt in range(4):
|
107 |
if attempt != 0:
|
108 |
+
axiom_instance.send_axiom(
|
109 |
+
f"------------- FORMATAÇÃO DO CONTEXTUAL INCORRETA - TENTANDO NOVAMENTE (TENTATIVA: {attempt + 1}) -------------"
|
110 |
)
|
|
|
111 |
print("COMEÇANDO UMA REQUISIÇÃO DO CONTEXTUAL")
|
|
|
|
|
112 |
raw_response = await agemini_answer(prompt, "gemini-2.0-flash-lite")
|
113 |
|
114 |
print("TERMINOU UMA REQUISIÇÃO DO CONTEXTUAL")
|
115 |
response = cast(str, raw_response)
|
|
|
|
|
116 |
|
117 |
matches = validate_many_chunks_in_one_request(
|
118 |
response, all_document_ids
|
119 |
)
|
120 |
|
121 |
if matches:
|
122 |
+
axiom_instance.send_axiom(
|
123 |
+
f"CONTEXTUAL FUNCIONOU NA TENTATIVA {attempt + 1}"
|
124 |
+
)
|
125 |
return self.get_info_from_validated_chunks(matches)
|
126 |
+
else:
|
127 |
+
# raise ValueError(f"FORMATAÇÃO DOS CHUNKS FOI INVÁLIDA: {response}")
|
128 |
+
axiom_instance.send_axiom(
|
129 |
+
f"---------- FORMATAÇÃO DE UM DOS CHUNKS FOI INVÁLIDA - {response}"
|
130 |
+
)
|
131 |
+
return [[""]]
|
132 |
except Exception as e:
|
133 |
self.logger.error(f"Context generation failed for chunks .... : {str(e)}")
|
134 |
return [[""]]
|
135 |
|
136 |
async def contextualize_uma_lista_de_chunks(
|
137 |
+
self,
|
138 |
+
lista_com_20_chunks: List[DocumentChunk],
|
139 |
+
response_auxiliar_summary,
|
140 |
+
axiom_instance: Axiom,
|
141 |
):
|
142 |
lista_contador.append(0)
|
143 |
print("contador: ", len(lista_contador))
|
144 |
|
145 |
result = await self.llm_call_uma_lista_de_chunks(
|
146 |
+
lista_com_20_chunks, response_auxiliar_summary, axiom_instance
|
147 |
)
|
148 |
|
149 |
lista_chunks: List[ContextualizedChunk] = []
|
150 |
+
for index, chunk in enumerate(lista_com_20_chunks):
|
151 |
+
try:
|
152 |
lista_chunks.append(
|
153 |
ContextualizedChunk(
|
154 |
contextual_summary=result[index][2],
|
|
|
161 |
context=result[index][1],
|
162 |
)
|
163 |
)
|
164 |
+
except BaseException as e:
|
165 |
+
print(
|
166 |
+
f"ERRO EM UMA LISTA COM 20 CHUNKS CONTEXTUALS {index + 1}: {result} ------- {e}"
|
167 |
+
)
|
168 |
|
169 |
+
axiom_instance.send_axiom(f"UMA LISTA COM 20 CHUNKS: {lista_chunks}")
|
170 |
return lista_chunks
|
171 |
|
172 |
async def contextualize_all_chunks(
|
173 |
self,
|
174 |
all_PDFs_chunks: List[DocumentChunk],
|
175 |
response_auxiliar_summary,
|
176 |
+
axiom_instance: Axiom,
|
177 |
) -> List[ContextualizedChunk]:
|
178 |
"""Add context to all chunks"""
|
179 |
|
|
|
185 |
tasks = [
|
186 |
tg.create_task(
|
187 |
self.contextualize_uma_lista_de_chunks(
|
188 |
+
lista_com_20_chunks, response_auxiliar_summary, axiom_instance
|
|
|
189 |
)
|
190 |
)
|
191 |
for lista_com_20_chunks in lista_de_listas_cada_com_20_chunks
|
_utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/llm_calls.py
RENAMED
File without changes
|
_utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/prompts.py
RENAMED
@@ -137,46 +137,6 @@ Please provide context for all {numero_de_chunks} chunks, following this structu
|
|
137 |
# Novo nome --> prompt-auxiliar --> Para gerar documentos (é usado como auxiliar no prompt final)
|
138 |
prompt_auxiliar_inicio = """You are a language model specialized in producing concise and well-structured legal case summaries in Portuguese. You will receive a variable `context`, which contains information about a legal case. Your task is to read the `context` carefully and produce a summary report in Portuguese, following the specific format provided below. Do not include any additional comments or reasoning steps in your final answer."""
|
139 |
|
140 |
-
prompt_auxiliar_padrao = """
|
141 |
-
**Instructions**:
|
142 |
-
1. **Chain of Thought**: Before producing your final answer, you must think through and plan your summary silently, without showing this reasoning in the final output. The final answer must only contain the required formatted report and nothing else.
|
143 |
-
2. **Reading the Context**: Extract the following information from `context`:
|
144 |
-
- The name of the defendant (réu).
|
145 |
-
- The crime they have been accused of (nome_do_crime).
|
146 |
-
- The applicable article and subsection of the Penal Code (artigo_e_inciso_do_crime).
|
147 |
-
- The date the accusation was accepted (data_do_recebimento).
|
148 |
-
- The ID of the decision document (id_do_documento).
|
149 |
-
3. **Prescriptive Details**: If no other interruptive or suspensive causes of prescription are mentioned, confirm that there are none.
|
150 |
-
4. **Formatting**: Your final answer must strictly follow the format below, in Portuguese, and replace the placeholders with the appropriate information:
|
151 |
-
```
|
152 |
-
<relatorio>
|
153 |
-
Trata-se de Ação Penal em que o Ministério Público denunciou [nome_do_reu], pela prática do [nome_do_crime] [artigo_e_inciso_do_crime], do Código Penal.
|
154 |
-
A denúncia foi recebida em [data_do_recebimento], conforme Decisão [id_do_documento].
|
155 |
-
Não há outras causas interruptivas ou suspensivas da prescrição.
|
156 |
-
</relatorio>
|
157 |
-
```
|
158 |
-
5. **Completeness**: If any piece of required information is missing in the `context`, note that explicitly in the final answer within the format.
|
159 |
-
**Reminder**:
|
160 |
-
- Do not include your chain of thought in the final output.
|
161 |
-
- Do not add extra information or commentary beyond the specified format.
|
162 |
-
- The final answer must be in Portuguese.
|
163 |
-
---
|
164 |
-
|
165 |
-
**Contextual Information (provided separately):**
|
166 |
-
{context}
|
167 |
-
---
|
168 |
-
**Example with a given context**:
|
169 |
-
- Input:
|
170 |
-
`context` = 'Em 10/03/2021, o Ministério Público denunciou João da Silva, imputando-lhe o crime de furto qualificado, previsto no art. 155, §4º, inciso II, do Código Penal. A denúncia foi recebida em 12/03/2021, conforme Decisão nº 20210312-01. Não há menção a qualquer causa interruptiva ou suspensiva da prescrição.'
|
171 |
-
- Expected final answer:
|
172 |
-
```
|
173 |
-
<formato>
|
174 |
-
Trata-se de Ação Penal em que o Ministério Público denunciou João da Silva, pela prática do furto qualificado (art. 155, §4º, inciso II do Código Penal).
|
175 |
-
A denúncia foi recebida em 12/03/2021, conforme Decisão 20210312-01.
|
176 |
-
Não há outras causas interruptivas ou suspensivas da prescrição.
|
177 |
-
</formato>
|
178 |
-
"""
|
179 |
-
|
180 |
# Novo nome --> prompt-gerar-documento --> Para gerar documentos
|
181 |
prompt_gerar_documento = """
|
182 |
You are a large language model that must produce a single final document in **Portuguese**. To do this, you will follow a private chain of thought and then produce a final answer. The final answer must follow the formatting and stylistic conventions shown in the user-provided model `user's template`. The information to be included in the final document is derived from the `context` (a report describing a legal case).
|
|
|
137 |
# Novo nome --> prompt-auxiliar --> Para gerar documentos (é usado como auxiliar no prompt final)
|
138 |
prompt_auxiliar_inicio = """You are a language model specialized in producing concise and well-structured legal case summaries in Portuguese. You will receive a variable `context`, which contains information about a legal case. Your task is to read the `context` carefully and produce a summary report in Portuguese, following the specific format provided below. Do not include any additional comments or reasoning steps in your final answer."""
|
139 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
# Novo nome --> prompt-gerar-documento --> Para gerar documentos
|
141 |
prompt_gerar_documento = """
|
142 |
You are a large language model that must produce a single final document in **Portuguese**. To do this, you will follow a private chain of thought and then produce a final answer. The final answer must follow the formatting and stylistic conventions shown in the user-provided model `user's template`. The information to be included in the final document is derived from the `context` (a report describing a legal case).
|
_utils/gerar_documento_utils/tests/conftest.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
from tests import conftest
|
2 |
+
|
3 |
+
conftest.django.setup()
|
_utils/{gerar_relatorio_modelo_usuario → gerar_documento_utils}/utils.py
RENAMED
@@ -2,10 +2,10 @@ from typing import Any, List, Tuple, Union
|
|
2 |
from langchain_core.documents import Document
|
3 |
from langchain_core.messages import HumanMessage
|
4 |
|
5 |
-
from _utils.
|
6 |
from _utils.langchain_utils.Splitter_class import Splitter
|
7 |
from _utils.langchain_utils.LLM_class import LLM
|
8 |
-
from _utils.
|
9 |
create_prompt_auxiliar_do_contextual_prompt,
|
10 |
)
|
11 |
import re
|
|
|
2 |
from langchain_core.documents import Document
|
3 |
from langchain_core.messages import HumanMessage
|
4 |
|
5 |
+
from _utils.gerar_documento_utils.llm_calls import agemini_answer
|
6 |
from _utils.langchain_utils.Splitter_class import Splitter
|
7 |
from _utils.langchain_utils.LLM_class import LLM
|
8 |
+
from _utils.gerar_documento_utils.prompts import (
|
9 |
create_prompt_auxiliar_do_contextual_prompt,
|
10 |
)
|
11 |
import re
|
_utils/ragas.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
import os
|
2 |
from langchain_community.document_loaders import PyPDFLoader
|
3 |
-
from _utils.
|
4 |
from rest_framework.response import Response
|
5 |
from ragas import evaluate
|
6 |
|
@@ -10,6 +10,8 @@ from langchain.prompts import PromptTemplate
|
|
10 |
# from langchain.schema import ChainResult
|
11 |
from langchain.memory import SimpleMemory
|
12 |
|
|
|
|
|
13 |
|
14 |
def test_ragas(serializer, listaPDFs):
|
15 |
|
|
|
1 |
import os
|
2 |
from langchain_community.document_loaders import PyPDFLoader
|
3 |
+
from _utils.gerar_documento_utils import GerarDocumento
|
4 |
from rest_framework.response import Response
|
5 |
from ragas import evaluate
|
6 |
|
|
|
10 |
# from langchain.schema import ChainResult
|
11 |
from langchain.memory import SimpleMemory
|
12 |
|
13 |
+
from _utils.models.gerar_relatorio import RetrievalConfig
|
14 |
+
|
15 |
|
16 |
def test_ragas(serializer, listaPDFs):
|
17 |
|
gerar_documento/serializer.py
CHANGED
@@ -1,10 +1,8 @@
|
|
1 |
from dataclasses import dataclass, field
|
2 |
-
from email.policy import default
|
3 |
from typing import List, Optional, Union
|
4 |
from rest_framework import serializers
|
5 |
-
from _utils.
|
6 |
prompt_gerar_documento,
|
7 |
-
prompt_auxiliar_padrao,
|
8 |
)
|
9 |
from gerar_documento.serializer_base import (
|
10 |
GerarDocumentoParametros,
|
@@ -15,6 +13,7 @@ from django.core.files.uploadedfile import UploadedFile
|
|
15 |
|
16 |
user_message = "What are the main points of this document?"
|
17 |
|
|
|
18 |
class GerarDocumentoInitialSerializer(serializers.Serializer):
|
19 |
files = serializers.ListField(child=serializers.FileField(), required=True)
|
20 |
user_message = serializers.CharField(required=False, default=user_message)
|
|
|
1 |
from dataclasses import dataclass, field
|
|
|
2 |
from typing import List, Optional, Union
|
3 |
from rest_framework import serializers
|
4 |
+
from _utils.gerar_documento_utils.prompts import (
|
5 |
prompt_gerar_documento,
|
|
|
6 |
)
|
7 |
from gerar_documento.serializer_base import (
|
8 |
GerarDocumentoParametros,
|
|
|
13 |
|
14 |
user_message = "What are the main points of this document?"
|
15 |
|
16 |
+
|
17 |
class GerarDocumentoInitialSerializer(serializers.Serializer):
|
18 |
files = serializers.ListField(child=serializers.FileField(), required=True)
|
19 |
user_message = serializers.CharField(required=False, default=user_message)
|
gerar_documento/serializer_base.py
CHANGED
@@ -1,13 +1,6 @@
|
|
1 |
from dataclasses import dataclass, field
|
2 |
-
from email.policy import default
|
3 |
from typing import List, Optional, Union
|
4 |
from rest_framework import serializers
|
5 |
-
from _utils.gerar_relatorio_modelo_usuario.prompts import (
|
6 |
-
prompt_gerar_documento,
|
7 |
-
prompt_auxiliar_padrao,
|
8 |
-
)
|
9 |
-
from setup.environment import default_model
|
10 |
-
from django.core.files.uploadedfile import UploadedFile
|
11 |
|
12 |
|
13 |
class GerarDocumentoParametros:
|
|
|
1 |
from dataclasses import dataclass, field
|
|
|
2 |
from typing import List, Optional, Union
|
3 |
from rest_framework import serializers
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
|
6 |
class GerarDocumentoParametros:
|
gerar_documento/views.py
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
from typing import Any, Dict, cast
|
2 |
from langchain.prompts import PromptTemplate
|
3 |
from _utils.langchain_utils.LLM_class import LLM
|
4 |
-
from _utils.
|
5 |
get_full_text_and_all_PDFs_chunks,
|
6 |
)
|
7 |
from _utils.langchain_utils.Prompt_class import Prompt
|
@@ -18,7 +18,7 @@ from _utils.handle_files import handle_pdf_files_from_serializer, remove_pdf_tem
|
|
18 |
from _utils.gerar_documento import (
|
19 |
gerar_documento,
|
20 |
)
|
21 |
-
from _utils.
|
22 |
from setup.logging import Axiom, send_axiom
|
23 |
from .serializer import (
|
24 |
GerarDocumentoComPDFProprioSerializer,
|
|
|
1 |
from typing import Any, Dict, cast
|
2 |
from langchain.prompts import PromptTemplate
|
3 |
from _utils.langchain_utils.LLM_class import LLM
|
4 |
+
from _utils.gerar_documento_utils.utils import (
|
5 |
get_full_text_and_all_PDFs_chunks,
|
6 |
)
|
7 |
from _utils.langchain_utils.Prompt_class import Prompt
|
|
|
18 |
from _utils.gerar_documento import (
|
19 |
gerar_documento,
|
20 |
)
|
21 |
+
from _utils.gerar_documento_utils.prompts import prompt_auxiliar_inicio
|
22 |
from setup.logging import Axiom, send_axiom
|
23 |
from .serializer import (
|
24 |
GerarDocumentoComPDFProprioSerializer,
|
tests/gerar_relatorio_modelo_usuario/test_contextual_retriever.py
CHANGED
@@ -1,8 +1,8 @@
|
|
1 |
import pytest
|
2 |
-
from _utils.
|
3 |
ContextualRetriever,
|
4 |
)
|
5 |
-
from _utils.
|
6 |
validate_many_chunks_in_one_request,
|
7 |
)
|
8 |
from _utils.models.gerar_relatorio import RetrievalConfig
|
@@ -98,21 +98,19 @@ class TestContextualRetriever:
|
|
98 |
[fixture.resposta_cenario_01,fixture.lista_ids_cenario_01],
|
99 |
[fixture.resposta_cenario_02,fixture.lista_ids_cenario_02]
|
100 |
]
|
101 |
-
|
102 |
for cenario in lista_fixtures:
|
103 |
resultado = validate_many_chunks_in_one_request(
|
104 |
cenario[0],
|
105 |
cenario[1],
|
106 |
)
|
107 |
-
|
108 |
assert resultado and len(resultado) == len(cenario[1])
|
109 |
assert all( isinstance(item[0], int) and item[0] != 0 for item in resultado)
|
110 |
assert all( isinstance(item[1], str) and item[1] != "" for item in resultado)
|
111 |
assert all( isinstance(item[2], str) and item[2] != "" for item in resultado)
|
112 |
|
113 |
print("\n\nresultado", resultado)
|
114 |
-
|
115 |
-
|
116 |
|
117 |
@pytest.mark.asyncio
|
118 |
async def test_get_info_from_validated_chunks(self):
|
@@ -166,12 +164,15 @@ class TestContextualRetriever:
|
|
166 |
return validate_many_chunks_in_one_request(response, document_ids) # Call the real function after two mocks
|
167 |
|
168 |
monkeypatch.setattr(
|
169 |
-
"_utils.
|
170 |
-
custom_side_effect
|
171 |
)
|
172 |
|
173 |
mock_agpt_answer = AsyncMock(return_value=lista_respostas_contextuals_cenario_02[0])
|
174 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
175 |
|
176 |
resultado = await self.context_retrieval.llm_call_uma_lista_de_chunks(
|
177 |
cenario_01_lista_com_20_chunks, cenario_01_resumo_auxiliar
|
|
|
1 |
import pytest
|
2 |
+
from _utils.gerar_documento_utils.contextual_retriever import (
|
3 |
ContextualRetriever,
|
4 |
)
|
5 |
+
from _utils.gerar_documento_utils.utils import (
|
6 |
validate_many_chunks_in_one_request,
|
7 |
)
|
8 |
from _utils.models.gerar_relatorio import RetrievalConfig
|
|
|
98 |
[fixture.resposta_cenario_01,fixture.lista_ids_cenario_01],
|
99 |
[fixture.resposta_cenario_02,fixture.lista_ids_cenario_02]
|
100 |
]
|
101 |
+
|
102 |
for cenario in lista_fixtures:
|
103 |
resultado = validate_many_chunks_in_one_request(
|
104 |
cenario[0],
|
105 |
cenario[1],
|
106 |
)
|
107 |
+
|
108 |
assert resultado and len(resultado) == len(cenario[1])
|
109 |
assert all( isinstance(item[0], int) and item[0] != 0 for item in resultado)
|
110 |
assert all( isinstance(item[1], str) and item[1] != "" for item in resultado)
|
111 |
assert all( isinstance(item[2], str) and item[2] != "" for item in resultado)
|
112 |
|
113 |
print("\n\nresultado", resultado)
|
|
|
|
|
114 |
|
115 |
@pytest.mark.asyncio
|
116 |
async def test_get_info_from_validated_chunks(self):
|
|
|
164 |
return validate_many_chunks_in_one_request(response, document_ids) # Call the real function after two mocks
|
165 |
|
166 |
monkeypatch.setattr(
|
167 |
+
"_utils.gerar_documento_utils.contextual_retriever.validate_many_chunks_in_one_request",
|
168 |
+
custom_side_effect,
|
169 |
)
|
170 |
|
171 |
mock_agpt_answer = AsyncMock(return_value=lista_respostas_contextuals_cenario_02[0])
|
172 |
+
monkeypatch.setattr(
|
173 |
+
"_utils.gerar_documento_utils.contextual_retriever.agpt_answer",
|
174 |
+
mock_agpt_answer,
|
175 |
+
)
|
176 |
|
177 |
resultado = await self.context_retrieval.llm_call_uma_lista_de_chunks(
|
178 |
cenario_01_lista_com_20_chunks, cenario_01_resumo_auxiliar
|