Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,10 @@
|
|
| 1 |
# ╔════════════════════════════════════════════════════════════════════════════╗
|
| 2 |
-
# ║ PIPELINE
|
| 3 |
# ║ Layout: Chat | Depuração | Contexto | Config ║
|
| 4 |
# ╚════════════════════════════════════════════════════════════════════════════╝
|
| 5 |
|
| 6 |
import os
|
| 7 |
import json
|
| 8 |
-
import re
|
| 9 |
import time
|
| 10 |
from datetime import datetime
|
| 11 |
|
|
@@ -58,12 +57,12 @@ def ler_anexo(arquivo):
|
|
| 58 |
return ""
|
| 59 |
|
| 60 |
|
| 61 |
-
# -------- CONTEXTO GLOBAL --------
|
| 62 |
|
| 63 |
def contexto_vazio():
|
| 64 |
return {
|
| 65 |
-
"classificacao": "",
|
| 66 |
-
"fatos": [],
|
| 67 |
"objetivo_usuario": "",
|
| 68 |
"duvida_central_ultimos_input": "",
|
| 69 |
"timestamp": ""
|
|
@@ -87,47 +86,93 @@ def salvar_contexto(ctx):
|
|
| 87 |
return ctx
|
| 88 |
|
| 89 |
|
| 90 |
-
def atualizar_contexto(full_input, timeline,
|
| 91 |
"""
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
| 95 |
"""
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
|
| 102 |
-
texto_lower = full_input.lower()
|
| 103 |
-
if "?" in full_input:
|
| 104 |
-
ctx["classificacao"] = "duvida"
|
| 105 |
-
elif "reclama" in texto_lower or "problema" in texto_lower or "erro" in texto_lower:
|
| 106 |
-
ctx["classificacao"] = "critica"
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
|
| 121 |
-
# ==================== 3. ENGINE DE EXECUÇÃO ====================
|
| 122 |
|
| 123 |
def executar_no(timeline, config, contexto):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
modelo = model_pro if config.get("modelo") == "pro" else model_flash
|
| 125 |
|
| 126 |
contexto_timeline = json.dumps(timeline, ensure_ascii=False, indent=2)
|
| 127 |
contexto_global = json.dumps(contexto, ensure_ascii=False, indent=2)
|
| 128 |
|
| 129 |
prompt = (
|
| 130 |
-
f"--- CONTEXTO GLOBAL ---\n{contexto_global}\n"
|
| 131 |
f"--- TIMELINE ---\n{contexto_timeline}\n"
|
| 132 |
f"----------------\n"
|
| 133 |
f"AGENTE: {config['nome']}\n"
|
|
@@ -143,7 +188,6 @@ def executar_no(timeline, config, contexto):
|
|
| 143 |
tempo = time.time() - inicio
|
| 144 |
|
| 145 |
if config.get("tipo_saida") == "json":
|
| 146 |
-
# Tenta normalizar saída JSON simples
|
| 147 |
cleaned = out.strip().replace("``````", "")
|
| 148 |
content = json.loads(cleaned)
|
| 149 |
else:
|
|
@@ -154,7 +198,6 @@ def executar_no(timeline, config, contexto):
|
|
| 154 |
return {"role": "assistant", "agent": config["nome"], "content": content}, log, out
|
| 155 |
|
| 156 |
except Exception as e:
|
| 157 |
-
# Em caso de erro, registra no timeline como system
|
| 158 |
return {"role": "system", "error": str(e)}, f" (ERRO: {e})", str(e)
|
| 159 |
|
| 160 |
|
|
@@ -168,7 +211,6 @@ def orquestrador(texto, arquivo, history, json_config):
|
|
| 168 |
contexto = carregar_contexto()
|
| 169 |
|
| 170 |
if not full_input:
|
| 171 |
-
# Sem input, apenas retorna contexto atual
|
| 172 |
yield history, {}, "Sem input.", contexto
|
| 173 |
return
|
| 174 |
|
|
@@ -182,9 +224,10 @@ def orquestrador(texto, arquivo, history, json_config):
|
|
| 182 |
yield history, {}, "Erro JSON", contexto
|
| 183 |
return
|
| 184 |
|
|
|
|
| 185 |
timeline = [{"role": "user", "content": full_input}]
|
| 186 |
|
| 187 |
-
#
|
| 188 |
contexto = atualizar_contexto(full_input, timeline, contexto)
|
| 189 |
salvar_contexto(contexto)
|
| 190 |
|
|
@@ -193,7 +236,7 @@ def orquestrador(texto, arquivo, history, json_config):
|
|
| 193 |
history[-1][1] = "⏳ Iniciando análise..."
|
| 194 |
yield history, timeline, logs, contexto
|
| 195 |
|
| 196 |
-
#
|
| 197 |
final_response = ""
|
| 198 |
|
| 199 |
for cfg in protocolo:
|
|
@@ -204,7 +247,7 @@ def orquestrador(texto, arquivo, history, json_config):
|
|
| 204 |
timeline.append(res)
|
| 205 |
logs += log_add + "\n"
|
| 206 |
|
| 207 |
-
#
|
| 208 |
contexto = atualizar_contexto(full_input, timeline, contexto)
|
| 209 |
salvar_contexto(contexto)
|
| 210 |
|
|
@@ -217,7 +260,7 @@ def orquestrador(texto, arquivo, history, json_config):
|
|
| 217 |
yield history, timeline, logs, contexto
|
| 218 |
|
| 219 |
|
| 220 |
-
# ==================== 5. UI LIMPA (
|
| 221 |
|
| 222 |
def ui_clean():
|
| 223 |
css = """
|
|
@@ -237,7 +280,7 @@ def ui_clean():
|
|
| 237 |
show_label=False,
|
| 238 |
height=600,
|
| 239 |
show_copy_button=True,
|
| 240 |
-
render_markdown=True
|
| 241 |
)
|
| 242 |
|
| 243 |
with gr.Row():
|
|
@@ -262,7 +305,7 @@ def ui_clean():
|
|
| 262 |
size="sm",
|
| 263 |
)
|
| 264 |
|
| 265 |
-
# Feedback visual
|
| 266 |
file_status = gr.Markdown("", visible=True)
|
| 267 |
file_in.upload(
|
| 268 |
lambda x: f"📎 Anexo: {os.path.basename(x.name)}",
|
|
@@ -293,7 +336,6 @@ def ui_clean():
|
|
| 293 |
btn_save.click(salvar_protocolo, code_json, lbl_save)
|
| 294 |
|
| 295 |
# === TRIGGERS ===
|
| 296 |
-
# Enter ou Botão Enviar
|
| 297 |
triggers = [btn_send.click, txt_in.submit]
|
| 298 |
|
| 299 |
for trig in triggers:
|
|
|
|
| 1 |
# ╔════════════════════════════════════════════════════════════════════════════╗
|
| 2 |
+
# ║ PIPELINE v29: MEMÓRIA VAGA + CONTEXTO GLOBAL ║
|
| 3 |
# ║ Layout: Chat | Depuração | Contexto | Config ║
|
| 4 |
# ╚════════════════════════════════════════════════════════════════════════════╝
|
| 5 |
|
| 6 |
import os
|
| 7 |
import json
|
|
|
|
| 8 |
import time
|
| 9 |
from datetime import datetime
|
| 10 |
|
|
|
|
| 57 |
return ""
|
| 58 |
|
| 59 |
|
| 60 |
+
# -------- CONTEXTO GLOBAL (MEMÓRIA VAGA) --------
|
| 61 |
|
| 62 |
def contexto_vazio():
|
| 63 |
return {
|
| 64 |
+
"classificacao": "",
|
| 65 |
+
"fatos": [],
|
| 66 |
"objetivo_usuario": "",
|
| 67 |
"duvida_central_ultimos_input": "",
|
| 68 |
"timestamp": ""
|
|
|
|
| 86 |
return ctx
|
| 87 |
|
| 88 |
|
| 89 |
+
def atualizar_contexto(full_input, timeline, contexto_anterior):
|
| 90 |
"""
|
| 91 |
+
Agente MEMÓRIA VAGA:
|
| 92 |
+
- Só escuta o diálogo e o histórico.
|
| 93 |
+
- Atualiza e retorna APENAS o JSON de contexto global.
|
| 94 |
+
- Nunca escreve na timeline, nunca responde ao usuário.
|
| 95 |
"""
|
| 96 |
+
base_ctx = contexto_vazio()
|
| 97 |
+
ctx_prev = contexto_anterior if contexto_anterior else contexto_vazio()
|
| 98 |
+
|
| 99 |
+
modelo = model_pro # memória usa sempre o modelo mais robusto
|
| 100 |
+
|
| 101 |
+
instrucao = (
|
| 102 |
+
"Você está atuando como um 'ouvinte' que mantém um MEMORIAL do diálogo, "
|
| 103 |
+
"na posição de Promotor de Justiça em casos de violência doméstica. "
|
| 104 |
+
"Você NÃO responde ao usuário, NÃO sugere decisões, "
|
| 105 |
+
"apenas organiza o que é importante em um JSON de CONTEXTO GLOBAL.\n\n"
|
| 106 |
+
"TAREFA:\n"
|
| 107 |
+
"- Ler o input atual, o contexto anterior e a timeline.\n"
|
| 108 |
+
"- Atualizar o CONTEXTO GLOBAL com:\n"
|
| 109 |
+
" * classificacao: \"duvida\" ou \"critica\" (ou vazio se não se aplicar).\n"
|
| 110 |
+
" * fatos: lista de objetos {\"descricao\": str, \"peso\": float, \"ultima_mencao\": str ISO8601}\n"
|
| 111 |
+
" representando elementos factuais relevantes do caso, com peso de 0.0 a 1.0.\n"
|
| 112 |
+
" - Fatos que voltam a aparecer podem ter peso aumentado.\n"
|
| 113 |
+
" - Fatos que deixam de aparecer podem ter peso suavemente reduzido.\n"
|
| 114 |
+
" * objetivo_usuario: 1 frase objetiva sobre o que o usuário quer alcançar agora.\n"
|
| 115 |
+
" * duvida_central_ultimos_input: síntese em 1–2 frases da dúvida/foco do último input.\n"
|
| 116 |
+
" * timestamp: momento atual em ISO8601.\n\n"
|
| 117 |
+
"IMPORTANTE:\n"
|
| 118 |
+
"- Não explique, não comente. Retorne APENAS um JSON válido.\n"
|
| 119 |
+
"- Mantenha a mesma estrutura de chaves do contexto_anterior, atualizando o que fizer sentido.\n"
|
| 120 |
+
)
|
| 121 |
|
| 122 |
+
payload = {
|
| 123 |
+
"input_atual": full_input,
|
| 124 |
+
"contexto_anterior": ctx_prev,
|
| 125 |
+
"timeline": timeline,
|
| 126 |
+
}
|
| 127 |
|
| 128 |
+
schema_exemplo = base_ctx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
prompt = (
|
| 131 |
+
instrucao
|
| 132 |
+
+ "\n\n--- DADOS ---\n"
|
| 133 |
+
+ json.dumps(payload, ensure_ascii=False, indent=2)
|
| 134 |
+
+ "\n\n--- SCHEMA EXATO A SEGUIR ---\n"
|
| 135 |
+
+ json.dumps(schema_exemplo, ensure_ascii=False, indent=2)
|
| 136 |
+
+ "\n\n--- SAÍDA ---\n"
|
| 137 |
+
+ "Retorne APENAS um JSON válido seguindo o schema (sem comentários, sem texto extra)."
|
| 138 |
+
)
|
| 139 |
|
| 140 |
+
try:
|
| 141 |
+
resp = modelo.generate_content(prompt)
|
| 142 |
+
raw = resp.text.strip()
|
| 143 |
+
cleaned = raw.replace("``````", "").strip()
|
| 144 |
+
novo_ctx = json.loads(cleaned)
|
| 145 |
|
| 146 |
+
# Garantir chaves mínimas
|
| 147 |
+
for k, v in base_ctx.items():
|
| 148 |
+
if k not in novo_ctx:
|
| 149 |
+
novo_ctx[k] = v
|
| 150 |
|
| 151 |
+
return novo_ctx
|
| 152 |
+
except Exception:
|
| 153 |
+
# Fallback: preserva memória antiga e marca timestamp / classificação mínima
|
| 154 |
+
ctx_fallback = ctx_prev
|
| 155 |
+
ctx_fallback["timestamp"] = datetime.now().isoformat()
|
| 156 |
+
if "?" in full_input:
|
| 157 |
+
ctx_fallback["classificacao"] = "duvida"
|
| 158 |
+
return ctx_fallback
|
| 159 |
|
| 160 |
|
| 161 |
+
# ==================== 3. ENGINE DE EXECUÇÃO (AGENTES) ====================
|
| 162 |
|
| 163 |
def executar_no(timeline, config, contexto):
|
| 164 |
+
"""
|
| 165 |
+
Executa um nó do protocolo:
|
| 166 |
+
- Recebe timeline + contexto global (memória vaga).
|
| 167 |
+
- Gera resposta de agente (texto ou JSON).
|
| 168 |
+
"""
|
| 169 |
modelo = model_pro if config.get("modelo") == "pro" else model_flash
|
| 170 |
|
| 171 |
contexto_timeline = json.dumps(timeline, ensure_ascii=False, indent=2)
|
| 172 |
contexto_global = json.dumps(contexto, ensure_ascii=False, indent=2)
|
| 173 |
|
| 174 |
prompt = (
|
| 175 |
+
f"--- CONTEXTO GLOBAL (MEMÓRIA DE QUEM OUVE) ---\n{contexto_global}\n"
|
| 176 |
f"--- TIMELINE ---\n{contexto_timeline}\n"
|
| 177 |
f"----------------\n"
|
| 178 |
f"AGENTE: {config['nome']}\n"
|
|
|
|
| 188 |
tempo = time.time() - inicio
|
| 189 |
|
| 190 |
if config.get("tipo_saida") == "json":
|
|
|
|
| 191 |
cleaned = out.strip().replace("``````", "")
|
| 192 |
content = json.loads(cleaned)
|
| 193 |
else:
|
|
|
|
| 198 |
return {"role": "assistant", "agent": config["nome"], "content": content}, log, out
|
| 199 |
|
| 200 |
except Exception as e:
|
|
|
|
| 201 |
return {"role": "system", "error": str(e)}, f" (ERRO: {e})", str(e)
|
| 202 |
|
| 203 |
|
|
|
|
| 211 |
contexto = carregar_contexto()
|
| 212 |
|
| 213 |
if not full_input:
|
|
|
|
| 214 |
yield history, {}, "Sem input.", contexto
|
| 215 |
return
|
| 216 |
|
|
|
|
| 224 |
yield history, {}, "Erro JSON", contexto
|
| 225 |
return
|
| 226 |
|
| 227 |
+
# Timeline começa só com o usuário
|
| 228 |
timeline = [{"role": "user", "content": full_input}]
|
| 229 |
|
| 230 |
+
# 3. MEMÓRIA VAGA: atualiza contexto ANTES de qualquer agente responder
|
| 231 |
contexto = atualizar_contexto(full_input, timeline, contexto)
|
| 232 |
salvar_contexto(contexto)
|
| 233 |
|
|
|
|
| 236 |
history[-1][1] = "⏳ Iniciando análise..."
|
| 237 |
yield history, timeline, logs, contexto
|
| 238 |
|
| 239 |
+
# 4. Loop de nós do protocolo
|
| 240 |
final_response = ""
|
| 241 |
|
| 242 |
for cfg in protocolo:
|
|
|
|
| 247 |
timeline.append(res)
|
| 248 |
logs += log_add + "\n"
|
| 249 |
|
| 250 |
+
# Após cada nó, a memória vaga reouve tudo e atualiza o contexto
|
| 251 |
contexto = atualizar_contexto(full_input, timeline, contexto)
|
| 252 |
salvar_contexto(contexto)
|
| 253 |
|
|
|
|
| 260 |
yield history, timeline, logs, contexto
|
| 261 |
|
| 262 |
|
| 263 |
+
# ==================== 5. UI LIMPA (v29) ====================
|
| 264 |
|
| 265 |
def ui_clean():
|
| 266 |
css = """
|
|
|
|
| 280 |
show_label=False,
|
| 281 |
height=600,
|
| 282 |
show_copy_button=True,
|
| 283 |
+
render_markdown=True,
|
| 284 |
)
|
| 285 |
|
| 286 |
with gr.Row():
|
|
|
|
| 305 |
size="sm",
|
| 306 |
)
|
| 307 |
|
| 308 |
+
# Feedback visual do arquivo
|
| 309 |
file_status = gr.Markdown("", visible=True)
|
| 310 |
file_in.upload(
|
| 311 |
lambda x: f"📎 Anexo: {os.path.basename(x.name)}",
|
|
|
|
| 336 |
btn_save.click(salvar_protocolo, code_json, lbl_save)
|
| 337 |
|
| 338 |
# === TRIGGERS ===
|
|
|
|
| 339 |
triggers = [btn_send.click, txt_in.submit]
|
| 340 |
|
| 341 |
for trig in triggers:
|