luanpoppe commited on
Commit
f8e2c8b
·
1 Parent(s): f490f11

fix: enviar mensagens de erro para a bubble

Browse files
_utils/custom_exception_handler.py CHANGED
@@ -10,13 +10,31 @@ logger = logging.getLogger(__name__)
10
 
11
 
12
  def custom_exception_handler(exc, context):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  # Call REST framework's default exception handler first
14
  response = exception_handler(exc, context)
15
- serializer: Dict = context["view"].serializer
16
 
17
  if response and str(response.status_code)[0] != "2":
18
  logger.error(f"Validation error: {response.data}")
19
 
 
 
 
 
20
  print("INICIANDO RESPOSTA DE ERRO PARA O BUBBLE")
21
  resposta_bubble = enviar_resposta_final(
22
  serializer.get("doc_id", ""),
@@ -27,5 +45,4 @@ def custom_exception_handler(exc, context):
27
  )
28
  print("\n\nresposta_bubble.status_code", resposta_bubble.status_code)
29
  print("\n\nresposta_bubble.text", resposta_bubble.text)
30
-
31
- return response
 
10
 
11
 
12
  def custom_exception_handler(exc, context):
13
+ print("---------------- CHEGOU NA FUNÇÃO PERSONALIZADA DE ERRO ----------------")
14
+ if (context):
15
+ serializer: Dict = context["view"].serializer
16
+ else:
17
+ serializer = {}
18
+ print("INICIANDO RESPOSTA DE ERRO PARA O BUBBLE")
19
+ resposta_bubble = enviar_resposta_final(
20
+ serializer.get("doc_id", ""),
21
+ serializer.get("form_response_id", ""),
22
+ serializer.get("version", ""),
23
+ serializer.get("texto_completo", ""),
24
+ True,
25
+ )
26
+ print("\n\nresposta_bubble.status_code", resposta_bubble.status_code)
27
+ print("\n\nresposta_bubble.text", resposta_bubble.text)
28
  # Call REST framework's default exception handler first
29
  response = exception_handler(exc, context)
 
30
 
31
  if response and str(response.status_code)[0] != "2":
32
  logger.error(f"Validation error: {response.data}")
33
 
34
+
35
+ return response
36
+
37
+ def custom_exception_handler_wihout_api_handler(error, serializer: Dict):
38
  print("INICIANDO RESPOSTA DE ERRO PARA O BUBBLE")
39
  resposta_bubble = enviar_resposta_final(
40
  serializer.get("doc_id", ""),
 
45
  )
46
  print("\n\nresposta_bubble.status_code", resposta_bubble.status_code)
47
  print("\n\nresposta_bubble.text", resposta_bubble.text)
48
+ print("\n------------ MOTIVO DO ERRO -----------:", f"\n{error}")
 
_utils/gerar_relatorio_modelo_usuario/contextual_retriever.py CHANGED
@@ -115,7 +115,7 @@ class ContextualRetriever:
115
  lista_com_20_chunks, response_auxiliar_summary
116
  )
117
 
118
- lista_chunks = []
119
  try:
120
  for index, chunk in enumerate(lista_com_20_chunks):
121
  lista_chunks.append(
 
115
  lista_com_20_chunks, response_auxiliar_summary
116
  )
117
 
118
+ lista_chunks: List[ContextualizedChunk] = []
119
  try:
120
  for index, chunk in enumerate(lista_com_20_chunks):
