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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--- START OF FILE app.py ---
|
| 2 |
+
|
| 3 |
+
# -*- coding: utf-8 -*-
|
| 4 |
+
"""
|
| 5 |
+
Pipeline v10 - CÓDIGO FINAL E COESO
|
| 6 |
+
|
| 7 |
+
Características:
|
| 8 |
+
- Memória API: Passagem de histórico em genai.types.Content para contexto.
|
| 9 |
+
- Robustez: Chamada de API V1 com correções para Tools/ThinkingConfig.
|
| 10 |
+
- Prompts Dinâmicos: Carregamento, salvamento e edição dinâmica.
|
| 11 |
+
- Auditoria: Histórico de Governança compactado no DNA (últimos 10 turnos).
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
# ============================================================================
|
| 15 |
+
# 1. IMPORTAÇÕES E CONFIGURAÇÃO INICIAL
|
| 16 |
+
# ============================================================================
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import warnings
|
| 21 |
+
from datetime import datetime
|
| 22 |
+
from typing import Dict, List, Tuple, Any
|
| 23 |
+
|
| 24 |
+
import gradio as gr
|
| 25 |
+
|
| 26 |
+
from google import genai
|
| 27 |
+
from google.genai import types
|
| 28 |
+
|
| 29 |
+
# Define o nome do arquivo de prompts para uso centralizado
|
| 30 |
+
PROMPT_FILENAME = "prompts_pipeline.json"
|
| 31 |
+
|
| 32 |
+
warnings.filterwarnings("ignore", category=FutureWarning, module="google.api_core")
|
| 33 |
+
|
| 34 |
+
# --- Classes de Utilidade: LOGGER (Movido para garantir a definição inicial) ---
|
| 35 |
+
class Logger:
|
| 36 |
+
def __init__(self, verbose: bool = True): self.verbose = verbose
|
| 37 |
+
def log(self, msg: str, level: str = "INFO"):
|
| 38 |
+
log_msg = f"[{datetime.now().strftime('%H:%M:%S')}] [{level.upper()}] {msg}"; print(log_msg)
|
| 39 |
+
if level.upper() in ["TASK", "START", "SUCCESS", "ERROR", "WARN"]: print("=" * 70)
|
| 40 |
+
|
| 41 |
+
# INSTÂNCIA DO LOGGER
|
| 42 |
+
logger = Logger(verbose=True)
|
| 43 |
+
|
| 44 |
+
# --- Configuração da API ---
|
| 45 |
+
API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 46 |
+
if not API_KEY:
|
| 47 |
+
raise ValueError("A variável de ambiente GOOGLE_API_KEY não foi configurada.")
|
| 48 |
+
|
| 49 |
+
CLIENT = genai.Client(api_key=API_KEY)
|
| 50 |
+
|
| 51 |
+
# --- Definição dos Modelos e Título ---
|
| 52 |
+
COUNSELOR_MODEL_NAME = "gemini-2.5-pro"
|
| 53 |
+
SUPERVISOR_MODEL_NAME = "gemini-2.5-pro"
|
| 54 |
+
TITLE = "# 🚀 Pipeline v10 | Governanca e Memória API"
|
| 55 |
+
|
| 56 |
+
# ============================================================================
|
| 57 |
+
# 2. PROMPTS CENTRALIZADOS (FUNÇÕES DE CARREGAMENTO/SALVAMENTO)
|
| 58 |
+
# ============================================================================
|
| 59 |
+
PROMPTS = {} # Variável global para os prompts em memória
|
| 60 |
+
|
| 61 |
+
# Placeholder de fallback completo (para uso direto)
|
| 62 |
+
FALLBACK_PROMPTS = {
|
| 63 |
+
"P1_TRIAGEM": "METACOGNIÇÃO - TRIAGEM INICIAL.\nPERGUNTA: {pergunta}\n---\nAnalise a PERGUNTA do usuário e o histórico de conversa. Sua função é CLASSIFICAR e TOMAR UMA DECISÃO.\n\n### CRITÉRIOS DE CLASSIFICAÇÃO\n1. **tipo**: 'factual', 'objetiva_tecnica', ou 'subjetiva_complexa'.\n2. **confianca**: 'extrema', 'alta', 'media', 'baixa', ou 'insuficiente'.\n### DECISÃO\n- 'responder_direto': Use para 'factual' com confiança 'extrema' ou 'alta'.\n- 'analisar_profundamente': Use para todas as outras combinações.\nRETORNE JSON: {{\"tipo\": \"...\", \"confianca\": \"...\", \"decisao\": \"responder_direto|analisar_profundamente\"}}",
|
| 64 |
+
"GERAR_RESPOSTA_DIRETA": "TAREFA: Resposta Direta (Bypass).\nPERGUNTA: \"{pergunta}\"\n---\nConsiderando o histórico de conversa (memória), forneça uma resposta completa, precisa e concisa para a última PERGUNTA do usuário.\nRETORNE JSON: {{\"resposta_direta\": \"Sua resposta concisa e precisa aqui.\"}}",
|
| 65 |
+
"JUSTIFICAR_BYPASS": "METACOGNIÇÃO - JUSTIFICATIVA DE BYPASS.\nANÁLISE (P1): {p1}\n---\nJustifique, para a governança interna, por que a pipeline de raciocínio profundo foi pulada com base na Triagem P1 (JSON fornecido).\nRETORNE JSON: {{\"justificativa_bypass\": {{\"motivo\": \"A pergunta foi classificada como ... e a confiança era ....\", \"acao_tomada\": \"...\", \"proximo_passo\": \"...\", \"p1_decisao\": {p1}}}}}",
|
| 66 |
+
"P2_CENARIOS": "METACOGNIÇÃO - GERAÇÃO DE CENÁRIOS.\nANÁLISE (P1): {p1}, PERGUNTA: {pergunta}\n---\nCrie 2 cenários prováveis que VALIDAM e 2 cenários IMPROVÁVEIS que REFUTAM o princípio inerente da pergunta.\nRETORNE JSON: {{\"cenarios\": {{\"provaveis\": [\"Fato/Cenário que Valida 1\", \"Fato/Cenário que Valida 2\"], \"improvaveis\": [\"Fato/Cenário que Refuta 1\", \"Fato/Cenário que Refuta 2\"]}}, \"decisao\": \"prosseguir para as próximas validações.\"}}",
|
| 67 |
+
"P4_CRUZAR_VALIDACOES": "METACOGNIÇÃO - ABSTRAÇÃO E FUNDAMENTO.\nANÁLISES ANTERIORES: P1(Triagem): {p1}, P2(Cenários): {p2}, P3(Isolamento Simulado): {p3}\n---\nCruze as análises. Identifique o Princípio Central/Fundamento que guiará a resposta.\nRETORNE JSON: {{\"principio_central\": \"O Princípio Central da discussão é ...\", \"analise_de_inconsistencia\": \"...\", \"status_analise\": \"FUNDAMENTO_OK\"}}",
|
| 68 |
+
"P5_LACUNAS_FINAIS": "METACOGNIÇÃO - ANÁLISE DE INCERTEZA.\nPRINCÍPIO CENTRAL (P4): {p4}, PERGUNTA: {pergunta}\n---\nIdentifique a(s) lacuna(s) de informação.\n- Decisão: 'continuar' (pode resolver a incerteza) ou 'questionar' (precisa do dado do usuário).\nRETORNE JSON: {{\"pontos_de_incerteza\": [\"Detalhe 1\", \"Detalhe 2\"], \"decisao_interna\": \"questionar|continuar\", \"pergunta_chave_para_usuario\": \"Sua pergunta para o usuário (ou null se for 'continuar').\"}}",
|
| 69 |
+
"P7_SINTETIZAR": "SINTETIZADOR.\nDADOS CRÍTICOS (P6: Ponderação Final): {p6}\n---\nConverta todo o raciocínio profundo em uma RESPOSTA FINAL coesa e completa.\nRETORNE JSON: {{\"resposta\": \"Sua resposta completa aqui. Deve ser direta e refletir a profundidade da análise executada.\"}}",
|
| 70 |
+
"P8_VERIFICAR": "VERIFICADOR FINAL (SUPERVISOR DE QUALIDADE).\nRESPOSTA A VERIFICAR: {resposta_a_verificar}\n---\nRealize a verificação tripla (Factual, Lógica, Clareza). Se for necessário, corrija.\nRETORNE JSON: {{\"todas_aprovadas\": true|false, \"erros_encontrados\": \"...\", \"resposta_corrigida\": null}} (Se true) ou {{\"todas_aprovadas\": false, \"erros_encontrados\": \"...\", \"resposta_corrigida\": \"[Novo Texto Final e Corrigido].\"}} (Se false)"
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def carregar_prompts_externos(filename: str = PROMPT_FILENAME) -> Dict:
|
| 75 |
+
"""Carrega prompts do arquivo ou retorna o fallback."""
|
| 76 |
+
try:
|
| 77 |
+
with open(filename, 'r', encoding='utf-8') as f:
|
| 78 |
+
full_prompts = json.load(f)
|
| 79 |
+
if not all(key in full_prompts for key in FALLBACK_PROMPTS.keys()):
|
| 80 |
+
raise ValueError("O arquivo de prompts está incompleto ou malformatado.")
|
| 81 |
+
logger.log(f"Prompts carregados com sucesso do arquivo: {filename}", "SUCCESS")
|
| 82 |
+
return full_prompts
|
| 83 |
+
except Exception as e:
|
| 84 |
+
logger.log(f"Não foi possível carregar os prompts externos: {e}. Usando FALLBACK.", "ERROR")
|
| 85 |
+
return FALLBACK_PROMPTS
|
| 86 |
+
|
| 87 |
+
def get_prompts_raw_text(filename: str = PROMPT_FILENAME) -> str:
|
| 88 |
+
"""Lê o arquivo de prompts como texto bruto para o editor do Gradio, ou retorna fallback."""
|
| 89 |
+
try:
|
| 90 |
+
if not os.path.exists(filename):
|
| 91 |
+
return json.dumps(FALLBACK_PROMPTS, indent=2, ensure_ascii=False)
|
| 92 |
+
with open(filename, 'r', encoding='utf-8') as f:
|
| 93 |
+
return f.read()
|
| 94 |
+
except:
|
| 95 |
+
return json.dumps({"erro": "Não foi possível ler o arquivo."}, indent=2, ensure_ascii=False)
|
| 96 |
+
|
| 97 |
+
def salvar_e_recarregar_prompts(new_prompts_json_str: str) -> str:
|
| 98 |
+
"""Salva o novo JSON no arquivo e recarrega a variável PROMPTS global."""
|
| 99 |
+
global PROMPTS
|
| 100 |
+
try:
|
| 101 |
+
novo_dicionario = json.loads(new_prompts_json_str)
|
| 102 |
+
with open(PROMPT_FILENAME, 'w', encoding='utf-8') as f:
|
| 103 |
+
json.dump(novo_dicionario, f, indent=2, ensure_ascii=False)
|
| 104 |
+
PROMPTS = novo_dicionario
|
| 105 |
+
logger.log(f"Novo arquivo de prompts salvo e recarregado com sucesso.", "SUCCESS")
|
| 106 |
+
return f"✅ SUCESSO! Prompts salvos em {PROMPT_FILENAME} e variáveis em memória atualizadas. Última atualização: {datetime.now().strftime('%H:%M:%S')}."
|
| 107 |
+
except json.JSONDecodeError:
|
| 108 |
+
logger.log("ERRO: O JSON enviado é inválido. Não foi possível salvar ou recarregar.", "ERROR")
|
| 109 |
+
return "❌ ERRO: O JSON enviado está malformado. Corrija o JSON antes de salvar."
|
| 110 |
+
except Exception as e:
|
| 111 |
+
logger.log(f"ERRO CRÍTICO no servidor: Falha ao escrever o arquivo. Detalhes: {e}", "ERROR")
|
| 112 |
+
return f"❌ ERRO CRÍTICO no servidor: Falha ao escrever o arquivo. Detalhes: {e}"
|
| 113 |
+
|
| 114 |
+
# INICIALIZAÇÃO OBRIGATÓRIA DA VARIÁVEL GLOBAL DE PROMPTS
|
| 115 |
+
PROMPTS = carregar_prompts_externos()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ============================================================================
|
| 119 |
+
# 3. CLASSES E FUNÇÕES HELPERS ADICIONAIS
|
| 120 |
+
# ============================================================================
|
| 121 |
+
def sanitizar_texto(texto: str) -> str:
|
| 122 |
+
if not isinstance(texto, str): return ""
|
| 123 |
+
texto_limpo = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', texto)
|
| 124 |
+
texto_limpo = re.sub(r'\s{2,}', ' ', texto_limpo).replace('\\n', '\n')
|
| 125 |
+
return texto_limpo.strip()
|
| 126 |
+
|
| 127 |
+
def to_gemini_contents(historico: List[Dict]) -> List[types.Content]:
|
| 128 |
+
"""Converte o histórico Gradio-compatível para o formato genai.types.Content (user/model)."""
|
| 129 |
+
gemini_contents = []
|
| 130 |
+
for entry in historico:
|
| 131 |
+
role = "model" if entry["role"] == "assistant" else "user"
|
| 132 |
+
content_for_api = re.sub(r'\*\*JUSTIFICATIVA DE RESPOSTA DIRETA:\*\*.*?\-\-\-\n\n', '', entry["content"], flags=re.DOTALL)
|
| 133 |
+
if content_for_api:
|
| 134 |
+
gemini_contents.append(
|
| 135 |
+
types.Content(
|
| 136 |
+
role=role,
|
| 137 |
+
parts=[types.Part.from_text(text=content_for_api)]
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
return gemini_contents
|
| 141 |
+
|
| 142 |
+
def chamar_gemini_json(model_name: str, prompt: str,
|
| 143 |
+
historico_conversa: List[types.Content] = None,
|
| 144 |
+
temperatura: float = 0.4, max_tokens: int = 8192) -> Dict:
|
| 145 |
+
prompt_completo = f"{prompt}\n\n---\n\n**INSTRUÇÃO CRÍTICA: Não use formatação Markdown. Sua resposta DEVE ser estritamente um único objeto JSON válido.**"
|
| 146 |
+
try:
|
| 147 |
+
contents = historico_conversa if historico_conversa else []
|
| 148 |
+
contents.append(types.Content(role="user", parts=[types.Part.from_text(text=prompt_completo)]))
|
| 149 |
+
tools = [types.Tool(google_search=types.GoogleSearch())]
|
| 150 |
+
generate_content_config = types.GenerateContentConfig(
|
| 151 |
+
temperature=temperatura,
|
| 152 |
+
max_output_tokens=max_tokens,
|
| 153 |
+
thinking_config=types.ThinkingConfig(thinking_budget=8192),
|
| 154 |
+
tools=tools
|
| 155 |
+
)
|
| 156 |
+
stream = CLIENT.models.generate_content_stream(model=model_name, contents=contents, config=generate_content_config)
|
| 157 |
+
|
| 158 |
+
resposta_bruta = "".join(chunk.text for chunk in stream if chunk.text)
|
| 159 |
+
resposta_sanitizada = sanitizar_texto(resposta_bruta)
|
| 160 |
+
|
| 161 |
+
if not resposta_sanitizada:
|
| 162 |
+
return {"erro": "API_EMPTY_RESPONSE"}
|
| 163 |
+
|
| 164 |
+
match = re.search(r'\{.*\}', resposta_sanitizada, re.DOTALL)
|
| 165 |
+
if match:
|
| 166 |
+
return json.loads(match.group(0))
|
| 167 |
+
else:
|
| 168 |
+
return json.loads(resposta_sanitizada)
|
| 169 |
+
|
| 170 |
+
except Exception as e:
|
| 171 |
+
logger.log(f"Falha na chamada da API ou no parse do JSON: {e}", "ERROR")
|
| 172 |
+
return {"erro": "API_CALL_FAILED", "detalhes": str(e)}
|
| 173 |
+
|
| 174 |
+
def criar_dna() -> Dict:
|
| 175 |
+
return {
|
| 176 |
+
"historico_governanca": [],
|
| 177 |
+
"meta": {"total_turnos": 0},
|
| 178 |
+
"pipeline_state": { "status": "completed", "paused_at_step": None, "saved_data": {} },
|
| 179 |
+
"P1_data": {}, "P2_data": {}, "P4_data": {}, "P5_data": {}, "P8_data": {},
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
def formatar_dna_json(data: Dict) -> str:
|
| 183 |
+
"""Retorna um JSON formatado com dois espaços de indentação."""
|
| 184 |
+
try:
|
| 185 |
+
return json.dumps(data, indent=2, ensure_ascii=False)
|
| 186 |
+
except:
|
| 187 |
+
return f"Erro ao serializar dados: {data}"
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# ============================================================================
|
| 191 |
+
# 4. PASSOS DA PIPELINE
|
| 192 |
+
# ============================================================================
|
| 193 |
+
def passo_1_triagem(pergunta: str, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[Dict, Dict]:
|
| 194 |
+
logger.log("📊 PASSO 1: TRIAGEM INICIAL", "TASK")
|
| 195 |
+
p1 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P1_TRIAGEM"].format(pergunta=pergunta), historico_conversa=historico_memoria)
|
| 196 |
+
dna["P1_data"] = p1
|
| 197 |
+
return p1, dna
|
| 198 |
+
def passo_gerar_resposta_direta(pergunta: str, historico_memoria: List[types.Content]) -> Dict:
|
| 199 |
+
logger.log("⚡ FAST PATH: GERANDO RESPOSTA DIRETA", "TASK")
|
| 200 |
+
return chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["GERAR_RESPOSTA_DIRETA"].format(pergunta=pergunta), historico_conversa=historico_memoria)
|
| 201 |
+
def passo_justificar_bypass(p1: Dict) -> Dict:
|
| 202 |
+
logger.log("⚡ FAST PATH: GERANDO JUSTIFICATIVA", "TASK")
|
| 203 |
+
return chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["JUSTIFICAR_BYPASS"].format(p1=json.dumps(p1)))
|
| 204 |
+
def passo_2_cenarios(pergunta: str, p1: Dict, dna: Dict) -> Tuple[Dict, Dict]:
|
| 205 |
+
logger.log("🧠 PASSO 2: GERAÇÃO DE CENÁRIOS", "TASK")
|
| 206 |
+
p2 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P2_CENARIOS"].format(p1=json.dumps(p1), pergunta=pergunta))
|
| 207 |
+
dna["P2_data"] = p2
|
| 208 |
+
return p2, dna
|
| 209 |
+
def passo_4_cruzar_validacoes(p1: Dict, p2: Dict, p3: Dict, dna: Dict) -> Tuple[Dict, Dict]:
|
| 210 |
+
logger.log("🧠 PASSO 4: IDENTIFICAÇÃO DO PRINCÍPIO CENTRAL", "TASK")
|
| 211 |
+
p4 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P4_CRUZAR_VALIDACOES"].format(p1=json.dumps(p1), p2=json.dumps(p2), p3=json.dumps(p3)))
|
| 212 |
+
dna["P4_data"] = p4
|
| 213 |
+
return p4, dna
|
| 214 |
+
def passo_5_lacunas_finais(pergunta: str, p4: Dict, dna: Dict) -> Tuple[Dict, Dict]:
|
| 215 |
+
logger.log("🧠 PASSO 5: ANÁLISE DE INCERTEZA", "TASK")
|
| 216 |
+
p5 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P5_LACUNAS_FINAIS"].format(p4=json.dumps(p4), pergunta=pergunta))
|
| 217 |
+
dna["P5_data"] = p5
|
| 218 |
+
return p5, dna
|
| 219 |
+
def passo_8_verificar(resposta_a_verificar: str, dna: Dict) -> Tuple[Dict, Dict]:
|
| 220 |
+
logger.log("✅ PASSO 8: VERIFICAÇÃO FINAL", "TASK")
|
| 221 |
+
p8 = chamar_gemini_json(SUPERVISOR_MODEL_NAME, PROMPTS["P8_VERIFICAR"].format(resposta_a_verificar=resposta_a_verificar))
|
| 222 |
+
dna["P8_data"] = p8
|
| 223 |
+
return p8, dna
|
| 224 |
+
# Simulado
|
| 225 |
+
def passo_3_isolar_cenarios(p2: Dict) -> Dict: return {"simulado": True}
|
| 226 |
+
def passo_6_ponderar(p2: Dict, p4: Dict, p5: Dict) -> Dict: return {"simulado": True}
|
| 227 |
+
def passo_7_sintetizar(p6: Dict) -> Dict: return {"resposta": "Resposta sintetizada vinda da pipeline completa (simulado)."}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ============================================================================
|
| 231 |
+
# 5. ORQUESTRADOR PRINCIPAL
|
| 232 |
+
# ============================================================================
|
| 233 |
+
def salvar_governanca(dna: Dict, pergunta: str, tipo: str, **data) -> None:
|
| 234 |
+
"""Salva o registro da iteração de governança."""
|
| 235 |
+
entry = {"turno": dna['meta']['total_turnos'], "timestamp": datetime.now().strftime('%H:%M:%S'), "tipo": tipo, "pergunta": pergunta, **data}
|
| 236 |
+
dna["historico_governanca"].append(entry)
|
| 237 |
+
if len(dna["historico_governanca"]) > 10:
|
| 238 |
+
dna["historico_governanca"] = dna["historico_governanca"][-10:]
|
| 239 |
+
|
| 240 |
+
def iniciar_nova_pipeline(pergunta_original: str, historico: List[Dict], anexo: Any, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[str, List, Dict]:
|
| 241 |
+
pergunta = sanitizar_texto(pergunta_original)
|
| 242 |
+
|
| 243 |
+
p1, dna = passo_1_triagem(pergunta, dna, historico_memoria)
|
| 244 |
+
if "erro" in p1: return f"Erro na Triagem: {p1.get('detalhes', 'Não foi possível classificar a pergunta.')}", historico, dna
|
| 245 |
+
|
| 246 |
+
# FAST PATH
|
| 247 |
+
if p1.get("decisao") == "responder_direto":
|
| 248 |
+
resposta_direta_data = passo_gerar_resposta_direta(pergunta, historico_memoria)
|
| 249 |
+
justificativa_data = passo_justificar_bypass(p1)
|
| 250 |
+
if "erro" in resposta_direta_data:
|
| 251 |
+
return f"Erro ao gerar a resposta direta: {resposta_direta_data['detalhes']}", historico, dna
|
| 252 |
+
|
| 253 |
+
resposta_direta = resposta_direta_data.get("resposta_direta", "Não foi possível gerar a resposta.")
|
| 254 |
+
justificativa = justificativa_data.get("justificativa_bypass", {})
|
| 255 |
+
verificacao, dna = passo_8_verificar(resposta_direta, dna)
|
| 256 |
+
resposta_final = verificacao.get("resposta_corrigida") or resposta_direta
|
| 257 |
+
|
| 258 |
+
justificativa_texto = f"**JUSTIFICATIVA DE RESPOSTA DIRETA:**\n- **Tipo/Confiança (P1):** {p1.get('tipo', 'N/A')}/{p1.get('confianca', 'N/A')}\n- **Motivo:** {justificativa.get('motivo', 'N/A')}\n\n---\n"
|
| 259 |
+
resposta_formatada = justificativa_texto + resposta_final
|
| 260 |
+
|
| 261 |
+
novo_historico = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": resposta_formatada}]
|
| 262 |
+
salvar_governanca(dna, pergunta_original, "FAST_PATH", p1=p1, p8=verificacao)
|
| 263 |
+
return "PIPELINE_COMPLETED", novo_historico, dna
|
| 264 |
+
|
| 265 |
+
# FULL PATH
|
| 266 |
+
else:
|
| 267 |
+
p2, dna = passo_2_cenarios(pergunta, p1, dna)
|
| 268 |
+
p3 = passo_3_isolar_cenarios(p2)
|
| 269 |
+
p4, dna = passo_4_cruzar_validacoes(p1, p2, p3, dna)
|
| 270 |
+
p5, dna = passo_5_lacunas_finais(pergunta, p4, dna)
|
| 271 |
+
|
| 272 |
+
if p5.get("decisao_interna") == "questionar":
|
| 273 |
+
salvar_governanca(dna, pergunta_original, "FULL_PATH_PAUSA", p1=p1, p5=p5)
|
| 274 |
+
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}}
|
| 275 |
+
pergunta_do_bot = p5.get('pergunta_chave_para_usuario', 'Preciso de mais informações.')
|
| 276 |
+
historico_atualizado = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": pergunta_do_bot}]
|
| 277 |
+
return "PIPELINE_PAUSED", historico_atualizado, dna
|
| 278 |
+
|
| 279 |
+
p6 = passo_6_ponderar(p2, p4, p5)
|
| 280 |
+
p7 = passo_7_sintetizar(p6)
|
| 281 |
+
p8, dna = passo_8_verificar(p7.get("resposta", ""), dna)
|
| 282 |
+
|
| 283 |
+
resposta_final = p8.get("resposta_corrigida") or p7.get("resposta", "Não foi possível gerar a resposta.")
|
| 284 |
+
novo_historico = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": resposta_final}]
|
| 285 |
+
dna['pipeline_state']['status'] = 'completed'
|
| 286 |
+
|
| 287 |
+
salvar_governanca(dna, pergunta_original, "FULL_PATH_CONCLUIDO", p1=p1, p2=p2, p4=p4, p5=p5, p8=p8)
|
| 288 |
+
return "PIPELINE_COMPLETED", novo_historico, dna
|
| 289 |
+
|
| 290 |
+
def resumir_pipeline(esclarecimento_usuario_original: str, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[str, List, Dict]:
|
| 291 |
+
# Lógica de Retomada Simulada
|
| 292 |
+
dados_salvos = dna['pipeline_state']['saved_data']
|
| 293 |
+
resposta = "RESUMIDO! A pipeline (pausada) foi retomada com o seu esclarecimento, mas a lógica de retomada completa precisa ser implementada."
|
| 294 |
+
dna['pipeline_state']['status'] = 'completed'
|
| 295 |
+
historico_atualizado = dados_salvos['historico_original'] + [{"role": "user", "content": esclarecimento_usuario_original}, {"role": "assistant", "content": resposta}]
|
| 296 |
+
salvar_governanca(dna, esclarecimento_usuario_original, "RETOMADA_SIMULADA", p_resumido=True, status="P_COMPLETED")
|
| 297 |
+
return "PIPELINE_COMPLETED", historico_atualizado, dna
|
| 298 |
+
|
| 299 |
+
def executar_pipeline(pergunta: str, historico: List[Dict], anexo: Any, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[str, List, Dict]:
|
| 300 |
+
try:
|
| 301 |
+
if 'pipeline_state' not in dna: dna.update(criar_dna())
|
| 302 |
+
dna['meta']['total_turnos'] = dna['meta'].get('total_turnos', 0) + 1
|
| 303 |
+
|
| 304 |
+
if dna['pipeline_state']['status'] == 'paused':
|
| 305 |
+
return resumir_pipeline(pergunta, dna, historico_memoria)
|
| 306 |
+
|
| 307 |
+
for key in ["P1_data", "P2_data", "P4_data", "P5_data", "P8_data"]:
|
| 308 |
+
dna[key] = {}
|
| 309 |
+
|
| 310 |
+
return iniciar_nova_pipeline(pergunta, historico, anexo, dna, historico_memoria)
|
| 311 |
+
|
| 312 |
+
except Exception as e:
|
| 313 |
+
logger.log(f"Erro catastrófico no orquestrador: {e}", "ERROR")
|
| 314 |
+
resposta_erro = f"Ocorreu um erro inesperado na pipeline: {e}"
|
| 315 |
+
dna['pipeline_state']['status'] = 'error'
|
| 316 |
+
salvar_governanca(dna, pergunta, "ERRO_CATASTRÓFICO", erro=str(e))
|
| 317 |
+
return "PIPELINE_ERROR", historico + [{"role": "user", "content": pergunta}, {"role": "assistant", "content": resposta_erro}], dna
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
# ============================================================================
|
| 321 |
+
# 6. INTERFACE COM GRADIO
|
| 322 |
+
# ============================================================================
|
| 323 |
+
|
| 324 |
+
def chat_interface(pergunta: str, historico_gradio: List[List[str]], anexo: Any, dna_json_str: str) -> Tuple[List, str, str, None, str, str, str, str, str, str, str]:
|
| 325 |
+
|
| 326 |
+
try:
|
| 327 |
+
dna = json.loads(dna_json_str) if dna_json_str and dna_json_str.strip() else criar_dna()
|
| 328 |
+
except:
|
| 329 |
+
dna = criar_dna()
|
| 330 |
+
|
| 331 |
+
# Prepara o histórico
|
| 332 |
+
historico_interno = []
|
| 333 |
+
for turno in historico_gradio:
|
| 334 |
+
if turno and turno[0]: historico_interno.append({"role": "user", "content": turno[0]})
|
| 335 |
+
if turno and turno[1]: historico_interno.append({"role": "assistant", "content": turno[1]})
|
| 336 |
+
|
| 337 |
+
historico_para_gemini = to_gemini_contents(historico_interno)
|
| 338 |
+
|
| 339 |
+
# Execução
|
| 340 |
+
_ , novo_historico_para_exibir, dna_atualizado = executar_pipeline(pergunta, historico_interno, anexo, dna, historico_para_gemini)
|
| 341 |
+
|
| 342 |
+
# Conversão de Outputs
|
| 343 |
+
novo_historico_gradio = []
|
| 344 |
+
for i in range(0, len(novo_historico_para_exibir), 2):
|
| 345 |
+
user_msg = novo_historico_para_exibir[i]['content']
|
| 346 |
+
assistant_msg = novo_historico_para_exibir[i+1]['content'] if i + 1 < len(novo_historico_para_exibir) else ""
|
| 347 |
+
novo_historico_gradio.append([user_msg, assistant_msg])
|
| 348 |
+
|
| 349 |
+
dna_completo_str = formatar_dna_json(dna_atualizado)
|
| 350 |
+
p1_data_str = formatar_dna_json(dna_atualizado.get('P1_data', {}))
|
| 351 |
+
p2_data_str = formatar_dna_json(dna_atualizado.get('P2_data', {}))
|
| 352 |
+
p4_data_str = formatar_dna_json(dna_atualizado.get('P4_data', {}))
|
| 353 |
+
p5_data_str = formatar_dna_json(dna_atualizado.get('P5_data', {}))
|
| 354 |
+
p8_data_str = formatar_dna_json(dna_atualizado.get('P8_data', {}))
|
| 355 |
+
historico_gov_str = formatar_dna_json(dna_atualizado.get('historico_governanca', []))
|
| 356 |
+
|
| 357 |
+
return (novo_historico_gradio,
|
| 358 |
+
"",
|
| 359 |
+
json.dumps(dna_atualizado, indent=2, ensure_ascii=False),
|
| 360 |
+
None,
|
| 361 |
+
dna_completo_str,
|
| 362 |
+
p1_data_str,
|
| 363 |
+
p2_data_str,
|
| 364 |
+
p4_data_str,
|
| 365 |
+
p5_data_str,
|
| 366 |
+
p8_data_str,
|
| 367 |
+
historico_gov_str
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
if __name__ == "__main__":
|
| 372 |
+
prompts_text_inicial = get_prompts_raw_text()
|
| 373 |
+
|
| 374 |
+
with gr.Blocks(title="Pipeline v10 - Raciocínio Adaptativo", theme=gr.themes.Soft()) as demo:
|
| 375 |
+
|
| 376 |
+
# Variáveis de Visualização (Debug/Governança)
|
| 377 |
+
p1_out = gr.Code(label="1. TRIAGEM (P1)", language="json", interactive=False, value="{}")
|
| 378 |
+
p2_out = gr.Code(label="2. CENÁRIOS (P2)", language="json", interactive=False, value="{}")
|
| 379 |
+
p4_out = gr.Code(label="4. PRINCÍPIO (P4)", language="json", interactive=False, value="{}")
|
| 380 |
+
p5_out = gr.Code(label="5. LACUNAS/DECISÃO (P5)", language="json", interactive=False, value="{}")
|
| 381 |
+
p8_out = gr.Code(label="8. VERIFICAÇÃO (P8)", language="json", interactive=False, value="{}")
|
| 382 |
+
gov_out = gr.Code(label=f"Histórico de Governança (Últimos 10 Turnos)", language="json", interactive=False, value="[]")
|
| 383 |
+
|
| 384 |
+
gr.Markdown(TITLE)
|
| 385 |
+
|
| 386 |
+
with gr.Tab("💬 Chat e Resposta"):
|
| 387 |
+
with gr.Row():
|
| 388 |
+
with gr.Column(scale=3):
|
| 389 |
+
chatbot = gr.Chatbot(label="Chat", height=500, bubble_full_width=False)
|
| 390 |
+
input_textbox = gr.Textbox(label="Digite sua pergunta...", lines=3)
|
| 391 |
+
with gr.Row():
|
| 392 |
+
submit_button = gr.Button("🚀 Enviar", variant="primary", scale=1)
|
| 393 |
+
file_upload = gr.File(label="Anexar Arquivo", scale=1)
|
| 394 |
+
|
| 395 |
+
with gr.Column(scale=2):
|
| 396 |
+
dna_json_hidden = gr.Textbox(value=json.dumps(criar_dna()), visible=False)
|
| 397 |
+
dna_view = gr.Code(label="DNA (Estado Completo da Conversa/Meta-Dados)", language="json", interactive=False, value=json.dumps(criar_dna(), indent=2, ensure_ascii=False))
|
| 398 |
+
|
| 399 |
+
with gr.Group():
|
| 400 |
+
with gr.Accordion("📜 Ver Histórico de Governança", open=False):
|
| 401 |
+
gov_out.render()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
with gr.Tab("🛠️ Debug da Pipeline"):
|
| 405 |
+
gr.Markdown("## Visualização JSON por Passo do TURNO ATUAL")
|
| 406 |
+
with gr.Row():
|
| 407 |
+
p1_out.render()
|
| 408 |
+
p2_out.render()
|
| 409 |
+
with gr.Row():
|
| 410 |
+
p4_out.render()
|
| 411 |
+
p5_out.render()
|
| 412 |
+
with gr.Row():
|
| 413 |
+
p8_out.render()
|
| 414 |
+
|
| 415 |
+
with gr.Tab("📝 Editor de Prompts"):
|
| 416 |
+
gr.Markdown(f"## Editor Dinâmico de Prompts ({PROMPT_FILENAME})")
|
| 417 |
+
prompts_editor = gr.Code(label="Conteúdo do JSON de Prompts", language="json", value=prompts_text_inicial, interactive=True, lines=30)
|
| 418 |
+
save_button = gr.Button("💾 SALVAR E RECARREGAR PROMPTS NO SERVIDOR", variant="stop")
|
| 419 |
+
save_status = gr.Textbox(label="Status do Servidor", interactive=False)
|
| 420 |
+
|
| 421 |
+
save_button.click(fn=salvar_e_recarregar_prompts, inputs=[prompts_editor], outputs=[save_status])
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# Mapeamento Completo de Inputs e Outputs (11 Saídas)
|
| 425 |
+
fn_args = {
|
| 426 |
+
"fn": chat_interface,
|
| 427 |
+
"inputs": [input_textbox, chatbot, file_upload, dna_json_hidden],
|
| 428 |
+
"outputs": [chatbot,
|
| 429 |
+
input_textbox,
|
| 430 |
+
dna_json_hidden,
|
| 431 |
+
file_upload,
|
| 432 |
+
dna_view,
|
| 433 |
+
p1_out,
|
| 434 |
+
p2_out,
|
| 435 |
+
p4_out,
|
| 436 |
+
p5_out,
|
| 437 |
+
p8_out,
|
| 438 |
+
gov_out
|
| 439 |
+
]
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
submit_button.click(**fn_args)
|
| 443 |
+
input_textbox.submit(**fn_args)
|
| 444 |
+
|
| 445 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
| 446 |
+
--- END OF FILE app.py ---
|