caarleexx commited on
Commit
34c9de8
·
verified ·
1 Parent(s): d419754

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -498
app.py DELETED
@@ -1,498 +0,0 @@
1
-
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 e salvamento via editor Gradio.
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
- # --- 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
- CLIENT = genai.Client(api_key=API_KEY)
40
-
41
- # --- Definição dos Modelos e Título ---
42
- COUNSELOR_MODEL_NAME = "gemini-2.5-pro"
43
- SUPERVISOR_MODEL_NAME = "gemini-2.5-pro"
44
- TITLE = "# 🚀 Pipeline v10 | Governanca e Memória API"
45
-
46
- # ============================================================================
47
- # 2. PROMPTS CENTRALIZADOS (FUNÇÕES DE CARREGAMENTO/SALVAMENTO)
48
- # ============================================================================
49
- # Define a variável global que será usada para armazenar os prompts em tempo real
50
- PROMPTS = {}
51
-
52
- # Placeholder de fallback para garantir a inicialização em caso de falha de leitura
53
- FALLBACK_PROMPTS = {
54
- "P1_TRIAGEM": "METACOGNIÇÃO - TRIAGEM INICIAL.\nPERGUNTA: {pergunta}...\nRETORNE JSON: {{\"tipo\": \"...\"}}",
55
- "P2_CENARIOS": "METACOGNIÇÃO - GERAÇÃO DE CENÁRIOS.\nANÁLISE (P1): {p1}, PERGUNTA: {pergunta}...\nRETORNE JSON: {{\"cenarios\": {{\"provaveis\": [], ...}}}}",
56
- "GERAR_RESPOSTA_DIRETA": "TAREFA: Resposta Direta (Bypass).\nPERGUNTA: \"{pergunta}\"...\nRETORNE JSON: {{\"resposta_direta\": \"...\"}}",
57
- "JUSTIFICAR_BYPASS": "METACOGNIÇÃO - JUSTIFICATIVA DE BYPASS. ANÁLISE (P1): {p1}...\nRETORNE JSON: {{\"justificativa_bypass\": {...}}}}",
58
- "P4_CRUZAR_VALIDACOES": "METACOGNIÇÃO - ABSTRAÇÃO...\nRETORNE JSON: {{\"principio_central\": \"...\"}}",
59
- "P5_LACUNAS_FINAIS": "METACOGNIÇÃO - ANÁLISE DE INCERTEZA...\nRETORNE JSON: {{\"pontos_de_incerteza\": [], \"decisao_interna\": \"...\"}}",
60
- "P7_SINTETIZAR": "SINTETIZADOR. DADOS (P6): {p6}...\nRETORNE JSON: {{\"resposta\": \"...\"}}",
61
- "P8_VERIFICAR": "VERIFICADOR FINAL.\nRESPOSTA: {resposta_a_verificar}...\nRETORNE JSON: {{\"todas_aprovadas\": true|false, \"resposta_corrigida\": null}}"
62
- }
63
-
64
- def carregar_prompts_externos(filename: str = PROMPT_FILENAME) -> Dict:
65
- """Carrega prompts do arquivo ou retorna o fallback se houver falha na leitura ou validação."""
66
- try:
67
- with open(filename, 'r', encoding='utf-8') as f:
68
- full_prompts = json.load(f)
69
- # Uma verificação rápida se o arquivo tem os prompts chave
70
- if not all(key in full_prompts for key in FALLBACK_PROMPTS.keys()):
71
- raise ValueError("O arquivo de prompts está incompleto ou malformatado.")
72
-
73
- logger.log(f"Prompts carregados com sucesso do arquivo: {filename}", "SUCCESS")
74
- return full_prompts
75
-
76
- except Exception as e:
77
- logger.log(f"Não foi possível carregar os prompts externos: {e}. Usando FALLBACK.", "ERROR")
78
- return FALLBACK_PROMPTS
79
-
80
- def get_prompts_raw_text(filename: str = PROMPT_FILENAME) -> str:
81
- """Lê o arquivo de prompts como texto bruto para o editor do Gradio, ou retorna fallback."""
82
- try:
83
- if not os.path.exists(filename):
84
- return json.dumps(FALLBACK_PROMPTS, indent=2, ensure_ascii=False)
85
-
86
- with open(filename, 'r', encoding='utf-8') as f:
87
- return f.read()
88
- except:
89
- return json.dumps({"erro": "Não foi possível ler o arquivo."}, indent=2, ensure_ascii=False)
90
-
91
- def salvar_e_recarregar_prompts(new_prompts_json_str: str) -> str:
92
- """Salva o novo JSON no arquivo e recarrega a variável PROMPTS global."""
93
- global PROMPTS
94
- try:
95
- # 1. Tenta carregar/validar o JSON
96
- novo_dicionario = json.loads(new_prompts_json_str)
97
-
98
- # 2. Tenta salvar no disco
99
- with open(PROMPT_FILENAME, 'w', encoding='utf-8') as f:
100
- json.dump(novo_dicionario, f, indent=2, ensure_ascii=False)
101
-
102
- # 3. Atualiza a variável global em memória
103
- PROMPTS = novo_dicionario
104
- logger.log(f"Novo arquivo de prompts salvo e recarregado com sucesso.", "SUCCESS")
105
- return f"✅ SUCESSO! Prompts salvos em {PROMPT_FILENAME} e variáveis em memória atualizadas. Última atualização: {datetime.now().strftime('%H:%M:%S')}."
106
-
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: Falha ao salvar ou recarregar o arquivo: {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
115
- PROMPTS = carregar_prompts_externos()
116
-
117
- # ============================================================================
118
- # 3. CLASSES E FUNÇÕES HELPERS
119
- # ============================================================================
120
-
121
- class Logger:
122
- def __init__(self, verbose: bool = True): self.verbose = verbose
123
- def log(self, msg: str, level: str = "INFO"):
124
- log_msg = f"[{datetime.now().strftime('%H:%M:%S')}] [{level.upper()}] {msg}"; print(log_msg)
125
- if level.upper() in ["TASK", "START", "SUCCESS", "ERROR", "WARN"]: print("=" * 70)
126
- logger = Logger(verbose=True)
127
-
128
- def sanitizar_texto(texto: str) -> str:
129
- if not isinstance(texto, str): return ""
130
- texto_limpo = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', texto)
131
- texto_limpo = re.sub(r'\s{2,}', ' ', texto_limpo).replace('\\n', '\n')
132
- return texto_limpo.strip()
133
-
134
- def to_gemini_contents(historico: List[Dict]) -> List[types.Content]:
135
- """Converte o histórico Gradio-compatível para o formato genai.types.Content (user/model)."""
136
- gemini_contents = []
137
- for entry in historico:
138
- role = "model" if entry["role"] == "assistant" else "user"
139
- # Garante que só há conteúdo limpo para a API (exclui a JUSTIFICATIVA GRADIO)
140
- content_for_api = re.sub(r'\*\*JUSTIFICATIVA DE RESPOSTA DIRETA:\*\*.*?\-\-\-\n\n', '', entry["content"], flags=re.DOTALL)
141
-
142
- if content_for_api:
143
- gemini_contents.append(
144
- types.Content(
145
- role=role,
146
- parts=[types.Part.from_text(text=content_for_api)]
147
- )
148
- )
149
- return gemini_contents
150
-
151
- # ATUALIZADO/CORRIGIDO: Chamada com Memória API e ThinkingConfig
152
- def chamar_gemini_json(model_name: str, prompt: str,
153
- historico_conversa: List[types.Content] = None, # Histórico da API para memória
154
- temperatura: float = 0.4, max_tokens: int = 8192) -> Dict:
155
- 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.**"
156
- # print(f"\n{'='*25} 💬 API INPUT PARA [{model_name}] {'='*25}\n{prompt_completo}\n{'='*78}\n")
157
-
158
- try:
159
- # 1. Conteúdo: Combina histórico + prompt da tarefa
160
- contents = historico_conversa if historico_conversa else []
161
- contents.append(
162
- types.Content(role="user", parts=[types.Part.from_text(text=prompt_completo)])
163
- )
164
-
165
- # 2. Configuração: Tools e Pensamento (ThinkingConfig)
166
- tools = [types.Tool(google_search=types.GoogleSearch())]
167
- generate_content_config = types.GenerateContentConfig(
168
- temperature=temperatura,
169
- max_output_tokens=max_tokens,
170
- thinking_config=types.ThinkingConfig(thinking_budget=8192),
171
- tools=tools
172
- )
173
-
174
- # 3. Chamada de API Corrigida (V1 SDK)
175
- stream = CLIENT.models.generate_content_stream(
176
- model=model_name, contents=contents, config=generate_content_config
177
- )
178
-
179
- # 4. Processamento da Resposta
180
- resposta_bruta = "".join(chunk.text for chunk in stream if chunk.text)
181
- resposta_sanitizada = sanitizar_texto(resposta_bruta)
182
-
183
- if not resposta_sanitizada:
184
- return {"erro": "API_EMPTY_RESPONSE"}
185
-
186
- match = re.search(r'\{.*\}', resposta_sanitizada, re.DOTALL)
187
- if match:
188
- return json.loads(match.group(0))
189
- else:
190
- # Tenta carregar o conteúdo restante como JSON se a expressão regular falhar
191
- return json.loads(resposta_sanitizada)
192
-
193
- except Exception as e:
194
- logger.log(f"Falha na chamada da API ou no parse do JSON: {e}", "ERROR")
195
- return {"erro": "API_CALL_FAILED", "detalhes": str(e)}
196
-
197
-
198
- def criar_dna() -> Dict:
199
- return {
200
- "historico_governanca": [],
201
- "meta": {"total_turnos": 0},
202
- "pipeline_state": {
203
- "status": "completed",
204
- "paused_at_step": None,
205
- "saved_data": {}
206
- },
207
- "P1_data": {}, "P2_data": {}, "P4_data": {}, "P5_data": {}, "P8_data": {},
208
- }
209
-
210
- def formatar_dna_json(data: Dict) -> str:
211
- """Retorna um JSON formatado com dois espaços de indentação."""
212
- try:
213
- return json.dumps(data, indent=2, ensure_ascii=False)
214
- except:
215
- return f"Erro ao serializar dados: {data}"
216
-
217
- # ============================================================================
218
- # 4. PASSOS DA PIPELINE
219
- # ============================================================================
220
- # OBS: O parâmetro 'historico_memoria' só é passado nas chamadas onde o contexto é CRÍTICO.
221
-
222
- def passo_1_triagem(pergunta: str, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[Dict, Dict]:
223
- logger.log("📊 PASSO 1: TRIAGEM INICIAL", "TASK")
224
- p1 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P1_TRIAGEM"].format(pergunta=pergunta), historico_conversa=historico_memoria)
225
- dna["P1_data"] = p1
226
- return p1, dna
227
-
228
- def passo_gerar_resposta_direta(pergunta: str, historico_memoria: List[types.Content]) -> Dict:
229
- logger.log("⚡ FAST PATH: GERANDO RESPOSTA DIRETA", "TASK")
230
- return chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["GERAR_RESPOSTA_DIRETA"].format(pergunta=pergunta), historico_conversa=historico_memoria)
231
-
232
- def passo_justificar_bypass(p1: Dict) -> Dict:
233
- logger.log("⚡ FAST PATH: GERANDO JUSTIFICATIVA", "TASK")
234
- return chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["JUSTIFICAR_BYPASS"].format(p1=json.dumps(p1)))
235
-
236
- def passo_2_cenarios(pergunta: str, p1: Dict, dna: Dict) -> Tuple[Dict, Dict]:
237
- logger.log("🧠 PASSO 2: GERAÇÃO DE CENÁRIOS", "TASK")
238
- # Não precisa de memória, o JSON anterior é o suficiente
239
- p2 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P2_CENARIOS"].format(p1=json.dumps(p1), pergunta=pergunta))
240
- dna["P2_data"] = p2
241
- return p2, dna
242
-
243
- def passo_4_cruzar_validacoes(p1: Dict, p2: Dict, p3: Dict, dna: Dict) -> Tuple[Dict, Dict]:
244
- logger.log("🧠 PASSO 4: IDENTIFICAÇÃO DO PRINCÍPIO CENTRAL", "TASK")
245
- p4 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P4_CRUZAR_VALIDACOES"].format(p1=json.dumps(p1), p2=json.dumps(p2), p3=json.dumps(p3)))
246
- dna["P4_data"] = p4
247
- return p4, dna
248
-
249
- def passo_5_lacunas_finais(pergunta: str, p4: Dict, dna: Dict) -> Tuple[Dict, Dict]:
250
- logger.log("🧠 PASSO 5: ANÁLISE DE INCERTEZA", "TASK")
251
- p5 = chamar_gemini_json(COUNSELOR_MODEL_NAME, PROMPTS["P5_LACUNAS_FINAIS"].format(p4=json.dumps(p4), pergunta=pergunta))
252
- dna["P5_data"] = p5
253
- return p5, dna
254
-
255
- def passo_8_verificar(resposta_a_verificar: str, dna: Dict) -> Tuple[Dict, Dict]:
256
- logger.log("✅ PASSO 8: VERIFICAÇÃO FINAL", "TASK")
257
- p8 = chamar_gemini_json(SUPERVISOR_MODEL_NAME, PROMPTS["P8_VERIFICAR"].format(resposta_a_verificar=resposta_a_verificar))
258
- dna["P8_data"] = p8
259
- return p8, dna
260
-
261
- # Passos Simluados
262
- def passo_3_isolar_cenarios(p2: Dict) -> Dict: return {"simulado": True}
263
- def passo_6_ponderar(p2: Dict, p4: Dict, p5: Dict) -> Dict: return {"simulado": True}
264
- def passo_7_sintetizar(p6: Dict) -> Dict: return {"resposta": "Resposta sintetizada vinda da pipeline completa (simulado)."}
265
-
266
-
267
- # ============================================================================
268
- # 5. ORQUESTRADOR PRINCIPAL
269
- # ============================================================================
270
- def salvar_governanca(dna: Dict, pergunta: str, tipo: str, **data) -> None:
271
- """Função helper para salvar o histórico de governança."""
272
- entry = {"turno": dna['meta']['total_turnos'], "timestamp": datetime.now().strftime('%H:%M:%S'), "tipo": tipo, "pergunta": pergunta, **data}
273
- dna["historico_governanca"].append(entry)
274
- # Mantém o histórico com o limite de 10 entradas (os últimos)
275
- if len(dna["historico_governanca"]) > 10:
276
- dna["historico_governanca"] = dna["historico_governanca"][-10:]
277
-
278
- def iniciar_nova_pipeline(pergunta_original: str, historico: List[Dict], anexo: Any, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[str, List, Dict]:
279
- pergunta = sanitizar_texto(pergunta_original)
280
-
281
- # PASSO 1
282
- p1, dna = passo_1_triagem(pergunta, dna, historico_memoria)
283
- if "erro" in p1: return f"Erro na Triagem: {p1.get('detalhes', 'Não foi possível classificar a pergunta.')}", historico, dna
284
-
285
- # FAST PATH
286
- if p1.get("decisao") == "responder_direto":
287
- resposta_direta_data = passo_gerar_resposta_direta(pergunta, historico_memoria)
288
- justificativa_data = passo_justificar_bypass(p1)
289
- if "erro" in resposta_direta_data:
290
- return f"Erro ao gerar a resposta direta: {resposta_direta_data['detalhes']}", historico, dna
291
-
292
- # Consolidação
293
- resposta_direta = resposta_direta_data.get("resposta_direta", "Não foi possível gerar a resposta.")
294
- justificativa = justificativa_data.get("justificativa_bypass", {})
295
- verificacao, dna = passo_8_verificar(resposta_direta, dna)
296
- resposta_final = verificacao.get("resposta_corrigida") or resposta_direta
297
-
298
- 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"
299
- resposta_formatada = justificativa_texto + resposta_final
300
-
301
- novo_historico = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": resposta_formatada}]
302
- salvar_governanca(dna, pergunta_original, "FAST_PATH", p1=p1, p8=verificacao) # <-- GOVERNANÇA SALVA
303
- return "PIPELINE_COMPLETED", novo_historico, dna
304
-
305
- # FULL PATH
306
- else:
307
- p2, dna = passo_2_cenarios(pergunta, p1, dna)
308
- p3 = passo_3_isolar_cenarios(p2)
309
- p4, dna = passo_4_cruzar_validacoes(p1, p2, p3, dna)
310
- p5, dna = passo_5_lacunas_finais(pergunta, p4, dna)
311
-
312
- # Interrupção/Pausa
313
- if p5.get("decisao_interna") == "questionar":
314
- salvar_governanca(dna, pergunta_original, "FULL_PATH_PAUSA", p1=p1, p5=p5) # <-- GOVERNANÇA SALVA (PAUSA)
315
- 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}}
316
- pergunta_do_bot = p5.get('pergunta_chave_para_usuario', 'Preciso de mais informações.')
317
- historico_atualizado = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": pergunta_do_bot}]
318
- return "PIPELINE_PAUSED", historico_atualizado, dna
319
-
320
- # Conclusão do Full Path
321
- p6 = passo_6_ponderar(p2, p4, p5)
322
- p7 = passo_7_sintetizar(p6)
323
- p8, dna = passo_8_verificar(p7.get("resposta", ""), dna)
324
- resposta_final = p8.get("resposta_corrigida") or p7.get("resposta", "Não foi possível gerar a resposta.")
325
- novo_historico = historico + [{"role": "user", "content": pergunta_original}, {"role": "assistant", "content": resposta_final}]
326
- dna['pipeline_state']['status'] = 'completed'
327
-
328
- salvar_governanca(dna, pergunta_original, "FULL_PATH_CONCLUIDO", p1=p1, p2=p2, p4=p4, p5=p5, p8=p8) # <-- GOVERNANÇA SALVA
329
- return "PIPELINE_COMPLETED", novo_historico, dna
330
-
331
- def resumir_pipeline(esclarecimento_usuario_original: str, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[str, List, Dict]:
332
- # SIMULAÇÃO: Lógica de Retomada...
333
- dados_salvos = dna['pipeline_state']['saved_data']
334
- resposta = "RESUMIDO! A pipeline (pausada) foi retomada com o seu esclarecimento, mas a lógica de retomada completa precisa ser implementada."
335
- dna['pipeline_state']['status'] = 'completed'
336
- historico_atualizado = dados_salvos['historico_original'] + [{"role": "user", "content": esclarecimento_usuario_original}, {"role": "assistant", "content": resposta}]
337
-
338
- salvar_governanca(dna, esclarecimento_usuario_original, "RETOMADA_SIMULADA", p_resumido=True, status="P_COMPLETED")
339
- return "PIPELINE_COMPLETED", historico_atualizado, dna
340
-
341
-
342
- def executar_pipeline(pergunta: str, historico: List[Dict], anexo: Any, dna: Dict, historico_memoria: List[types.Content]) -> Tuple[str, List, Dict]:
343
- try:
344
- if 'pipeline_state' not in dna: dna.update(criar_dna())
345
-
346
- dna['meta']['total_turnos'] = dna['meta'].get('total_turnos', 0) + 1
347
-
348
- # Se pausado, retoma.
349
- if dna['pipeline_state']['status'] == 'paused':
350
- return resumir_pipeline(pergunta, dna, historico_memoria) # <--- PASSANDO MEMÓRIA
351
-
352
- # Limpa dados de passos anteriores para o TURNO ATUAL
353
- for key in ["P1_data", "P2_data", "P4_data", "P5_data", "P8_data"]:
354
- dna[key] = {}
355
-
356
- return iniciar_nova_pipeline(pergunta, historico, anexo, dna, historico_memoria) # <--- PASSANDO MEMÓRIA
357
-
358
- except Exception as e:
359
- logger.log(f"Erro catastrófico no orquestrador: {e}", "ERROR")
360
- resposta_erro = f"Ocorreu um erro inesperado na pipeline: {e}"
361
- dna['pipeline_state']['status'] = 'error'
362
-
363
- salvar_governanca(dna, pergunta, "ERRO_CATASTRÓFICO", erro=str(e)) # <-- GOVERNANÇA SALVA (ERRO)
364
- return "PIPELINE_ERROR", historico + [{"role": "user", "content": pergunta}, {"role": "assistant", "content": resposta_erro}], dna
365
-
366
- # ============================================================================
367
- # 6. INTERFACE COM GRADIO
368
- # ============================================================================
369
-
370
- 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]:
371
-
372
- # 1. Carga do Estado (DNA)
373
- try:
374
- dna = json.loads(dna_json_str) if dna_json_str and dna_json_str.strip() else criar_dna()
375
- except:
376
- dna = criar_dna()
377
-
378
- # 2. Formato de Histórico para o Orquestrador/API
379
- historico_interno = []
380
- for turno in historico_gradio:
381
- if turno and turno[0]: historico_interno.append({"role": "user", "content": turno[0]})
382
- if turno and turno[1]: historico_interno.append({"role": "assistant", "content": turno[1]})
383
-
384
- historico_para_gemini = to_gemini_contents(historico_interno)
385
-
386
- # 3. Execução
387
- _ , novo_historico_para_exibir, dna_atualizado = executar_pipeline(
388
- pergunta, historico_interno, anexo, dna, historico_para_gemini
389
- )
390
-
391
- # 4. Saídas para Gradio Chat e Elementos de UI
392
- novo_historico_gradio = []
393
- for i in range(0, len(novo_historico_para_exibir), 2):
394
- user_msg = novo_historico_para_exibir[i]['content']
395
- assistant_msg = novo_historico_para_exibir[i+1]['content'] if i + 1 < len(novo_historico_para_exibir) else ""
396
- novo_historico_gradio.append([user_msg, assistant_msg])
397
-
398
- dna_completo_str = json.dumps(dna_atualizado, indent=2, ensure_ascii=False)
399
- p1_data_str = formatar_dna_json(dna_atualizado.get('P1_data', {}))
400
- p2_data_str = formatar_dna_json(dna_atualizado.get('P2_data', {}))
401
- p4_data_str = formatar_dna_json(dna_atualizado.get('P4_data', {}))
402
- p5_data_str = formatar_dna_json(dna_atualizado.get('P5_data', {}))
403
- p8_data_str = formatar_dna_json(dna_atualizado.get('P8_data', {}))
404
- historico_gov_str = formatar_dna_json(dna_atualizado.get('historico_governanca', []))
405
-
406
- return (novo_historico_gradio,
407
- "",
408
- json.dumps(dna_atualizado, indent=2, ensure_ascii=False), # 3: dna_json_hidden (Oculto)
409
- None, # 4: file_upload
410
- dna_completo_str, # 5: dna_view (Completo Formatado)
411
- p1_data_str, # 6: P1
412
- p2_data_str, # 7: P2
413
- p4_data_str, # 8: P4
414
- p5_data_str, # 9: P5
415
- p8_data_str, # 10: P8
416
- historico_gov_str # 11: Novo Painel de Governança
417
- )
418
-
419
-
420
- if __name__ == "__main__":
421
- prompts_text_inicial = get_prompts_raw_text()
422
-
423
- with gr.Blocks(title="Pipeline v10 - Raciocínio Adaptativo", theme=gr.themes.Soft()) as demo:
424
-
425
- # Variáveis de Visualização do Turno Atual (aba Debug)
426
- p1_out = gr.Code(label="1. TRIAGEM (P1)", language="json", interactive=False, value="{}")
427
- p2_out = gr.Code(label="2. CENÁRIOS (P2)", language="json", interactive=False, value="{}")
428
- p4_out = gr.Code(label="4. PRINCÍPIO (P4)", language="json", interactive=False, value="{}")
429
- p5_out = gr.Code(label="5. LACUNAS/DECISÃO (P5)", language="json", interactive=False, value="{}")
430
- p8_out = gr.Code(label="8. VERIFICAÇÃO (P8)", language="json", interactive=False, value="{}")
431
-
432
- # Variável de Histórico de Governança (Rodapé do DNA)
433
- gov_out = gr.Code(label=f"Histórico de Governança (Últimos 10 Turnos)", language="json", interactive=False, value="[]")
434
-
435
- gr.Markdown(TITLE)
436
-
437
- with gr.Tab("💬 Chat e Resposta"):
438
- with gr.Row():
439
- with gr.Column(scale=3):
440
- chatbot = gr.Chatbot(label="Chat", height=500, bubble_full_width=False)
441
- input_textbox = gr.Textbox(label="Digite sua pergunta...", lines=3)
442
- with gr.Row():
443
- submit_button = gr.Button("🚀 Enviar", variant="primary", scale=1)
444
- file_upload = gr.File(label="Anexar Arquivo", scale=1)
445
-
446
- with gr.Column(scale=2):
447
- # Estado Completo do DNA (Oculto + Visível)
448
- dna_json_hidden = gr.Textbox(value=json.dumps(criar_dna()), visible=False)
449
- 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))
450
-
451
- # Expansível para Governança
452
- with gr.Group():
453
- with gr.Accordion("📜 Ver Histórico de Governança", open=False):
454
- gov_out.render()
455
-
456
-
457
- with gr.Tab("🛠️ Debug da Pipeline"):
458
- gr.Markdown("## Visualização JSON por Passo do TURNO ATUAL")
459
- with gr.Row():
460
- p1_out.render()
461
- p2_out.render()
462
- with gr.Row():
463
- p4_out.render()
464
- p5_out.render()
465
- with gr.Row():
466
- p8_out.render()
467
-
468
- with gr.Tab("📝 Editor de Prompts"):
469
- gr.Markdown(f"## Editor Dinâmico de Prompts ({PROMPT_FILENAME})")
470
- prompts_editor = gr.Code(label="Conteúdo do JSON de Prompts", language="json", value=prompts_text_inicial, interactive=True, lines=30)
471
- save_button = gr.Button("💾 SALVAR E RECARREGAR PROMPTS NO SERVIDOR", variant="stop")
472
- save_status = gr.Textbox(label="Status do Servidor", interactive=False)
473
-
474
- save_button.click(fn=salvar_e_recarregar_prompts, inputs=[prompts_editor], outputs=[save_status])
475
-
476
-
477
- # Ações do Botão/Entrada do Chat
478
- fn_args = {
479
- "fn": chat_interface,
480
- "inputs": [input_textbox, chatbot, file_upload, dna_json_hidden],
481
- "outputs": [chatbot,
482
- input_textbox,
483
- dna_json_hidden,
484
- file_upload,
485
- dna_view, # 5: DNA Completo
486
- p1_out, # 6
487
- p2_out, # 7
488
- p4_out, # 8
489
- p5_out, # 9
490
- p8_out, # 10
491
- gov_out # 11: Governança
492
- ]
493
- }
494
-
495
- submit_button.click(**fn_args)
496
- input_textbox.submit(**fn_args)
497
-
498
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)