121
  lista_chunks.append(
_utils/resumo_completo_cursor.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
 
3
  from _utils.gerar_relatorio_modelo_usuario.prompts import prompt_auxiliar_SEM_CONTEXT
4
  from _utils.gerar_relatorio_modelo_usuario.GerarDocumento import (
5
  GerarDocumento,
@@ -46,93 +47,97 @@ async def get_llm_summary_answer_by_cursor_complete(
46
  serializer, listaPDFs, isBubble=False
47
  ):
48
  """Parâmetro "contexto" só deve ser passado quando quiser utilizar o teste com ragas, e assim, não quiser passar PDFs"""
49
- # Configuration
50
- config = RetrievalConfig(
51
- num_chunks=serializer["num_chunks_retrieval"],
52
- embedding_weight=serializer["embedding_weight"],
53
- bm25_weight=serializer["bm25_weight"],
54
- context_window=serializer["context_window"],
55
- chunk_overlap=serializer["chunk_overlap"],
56
- )
57
-
58
- contextual_retriever = ContextualRetriever(
59
- config, serializer["claude_context_model"]
60
- )
61
-
62
- # Initialize enhanced summarizer
63
- summarizer = GerarDocumento(
64
- config=config,
65
- embedding_model=serializer["hf_embedding"],
66
- chunk_overlap=serializer["chunk_overlap"],
67
- chunk_size=serializer["chunk_size"],
68
- num_k_rerank=serializer["num_k_rerank"],
69
- model_cohere_rerank=serializer["model_cohere_rerank"],
70
- # prompt_auxiliar=serializer["prompt_auxiliar"],
71
- gpt_model=serializer["model"],
72
- gpt_temperature=serializer["gpt_temperature"],
73
- prompt_gerar_documento=serializer["prompt_gerar_documento"],
74
- reciprocal_rank_fusion=reciprocal_rank_fusion,
75
- )
76
-
77
- all_PDFs_chunks, full_text_as_array = await get_full_text_and_all_PDFs_chunks(
78
- listaPDFs, summarizer.splitter, serializer["should_use_llama_parse"], isBubble
79
- )
80
-
81
- is_contextualized_chunk = serializer["should_have_contextual_chunks"]
82
-
83
- if is_contextualized_chunk:
84
- response_auxiliar_summary = await get_response_from_auxiliar_contextual_prompt(
85
- full_text_as_array
86
  )
87
 
88
- print("\nCOMEÇANDO A FAZER AS REQUISIÇÕES DO CONTEXTUAL")
89
- contextualized_chunks = await contextual_retriever.contextualize_all_chunks(
90
- all_PDFs_chunks, response_auxiliar_summary
91
  )
92
- print("\nTERMINOU DE FAZER TODAS AS REQUISIÇÕES DO CONTEXTUAL")
93
- chunks_processados = contextualized_chunks
94
- else:
95
- chunks_processados = all_PDFs_chunks
96
-
97
- # Create enhanced vector store and BM25 index
98
- vector_store, bm25, chunk_ids = (
99
- summarizer.vector_store.create_enhanced_vector_store(
100
- chunks_processados, is_contextualized_chunk
 
 
 
 
 
101
  )
102
- )
103
-
104
- llm_ultimas_requests = serializer["llm_ultimas_requests"]
105
- print("\nCOMEÇANDO A FAZER ÚLTIMA REQUISIÇÃO")
106
- structured_summaries = await summarizer.gerar_documento_final(
107
- vector_store, bm25, chunk_ids, llm_ultimas_requests, prompt_auxiliar_SEM_CONTEXT
108
- )
109
- print("\nTERMINOU DE FAZER A ÚLTIMA REQUISIÇÃO")
110
-
111
- if not isinstance(structured_summaries, list):
112
- from rest_framework.response import Response
113
-
114
- return Response({"erro": structured_summaries})
115
-
116
- texto_completo = summarizer.resumo_gerado + "\n\n"
117
-
118
- for x in structured_summaries:
119
- texto_completo = texto_completo + x["content"] + "\n"
120
- x["source"]["text"] = x["source"]["text"][0:200]
121
- x["source"]["context"] = x["source"]["context"][0:200]
122
-
123
- if isBubble:
124
- print("COMEÇANDO A REQUISIÇÃO FINAL PARA O BUBBLE")
125
- enviar_resposta_final(
126
- serializer["doc_id"],
127
- serializer["form_response_id"],
128
- serializer["version"],
129
- texto_completo,
130
- False,
131
  )
132
- print("TERMINOU A REQUISIÇÃO FINAL PARA O BUBBLE")
133
 
134
- return {
135
- "texto_completo": texto_completo,
136
- "resultado": structured_summaries,
137
- "parametros-utilizados": gerar_resposta_compilada(serializer),
138
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
3
+ from _utils.custom_exception_handler import custom_exception_handler_wihout_api_handler
4
  from _utils.gerar_relatorio_modelo_usuario.prompts import prompt_auxiliar_SEM_CONTEXT
5
  from _utils.gerar_relatorio_modelo_usuario.GerarDocumento import (
6
  GerarDocumento,
 
47
  serializer, listaPDFs, isBubble=False
48
  ):
49
  """Parâmetro "contexto" só deve ser passado quando quiser utilizar o teste com ragas, e assim, não quiser passar PDFs"""
50
+ try:
51
+ # Configuration
52
+ config = RetrievalConfig(
53
+ num_chunks=serializer["num_chunks_retrieval"],
54
+ embedding_weight=serializer["embedding_weight"],
55
+ bm25_weight=serializer["bm25_weight"],
56
+ context_window=serializer["context_window"],
57
+ chunk_overlap=serializer["chunk_overlap"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  )
59
 
60
+ contextual_retriever = ContextualRetriever(
61
+ config, serializer["claude_context_model"]
 
62
  )
63
+
64
+ # Initialize enhanced summarizer
65
+ summarizer = GerarDocumento(
66
+ config=config,
67
+ embedding_model=serializer["hf_embedding"],
68
+ chunk_overlap=serializer["chunk_overlap"],
69
+ chunk_size=serializer["chunk_size"],
70
+ num_k_rerank=serializer["num_k_rerank"],
71
+ model_cohere_rerank=serializer["model_cohere_rerank"],
72
+ # prompt_auxiliar=serializer["prompt_auxiliar"],
73
+ gpt_model=serializer["model"],
74
+ gpt_temperature=serializer["gpt_temperature"],
75
+ prompt_gerar_documento=serializer["prompt_gerar_documento"],
76
+ reciprocal_rank_fusion=reciprocal_rank_fusion,
77
  )
78
+
79
+ all_PDFs_chunks, full_text_as_array = await get_full_text_and_all_PDFs_chunks(
80
+ listaPDFs, summarizer.splitter, serializer["should_use_llama_parse"], isBubble
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  )
 
82
 
83
+ is_contextualized_chunk = serializer["should_have_contextual_chunks"]
84
+
85
+ if is_contextualized_chunk:
86
+ response_auxiliar_summary = await get_response_from_auxiliar_contextual_prompt(
87
+ full_text_as_array
88
+ )
89
+
90
+ print("\nCOMEÇANDO A FAZER AS REQUISIÇÕES DO CONTEXTUAL")
91
+ contextualized_chunks = await contextual_retriever.contextualize_all_chunks(
92
+ all_PDFs_chunks, response_auxiliar_summary
93
+ )
94
+ print("\nTERMINOU DE FAZER TODAS AS REQUISIÇÕES DO CONTEXTUAL")
95
+ chunks_processados = contextualized_chunks
96
+ else:
97
+ chunks_processados = all_PDFs_chunks
98
+
99
+ # Create enhanced vector store and BM25 index
100
+ vector_store, bm25, chunk_ids = (
101
+ summarizer.vector_store.create_enhanced_vector_store(
102
+ chunks_processados, is_contextualized_chunk
103
+ )
104
+ )
105
+
106
+ llm_ultimas_requests = serializer["llm_ultimas_requests"]
107
+ print("\nCOMEÇANDO A FAZER ÚLTIMA REQUISIÇÃO")
108
+ structured_summaries = await summarizer.gerar_documento_final(
109
+ vector_store, bm25, chunk_ids, llm_ultimas_requests, prompt_auxiliar_SEM_CONTEXT
110
+ )
111
+ print("\nTERMINOU DE FAZER A ÚLTIMA REQUISIÇÃO")
112
+
113
+ if not isinstance(structured_summaries, list):
114
+ from rest_framework.response import Response
115
+
116
+ return Response({"erro": structured_summaries})
117
+
118
+ texto_completo = summarizer.resumo_gerado + "\n\n"
119
+
120
+ for x in structured_summaries:
121
+ texto_completo = texto_completo + x["content"] + "\n"
122
+ x["source"]["text"] = x["source"]["text"][0:200]
123
+ x["source"]["context"] = x["source"]["context"][0:200]
124
+
125
+ if isBubble:
126
+ print("COMEÇANDO A REQUISIÇÃO FINAL PARA O BUBBLE")
127
+ enviar_resposta_final(
128
+ serializer["doc_id"],
129
+ serializer["form_response_id"],
130
+ serializer["version"],
131
+ texto_completo,
132
+ False,
133
+ )
134
+ print("TERMINOU A REQUISIÇÃO FINAL PARA O BUBBLE")
135
+
136
+ return {
137
+ "texto_completo": texto_completo,
138
+ "resultado": structured_summaries,
139
+ "parametros-utilizados": gerar_resposta_compilada(serializer),
140
+ }
141
+ except Exception as e:
142
+ custom_exception_handler_wihout_api_handler(e, serializer)
143
+ raise
_utils/vector_stores/Vector_store_class.py CHANGED
@@ -59,4 +59,4 @@ class VectorStore:
59
 
60
  except Exception as e:
61
  self.logger.error(f"Error creating enhanced vector store: {str(e)}")
62
- raise
 
59
 
60
  except Exception as e:
61
  self.logger.error(f"Error creating enhanced vector store: {str(e)}")
62
+ raise Exception(f"Error creating enhanced vector store: {str(e)}")