Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -360,39 +360,47 @@ def automacao_upload_processamento(files, history, config_json):
|
|
| 360 |
|
| 361 |
|
| 362 |
def chat_orquestrador(message, history, config_json):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
try:
|
| 364 |
prompt_contexto = gerenciador.gerar_prompt_com_transcricoes(message)
|
| 365 |
except Exception as e:
|
| 366 |
history.append([message, f"❌ Erro ao gerar contexto: {str(e)}"])
|
| 367 |
-
yield history
|
| 368 |
return
|
| 369 |
|
| 370 |
try:
|
| 371 |
protocolo = json.loads(config_json)
|
| 372 |
except:
|
| 373 |
history.append([message, "❌ Erro no JSON de Configuração."])
|
| 374 |
-
yield history
|
| 375 |
return
|
| 376 |
|
| 377 |
history.append([message, None])
|
| 378 |
-
yield history
|
| 379 |
-
|
| 380 |
-
timeline_execucao = [{"role": "user", "content": prompt_contexto}]
|
| 381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
for cfg in protocolo:
|
| 383 |
nome_agente = cfg.get("nome", "Agente")
|
| 384 |
modelo_agente = model_pro if cfg.get("modelo") == "pro" else model_flash
|
| 385 |
|
| 386 |
-
|
| 387 |
-
|
|
|
|
|
|
|
| 388 |
|
| 389 |
prompt_agente = f"""
|
| 390 |
-
--- HISTÓRICO ---
|
| 391 |
-
{json.dumps(timeline_execucao, ensure_ascii=False)}
|
| 392 |
-----------------
|
| 393 |
-
|
| 394 |
-
Sua Missão: {cfg['missao']}
|
| 395 |
-
Responda de forma concisa e direta.
|
| 396 |
"""
|
| 397 |
try:
|
| 398 |
inicio = time.time()
|
|
@@ -400,19 +408,25 @@ Responda de forma concisa e direta.
|
|
| 400 |
texto_resp = resp.text
|
| 401 |
duracao = time.time() - inicio
|
| 402 |
|
| 403 |
-
|
|
|
|
| 404 |
|
|
|
|
| 405 |
msg_atual = history[-1][1]
|
| 406 |
-
|
| 407 |
|
| 408 |
novo_trecho = f"**[{nome_agente}]** ({duracao:.1f}s):\n{texto_resp}\n\n"
|
| 409 |
history[-1][1] = msg_atual + novo_trecho
|
| 410 |
-
yield history
|
| 411 |
|
| 412 |
except Exception as e:
|
|
|
|
|
|
|
| 413 |
msg_atual = history[-1][1]
|
| 414 |
-
history[-1][1] = msg_atual + f"\n❌ Erro em {nome_agente}: {str(e)}\n"
|
| 415 |
-
yield history
|
|
|
|
|
|
|
| 416 |
|
| 417 |
# ==================== 6. UI (Gradio) ====================
|
| 418 |
|
|
@@ -455,6 +469,11 @@ def ui_v28_corrected():
|
|
| 455 |
label="Arraste arquivos aqui ou clique para selecionar"
|
| 456 |
)
|
| 457 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
with gr.Tab("⚙️ Contexto & Config"):
|
| 459 |
gr.Markdown("### Protocolo dos Agentes")
|
| 460 |
with gr.Row():
|
|
@@ -466,10 +485,11 @@ def ui_v28_corrected():
|
|
| 466 |
btn_save_cfg.click(salvar_protocolo, inputs=[code_config], outputs=[lbl_cfg_status])
|
| 467 |
btn_save_cfg.click(lambda x: x, inputs=[code_config], outputs=[state_config])
|
| 468 |
|
|
|
|
| 469 |
btn_enviar.click(
|
| 470 |
chat_orquestrador,
|
| 471 |
inputs=[txt_input, chatbot, state_config],
|
| 472 |
-
outputs=[chatbot]
|
| 473 |
).then(
|
| 474 |
lambda: "", outputs=[txt_input]
|
| 475 |
)
|
|
@@ -483,4 +503,4 @@ def ui_v28_corrected():
|
|
| 483 |
return app
|
| 484 |
|
| 485 |
if __name__ == "__main__":
|
| 486 |
-
ui_v28_corrected().launch()
|
|
|
|
| 360 |
|
| 361 |
|
| 362 |
def chat_orquestrador(message, history, config_json):
|
| 363 |
+
"""
|
| 364 |
+
Orquestra a conversa, passando o contexto e as missões para cada agente em sequência.
|
| 365 |
+
Agora também retorna a trilha de auditoria para a nova aba.
|
| 366 |
+
"""
|
| 367 |
try:
|
| 368 |
prompt_contexto = gerenciador.gerar_prompt_com_transcricoes(message)
|
| 369 |
except Exception as e:
|
| 370 |
history.append([message, f"❌ Erro ao gerar contexto: {str(e)}"])
|
| 371 |
+
yield history, []
|
| 372 |
return
|
| 373 |
|
| 374 |
try:
|
| 375 |
protocolo = json.loads(config_json)
|
| 376 |
except:
|
| 377 |
history.append([message, "❌ Erro no JSON de Configuração."])
|
| 378 |
+
yield history, []
|
| 379 |
return
|
| 380 |
|
| 381 |
history.append([message, None])
|
|
|
|
|
|
|
|
|
|
| 382 |
|
| 383 |
+
# A trilha de auditoria começa com o prompt completo enviado pelo usuário
|
| 384 |
+
timeline_execucao = [{"passo": 1, "tipo": "prompt_usuario", "conteudo": prompt_contexto}]
|
| 385 |
+
yield history, timeline_execucao
|
| 386 |
+
|
| 387 |
+
passo_atual = 2
|
| 388 |
for cfg in protocolo:
|
| 389 |
nome_agente = cfg.get("nome", "Agente")
|
| 390 |
modelo_agente = model_pro if cfg.get("modelo") == "pro" else model_flash
|
| 391 |
|
| 392 |
+
# Atualiza o chatbot com o status do agente atual
|
| 393 |
+
msg_atual = history[-1][1] or ""
|
| 394 |
+
history[-1][1] = msg_atual + f"⏳ **{nome_agente}** está analisando...\n"
|
| 395 |
+
yield history, timeline_execucao
|
| 396 |
|
| 397 |
prompt_agente = f"""
|
| 398 |
+
--- HISTÓRICO DA CONVERSA ATÉ AGORA ---
|
| 399 |
+
{json.dumps(timeline_execucao, ensure_ascii=False, indent=2)}
|
| 400 |
-----------------
|
| 401 |
+
Sua Identidade: {nome_agente}
|
| 402 |
+
Sua Missão Específica Agora: {cfg['missao']}
|
| 403 |
+
Responda de forma concisa e direta, focando apenas na sua missão.
|
| 404 |
"""
|
| 405 |
try:
|
| 406 |
inicio = time.time()
|
|
|
|
| 408 |
texto_resp = resp.text
|
| 409 |
duracao = time.time() - inicio
|
| 410 |
|
| 411 |
+
# Adiciona a resposta do agente à trilha de auditoria
|
| 412 |
+
timeline_execucao.append({"passo": passo_atual, "tipo": "resposta_agente", "agente": nome_agente, "resposta": texto_resp})
|
| 413 |
|
| 414 |
+
# Remove o status "analisando..." e adiciona a resposta final do agente
|
| 415 |
msg_atual = history[-1][1]
|
| 416 |
+
msg_atual = msg_atual.replace(f"⏳ **{nome_agente}** está analisando...\n", "")
|
| 417 |
|
| 418 |
novo_trecho = f"**[{nome_agente}]** ({duracao:.1f}s):\n{texto_resp}\n\n"
|
| 419 |
history[-1][1] = msg_atual + novo_trecho
|
| 420 |
+
yield history, timeline_execucao
|
| 421 |
|
| 422 |
except Exception as e:
|
| 423 |
+
# Adiciona o erro à trilha de auditoria e ao chat
|
| 424 |
+
timeline_execucao.append({"passo": passo_atual, "tipo": "erro_agente", "agente": nome_agente, "erro": str(e)})
|
| 425 |
msg_atual = history[-1][1]
|
| 426 |
+
history[-1][1] = msg_atual.replace(f"⏳ **{nome_agente}** está analisando...\n", "") + f"\n❌ Erro em {nome_agente}: {str(e)}\n"
|
| 427 |
+
yield history, timeline_execucao
|
| 428 |
+
|
| 429 |
+
passo_atual += 1
|
| 430 |
|
| 431 |
# ==================== 6. UI (Gradio) ====================
|
| 432 |
|
|
|
|
| 469 |
label="Arraste arquivos aqui ou clique para selecionar"
|
| 470 |
)
|
| 471 |
|
| 472 |
+
# NOVA ABA DE AUDITORIA
|
| 473 |
+
with gr.Tab("🕵️ Auditoria"):
|
| 474 |
+
gr.Markdown("### Trilha de Auditoria\nExibe o histórico completo de prompts e respostas de cada agente na última execução. O conteúdo é atualizado a cada nova mensagem enviada.")
|
| 475 |
+
json_audit = gr.JSON(label="Timeline da Execução da Última Mensagem")
|
| 476 |
+
|
| 477 |
with gr.Tab("⚙️ Contexto & Config"):
|
| 478 |
gr.Markdown("### Protocolo dos Agentes")
|
| 479 |
with gr.Row():
|
|
|
|
| 485 |
btn_save_cfg.click(salvar_protocolo, inputs=[code_config], outputs=[lbl_cfg_status])
|
| 486 |
btn_save_cfg.click(lambda x: x, inputs=[code_config], outputs=[state_config])
|
| 487 |
|
| 488 |
+
# A ação de clique agora atualiza tanto o chatbot quanto a aba de auditoria
|
| 489 |
btn_enviar.click(
|
| 490 |
chat_orquestrador,
|
| 491 |
inputs=[txt_input, chatbot, state_config],
|
| 492 |
+
outputs=[chatbot, json_audit] # Adicionado json_audit como saída
|
| 493 |
).then(
|
| 494 |
lambda: "", outputs=[txt_input]
|
| 495 |
)
|
|
|
|
| 503 |
return app
|
| 504 |
|
| 505 |
if __name__ == "__main__":
|
| 506 |
+
ui_v28_corrected().launch()```
|