caarleexx commited on
Commit
a28de06
·
verified ·
1 Parent(s): 1783d1f

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -368
app.py DELETED
@@ -1,368 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Pipeline v10 - VERSÃO FINAL COM LÓGICA DE RETOMADA REATIVADA.
4
-
5
- Este script corrige a desativação acidental da funcionalidade de resumir a
6
- pipeline após uma pausa. Agora, o sistema está totalmente interativo.
7
-
8
- PRINCIPAIS FUNCIONALIDADES:
9
- - LÓGICA DE RETOMADA (RESUMIR) REATIVADA: O orquestrador agora chama
10
- corretamente a função `resumir_pipeline` quando o estado está 'paused',
11
- garantindo que a resposta do usuário seja usada para continuar o raciocínio.
12
- - SANITIZAÇÃO DE TEXTO: Mantida para robustez.
13
- - ROBUSTEZ COM TRY/EXCEPT: Mantida para tratamento de erros.
14
- - BYPASS INTELIGENTE (FAST PATH): Mantido para respostas rápidas.
15
- - PIPELINE GENERALIZADA: Mantida para versatilidade.
16
- - LOGS DE API: Mantidos para depuração.
17
- """
18
-
19
- # ============================================================================
20
- # 1. IMPORTAÇÕES E CONFIGURAÇÃO INICIAL
21
- # ============================================================================
22
- import json
23
- import os
24
- import re
25
- import warnings
26
- from datetime import datetime
27
- from typing import Dict, List, Tuple, Any
28
-
29
- import gradio as gr
30
- import google.generativeai as genai
31
-
32
- warnings.filterwarnings("ignore", category=FutureWarning, module="google.api_core")
33
-
34
- # --- Configuração da API ---
35
- API_KEY = os.getenv("GOOGLE_API_KEY")
36
- if not API_KEY:
37
- raise ValueError("A variável de ambiente GOOGLE_API_KEY não foi configurada.")
38
-
39
- genai.configure(api_key=API_KEY)
40
-
41
- # --- Definição dos Modelos ---
42
- COUNSELOR_MODEL = genai.GenerativeModel("gemini-2.5-flash")
43
- SUPERVISOR_MODEL = genai.GenerativeModel("gemini-2.5-pro")
44
-
45
- # --- Título da Interface ---
46
- TITLE = "# 🚀 Pipeline v10 | Raciocínio Adaptativo e Interativo\n**Com 'Fast Path', Pausa/Retomada e tratamento de erros.**"
47
-
48
- # ============================================================================
49
- # 2. PROMPTS CENTRALIZADOS
50
- # ============================================================================
51
- # (Os prompts permanecem os mesmos da versão anterior, sem alterações)
52
- PROMPTS = {
53
- "P1_TRIAGEM": """
54
- METACOGNIÇÃO - TRIAGEM INICIAL.
55
- PERGUNTA: {pergunta}
56
- ---
57
- Analise a pergunta do usuário e classifique-a de acordo com o tipo e a sua confiança para respondê-la de forma direta.
58
-
59
- Use as seguintes categorias:
60
- - tipo: 'factual' (pede um fato concreto), 'objetiva_tecnica' (pede uma resposta técnica com uma única resposta correta), 'subjetiva_complexa' (envolve opinião, análise, múltiplos fatores).
61
- - confianca: 'extrema' (certeza absoluta, como "Qual a capital do Brasil?"), 'alta', 'media', 'baixa', 'insuficiente'.
62
-
63
- RETORNE JSON:
64
- {{
65
- "tipo": "...",
66
- "confianca": "...",
67
- "decisao": "Com base na classificação, decida se deve 'responder_direto' (para factual/extrema ou objetiva_tecnica com confiança alta/extrema) ou 'analisar_profundamente' (para todas as outras)."
68
- }}
69
- """,
70
- "GERAR_RESPOSTA_DIRETA": """
71
- TAREFA: Resposta Direta (Bypass)
72
- A pergunta do usuário foi classificada como factual com extrema certeza ou objetiva-técnica.
73
- PERGUNTA: "{pergunta}"
74
- ---
75
- Forneça uma resposta direta, precisa e concisa.
76
-
77
- RETORNE JSON:
78
- {{"resposta_direta": "Sua resposta concisa aqui."}}
79
- """,
80
- "JUSTIFICAR_BYPASS": """
81
- METACOGNIÇÃO - JUSTIFICATIVA DE BYPASS.
82
- ANÁLISE DA TRIAGEM (P1): {p1}
83
- ---
84
- Você está pulando a pipeline de raciocínio profundo. Justifique esta decisão.
85
-
86
- RETORNE JSON:
87
- {{
88
- "justificativa_bypass": {{
89
- "motivo": "A pergunta foi identificada como [tipo da pergunta] para a qual a confiança de uma resposta direta é [nível de confiança].",
90
- "acao_tomada": "A pipeline de análise profunda foi pulada para fornecer uma resposta mais rápida e eficiente.",
91
- "proximo_passo": "A resposta direta será submetida a uma verificação final de qualidade."
92
- }}
93
- }}
94
- """,
95
- "P2_CENARIOS": """
96
- METACOGNIÇÃO - GERAÇÃO DE CENÁRIOS.
97
- ANÁLISE (P1): {p1}, PERGUNTA: {pergunta}
98
- ---
99
- Gere o cenário de interpretação mais provável e um cenário alternativo (improvável, mas plausível).
100
- RETORNE JSON:
101
- {{
102
- "cenarios": {{
103
- "provaveis": [{{"id": "C1_PROVAVEL", "desc": "Descrição do cenário mais provável."}}],
104
- "improvaveis": [{{"id": "C2_IMPROVAVEL", "desc": "Descrição do cenário alternativo."}}]
105
- }}, "decisao": "prosseguir"
106
- }}
107
- """,
108
- "P4_CRUZAR_VALIDACOES": """
109
- METACOGNIÇÃO - ABSTRAÇÃO DE CONHECcimento.
110
- ANÁLISES ANTERIORES: {p1}, {p2}, {p3}
111
- ---
112
- Identifique o princípio fundamental que rege a discussão.
113
- RETORNE JSON: {{"principio_central": "Descrição do princípio identificado."}}
114
- """,
115
- "P5_LACUNAS_FINAIS": """
116
- METACOGNIÇÃO - ANÁLISE DE INCERTEZA.
117
- PRINCÍPIO CENTRAL (P4): {p4}
118
- PERGUNTA ORIGINAL: {pergunta}
119
- ---
120
- Com base no princípio central, identifique a principal lacuna de informação. Formule uma pergunta clara para o usuário.
121
-
122
- RETORNE JSON:
123
- {{
124
- "pontos_de_incerteza": ["A principal dúvida que ainda resta."],
125
- "decisao_interna": "questionar",
126
- "pergunta_chave_para_usuario": "A pergunta clara e contextual que você fará ao usuário."
127
- }}
128
- """,
129
- "P7_SINTETIZAR": """
130
- SINTETIZADOR.
131
- DADOS DO JULGAMENTO (P6): {p6}
132
- ---
133
- Converta a análise técnica em uma resposta final coesa.
134
- RETORNE JSON: {{"resposta": "O texto da sua resposta final aqui."}}
135
- """,
136
- "P8_VERIFICAR": """
137
- VERIFICADOR FINAL.
138
- RESPOSTA A SER VERIFICADA: {resposta_a_verificar}
139
- ---
140
- Realize uma verificação tripla (factual, lógica, clareza). Se houver problemas, corrija-os.
141
- RETORNE JSON:
142
- {{
143
- "todas_aprovadas": true|false,
144
- "problemas_identificados": ["..."],
145
- "resposta_corrigida": "O texto da resposta corrigida, se necessário. Senão, null."
146
- }}
147
- """
148
- }
149
- # ============================================================================
150
- # 3. CLASSES E FUNÇÕES HELPERS
151
- # ============================================================================
152
-
153
- class Logger:
154
- # ... (código do Logger sem alterações) ...
155
- def __init__(self, verbose: bool = True): self.verbose = verbose
156
- def log(self, msg: str, level: str = "INFO"):
157
- log_msg = f"[{datetime.now().strftime('%H:%M:%S')}] [{level.upper()}] {msg}"; print(log_msg)
158
- if level.upper() in ["TASK", "START", "SUCCESS", "ERROR", "WARN"]: print("=" * 70)
159
-
160
- logger = Logger(verbose=True)
161
-
162
- def sanitizar_texto(texto: str) -> str:
163
- """Limpa e normaliza uma string para garantir um formato seguro e consistente."""
164
- if not isinstance(texto, str): return ""
165
- texto_limpo = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', texto)
166
- texto_limpo = re.sub(r'\s{2,}', ' ', texto_limpo).replace('\\n', '\n')
167
- return texto_limpo.strip()
168
-
169
- def chamar_gemini_json(modelo: genai.GenerativeModel, prompt: str, temperatura: float = 0.4, max_tokens: int = 2048) -> Dict:
170
- prompt_completo = f"{prompt}\n\n---\n\n**INSTRUÇÃO OBRIGATÓRIA: Sua resposta DEVE ser um único e válido objeto JSON.**"
171
- print(f"\n{'='*25} 💬 API INPUT PARA [{modelo.model_name}] {'='*25}\n{prompt_completo}\n{'='*78}\n")
172
- try:
173
- response = modelo.generate_content(prompt_completo, generation_config=genai.types.GenerationConfig(temperature=temperatura, max_output_tokens=max_tokens))
174
- resposta_bruta = response.text or ""
175
- print(f"\n{'='*25} 📥 API RAW OUTPUT DE [{modelo.model_name}] {'='*25}\n{resposta_bruta}\n{'='*78}\n")
176
-
177
- if not resposta_bruta.strip():
178
- logger.log("A API Gemini retornou uma resposta vazia. Causa provável: Filtros de segurança.", "WARN")
179
- return {"erro": "API_EMPTY_RESPONSE", "causa_provavel": "Filtro de segurança do modelo."}
180
-
181
- match = re.search(r'\{.*\}', resposta_bruta, re.DOTALL)
182
- if not match:
183
- return {"erro": "JSON_NOT_FOUND", "detalhes": "Nenhum objeto JSON encontrado na resposta da API."}
184
-
185
- return json.loads(match.group(0))
186
- except Exception as e:
187
- logger.log(f"Falha na chamada da API ou no parse do JSON: {e}", "ERROR")
188
- return {"erro": "API_CALL_OR_PARSE_FAILED", "detalhes": str(e)}
189
-
190
- def criar_dna() -> Dict:
191
- return { "historico_chat": [], "meta": {"total_turnos": 0}, "pipeline_state": { "status": "completed", "paused_at_step": None, "saved_data": {} } }
192
-
193
- # ============================================================================
194
- # 4. PASSOS DA PIPELINE
195
- # ============================================================================
196
- # (Funções de passo permanecem as mesmas)
197
- def passo_1_triagem(pergunta: str) -> Dict:
198
- logger.log("📊 PASSO 1: TRIAGEM INICIAL", "TASK")
199
- return chamar_gemini_json(COUNSELOR_MODEL, PROMPTS["P1_TRIAGEM"].format(pergunta=pergunta))
200
- def passo_gerar_resposta_direta(pergunta: str) -> Dict:
201
- logger.log("⚡ FAST PATH: GERANDO RESPOSTA DIRETA", "TASK")
202
- return chamar_gemini_json(COUNSELOR_MODEL, PROMPTS["GERAR_RESPOSTA_DIRETA"].format(pergunta=pergunta))
203
- def passo_justificar_bypass(p1: Dict) -> Dict:
204
- logger.log("⚡ FAST PATH: GERANDO JUSTIFICATIVA", "TASK")
205
- return chamar_gemini_json(COUNSELOR_MODEL, PROMPTS["JUSTIFICAR_BYPASS"].format(p1=json.dumps(p1)))
206
- def passo_2_cenarios(pergunta: str, p1: Dict) -> Dict:
207
- logger.log("🧠 PASSO 2: GERAÇÃO DE CENÁRIOS", "TASK")
208
- return chamar_gemini_json(COUNSELOR_MODEL, PROMPTS["P2_CENARIOS"].format(p1=json.dumps(p1), pergunta=pergunta))
209
- def passo_4_cruzar_validacoes(p1: Dict, p2: Dict, p3: Dict) -> Dict:
210
- logger.log("🧠 PASSO 4: IDENTIFICAÇÃO DO PRINCÍPIO CENTRAL", "TASK")
211
- return chamar_gemini_json(COUNSELOR_MODEL, PROMPTS["P4_CRUZAR_VALIDACOES"].format(p1=json.dumps(p1), p2=json.dumps(p2), p3=json.dumps(p3)))
212
- def passo_5_lacunas_finais(pergunta: str, p4: Dict) -> Dict:
213
- logger.log("🧠 PASSO 5: ANÁLISE DE INCERTEZA", "TASK")
214
- return chamar_gemini_json(COUNSELOR_MODEL, PROMPTS["P5_LACUNAS_FINAIS"].format(p4=json.dumps(p4), pergunta=pergunta))
215
- def passo_8_verificar(resposta_a_verificar: str) -> Dict:
216
- logger.log("✅ PASSO 8: VERIFICAÇÃO FINAL", "TASK")
217
- return chamar_gemini_json(SUPERVISOR_MODEL, PROMPTS["P8_VERIFICAR"].format(resposta_a_verificar=resposta_a_verificar))
218
- def passo_3_isolar_cenarios(p2: Dict) -> Dict: return {"simulado": True}
219
- def passo_6_ponderar(p2: Dict, p4: Dict, p5: Dict) -> Dict: return {"simulado": True}
220
- def passo_7_sintetizar(p6: Dict) -> Dict: return {"resposta": "Resposta vinda da pipeline completa."}
221
-
222
- # ============================================================================
223
- # 5. ORQUESTRADOR PRINCIPAL
224
- # ============================================================================
225
-
226
- def iniciar_nova_pipeline(pergunta_original: str, historico: List[Dict], anexo: Any, dna: Dict) -> Tuple[str, List, Dict]:
227
- pergunta = sanitizar_texto(pergunta_original)
228
- logger.log(f"INICIANDO NOVA PIPELINE (Input Sanitizado): '{pergunta[:70]}...'", "START")
229
-
230
- p1 = passo_1_triagem(pergunta)
231
- if "erro" in p1: return f"Erro na Triagem: {p1.get('detalhes', 'Não foi possível classificar a pergunta.')}", historico, dna
232
-
233
- if p1.get("decisao") == "responder_direto":
234
- logger.log("DECISÃO: Tomar o Caminho Rápido (Bypass).", "INFO")
235
- resposta_direta_data = passo_gerar_resposta_direta(pergunta)
236
- justificativa_data = passo_justificar_bypass(p1)
237
-
238
- if "erro" in resposta_direta_data or "erro" in justificativa_data:
239
- return "Erro ao gerar a resposta direta.", historico, dna
240
-
241
- resposta_direta = resposta_direta_data.get("resposta_direta", "Não foi possível gerar a resposta.")
242
- justificativa = justificativa_data.get("justificativa_bypass", {})
243
-
244
- verificacao = passo_8_verificar(resposta_direta)
245
- resposta_final = verificacao.get("resposta_corrigida") or resposta_direta
246
-
247
- justificativa_texto = f"**JUSTIFICATIVA DE RESPOSTA DIRETA:**\n- **Motivo:** {justificativa.get('motivo', 'N/A')}\n- **Ação:** {justificativa.get('acao_tomada', 'N/A')}\n\n---\n"
248
- resposta_formatada = justificativa_texto + resposta_final
249
-
250
- novo_historico = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": resposta_formatada}]
251
- logger.log("PIPELINE (FAST PATH) CONCLUÍDA", "SUCCESS")
252
- return "PIPELINE_COMPLETED", novo_historico, dna
253
-
254
- else:
255
- logger.log("DECISÃO: Tomar o Caminho Completo de Análise Profunda.", "INFO")
256
- p2 = passo_2_cenarios(pergunta, p1)
257
- p3 = passo_3_isolar_cenarios(p2)
258
- p4 = passo_4_cruzar_validacoes(p1, p2, p3)
259
- p5 = passo_5_lacunas_finais(pergunta, p4)
260
-
261
- if p5.get("decisao_interna") == "questionar":
262
- logger.log("INTERRUPÇÃO no P5. Salvando estado no DNA.", "WARN")
263
- dna['pipeline_state'] = {"status": "paused", "paused_at_step": "P5", "saved_data": {'p1':p1, 'p2':p2, 'p3':p3, 'p4':p4, 'pergunta_original': pergunta, 'historico_original': historico}}
264
- pergunta_do_bot = p5.get('pergunta_chave_para_usuario', 'Preciso de mais informações.')
265
- historico_atualizado = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": pergunta_do_bot}]
266
- return "PIPELINE_PAUSED", historico_atualizado, dna
267
-
268
- p6 = passo_6_ponderar(p2, p4, p5)
269
- p7 = passo_7_sintetizar(p6)
270
- p8 = passo_8_verificar(p7.get("resposta", ""))
271
- resposta_final = p8.get("resposta_corrigida") or p7.get("resposta", "Não foi possível gerar a resposta.")
272
- novo_historico = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": resposta_final}]
273
- logger.log("PIPELINE (COMPLETA) CONCLUÍDA", "SUCCESS")
274
- return "PIPELINE_COMPLETED", novo_historico, dna
275
-
276
- def resumir_pipeline(esclarecimento_usuario_original: str, dna: Dict) -> Tuple[str, List, Dict]:
277
- esclarecimento_usuario = sanitizar_texto(esclarecimento_usuario_original)
278
- logger.log(f"RESUMINDO PIPELINE com esclarecimento: '{esclarecimento_usuario[:70]}...'", "START")
279
-
280
- estado_salvo = dna['pipeline_state']['saved_data']
281
- ponto_parada = dna['pipeline_state']['paused_at_step']
282
- historico = estado_salvo['historico_original']
283
- pergunta_original = estado_salvo['pergunta_original']
284
- pergunta_atualizada = f"{pergunta_original}\n\n---ESCLARECIMENTO ADICIONAL DO USUÁRIO---\n{esclarecimento_usuario}"
285
-
286
- dna['pipeline_state'] = criar_dna()['pipeline_state'] # Limpa o estado de pausa
287
-
288
- # Continua do Ponto de Parada
289
- if ponto_parada == 'P5':
290
- logger.log("Retomando a partir do passo P6...", "INFO")
291
- p1, p2, p3, p4 = estado_salvo['p1'], estado_salvo['p2'], estado_salvo['p3'], estado_salvo['p4']
292
-
293
- # Reavalia as lacunas com a nova informação, mas agora com o objetivo de responder
294
- p5_novo = passo_5_lacunas_finais(pergunta_atualizada, p4)
295
- p5_novo['decisao_interna'] = 'responder' # Força a continuação
296
-
297
- p6 = passo_6_ponderar(p2, p4, p5_novo)
298
- else:
299
- # Fallback para outros pontos de parada (se implementados)
300
- raise ValueError(f"Ponto de retomada não implementado: {ponto_parada}")
301
-
302
- p7 = passo_7_sintetizar(p6)
303
- p8 = passo_8_verificar(p7.get("resposta", ""))
304
- resposta_final = p8.get("resposta_corrigida") or p7.get("resposta", "Não foi possível gerar uma resposta.")
305
-
306
- # Monta o histórico final para exibição
307
- historico_da_pausa = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": estado_salvo.get('pergunta_chave_para_usuario', '...')}]
308
- novo_historico = historico_da_pausa + [{"role": "user", "content": esclarecimento_usuario_original}, {"role": "assistant", "content": resposta_final}]
309
-
310
- logger.log("PIPELINE (RESUMIDA) CONCLUÍDA", "SUCCESS")
311
- return "PIPELINE_COMPLETED", novo_historico, dna
312
-
313
- def executar_pipeline(pergunta: str, historico: List[Dict], anexo: Any, dna: Dict) -> Tuple[str, List, Dict]:
314
- try:
315
- if 'pipeline_state' not in dna: dna.update(criar_dna())
316
-
317
- # CORREÇÃO: A chamada para 'resumir_pipeline' foi reativada.
318
- if dna['pipeline_state']['status'] == 'paused':
319
- return resumir_pipeline(pergunta, dna)
320
- else:
321
- return iniciar_nova_pipeline(pergunta, historico, anexo, dna)
322
-
323
- except Exception as e:
324
- logger.log(f"Erro catastrófico no orquestrador: {e}", "ERROR")
325
- resposta_erro = f"Ocorreu um erro inesperado na pipeline: {e}"
326
- return "PIPELINE_ERROR", historico + [{"role": "user", "content": pergunta}, {"role": "assistant", "content": resposta_erro}], dna
327
-
328
- # ============================================================================
329
- # 6. INTERFACE COM GRADIO
330
- # ============================================================================
331
- def converter_historico_para_gradio(historico_interno: List[Dict]) -> List[List[str]]:
332
- historico_gradio = []
333
- for i in range(0, len(historico_interno), 2):
334
- if i + 1 < len(historico_interno):
335
- historico_gradio.append([historico_interno[i]['content'], historico_interno[i+1]['content']])
336
- return historico_gradio
337
-
338
- def chat_interface(pergunta: str, historico_gradio: List[List[str]], anexo: Any, dna_json_str: str) -> Tuple[List, str, str, None]:
339
- try:
340
- dna = json.loads(dna_json_str) if dna_json_str and dna_json_str.strip() else criar_dna()
341
- except:
342
- dna = criar_dna()
343
-
344
- historico_interno = [item for turno in historico_gradio for item in ({"role": "user", "content": turno[0]}, {"role": "assistant", "content": turno[1]}) if turno and item['content']]
345
-
346
- _ , novo_historico_para_exibir, dna_atualizado = executar_pipeline(pergunta, historico_interno, anexo, dna)
347
-
348
- novo_historico_gradio = converter_historico_para_gradio(novo_historico_para_exibir)
349
-
350
- return novo_historico_gradio, "", json.dumps(dna_atualizado, indent=2, ensure_ascii=False), None
351
-
352
- if __name__ == "__main__":
353
- with gr.Blocks(title="Pipeline v10 - Raciocínio Adaptativo", theme=gr.themes.Soft()) as demo:
354
- gr.Markdown(TITLE)
355
- with gr.Row():
356
- with gr.Column(scale=3):
357
- chatbot = gr.Chatbot(label="Chat", height=600, bubble_full_width=False)
358
- input_textbox = gr.Textbox(label="Digite sua pergunta...", lines=3)
359
- with gr.Row():
360
- submit_button = gr.Button("🚀 Enviar", variant="primary", scale=1)
361
- file_upload = gr.File(label="Anexar Arquivo", scale=1)
362
- with gr.Column(scale=2):
363
- dna_view = gr.Code(label="DNA (Estado da Conversa)", language="json", interactive=False, value=json.dumps(criar_dna(), indent=2, ensure_ascii=False))
364
- dna_json_hidden = gr.Textbox(value=json.dumps(criar_dna()), visible=False)
365
- submit_button.click(fn=chat_interface, inputs=[input_textbox, chatbot, file_upload, dna_json_hidden], outputs=[chatbot, input_textbox, dna_json_hidden, file_upload])
366
- input_textbox.submit(fn=chat_interface, inputs=[input_textbox, chatbot, file_upload, dna_json_hidden], outputs=[chatbot, input_textbox, dna_json_hidden, file_upload])
367
- dna_json_hidden.change(fn=lambda x: x, inputs=[dna_json_hidden], outputs=[dna_view])
368
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)