diff --git a/Tuning-Performance/Authentication/agent_template_backend_authentication/app/agents/runtime.py b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/agents/runtime.py index e6429c4..7a1a9be 100644 --- a/Tuning-Performance/Authentication/agent_template_backend_authentication/app/agents/runtime.py +++ b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/agents/runtime.py @@ -3,5 +3,8 @@ from __future__ import annotations # Compatibilidade local do template/backend. # A implementação oficial agora fica no framework para evitar duplicação entre agentes. from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext +from app.presentation import register_tool_renderers + +register_tool_renderers() __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] diff --git a/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/__init__.py b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/__init__.py new file mode 100644 index 0000000..c0eba0d --- /dev/null +++ b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/__init__.py @@ -0,0 +1,3 @@ +from .tool_renderers import register_tool_renderers + +__all__ = ["register_tool_renderers"] diff --git a/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/__pycache__/tool_renderers.cpython-313.pyc b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/__pycache__/tool_renderers.cpython-313.pyc new file mode 100644 index 0000000..0c79403 Binary files /dev/null and b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/__pycache__/tool_renderers.cpython-313.pyc differ diff --git a/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/tool_renderers.py b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/tool_renderers.py new file mode 100644 index 0000000..f77c47a --- /dev/null +++ b/Tuning-Performance/Authentication/agent_template_backend_authentication/app/presentation/tool_renderers.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any + +from agent_framework.presentation import register_tool_response_renderer + + +def _money_brl(value: Any) -> str: + try: + return f"{float(value):.2f}".replace(".", ",") + except (TypeError, ValueError): + return str(value) + + +def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + return f"[{agent_label}] Fatura consultada: {result}." + + +def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + plano = result.get("plano") + if plano is None: + return None + parts = [f"[{agent_label}] Seu plano é {plano}"] + internet_gb = result.get("internet_gb") + status = result.get("status") + if internet_gb is not None: + parts.append(f"com {internet_gb} GB") + if status is not None: + parts.append(f"status {status}") + return ", ".join(parts) + "." + + +def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + status = result.get("status") + if order_id is None or status is None: + return None + lines = [f"[{agent_label}] Pedido {order_id}: status {status}."] + total = result.get("valor_total") + if total is not None: + lines.append(f"Valor total: R$ {_money_brl(total)}.") + items = result.get("itens") or [] + rendered_items: list[str] = [] + if isinstance(items, list): + for item in items: + if isinstance(item, dict): + value = item.get("descricao") or item.get("nome") or item.get("sku") + else: + value = item + if value not in (None, ""): + rendered_items.append(str(value)) + if rendered_items: + lines.append("Itens: " + "; ".join(rendered_items) + ".") + return " ".join(lines) + + +def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + transportadora = result.get("transportadora") + codigo = result.get("codigo_rastreio") + previsao = result.get("previsao_entrega") + if any(v is None for v in (order_id, transportadora, codigo, previsao)): + return None + return ( + f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, " + f"rastreio {codigo}, previsão {previsao}." + ) + + +def register_tool_renderers() -> None: + register_tool_response_renderer("telecom.invoice", render_telecom_invoice) + register_tool_response_renderer("telecom.plan", render_telecom_plan) + register_tool_response_renderer("retail.order", render_retail_order) + register_tool_response_renderer("retail.delivery", render_retail_delivery) diff --git a/Tuning-Performance/Authentication/agent_template_backend_authentication/config/tools.yaml b/Tuning-Performance/Authentication/agent_template_backend_authentication/config/tools.yaml index d85fae1..6273371 100644 --- a/Tuning-Performance/Authentication/agent_template_backend_authentication/config/tools.yaml +++ b/Tuning-Performance/Authentication/agent_template_backend_authentication/config/tools.yaml @@ -10,6 +10,9 @@ tools: - fatura - conta - boleto + response: + mode: renderer + renderer: telecom.invoice consultar_pagamentos: description: Consulta histórico de pagamentos do cliente. mcp_server: telecom @@ -28,6 +31,9 @@ tools: asset_id: string selection_keywords: - plano + response: + mode: renderer + renderer: telecom.plan listar_servicos: description: Lista serviços ativos e adicionais VAS. mcp_server: telecom @@ -49,6 +55,9 @@ tools: - consultar pedido - status do pedido - pedido + response: + mode: renderer + renderer: retail.order consultar_entrega: description: Consulta entrega e rastreamento do pedido. mcp_server: retail @@ -61,6 +70,9 @@ tools: - rastreamento - transportadora - previsão + response: + mode: renderer + renderer: retail.delivery solicitar_troca: description: Simula abertura de solicitação de troca. mcp_server: retail diff --git a/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/__init__.py b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/__init__.py new file mode 100644 index 0000000..c0eba0d --- /dev/null +++ b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/__init__.py @@ -0,0 +1,3 @@ +from .tool_renderers import register_tool_renderers + +__all__ = ["register_tool_renderers"] diff --git a/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc new file mode 100644 index 0000000..009b7c1 Binary files /dev/null and b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc differ diff --git a/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/tool_renderers.py b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/tool_renderers.py new file mode 100644 index 0000000..f77c47a --- /dev/null +++ b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/app/presentation/tool_renderers.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any + +from agent_framework.presentation import register_tool_response_renderer + + +def _money_brl(value: Any) -> str: + try: + return f"{float(value):.2f}".replace(".", ",") + except (TypeError, ValueError): + return str(value) + + +def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + return f"[{agent_label}] Fatura consultada: {result}." + + +def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + plano = result.get("plano") + if plano is None: + return None + parts = [f"[{agent_label}] Seu plano é {plano}"] + internet_gb = result.get("internet_gb") + status = result.get("status") + if internet_gb is not None: + parts.append(f"com {internet_gb} GB") + if status is not None: + parts.append(f"status {status}") + return ", ".join(parts) + "." + + +def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + status = result.get("status") + if order_id is None or status is None: + return None + lines = [f"[{agent_label}] Pedido {order_id}: status {status}."] + total = result.get("valor_total") + if total is not None: + lines.append(f"Valor total: R$ {_money_brl(total)}.") + items = result.get("itens") or [] + rendered_items: list[str] = [] + if isinstance(items, list): + for item in items: + if isinstance(item, dict): + value = item.get("descricao") or item.get("nome") or item.get("sku") + else: + value = item + if value not in (None, ""): + rendered_items.append(str(value)) + if rendered_items: + lines.append("Itens: " + "; ".join(rendered_items) + ".") + return " ".join(lines) + + +def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + transportadora = result.get("transportadora") + codigo = result.get("codigo_rastreio") + previsao = result.get("previsao_entrega") + if any(v is None for v in (order_id, transportadora, codigo, previsao)): + return None + return ( + f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, " + f"rastreio {codigo}, previsão {previsao}." + ) + + +def register_tool_renderers() -> None: + register_tool_response_renderer("telecom.invoice", render_telecom_invoice) + register_tool_response_renderer("telecom.plan", render_telecom_plan) + register_tool_response_renderer("retail.order", render_retail_order) + register_tool_response_renderer("retail.delivery", render_retail_delivery) diff --git a/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/config/tools.yaml b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/config/tools.yaml index d85fae1..6273371 100644 --- a/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/config/tools.yaml +++ b/Tuning-Performance/Deterministic_Transactional_Workflow/agent_template_backend/config/tools.yaml @@ -10,6 +10,9 @@ tools: - fatura - conta - boleto + response: + mode: renderer + renderer: telecom.invoice consultar_pagamentos: description: Consulta histórico de pagamentos do cliente. mcp_server: telecom @@ -28,6 +31,9 @@ tools: asset_id: string selection_keywords: - plano + response: + mode: renderer + renderer: telecom.plan listar_servicos: description: Lista serviços ativos e adicionais VAS. mcp_server: telecom @@ -49,6 +55,9 @@ tools: - consultar pedido - status do pedido - pedido + response: + mode: renderer + renderer: retail.order consultar_entrega: description: Consulta entrega e rastreamento do pedido. mcp_server: retail @@ -61,6 +70,9 @@ tools: - rastreamento - transportadora - previsão + response: + mode: renderer + renderer: retail.delivery solicitar_troca: description: Simula abertura de solicitação de troca. mcp_server: retail diff --git a/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/agents/runtime.py b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/agents/runtime.py index e6429c4..7a1a9be 100644 --- a/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/agents/runtime.py +++ b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/agents/runtime.py @@ -3,5 +3,8 @@ from __future__ import annotations # Compatibilidade local do template/backend. # A implementação oficial agora fica no framework para evitar duplicação entre agentes. from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext +from app.presentation import register_tool_renderers + +register_tool_renderers() __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] diff --git a/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/__init__.py b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/__init__.py new file mode 100644 index 0000000..c0eba0d --- /dev/null +++ b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/__init__.py @@ -0,0 +1,3 @@ +from .tool_renderers import register_tool_renderers + +__all__ = ["register_tool_renderers"] diff --git a/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc new file mode 100644 index 0000000..32cbdf8 Binary files /dev/null and b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc differ diff --git a/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/tool_renderers.py b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/tool_renderers.py new file mode 100644 index 0000000..f77c47a --- /dev/null +++ b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/app/presentation/tool_renderers.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any + +from agent_framework.presentation import register_tool_response_renderer + + +def _money_brl(value: Any) -> str: + try: + return f"{float(value):.2f}".replace(".", ",") + except (TypeError, ValueError): + return str(value) + + +def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + return f"[{agent_label}] Fatura consultada: {result}." + + +def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + plano = result.get("plano") + if plano is None: + return None + parts = [f"[{agent_label}] Seu plano é {plano}"] + internet_gb = result.get("internet_gb") + status = result.get("status") + if internet_gb is not None: + parts.append(f"com {internet_gb} GB") + if status is not None: + parts.append(f"status {status}") + return ", ".join(parts) + "." + + +def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + status = result.get("status") + if order_id is None or status is None: + return None + lines = [f"[{agent_label}] Pedido {order_id}: status {status}."] + total = result.get("valor_total") + if total is not None: + lines.append(f"Valor total: R$ {_money_brl(total)}.") + items = result.get("itens") or [] + rendered_items: list[str] = [] + if isinstance(items, list): + for item in items: + if isinstance(item, dict): + value = item.get("descricao") or item.get("nome") or item.get("sku") + else: + value = item + if value not in (None, ""): + rendered_items.append(str(value)) + if rendered_items: + lines.append("Itens: " + "; ".join(rendered_items) + ".") + return " ".join(lines) + + +def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + transportadora = result.get("transportadora") + codigo = result.get("codigo_rastreio") + previsao = result.get("previsao_entrega") + if any(v is None for v in (order_id, transportadora, codigo, previsao)): + return None + return ( + f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, " + f"rastreio {codigo}, previsão {previsao}." + ) + + +def register_tool_renderers() -> None: + register_tool_response_renderer("telecom.invoice", render_telecom_invoice) + register_tool_response_renderer("telecom.plan", render_telecom_plan) + register_tool_response_renderer("retail.order", render_retail_order) + register_tool_response_renderer("retail.delivery", render_retail_delivery) diff --git a/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/config/tools.yaml b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/config/tools.yaml index d85fae1..6273371 100644 --- a/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/config/tools.yaml +++ b/Tuning-Performance/Long_Term_Memory/templates/agent_template_backend/config/tools.yaml @@ -10,6 +10,9 @@ tools: - fatura - conta - boleto + response: + mode: renderer + renderer: telecom.invoice consultar_pagamentos: description: Consulta histórico de pagamentos do cliente. mcp_server: telecom @@ -28,6 +31,9 @@ tools: asset_id: string selection_keywords: - plano + response: + mode: renderer + renderer: telecom.plan listar_servicos: description: Lista serviços ativos e adicionais VAS. mcp_server: telecom @@ -49,6 +55,9 @@ tools: - consultar pedido - status do pedido - pedido + response: + mode: renderer + renderer: retail.order consultar_entrega: description: Consulta entrega e rastreamento do pedido. mcp_server: retail @@ -61,6 +70,9 @@ tools: - rastreamento - transportadora - previsão + response: + mode: renderer + renderer: retail.delivery solicitar_troca: description: Simula abertura de solicitação de troca. mcp_server: retail diff --git a/Tuning-Performance/Normal/templates/agent_template_backend/app/agents/runtime.py b/Tuning-Performance/Normal/templates/agent_template_backend/app/agents/runtime.py index e6429c4..7a1a9be 100644 --- a/Tuning-Performance/Normal/templates/agent_template_backend/app/agents/runtime.py +++ b/Tuning-Performance/Normal/templates/agent_template_backend/app/agents/runtime.py @@ -3,5 +3,8 @@ from __future__ import annotations # Compatibilidade local do template/backend. # A implementação oficial agora fica no framework para evitar duplicação entre agentes. from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext +from app.presentation import register_tool_renderers + +register_tool_renderers() __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] diff --git a/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/__init__.py b/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/__init__.py new file mode 100644 index 0000000..c0eba0d --- /dev/null +++ b/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/__init__.py @@ -0,0 +1,3 @@ +from .tool_renderers import register_tool_renderers + +__all__ = ["register_tool_renderers"] diff --git a/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc b/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc new file mode 100644 index 0000000..23b52e1 Binary files /dev/null and b/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc differ diff --git a/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/tool_renderers.py b/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/tool_renderers.py new file mode 100644 index 0000000..f77c47a --- /dev/null +++ b/Tuning-Performance/Normal/templates/agent_template_backend/app/presentation/tool_renderers.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any + +from agent_framework.presentation import register_tool_response_renderer + + +def _money_brl(value: Any) -> str: + try: + return f"{float(value):.2f}".replace(".", ",") + except (TypeError, ValueError): + return str(value) + + +def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + return f"[{agent_label}] Fatura consultada: {result}." + + +def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + plano = result.get("plano") + if plano is None: + return None + parts = [f"[{agent_label}] Seu plano é {plano}"] + internet_gb = result.get("internet_gb") + status = result.get("status") + if internet_gb is not None: + parts.append(f"com {internet_gb} GB") + if status is not None: + parts.append(f"status {status}") + return ", ".join(parts) + "." + + +def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + status = result.get("status") + if order_id is None or status is None: + return None + lines = [f"[{agent_label}] Pedido {order_id}: status {status}."] + total = result.get("valor_total") + if total is not None: + lines.append(f"Valor total: R$ {_money_brl(total)}.") + items = result.get("itens") or [] + rendered_items: list[str] = [] + if isinstance(items, list): + for item in items: + if isinstance(item, dict): + value = item.get("descricao") or item.get("nome") or item.get("sku") + else: + value = item + if value not in (None, ""): + rendered_items.append(str(value)) + if rendered_items: + lines.append("Itens: " + "; ".join(rendered_items) + ".") + return " ".join(lines) + + +def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + transportadora = result.get("transportadora") + codigo = result.get("codigo_rastreio") + previsao = result.get("previsao_entrega") + if any(v is None for v in (order_id, transportadora, codigo, previsao)): + return None + return ( + f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, " + f"rastreio {codigo}, previsão {previsao}." + ) + + +def register_tool_renderers() -> None: + register_tool_response_renderer("telecom.invoice", render_telecom_invoice) + register_tool_response_renderer("telecom.plan", render_telecom_plan) + register_tool_response_renderer("retail.order", render_retail_order) + register_tool_response_renderer("retail.delivery", render_retail_delivery) diff --git a/Tuning-Performance/Normal/templates/agent_template_backend/config/tools.yaml b/Tuning-Performance/Normal/templates/agent_template_backend/config/tools.yaml index d85fae1..6273371 100644 --- a/Tuning-Performance/Normal/templates/agent_template_backend/config/tools.yaml +++ b/Tuning-Performance/Normal/templates/agent_template_backend/config/tools.yaml @@ -10,6 +10,9 @@ tools: - fatura - conta - boleto + response: + mode: renderer + renderer: telecom.invoice consultar_pagamentos: description: Consulta histórico de pagamentos do cliente. mcp_server: telecom @@ -28,6 +31,9 @@ tools: asset_id: string selection_keywords: - plano + response: + mode: renderer + renderer: telecom.plan listar_servicos: description: Lista serviços ativos e adicionais VAS. mcp_server: telecom @@ -49,6 +55,9 @@ tools: - consultar pedido - status do pedido - pedido + response: + mode: renderer + renderer: retail.order consultar_entrega: description: Consulta entrega e rastreamento do pedido. mcp_server: retail @@ -61,6 +70,9 @@ tools: - rastreamento - transportadora - previsão + response: + mode: renderer + renderer: retail.delivery solicitar_troca: description: Simula abertura de solicitação de troca. mcp_server: retail diff --git a/Tuning-Performance/Offline_Workflow_Regression/README.md b/Tuning-Performance/Offline_Workflow_Regression/README.md index bbd3250..f3bc196 100644 --- a/Tuning-Performance/Offline_Workflow_Regression/README.md +++ b/Tuning-Performance/Offline_Workflow_Regression/README.md @@ -2,7 +2,7 @@ O backend de produção de `WorkflowRuntime` continua sendo **LangGraph**. A ausência do pacote `langgraph` em produção é erro de configuração. -Para builders restritos/offline, o runtime aceita `allow_deterministic_fallback=True`. Esse modo é deliberadamente opt-in e existe somente para exercitar a DSL do framework (actions, edges, condições, pause/resume e trace) de forma reproduzível em testes offline/regressão. Quando `allow_deterministic_fallback=True`, o backend determinístico é selecionado explicitamente mesmo que LangGraph esteja instalado. Ele nunca é selecionado automaticamente em produção. +Para builders restritos/offline, o runtime aceita `allow_deterministic_fallback=True`. Esse modo é deliberadamente opt-in e existe somente para exercitar a DSL do framework (actions, edges, condições, pause/resume e trace) quando a dependência externa não pode ser instalada. Ele não é selecionado automaticamente. Exemplo de teste: diff --git a/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/agents/runtime.py b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/agents/runtime.py index e6429c4..7a1a9be 100644 --- a/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/agents/runtime.py +++ b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/agents/runtime.py @@ -3,5 +3,8 @@ from __future__ import annotations # Compatibilidade local do template/backend. # A implementação oficial agora fica no framework para evitar duplicação entre agentes. from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext +from app.presentation import register_tool_renderers + +register_tool_renderers() __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] diff --git a/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/__init__.py b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/__init__.py new file mode 100644 index 0000000..c0eba0d --- /dev/null +++ b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/__init__.py @@ -0,0 +1,3 @@ +from .tool_renderers import register_tool_renderers + +__all__ = ["register_tool_renderers"] diff --git a/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc new file mode 100644 index 0000000..567eb4d Binary files /dev/null and b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc differ diff --git a/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/tool_renderers.py b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/tool_renderers.py new file mode 100644 index 0000000..f77c47a --- /dev/null +++ b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/app/presentation/tool_renderers.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any + +from agent_framework.presentation import register_tool_response_renderer + + +def _money_brl(value: Any) -> str: + try: + return f"{float(value):.2f}".replace(".", ",") + except (TypeError, ValueError): + return str(value) + + +def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + return f"[{agent_label}] Fatura consultada: {result}." + + +def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + plano = result.get("plano") + if plano is None: + return None + parts = [f"[{agent_label}] Seu plano é {plano}"] + internet_gb = result.get("internet_gb") + status = result.get("status") + if internet_gb is not None: + parts.append(f"com {internet_gb} GB") + if status is not None: + parts.append(f"status {status}") + return ", ".join(parts) + "." + + +def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + status = result.get("status") + if order_id is None or status is None: + return None + lines = [f"[{agent_label}] Pedido {order_id}: status {status}."] + total = result.get("valor_total") + if total is not None: + lines.append(f"Valor total: R$ {_money_brl(total)}.") + items = result.get("itens") or [] + rendered_items: list[str] = [] + if isinstance(items, list): + for item in items: + if isinstance(item, dict): + value = item.get("descricao") or item.get("nome") or item.get("sku") + else: + value = item + if value not in (None, ""): + rendered_items.append(str(value)) + if rendered_items: + lines.append("Itens: " + "; ".join(rendered_items) + ".") + return " ".join(lines) + + +def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + transportadora = result.get("transportadora") + codigo = result.get("codigo_rastreio") + previsao = result.get("previsao_entrega") + if any(v is None for v in (order_id, transportadora, codigo, previsao)): + return None + return ( + f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, " + f"rastreio {codigo}, previsão {previsao}." + ) + + +def register_tool_renderers() -> None: + register_tool_response_renderer("telecom.invoice", render_telecom_invoice) + register_tool_response_renderer("telecom.plan", render_telecom_plan) + register_tool_response_renderer("retail.order", render_retail_order) + register_tool_response_renderer("retail.delivery", render_retail_delivery) diff --git a/Tuning-Performance/Route_Stickness/templates/agent_template_backend/config/tools.yaml b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/config/tools.yaml index d85fae1..6273371 100644 --- a/Tuning-Performance/Route_Stickness/templates/agent_template_backend/config/tools.yaml +++ b/Tuning-Performance/Route_Stickness/templates/agent_template_backend/config/tools.yaml @@ -10,6 +10,9 @@ tools: - fatura - conta - boleto + response: + mode: renderer + renderer: telecom.invoice consultar_pagamentos: description: Consulta histórico de pagamentos do cliente. mcp_server: telecom @@ -28,6 +31,9 @@ tools: asset_id: string selection_keywords: - plano + response: + mode: renderer + renderer: telecom.plan listar_servicos: description: Lista serviços ativos e adicionais VAS. mcp_server: telecom @@ -49,6 +55,9 @@ tools: - consultar pedido - status do pedido - pedido + response: + mode: renderer + renderer: retail.order consultar_entrega: description: Consulta entrega e rastreamento do pedido. mcp_server: retail @@ -61,6 +70,9 @@ tools: - rastreamento - transportadora - previsão + response: + mode: renderer + renderer: retail.delivery solicitar_troca: description: Simula abertura de solicitação de troca. mcp_server: retail diff --git a/docs/features/01_authentication.md b/docs/features/01_authentication.md new file mode 100644 index 0000000..1460cbb --- /dev/null +++ b/docs/features/01_authentication.md @@ -0,0 +1,165 @@ +# Autenticação / Authentication + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `security/authentication.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Verifica quem pode acessar APIs, gateways e serviços protegidos antes que a requisição chegue ao agente. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Cliente/Sistema + ↓ +Authentication Provider + ↓ +credencial válida? + ├─ não → 401/nega acesso + └─ sim → principal autenticado → agente +``` + +### 4. Como funciona internamente + +O framework contém uma abstração `AuthenticationProvider` e implementações para cenários diferentes. Entre as implementações atuais estão `NoAuthenticationProvider`, `DenyAuthenticationProvider`, `BasicAuthenticationProvider`, `ApiKeyAuthenticationProvider`, `StaticBearerAuthenticationProvider`, `JwtAuthenticationProvider`, `OAuth2IntrospectionAuthenticationProvider` e `TrustedProxyAuthenticationProvider`. + +A autenticação produz um `AuthenticatedPrincipal` com `subject`, `scheme` e, quando aplicável, `claims`. A regra de negócio do agente não deve validar senha/token diretamente. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```python +from agent_framework.security.authentication import BasicAuthenticationProvider + +provider = BasicAuthenticationProvider( + client_id="client-a", + secret_hash="pbkdf2_sha256:...", +) +result = await provider.authenticate(request) +if not result.authenticated: + # negar acesso + ... +``` + +Segredos podem ser verificados em formato simples, SHA-256 ou PBKDF2; em produção, prefira hashes fortes e secret stores. + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Basic auth retornando 401: validar `Authorization: Basic ...` e o secret configurado. +- Confundir autenticação do usuário com `OCI_AUTH_MODE`: são problemas diferentes. +- Usar `NoAuthenticationProvider` em produção sem decisão explícita de arquitetura. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/security/authentication.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Checks who may access protected APIs, gateways, and services before the request reaches the agent. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +Client/System + ↓ +Authentication Provider + ↓ +valid credential? + ├─ no → 401/deny + └─ yes → authenticated principal → agent +``` + +### 4. How it works internally + +The framework exposes an `AuthenticationProvider` abstraction with multiple implementations. Current providers include `NoAuthenticationProvider`, `DenyAuthenticationProvider`, `BasicAuthenticationProvider`, `ApiKeyAuthenticationProvider`, `StaticBearerAuthenticationProvider`, `JwtAuthenticationProvider`, `OAuth2IntrospectionAuthenticationProvider`, and `TrustedProxyAuthenticationProvider`. + +Authentication produces an `AuthenticatedPrincipal` containing `subject`, `scheme`, and optional `claims`. Domain code should not validate credentials directly. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```python +from agent_framework.security.authentication import BasicAuthenticationProvider + +provider = BasicAuthenticationProvider( + client_id="client-a", + secret_hash="pbkdf2_sha256:...", +) +result = await provider.authenticate(request) +if not result.authenticated: + # deny access + ... +``` + +Secrets may be verified as plain, SHA-256, or PBKDF2 values; for production, prefer strong hashes and managed secret stores. + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Basic auth returns 401: validate the `Authorization: Basic ...` header and configured secret. +- Do not confuse API authentication with `OCI_AUTH_MODE`; they solve different problems. +- Avoid `NoAuthenticationProvider` in production unless explicitly accepted by architecture. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/security/authentication.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/02_deterministic_transactional_workflow.md b/docs/features/02_deterministic_transactional_workflow.md new file mode 100644 index 0000000..5485b94 --- /dev/null +++ b/docs/features/02_deterministic_transactional_workflow.md @@ -0,0 +1,183 @@ +# Workflow Transacional Determinístico / Deterministic Transactional Workflow + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `workflows/runtime.py + mcp/tool_policy.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Garante que operações que alteram estado sigam passos previsíveis, com confirmação e controle de execução, em vez de depender da criatividade do LLM. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Mensagem do cliente + ↓ +LLM entende intenção + ↓ +Tool policy = transactional + ↓ +Workflow determinístico + ↓ +confirmação + ↓ +execução controlada + ↓ +resultado +``` + +### 4. Como funciona internamente + +O LLM pode ajudar a interpretar a intenção e extrair parâmetros, mas não deve decidir a sequência crítica de uma transação. O `ToolPolicyRegistry` classifica tools, e `operation_type: transactional` ativa a política transacional. O `WorkflowRuntime` executa o workflow, mantém estado e integra pause/resume e recuperação de erro. + +A configuração `ENABLE_TRANSACTIONAL_WORKFLOWS` controla a capability global, e `WORKFLOWS_PATH` aponta para os YAMLs. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```yaml +tools: + cancelar_servico: + operation_type: transactional + requires_confirmation: true +``` + +```text +1. localizar serviço +2. validar elegibilidade +3. pedir confirmação +4. PAUSE +5. receber confirmação +6. RESUME +7. executar side effect +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Marcar uma tool de escrita como `read_only` elimina proteções transacionais. +- Reexecutar steps anteriores ao pause pode duplicar side effects; use o runtime oficial. +- Não use prompt como única garantia de confirmação. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Ensures state-changing operations follow predictable steps with confirmation and execution control instead of depending on LLM creativity. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +Customer message + ↓ +LLM understands intent + ↓ +Tool policy = transactional + ↓ +Deterministic workflow + ↓ +confirmation + ↓ +controlled execution + ↓ +result +``` + +### 4. How it works internally + +The LLM may help interpret intent and extract parameters, but it should not decide the critical sequence of a transaction. `ToolPolicyRegistry` classifies tools, and `operation_type: transactional` activates transactional behavior. `WorkflowRuntime` executes the workflow, preserves state, and integrates pause/resume and error recovery. + +`ENABLE_TRANSACTIONAL_WORKFLOWS` controls the capability globally, while `WORKFLOWS_PATH` points to workflow YAML files. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```yaml +tools: + cancel_service: + operation_type: transactional + requires_confirmation: true +``` + +```text +1. locate service +2. validate eligibility +3. ask for confirmation +4. PAUSE +5. receive confirmation +6. RESUME +7. execute side effect +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Marking a write tool as `read_only` bypasses transactional protections. +- Re-running steps before a pause can duplicate side effects; use the official runtime. +- Do not use prompts as the only confirmation guarantee. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/03_domain_requested_llm_composition.md b/docs/features/03_domain_requested_llm_composition.md new file mode 100644 index 0000000..4d70018 --- /dev/null +++ b/docs/features/03_domain_requested_llm_composition.md @@ -0,0 +1,157 @@ +# Composição por LLM Solicitada pelo Domínio / Domain Requested LLM Composition + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `runtime/agent_runtime.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Permite que a regra de negócio calcule o resultado e peça ao LLM apenas para redigir a resposta final. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Regra de negócio calcula + ↓ +requires_llm_composition=true + ↓ +framework impede resposta MCP direta + ↓ +LLMProvider oficial + ↓ +redação natural +``` + +### 4. Como funciona internamente + +O domínio retorna dados confiáveis e uma instrução de composição. O `AgentRuntimeMixin` detecta `requires_llm_composition` de forma recursiva no resultado da tool/workflow e não encerra a resposta pelo caminho direto de MCP. A composição segue pelo LLM oficial do agente, preservando profiles, tracing, usage e políticas do framework. + +O LLM deve redigir; ele não deve recalcular valores nem decidir regras de negócio já resolvidas. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```json +{ + "success": true, + "refund_amount": "38,00", + "requires_llm_composition": true, + "response_instruction": "Explique a devolução usando somente os valores calculados." +} +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Instrução muito aberta pode fazer o LLM adicionar conteúdo não autorizado. +- Não envie ao LLM a responsabilidade de recalcular valores determinísticos. +- Se não houver necessidade de redação livre, prefira resposta determinística direta. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Lets domain logic compute the authoritative result and ask the LLM only to compose the final user-facing response. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +Domain logic computes + ↓ +requires_llm_composition=true + ↓ +framework prevents direct MCP answer + ↓ +official LLMProvider + ↓ +natural-language response +``` + +### 4. How it works internally + +The domain returns authoritative data plus a composition instruction. `AgentRuntimeMixin` recursively detects `requires_llm_composition` in tool/workflow results and avoids terminating through the direct MCP-answer path. Composition then uses the agent's official LLM provider, preserving profiles, tracing, usage accounting, and framework policies. + +The LLM should compose language, not recalculate values or override already-resolved business rules. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```json +{ + "success": true, + "refund_amount": "38.00", + "requires_llm_composition": true, + "response_instruction": "Explain the refund using only the computed values." +} +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- An overly broad instruction may let the LLM add unauthorized content. +- Do not delegate deterministic calculations back to the LLM. +- If free-form wording is unnecessary, prefer a deterministic direct response. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/04_domain_requested_rag.md b/docs/features/04_domain_requested_rag.md new file mode 100644 index 0000000..745397f --- /dev/null +++ b/docs/features/04_domain_requested_rag.md @@ -0,0 +1,167 @@ +# RAG Solicitado pelo Domínio / Domain Requested RAG + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `runtime/agent_runtime.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Permite que uma tool ou workflow declare que a resposta precisa consultar conhecimento externo, mesmo quando já existe resultado MCP. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Tool/Workflow + ↓ +requires_rag=true + ↓ +rag_query / rag_queries + ↓ +RagService do framework + ↓ +Retrieval Guardrails + ↓ +LLM/resposta +``` + +### 4. Como funciona internamente + +Normalmente o framework pode pular RAG quando MCP já trouxe informação suficiente (`SKIP_RAG_WHEN_MCP_SUFFICIENT`). Esta feature permite que o domínio substitua essa decisão para um caso específico. O resultado pode declarar `requires_rag`, `rag_query` ou `rag_queries`; o runtime usa essas queries como override e executa o `RagService`. + +O domínio informa **o que precisa saber**. Ele não implementa cliente de vetor, retriever ou prompt RAG paralelo. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```json +{ + "requires_rag": true, + "rag_queries": [ + "Como cancelar YouTube Premium?", + "Como cancelar Aya Books?" + ] +} +``` + +Configurações relacionadas incluem `RAG_TOP_K` e `SKIP_RAG_WHEN_MCP_SUFFICIENT`. + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Declarar RAG para fatos transacionais já resolvidos pela API pode aumentar custo e latência. +- Query genérica demais reduz relevância. +- Nunca confie no retrieval sem `Retrieval Guardrails` quando o dado influencia resposta crítica. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Allows a tool or workflow to declare that external knowledge retrieval is required even when an MCP result already exists. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +Tool/Workflow + ↓ +requires_rag=true + ↓ +rag_query / rag_queries + ↓ +framework RagService + ↓ +Retrieval Guardrails + ↓ +LLM/response +``` + +### 4. How it works internally + +Normally the framework may skip RAG when MCP already provides sufficient data (`SKIP_RAG_WHEN_MCP_SUFFICIENT`). This feature lets the domain override that decision for a specific case. A result may declare `requires_rag`, `rag_query`, or `rag_queries`; the runtime uses those queries as overrides and invokes `RagService`. + +The domain declares **what knowledge is needed**. It does not implement its own vector client, retriever, or parallel RAG prompt stack. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```json +{ + "requires_rag": true, + "rag_queries": [ + "How to cancel YouTube Premium?", + "How to cancel Aya Books?" + ] +} +``` + +Related settings include `RAG_TOP_K` and `SKIP_RAG_WHEN_MCP_SUFFICIENT`. + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Requesting RAG for transactional facts already resolved by an API adds unnecessary cost and latency. +- Queries that are too broad reduce relevance. +- Do not trust retrieved content for critical responses without Retrieval Guardrails. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/05_long_term_memory.md b/docs/features/05_long_term_memory.md new file mode 100644 index 0000000..e9e43e3 --- /dev/null +++ b/docs/features/05_long_term_memory.md @@ -0,0 +1,167 @@ +# Memória de Longo Prazo / Long Term Memory + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `memory/long_term_memory.py + memory/long_term_store.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Permite lembrar informações úteis entre sessões diferentes, sem depender do histórico completo de uma conversa. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Sessão A + ↓ +extração de memória relevante + ↓ +Long Term Memory Store + ↓ +... dias depois ... + ↓ +Sessão B + ↓ +recupera contexto relevante + ↓ +agente +``` + +### 4. Como funciona internamente + +A memória de longo prazo é diferente de histórico de mensagens e de checkpoint. Ela persiste fatos/preferências úteis e os recupera como contexto de uma nova sessão. O framework oferece providers `memory`, `sqlite`, `autonomous` e `oracle`. + +Configurações importantes: `ENABLE_LONG_TERM_MEMORY`, `LONG_TERM_MEMORY_PROVIDER`, `LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS`, `LONG_TERM_MEMORY_MIN_CONFIDENCE`, `LONG_TERM_MEMORY_AUTO_EXTRACT` e `LONG_TERM_MEMORY_INJECT_CONTEXT`. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```env +ENABLE_LONG_TERM_MEMORY=true +LONG_TERM_MEMORY_PROVIDER=oracle +LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS=20 +LONG_TERM_MEMORY_MIN_CONFIDENCE=0.70 +LONG_TERM_MEMORY_AUTO_EXTRACT=true +LONG_TERM_MEMORY_INJECT_CONTEXT=true +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Não confundir LTM com replay de toda conversa. +- Memória irrelevante ou de baixa confiança não deveria ser injetada. +- Em múltiplas réplicas, prefira storage durável compartilhado em vez de memória local. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/memory/long_term_memory.py` +- `libs/agent_framework/src/agent_framework/memory/long_term_store.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Allows useful information to persist across different sessions without depending on the full transcript of a previous conversation. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +Session A + ↓ +extract relevant memory + ↓ +Long Term Memory Store + ↓ +... days later ... + ↓ +Session B + ↓ +retrieve relevant context + ↓ +agent +``` + +### 4. How it works internally + +Long-term memory is different from message history and checkpoints. It persists useful facts/preferences and retrieves them as context for a future session. The framework supports `memory`, `sqlite`, `autonomous`, and `oracle` providers. + +Important settings include `ENABLE_LONG_TERM_MEMORY`, `LONG_TERM_MEMORY_PROVIDER`, `LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS`, `LONG_TERM_MEMORY_MIN_CONFIDENCE`, `LONG_TERM_MEMORY_AUTO_EXTRACT`, and `LONG_TERM_MEMORY_INJECT_CONTEXT`. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```env +ENABLE_LONG_TERM_MEMORY=true +LONG_TERM_MEMORY_PROVIDER=oracle +LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS=20 +LONG_TERM_MEMORY_MIN_CONFIDENCE=0.70 +LONG_TERM_MEMORY_AUTO_EXTRACT=true +LONG_TERM_MEMORY_INJECT_CONTEXT=true +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Do not confuse LTM with replaying the entire transcript. +- Irrelevant or low-confidence memories should not be injected. +- For multiple replicas, prefer shared durable storage over local memory. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/memory/long_term_memory.py` +- `libs/agent_framework/src/agent_framework/memory/long_term_store.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/06_offline_workflow_regression.md b/docs/features/06_offline_workflow_regression.md new file mode 100644 index 0000000..5569f63 --- /dev/null +++ b/docs/features/06_offline_workflow_regression.md @@ -0,0 +1,163 @@ +# Regressão Offline de Workflow / Offline Workflow Regression + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `workflows/runtime.py + Tuning-Performance/Offline_Workflow_Regression` + +--- + +## Português (PT-BR) + +### 1. O que é + +Permite testar a lógica de workflows sem exigir toda a infraestrutura de produção. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Teste + ↓ +backend determinístico explicitamente habilitado + ↓ +run → PAUSED + ↓ +resume → COMPLETED + ↓ +asserts de estado/side effects +``` + +### 4. Como funciona internamente + +O `WorkflowRuntime` possui um caminho determinístico/offline **explicitamente opt-in para testes**. Ele permite validar DSL, condições, pause/resume e proteção contra reexecução sem exigir LangGraph, banco, OCI ou APIs externas. + +O comportamento de produção continua usando LangGraph. O modo offline não deve virar fallback silencioso quando LangGraph falha ou está ausente em produção. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```text +run(workflow) + action_a = 1 execução + status = PAUSED + +resume(workflow) + action_a continua com 1 execução + action_b = 1 execução + status = COMPLETED +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Usar o backend offline em produção mascara problemas reais. +- Mockar tanto que o teste deixa de validar a DSL real. +- Não verificar side effects anteriores ao pause pode esconder duplicações. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `libs/agent_framework/src/agent_framework/Tuning-Performance/Offline_Workflow_Regression` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Allows workflow logic to be regression-tested without requiring the full production infrastructure. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +Test + ↓ +explicit deterministic test backend + ↓ +run → PAUSED + ↓ +resume → COMPLETED + ↓ +state/side-effect assertions +``` + +### 4. How it works internally + +`WorkflowRuntime` includes an **explicitly opt-in deterministic/offline test backend**. It can validate DSL rules, conditions, pause/resume behavior, and duplicate-execution protection without requiring LangGraph, a database, OCI, or external APIs. + +Production behavior still uses LangGraph. Offline mode must never become a silent fallback when LangGraph fails or is unavailable in production. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```text +run(workflow) + action_a = executed once + status = PAUSED + +resume(workflow) + action_a remains executed once + action_b = executed once + status = COMPLETED +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Using the offline backend in production hides real issues. +- Over-mocking can stop the test from validating real DSL behavior. +- Failing to assert pre-pause side effects may hide duplicate execution. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `libs/agent_framework/src/agent_framework/Tuning-Performance/Offline_Workflow_Regression` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/07_pause_resume_workflow.md b/docs/features/07_pause_resume_workflow.md new file mode 100644 index 0000000..b600937 --- /dev/null +++ b/docs/features/07_pause_resume_workflow.md @@ -0,0 +1,165 @@ +# Pause / Resume de Workflow / Pause / Resume Workflow + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `workflows/runtime.py + workflows/graph.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Permite interromper um workflow em um ponto seguro, persistir o estado e continuar depois com a resposta do usuário ou outro evento. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Workflow + ↓ +ações prévias + ↓ +PAUSE + ↓ +checkpoint/estado + ↓ +nova mensagem + ↓ +RESUME + ↓ +ações seguintes +``` + +### 4. Como funciona internamente + +`WorkflowRuntime` expõe `arun(...)` e `aresume(...)`. O nó de pause é separado da action anterior para evitar reexecutar side effects quando o workflow retoma. O mesmo `execution_id/thread_id` identifica a execução pausada e retomada. + +O runtime suporta condições declarativas como `all`, `any`, `not`, `eq`, `neq` e `exists`, permitindo definir quando pausar ou continuar sem colocar lógica conversacional no prompt. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```text +status = await runtime.arun(...) +# status == PAUSED + +status = await runtime.aresume(execution_id, input={"confirmed": true}) +# status == COMPLETED +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Perder o `execution_id` impede retomar a execução correta. +- Reexecutar o workflow do zero após confirmação pode repetir side effects. +- Pause sem storage/checkpoint compartilhado é frágil em múltiplas réplicas. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `libs/agent_framework/src/agent_framework/workflows/graph.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Allows a workflow to stop at a safe point, persist state, and continue later using user input or another event. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +Workflow + ↓ +pre-pause actions + ↓ +PAUSE + ↓ +checkpoint/state + ↓ +new message + ↓ +RESUME + ↓ +remaining actions +``` + +### 4. How it works internally + +`WorkflowRuntime` exposes `arun(...)` and `aresume(...)`. The pause node is separated from the preceding action so previous side effects are not executed again on resume. The same `execution_id/thread_id` identifies the paused and resumed execution. + +The runtime supports declarative conditions such as `all`, `any`, `not`, `eq`, `neq`, and `exists`, so pause/continue decisions do not need to live in the prompt. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```text +status = await runtime.arun(...) +# status == PAUSED + +status = await runtime.aresume(execution_id, input={"confirmed": true}) +# status == COMPLETED +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Losing the `execution_id` prevents resuming the right execution. +- Restarting the workflow from scratch after confirmation may duplicate side effects. +- Pause without shared checkpoint/state storage is fragile across multiple replicas. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `libs/agent_framework/src/agent_framework/workflows/graph.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/08_route_stickiness.md b/docs/features/08_route_stickiness.md new file mode 100644 index 0000000..264a17e --- /dev/null +++ b/docs/features/08_route_stickiness.md @@ -0,0 +1,151 @@ +# Aderência de Rota / Route Stickiness + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `routing/enterprise_router.py + runtime/agent_runtime.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Evita que pequenas mensagens de continuação façam a conversa trocar de agente sem necessidade. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +mensagem atual + + histórico curto + + rota anterior + ↓ +continuidade semântica + ↓ +manter rota ou handoff +``` + +### 4. Como funciona internamente + +Route Stickiness avalia se a nova mensagem continua semanticamente ligada ao assunto/agente atual. Isso reduz ping-pong de agentes em mensagens como “e esse valor?”, “sim”, “o segundo” ou “e no mês passado?”. + +Configurações existentes incluem `ENABLE_ROUTE_STICKINESS`, `ROUTE_STICKINESS_LLM_PROFILE`, `ROUTE_STICKINESS_CONFIDENCE_THRESHOLD`, `ROUTE_STICKINESS_HISTORY_TURNS` e `ROUTE_STICKINESS_MAX_TOKENS`. A decisão pode permitir handoff quando há evidência suficiente de mudança de assunto. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```env +ENABLE_ROUTE_STICKINESS=true +ROUTE_STICKINESS_CONFIDENCE_THRESHOLD=0.90 +ROUTE_STICKINESS_HISTORY_TURNS=2 +ROUTE_STICKINESS_MAX_TOKENS=80 +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Threshold muito baixo pode prender o cliente no agente errado. +- Threshold alto demais perde continuidade em mensagens curtas. +- Stickiness não deve bloquear handoff explícito quando a intenção realmente mudou. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/routing/enterprise_router.py` +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Prevents short follow-up messages from unnecessarily switching the conversation to another agent. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +current message + + short history + + previous route + ↓ +semantic continuity + ↓ +keep route or handoff +``` + +### 4. How it works internally + +Route Stickiness evaluates whether a new message is semantically continuous with the current subject/agent. It reduces agent ping-pong for messages such as “what about that amount?”, “yes”, “the second one”, or “and last month?”. + +Existing settings include `ENABLE_ROUTE_STICKINESS`, `ROUTE_STICKINESS_LLM_PROFILE`, `ROUTE_STICKINESS_CONFIDENCE_THRESHOLD`, `ROUTE_STICKINESS_HISTORY_TURNS`, and `ROUTE_STICKINESS_MAX_TOKENS`. The decision may still allow handoff when there is enough evidence of a topic change. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```env +ENABLE_ROUTE_STICKINESS=true +ROUTE_STICKINESS_CONFIDENCE_THRESHOLD=0.90 +ROUTE_STICKINESS_HISTORY_TURNS=2 +ROUTE_STICKINESS_MAX_TOKENS=80 +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- A threshold that is too low may trap the user on the wrong agent. +- A threshold that is too high may lose continuity on short follow-ups. +- Stickiness should not block explicit handoff when the user clearly changes intent. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/routing/enterprise_router.py` +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/09_voice_interruption_replay.md b/docs/features/09_voice_interruption_replay.md new file mode 100644 index 0000000..85bd363 --- /dev/null +++ b/docs/features/09_voice_interruption_replay.md @@ -0,0 +1,153 @@ +# Replay em Interrupções de Voz / Voice Interruption Replay + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `channels/interruption.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Decide se um áudio recebido durante a fala do agente representa uma nova intenção, um ruído/backchannel ou algo que deve apenas repetir/continuar a última fala. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +áudio durante fala + ↓ +InterruptionPolicy + ├─ process → nova mensagem + ├─ classify → classificador leve + └─ replay → última fala +``` + +### 4. Como funciona internamente + +A política fica no framework, não no domínio. Ela diferencia sessão terminal, `idle_nudge`, fala não interrompível e fala potencialmente interrompível. Quando necessário, pode usar um classificador leve baseado no `LLMProvider`; quando a classificação falha, a política é conservadora e pode optar por replay. + +O objetivo é evitar que “aham”, ruído, eco ou fragmentos residuais sejam tratados como uma nova intenção completa. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```text +Agente: "Sua fatura possui..." +Cliente: "aham" +→ replay/continua + +Agente: "Sua fatura possui..." +Cliente: "espera, quero falar de outra coisa" +→ processa nova intenção +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Classificar todo ruído com LLM aumenta latência e custo. +- Permitir interrupção em fala transacional não interrompível pode corromper UX/estado. +- Replay deve usar uma fala real anterior, não um envelope técnico. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/channels/interruption.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Decides whether audio received while the agent is speaking represents a new intent, a backchannel/noise event, or something that should simply replay/continue the previous speech. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +audio during speech + ↓ +InterruptionPolicy + ├─ process → new message + ├─ classify → lightweight classifier + └─ replay → previous speech +``` + +### 4. How it works internally + +The policy lives in the framework rather than domain code. It distinguishes terminal sessions, `idle_nudge`, non-interruptible speech, and potentially interruptible speech. When needed, it may use a lightweight classifier backed by `LLMProvider`; on classification failure, it can fail safely to replay. + +The goal is to prevent “uh-huh”, noise, echo, or residual audio fragments from being interpreted as a full new intent. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```text +Agent: "Your invoice contains..." +User: "uh-huh" +→ replay/continue + +Agent: "Your invoice contains..." +User: "wait, I want to ask something else" +→ process new intent +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Sending every noise fragment to an LLM increases latency and cost. +- Allowing interruption during non-interruptible transactional speech may corrupt UX/state. +- Replay should use a real previous utterance, not a technical envelope. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/channels/interruption.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/10_workflow_error_recovery.md b/docs/features/10_workflow_error_recovery.md new file mode 100644 index 0000000..e5ef8d6 --- /dev/null +++ b/docs/features/10_workflow_error_recovery.md @@ -0,0 +1,167 @@ +# Recuperação de Erro em Workflow / Workflow Error Recovery + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `workflows/runtime.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Preserva o estado parcial de uma execução quando um passo posterior falha, permitindo entender o que já aconteceu e evitar repetir side effects. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +passo A ✅ +passo B ✅ +passo C ❌ + ↓ +FAILED + snapshot parcial + ↓ +recovery decide o que pode continuar/repetir +``` + +### 4. Como funciona internamente + +O runtime preserva o snapshot parcial do LangGraph quando uma etapa posterior falha e produz `error_details` genérico. Quando a exceção externa possui informações estruturadas, podem ser preservados status HTTP, body, número de tentativas, code e metadata. + +A feature não significa “tentar tudo de novo”. Recuperação segura depende de conhecer o estado já executado, a idempotência e a natureza do erro. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```json +{ + "status": "FAILED", + "error_details": { + "status": 503, + "attempts": 3, + "code": "UPSTREAM_UNAVAILABLE" + }, + "state": { + "protocol_created": true, + "operation_completed": true, + "sms_sent": false + } +} +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Retry indiscriminado pode repetir transações. +- Se a exceção externa perde metadata, a recuperação fica menos precisa. +- Combine sempre com Durable Idempotency em side effects críticos. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Preserves partial execution state when a later step fails, making it possible to know what already happened and avoid repeating side effects. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +step A ✅ +step B ✅ +step C ❌ + ↓ +FAILED + partial snapshot + ↓ +recovery decides what may continue/retry +``` + +### 4. How it works internally + +The runtime preserves the partial LangGraph snapshot when a later step fails and produces generic `error_details`. When an external exception provides structured information, HTTP status, body, attempt count, code, and metadata may be preserved. + +This feature does not mean “retry everything”. Safe recovery depends on knowing what already executed, idempotency guarantees, and the nature of the failure. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```json +{ + "status": "FAILED", + "error_details": { + "status": 503, + "attempts": 3, + "code": "UPSTREAM_UNAVAILABLE" + }, + "state": { + "protocol_created": true, + "operation_completed": true, + "sms_sent": false + } +} +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Blind retries may repeat transactions. +- If external exceptions discard metadata, recovery becomes less precise. +- Always combine with Durable Idempotency for critical side effects. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/workflows/runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/11_clarification.md b/docs/features/11_clarification.md new file mode 100644 index 0000000..6ef6a15 --- /dev/null +++ b/docs/features/11_clarification.md @@ -0,0 +1,169 @@ +# Clarificação / Clarification + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `runtime/agent_runtime.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Quando faltam dados ou uma tool encontra múltiplas opções, o framework pergunta ao usuário em vez de adivinhar. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +pedido ambíguo + ↓ +NEEDS_CLARIFICATION + ↓ +pergunta + opções + ↓ +usuário responde + ↓ +framework resolve + ↓ +retoma mesma tool/workflow +``` + +### 4. Como funciona internamente + +O runtime suporta clarificação tanto de parâmetros faltantes quanto de resultados de tools. Para tool-result clarification, um resultado com `status: NEEDS_CLARIFICATION` pode trazer opções; o runtime persiste `pending_tool_clarification`, entra em `TOOL_RESULT_CLARIFICATION` e consegue resolver respostas por ordinal ou nome. + +Depois da escolha, o framework reutiliza a mesma tool e injeta os argumentos resolvidos, evitando que o roteador trate a resposta curta como uma intenção nova. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```json +{ + "status": "NEEDS_CLARIFICATION", + "question": "Qual serviço?", + "options": [ + {"id": "tim_music", "label": "TIM Music"}, + {"id": "hbo_max", "label": "HBO Max"} + ] +} +``` + +Usuário: `o segundo` → `hbo_max`. + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Não descarte `pending_tool_clarification` entre turns. +- Uma resposta curta deve ser resolvida contra as opções antes do roteamento normal. +- Opções sem identificador/label consistente pioram a resolução. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +When required information is missing or a tool finds multiple options, the framework asks the user instead of guessing. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +ambiguous request + ↓ +NEEDS_CLARIFICATION + ↓ +question + options + ↓ +user answers + ↓ +framework resolves + ↓ +resume same tool/workflow +``` + +### 4. How it works internally + +The runtime supports clarification for both missing parameters and ambiguous tool results. For tool-result clarification, a result with `status: NEEDS_CLARIFICATION` may include options; the runtime persists `pending_tool_clarification`, moves to `TOOL_RESULT_CLARIFICATION`, and can resolve responses by ordinal or name. + +After selection, the framework reuses the same tool and injects resolved arguments, preventing the router from treating a short reply as a brand-new intent. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```json +{ + "status": "NEEDS_CLARIFICATION", + "question": "Which service?", + "options": [ + {"id": "tim_music", "label": "TIM Music"}, + {"id": "hbo_max", "label": "HBO Max"} + ] +} +``` + +User: `the second one` → `hbo_max`. + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Do not discard `pending_tool_clarification` between turns. +- A short answer should be resolved against pending options before normal routing. +- Options without stable identifiers/labels reduce resolution quality. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/12_durable_idempotency.md b/docs/features/12_durable_idempotency.md new file mode 100644 index 0000000..98969e3 --- /dev/null +++ b/docs/features/12_durable_idempotency.md @@ -0,0 +1,163 @@ +# Idempotência Durável / Durable Idempotency + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `idempotency.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Impede que a mesma operação crítica seja executada duas vezes, inclusive quando outra réplica/pod recebe a repetição. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +requisição + ↓ +idempotency key + ↓ +store durável + ├─ existe → retorna resultado anterior + └─ não existe → executa → persiste resultado +``` + +### 4. Como funciona internamente + +`create_idempotency_store(settings, ...)` escolhe o backend conforme configuração/plataforma. O framework possui `IdempotencyStore` e `InMemoryIdempotencyStore`, mas produção distribuída deve preferir storage compartilhado. As configurações incluem `IDEMPOTENCY_PROVIDER`, `IDEMPOTENCY_REQUIRE_DURABLE` e `IDEMPOTENCY_TTL_SECONDS`. + +Idempotência é diferente de retry: retry repete a tentativa; idempotência garante que a repetição não produza um novo side effect. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```text +Pod A recebe cancelamento +→ key=cliente:servico:operacao +→ executa +→ grava resultado + +Pod A cai + +Pod B recebe retry +→ mesma key +→ encontra resultado +→ NÃO cancela de novo +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Usar store em memória com múltiplos pods não é idempotência durável. +- Chave ampla demais pode bloquear operações legítimas; estreita demais permite duplicidade. +- TTL deve ser compatível com a janela real de retry/replay. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/idempotency.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Prevents the same critical operation from executing twice, including when a retry lands on another replica/pod. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +request + ↓ +idempotency key + ↓ +durable store + ├─ exists → return previous result + └─ missing → execute → persist result +``` + +### 4. How it works internally + +`create_idempotency_store(settings, ...)` chooses a backend according to configuration/platform. The framework provides `IdempotencyStore` and `InMemoryIdempotencyStore`, but distributed production should prefer shared storage. Settings include `IDEMPOTENCY_PROVIDER`, `IDEMPOTENCY_REQUIRE_DURABLE`, and `IDEMPOTENCY_TTL_SECONDS`. + +Idempotency is different from retry: retry repeats an attempt; idempotency guarantees that repetition does not create another side effect. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```text +Pod A receives cancellation +→ key=customer:service:operation +→ executes +→ stores result + +Pod A crashes + +Pod B receives retry +→ same key +→ finds stored result +→ DOES NOT cancel again +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- An in-memory store across multiple pods is not durable idempotency. +- A key that is too broad may block legitimate operations; too narrow may allow duplicates. +- TTL should match the real retry/replay window. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/idempotency.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/13_dynamic_transaction_states.md b/docs/features/13_dynamic_transaction_states.md new file mode 100644 index 0000000..6cd06ce --- /dev/null +++ b/docs/features/13_dynamic_transaction_states.md @@ -0,0 +1,157 @@ +# Estados Transacionais Dinâmicos / Dynamic Transaction States + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `runtime/agent_runtime.py + mcp/tool_policy.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Permite criar estados de confirmação baseados no agente/domínio atual sem hardcode de todos os domínios dentro do framework. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +tool transactional + ↓ +agente/domínio atual + ↓ +WAITING__CONFIRMATION + ↓ +confirmação/rejeição + ↓ +estado seguinte +``` + +### 4. Como funciona internamente + +Em vez de manter estados fixos como `WAITING_BILLING_CONFIRMATION`, `WAITING_PRODUCT_CONFIRMATION` etc. para cada domínio conhecido, o runtime deriva o prefixo do agente atual e gera o estado dinamicamente. A função interna de estado transacional mantém o framework genérico. + +A classificação `operation_type` aceita `read_only`, `transactional`, `conversational` e `internal`; somente `transactional` entra no caminho de confirmação transacional. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```text +VasAgent + cancelar_vas +→ WAITING_VAS_CONFIRMATION + +AddressAgent + alterar_endereco +→ WAITING_ADDRESS_CONFIRMATION +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Hardcode de estados no domínio reduz reutilização. +- Classificar uma tool como `conversational` não deve ativar confirmação transacional. +- Mudanças no identificador do agente podem mudar o prefixo; mantenha IDs estáveis. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Allows confirmation states to be derived from the current agent/domain instead of hardcoding every business domain into the framework. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +transactional tool + ↓ +current agent/domain + ↓ +WAITING__CONFIRMATION + ↓ +confirm/reject + ↓ +next state +``` + +### 4. How it works internally + +Instead of maintaining fixed states such as `WAITING_BILLING_CONFIRMATION`, `WAITING_PRODUCT_CONFIRMATION`, and so on for every known domain, the runtime derives a prefix from the current agent and builds the confirmation state dynamically. This keeps the framework generic. + +`operation_type` accepts `read_only`, `transactional`, `conversational`, and `internal`; only `transactional` enters the transactional confirmation path. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```text +VasAgent + cancel_vas +→ WAITING_VAS_CONFIRMATION + +AddressAgent + change_address +→ WAITING_ADDRESS_CONFIRMATION +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Hardcoding states in domain code reduces reuse. +- Classifying a tool as `conversational` should not trigger transactional confirmation. +- Changing agent identifiers may change state prefixes; keep IDs stable. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py` +- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/14_post_finalization_replay.md b/docs/features/14_post_finalization_replay.md new file mode 100644 index 0000000..8175336 --- /dev/null +++ b/docs/features/14_post_finalization_replay.md @@ -0,0 +1,159 @@ +# Replay Após Finalização / Post Finalization Replay + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `channels/interruption.py + config/settings.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Evita que áudio residual ou mensagens tardias reabram uma sessão já finalizada. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +sessão terminal + ↓ +entrada residual + ↓ +policy detecta finalização + ↓ +replay última fala/fallback + ↓ +NÃO reabre LangGraph +``` + +### 4. Como funciona internamente + +A política de interrupção verifica metadata de sessão terminal antes de tratar uma entrada como nova intenção. Quando há texto terminal disponível, usa `last_assistant_text`/`terminal_replay_text`; caso contrário, pode usar a mensagem configurada em `POST_FINALIZE_REPLAY_MESSAGE`. + +O objetivo é proteger o fechamento lógico da sessão, especialmente em canais de voz onde pacotes de áudio podem chegar depois do evento de finalização. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```text +Agente: "Atendimento concluído." +→ sessão finalizada + +chega fragmento: "ã..." +→ replay "Atendimento concluído." +→ nenhum routing / tool / LLM novo +``` + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Se o estado terminal não for persistido, outra réplica pode reabrir a jornada. +- Não use replay técnico/JSON como fala do cliente. +- Essa feature não substitui política de nova sessão intencional. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/channels/interruption.py` +- `libs/agent_framework/src/agent_framework/config/settings.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Prevents residual audio or late messages from reopening a session that has already been finalized. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +terminal session + ↓ +residual input + ↓ +policy detects finalization + ↓ +replay last utterance/fallback + ↓ +DO NOT reopen LangGraph +``` + +### 4. How it works internally + +The interruption policy checks terminal-session metadata before treating an input as a new intent. When terminal speech is available, it uses `last_assistant_text`/`terminal_replay_text`; otherwise it may use `POST_FINALIZE_REPLAY_MESSAGE`. + +The purpose is to protect the logical end of a session, especially on voice channels where audio packets may arrive after the finalization event. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```text +Agent: "The interaction is complete." +→ session finalized + +late fragment arrives: "uh..." +→ replay "The interaction is complete." +→ no new routing / tool / LLM call +``` + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- If terminal state is not persisted, another replica may reopen the journey. +- Do not replay technical/JSON envelopes as user-facing speech. +- This feature does not replace an intentional new-session policy. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/channels/interruption.py` +- `libs/agent_framework/src/agent_framework/config/settings.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/15_retrieval_tool_guardrails.md b/docs/features/15_retrieval_tool_guardrails.md new file mode 100644 index 0000000..0a565a0 --- /dev/null +++ b/docs/features/15_retrieval_tool_guardrails.md @@ -0,0 +1,171 @@ +# Guardrails de Retrieval e Tools / Retrieval / Tool Guardrails + +> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN. + +**Implementação principal / Main implementation:** `guardrails/pipeline.py + guardrails/rails.py` + +--- + +## Português (PT-BR) + +### 1. O que é + +Aplica proteção não apenas na mensagem do usuário e na resposta final, mas também no conhecimento recuperado por RAG e nos argumentos/resultados de ferramentas. + +### 2. Problema que resolve + +Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio. + +### 3. Fluxo simplificado + +```text +Usuário + ↓ +Input Guardrails + ↓ +RAG → Retrieval Guardrails + ↓ +LLM/Tool call → Tool Guardrails + ↓ +API + ↓ +Output Guardrails +``` + +### 4. Como funciona internamente + +O framework possui stages distintos de guardrails. Para retrieval, rails como `RAGSEC` e `RET_REL` podem validar segurança e relevância do conteúdo recuperado. Para tools, `TOOL_VAL` valida o uso/argumentos antes ou ao redor da execução. + +As configurações globais incluem `ENABLE_INPUT_GUARDRAILS`, `ENABLE_OUTPUT_GUARDRAILS`, `ENABLE_PARALLEL_GUARDRAILS`, `GUARDRAILS_FAIL_FAST` e `GUARDRAILS_CONFIG_PATH`. O YAML é a fonte de verdade dos rails ativados por agente. + +### 5. Como ativar/configurar + +A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow. + +### 6. Exemplo + +```yaml +retrieval: + rails: + - RAGSEC + - RET_REL + +tool: + rails: + - TOOL_VAL +``` + +Exemplo: a pergunta é sobre cancelamento de um serviço, mas o RAG retorna documentação de modem. `RET_REL` pode rejeitar o contexto antes que ele seja usado na resposta. + +### 7. Telemetria e observabilidade + +Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio. + +### 8. Como testar + +1. Crie um teste unitário do comportamento principal. +2. Crie um teste de integração do runtime quando houver estado entre turns. +3. Verifique o caso feliz e pelo menos um caso de falha/negação. +4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações. +5. Em produção, valide também telemetria e correlação de IDs. + +### 9. Erros comuns + +- Ter a implementação do rail não significa que ele está ativo: confira `guardrails.yaml`. +- Fail-fast deve ser escolhido conscientemente para cada stage. +- Tool guardrail não substitui validação de negócio dentro da própria API/action. + +### 10. Relação com outras features + +Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**. + +### 11. Referências no repositório + +- `libs/agent_framework/src/agent_framework/guardrails/pipeline.py` +- `libs/agent_framework/src/agent_framework/guardrails/rails.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` + +--- + +## English (EN) + +### 1. What it is + +Applies safety and validation not only to user input and final output, but also to RAG-retrieved knowledge and tool arguments/results. + +### 2. Problem it solves + +Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code. + +### 3. Simplified flow + +```text +User + ↓ +Input Guardrails + ↓ +RAG → Retrieval Guardrails + ↓ +LLM/Tool call → Tool Guardrails + ↓ +API + ↓ +Output Guardrails +``` + +### 4. How it works internally + +The framework has distinct guardrail stages. For retrieval, rails such as `RAGSEC` and `RET_REL` can validate retrieved-content safety and relevance. For tools, `TOOL_VAL` validates usage/arguments before or around execution. + +Global settings include `ENABLE_INPUT_GUARDRAILS`, `ENABLE_OUTPUT_GUARDRAILS`, `ENABLE_PARALLEL_GUARDRAILS`, `GUARDRAILS_FAIL_FAST`, and `GUARDRAILS_CONFIG_PATH`. The agent YAML is the source of truth for enabled rails. + +### 5. How to enable/configure + +Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow. + +### 6. Example + +```yaml +retrieval: + rails: + - RAGSEC + - RET_REL + +tool: + rails: + - TOOL_VAL +``` + +Example: the question concerns canceling a service, but RAG retrieves modem documentation. `RET_REL` can reject that context before it is used in the answer. + +### 7. Telemetry and observability + +When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain. + +### 8. How to test + +1. Add a unit test for the core behavior. +2. Add a runtime integration test when state spans multiple turns. +3. Test the happy path and at least one failure/rejection path. +4. Confirm retries/replays do not duplicate side effects for transactional features. +5. In production, also validate telemetry and ID correlation. + +### 9. Common mistakes + +- Having a rail implementation does not mean it is enabled: check `guardrails.yaml`. +- Fail-fast behavior should be chosen intentionally for each stage. +- Tool guardrails do not replace business validation inside the API/action itself. + +### 10. Relationship with other features + +Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**. + +### 11. Repository references + +- `libs/agent_framework/src/agent_framework/guardrails/pipeline.py` +- `libs/agent_framework/src/agent_framework/guardrails/rails.py` +- `Tuning-Performance/` +- `Documentacao/` +- `libs/agent_framework/docs/` diff --git a/docs/features/README.md b/docs/features/README.md index d09ad96..f925f85 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -1,10 +1,62 @@ -# Feature Guides / Guias de Features +# Feature Guide — agent_framework_oci -Escolha o idioma / Choose a language: +Guia consolidado e bilíngue das principais capabilities horizontais do framework. Cada página contém **Português (PT-BR)** e **English (EN)** no mesmo arquivo. -- [Português (PT-BR)](pt-BR/README.md) -- [English (EN)](en/README.md) +Consolidated bilingual guide for the framework's main horizontal capabilities. Each page contains **Portuguese (PT-BR)** and **English (EN)** in the same file. -Os 15 arquivos bilíngues originais continuam neste diretório para compatibilidade, mas as árvores `pt-BR/` e `en/` são as versões recomendadas para leitura e distribuição. +| # | Feature | +|---:|---| +| 01 | [Autenticação / Authentication](01_authentication.md) | +| 02 | [Workflow Transacional Determinístico / Deterministic Transactional Workflow](02_deterministic_transactional_workflow.md) | +| 03 | [Composição por LLM Solicitada pelo Domínio / Domain Requested LLM Composition](03_domain_requested_llm_composition.md) | +| 04 | [RAG Solicitado pelo Domínio / Domain Requested RAG](04_domain_requested_rag.md) | +| 05 | [Memória de Longo Prazo / Long Term Memory](05_long_term_memory.md) | +| 06 | [Regressão Offline de Workflow / Offline Workflow Regression](06_offline_workflow_regression.md) | +| 07 | [Pause / Resume de Workflow / Pause / Resume Workflow](07_pause_resume_workflow.md) | +| 08 | [Aderência de Rota / Route Stickiness](08_route_stickiness.md) | +| 09 | [Replay em Interrupções de Voz / Voice Interruption Replay](09_voice_interruption_replay.md) | +| 10 | [Recuperação de Erro em Workflow / Workflow Error Recovery](10_workflow_error_recovery.md) | +| 11 | [Clarificação / Clarification](11_clarification.md) | +| 12 | [Idempotência Durável / Durable Idempotency](12_durable_idempotency.md) | +| 13 | [Estados Transacionais Dinâmicos / Dynamic Transaction States](13_dynamic_transaction_states.md) | +| 14 | [Replay Após Finalização / Post Finalization Replay](14_post_finalization_replay.md) | +| 15 | [Guardrails de Retrieval e Tools / Retrieval / Tool Guardrails](15_retrieval_tool_guardrails.md) | -The original 15 bilingual files remain in this directory for backward compatibility, but the `pt-BR/` and `en/` trees are the recommended versions for reading and distribution. +## Mapa conceitual / Conceptual map + +```text +LLM +│ +├── Conversation +│ ├── Clarification +│ ├── Route Stickiness +│ └── Long Term Memory +│ +├── Knowledge +│ ├── Domain Requested RAG +│ └── Retrieval Guardrails +│ +├── Transactions +│ ├── Deterministic Transactional Workflow +│ ├── Pause / Resume +│ ├── Dynamic Transaction States +│ ├── Durable Idempotency +│ └── Workflow Error Recovery +│ +├── Response +│ └── Domain Requested LLM Composition +│ +├── Voice +│ ├── Voice Interruption Replay +│ └── Post Finalization Replay +│ +└── Platform + ├── Authentication + └── Offline Workflow Regression +``` + +## Princípio de arquitetura / Architecture principle + +**PT-BR:** o LLM entende e redige; o framework controla estado, segurança, memória, roteamento e transações; o domínio contém regras específicas de negócio. + +**EN:** the LLM understands and writes; the framework controls state, security, memory, routing, and transactions; the domain contains business-specific rules. diff --git a/libs/agent_framework/src/agent_framework.egg-info/SOURCES.txt b/libs/agent_framework/src/agent_framework.egg-info/SOURCES.txt index c6d6ac6..723d0a0 100644 --- a/libs/agent_framework/src/agent_framework.egg-info/SOURCES.txt +++ b/libs/agent_framework/src/agent_framework.egg-info/SOURCES.txt @@ -1,6 +1,7 @@ pyproject.toml src/agent_framework/__init__.py src/agent_framework/gateway_policy_context.py +src/agent_framework/idempotency.py src/agent_framework/observer.py src/agent_framework/runtime_mcp_gateway_adapter.py src/agent_framework.egg-info/PKG-INFO @@ -28,6 +29,8 @@ src/agent_framework/channels/__init__.py src/agent_framework/channels/adapters.py src/agent_framework/channels/base.py src/agent_framework/channels/gateway.py +src/agent_framework/channels/interruption.py +src/agent_framework/channels/transcription.py src/agent_framework/checkpoints/__init__.py src/agent_framework/checkpoints/checkpoint_repository.py src/agent_framework/checkpoints/langgraph_saver.py @@ -73,9 +76,11 @@ src/agent_framework/guardrails/calibrated/pipeline.py src/agent_framework/guardrails/calibrated/prompts/__init__.py src/agent_framework/guardrails/calibrated/prompts/_context.py src/agent_framework/guardrails/calibrated/prompts/ausencia_oferta_proativa.py +src/agent_framework/guardrails/calibrated/prompts/coerencia.py src/agent_framework/guardrails/calibrated/prompts/dlex_in.py src/agent_framework/guardrails/calibrated/prompts/dlex_out.py src/agent_framework/guardrails/calibrated/prompts/fallback.py +src/agent_framework/guardrails/calibrated/prompts/fraseologia.py src/agent_framework/guardrails/calibrated/prompts/out_of_scope.py src/agent_framework/guardrails/calibrated/prompts/pinj.py src/agent_framework/guardrails/calibrated/prompts/ragsec.py @@ -174,6 +179,8 @@ src/agent_framework/persistence/__init__.py src/agent_framework/persistence/mongodb_store.py src/agent_framework/persistence/oracle_store.py src/agent_framework/persistence/sqlite_store.py +src/agent_framework/presentation/__init__.py +src/agent_framework/presentation/renderers.py src/agent_framework/rag/__init__.py src/agent_framework/rag/embedding_provider.py src/agent_framework/rag/graph_store.py @@ -200,6 +207,7 @@ src/agent_framework/supervisor/__init__.py src/agent_framework/supervisor/router_supervisor.py src/agent_framework/supervisor/supervisor.py src/agent_framework/workflows/__init__.py +src/agent_framework/workflows/graph.py src/agent_framework/workflows/models.py src/agent_framework/workflows/registry.py src/agent_framework/workflows/repository.py diff --git a/libs/agent_framework/src/agent_framework/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/__pycache__/__init__.cpython-313.pyc index 35a5280..adb49c3 100644 Binary files a/libs/agent_framework/src/agent_framework/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/__pycache__/idempotency.cpython-313.pyc b/libs/agent_framework/src/agent_framework/__pycache__/idempotency.cpython-313.pyc new file mode 100644 index 0000000..96dd9a2 Binary files /dev/null and b/libs/agent_framework/src/agent_framework/__pycache__/idempotency.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/__pycache__/observer.cpython-313.pyc b/libs/agent_framework/src/agent_framework/__pycache__/observer.cpython-313.pyc index 7300893..cfb87c2 100644 Binary files a/libs/agent_framework/src/agent_framework/__pycache__/observer.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/__pycache__/observer.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/__pycache__/__init__.cpython-313.pyc index ffb0cb8..79a9c4c 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/__pycache__/composite_publisher.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/__pycache__/composite_publisher.cpython-313.pyc index 70b4275..b421026 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/__pycache__/composite_publisher.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/__pycache__/composite_publisher.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/__pycache__/event_builder.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/__pycache__/event_builder.cpython-313.pyc index a97974e..452a180 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/__pycache__/event_builder.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/__pycache__/event_builder.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/__pycache__/factory.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/__pycache__/factory.cpython-313.pyc index 1586e53..17536e6 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/__pycache__/factory.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/__pycache__/factory.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/__pycache__/publisher.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/__pycache__/publisher.cpython-313.pyc index b9d5d60..fa87ebb 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/__pycache__/publisher.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/__pycache__/publisher.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_payload_mapper.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_payload_mapper.cpython-313.pyc index 5086a19..0fffb66 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_payload_mapper.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_payload_mapper.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_sequence.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_sequence.cpython-313.pyc index 7b9a85a..e9ab31d 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_sequence.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/__pycache__/tim_sequence.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/__init__.cpython-313.pyc index 3eb59a0..3159299 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/kafka.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/kafka.cpython-313.pyc index 6cc8bb3..15e67e5 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/kafka.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/kafka.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/langfuse.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/langfuse.cpython-313.pyc index ce24c06..d351d93 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/langfuse.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/langfuse.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/oci_streaming.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/oci_streaming.cpython-313.pyc index d00300c..29655c5 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/oci_streaming.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/oci_streaming.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/pubsub.cpython-313.pyc b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/pubsub.cpython-313.pyc index 5c251f3..3d88873 100644 Binary files a/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/pubsub.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/analytics/providers/__pycache__/pubsub.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/billing/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/billing/__pycache__/__init__.cpython-313.pyc index 53bb2f9..385e821 100644 Binary files a/libs/agent_framework/src/agent_framework/billing/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/billing/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/billing/__pycache__/usage_repository.cpython-313.pyc b/libs/agent_framework/src/agent_framework/billing/__pycache__/usage_repository.cpython-313.pyc index 38aaf27..e33601f 100644 Binary files a/libs/agent_framework/src/agent_framework/billing/__pycache__/usage_repository.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/billing/__pycache__/usage_repository.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/cache/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/cache/__pycache__/__init__.cpython-313.pyc index dec5d15..f1202aa 100644 Binary files a/libs/agent_framework/src/agent_framework/cache/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/cache/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/cache/__pycache__/cache.cpython-313.pyc b/libs/agent_framework/src/agent_framework/cache/__pycache__/cache.cpython-313.pyc index 031db81..78b45b8 100644 Binary files a/libs/agent_framework/src/agent_framework/cache/__pycache__/cache.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/cache/__pycache__/cache.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/channels/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/channels/__pycache__/__init__.cpython-313.pyc index dfe01b6..eff88e2 100644 Binary files a/libs/agent_framework/src/agent_framework/channels/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/channels/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/channels/__pycache__/adapters.cpython-313.pyc b/libs/agent_framework/src/agent_framework/channels/__pycache__/adapters.cpython-313.pyc index 78a8552..299197d 100644 Binary files a/libs/agent_framework/src/agent_framework/channels/__pycache__/adapters.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/channels/__pycache__/adapters.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/channels/__pycache__/base.cpython-313.pyc b/libs/agent_framework/src/agent_framework/channels/__pycache__/base.cpython-313.pyc index 847f9ce..a10e14b 100644 Binary files a/libs/agent_framework/src/agent_framework/channels/__pycache__/base.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/channels/__pycache__/base.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/channels/__pycache__/gateway.cpython-313.pyc b/libs/agent_framework/src/agent_framework/channels/__pycache__/gateway.cpython-313.pyc index bdfb79a..f81ae9e 100644 Binary files a/libs/agent_framework/src/agent_framework/channels/__pycache__/gateway.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/channels/__pycache__/gateway.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/channels/__pycache__/interruption.cpython-313.pyc b/libs/agent_framework/src/agent_framework/channels/__pycache__/interruption.cpython-313.pyc new file mode 100644 index 0000000..fb06332 Binary files /dev/null and b/libs/agent_framework/src/agent_framework/channels/__pycache__/interruption.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/channels/__pycache__/transcription.cpython-313.pyc b/libs/agent_framework/src/agent_framework/channels/__pycache__/transcription.cpython-313.pyc new file mode 100644 index 0000000..e21bd77 Binary files /dev/null and b/libs/agent_framework/src/agent_framework/channels/__pycache__/transcription.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/__init__.cpython-313.pyc index ee2e131..aa50b8c 100644 Binary files a/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/checkpoint_repository.cpython-313.pyc b/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/checkpoint_repository.cpython-313.pyc index eb3a702..069919d 100644 Binary files a/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/checkpoint_repository.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/checkpoint_repository.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/langgraph_saver.cpython-313.pyc b/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/langgraph_saver.cpython-313.pyc index dbf7466..0c863dc 100644 Binary files a/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/langgraph_saver.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/checkpoints/__pycache__/langgraph_saver.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/config/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/config/__pycache__/__init__.cpython-313.pyc index 06f2a47..6d15035 100644 Binary files a/libs/agent_framework/src/agent_framework/config/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/config/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/config/__pycache__/agent_registry.cpython-313.pyc b/libs/agent_framework/src/agent_framework/config/__pycache__/agent_registry.cpython-313.pyc index ab95b57..30105a0 100644 Binary files a/libs/agent_framework/src/agent_framework/config/__pycache__/agent_registry.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/config/__pycache__/agent_registry.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/config/__pycache__/settings.cpython-313.pyc b/libs/agent_framework/src/agent_framework/config/__pycache__/settings.cpython-313.pyc index 6986b73..b5ac2ad 100644 Binary files a/libs/agent_framework/src/agent_framework/config/__pycache__/settings.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/config/__pycache__/settings.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/gateways/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/gateways/__pycache__/__init__.cpython-313.pyc index f0a3330..296f332 100644 Binary files a/libs/agent_framework/src/agent_framework/gateways/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/gateways/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/gateways/__pycache__/mcp_gateway_client.cpython-313.pyc b/libs/agent_framework/src/agent_framework/gateways/__pycache__/mcp_gateway_client.cpython-313.pyc index 7a436a5..1d1e2cc 100644 Binary files a/libs/agent_framework/src/agent_framework/gateways/__pycache__/mcp_gateway_client.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/gateways/__pycache__/mcp_gateway_client.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/__init__.cpython-313.pyc index 794591b..eb6b6ae 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/base.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/base.cpython-313.pyc index 1629582..b7c4933 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/base.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/base.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/config_loader.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/config_loader.cpython-313.pyc index aa5b2b8..77be6a8 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/config_loader.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/config_loader.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/custom_rails.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/custom_rails.cpython-313.pyc index 13504f3..35ac325 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/custom_rails.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/custom_rails.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/framework_llm_client.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/framework_llm_client.cpython-313.pyc index c0b1288..101812d 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/framework_llm_client.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/framework_llm_client.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/llm_rails.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/llm_rails.cpython-313.pyc index cbebd8d..1b25942 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/llm_rails.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/llm_rails.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/output_supervisor.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/output_supervisor.cpython-313.pyc index 0bbe55d..ccb9c0f 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/output_supervisor.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/output_supervisor.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/parallel_executor.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/parallel_executor.cpython-313.pyc index e3f5b3b..924a7ed 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/parallel_executor.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/parallel_executor.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/pipeline.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/pipeline.cpython-313.pyc index 1bee1db..037b023 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/pipeline.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/pipeline.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_action.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_action.cpython-313.pyc index 35ae617..06ba04d 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_action.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_action.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_decision.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_decision.cpython-313.pyc index a1aafa9..baa7d7b 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_decision.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_decision.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_result.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_result.cpython-313.pyc index db02d0e..d8b6116 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_result.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rail_result.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rails.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rails.cpython-313.pyc index bdfffe0..d1871ca 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rails.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/__pycache__/rails.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/__init__.cpython-313.pyc index 460b811..2b20525 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/_compat.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/_compat.cpython-313.pyc index e5b86f8..39c091e 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/_compat.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/_compat.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contestation_validation.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contestation_validation.cpython-313.pyc index a2222fe..c0a98cd 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contestation_validation.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contestation_validation.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contracts.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contracts.cpython-313.pyc index dbabeed..da84549 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contracts.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/contracts.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/input_size.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/input_size.cpython-313.pyc index 49b182a..0504ddb 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/input_size.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/input_size.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_adapter.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_adapter.cpython-313.pyc index 04c37f8..aa6764a 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_adapter.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_adapter.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_client.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_client.cpython-313.pyc index fed7d53..345834b 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_client.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_client.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_rails.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_rails.cpython-313.pyc index f79860c..079c6c3 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_rails.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/llm_rails.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/output_sanitization.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/output_sanitization.cpython-313.pyc index bc6a8e1..918515c 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/output_sanitization.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/output_sanitization.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/pipeline.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/pipeline.cpython-313.pyc index e1abd2c..2a98532 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/pipeline.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/__pycache__/pipeline.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/contestation_validation.py b/libs/agent_framework/src/agent_framework/guardrails/calibrated/contestation_validation.py index dc3d302..58bdc74 100644 --- a/libs/agent_framework/src/agent_framework/guardrails/calibrated/contestation_validation.py +++ b/libs/agent_framework/src/agent_framework/guardrails/calibrated/contestation_validation.py @@ -129,6 +129,8 @@ def _is_vas_section_name(section_name: str) -> bool: or "servicos de valor adicionado" in normalized or "servicos valor adicionado" in normalized or "sva detalhe total" in normalized + or "servicos contratados de parceiros" in normalized + or "servico contratado de parceiro" in normalized ) @@ -185,13 +187,23 @@ def _extract_contestation_invoice_items( "validatedAmount", ) if candidate_name and candidate_amount is not None and candidate_amount > 0: + payload_type = str(payload.get("type") or payload.get("tipo") or "").strip() + payload_desc = str(payload.get("desc") or "").strip() + classe = str(payload.get("classe", "")).strip().lower() + is_vas = ( + _is_vas_section_name(section_name) + or _is_vas_section_name(payload_type) + or classe in {"avulso", "estrategico"} + ) found.append( { "name": candidate_name, "amount": _money(candidate_amount), - "is_vas": _is_vas_section_name(section_name), + "is_vas": is_vas, "section": section_name, - "classe": str(payload.get("classe", "")).strip().lower(), + "source_type": payload_type, + "source_desc": payload_desc, + "classe": classe, "estrategico": bool(payload.get("estrategico")), "verb": str(payload.get("verb", "")).strip().lower(), } @@ -397,14 +409,25 @@ def validate_contestation_items( "vas_estrategico": False, "status": "em_validacao", } - matched_candidate = next( - ( - candidate - for candidate in candidates - if _is_same_plan_name(candidate.get("name", ""), item_name) - ), - None, + matching_candidates = [ + candidate + for candidate in candidates + if _is_same_plan_name(candidate.get("name", ""), item_name) + ] + # A mesma cobrança pode aparecer em múltiplas visões da fatura. + # Prefira a evidência que traz classificação explícita de VAS em vez + # de aceitar a primeira ocorrência genérica e concluir incorretamente + # que o item está fora da seção VAS. + matching_candidates.sort( + key=lambda candidate: ( + 0 if ( + str(candidate.get("classe", "")).strip().lower() in {"avulso", "estrategico"} + or bool(candidate.get("is_vas")) + ) else 1, + 0 if _normalize_match_text(candidate.get("name", "")) == _normalize_match_text(item_name) else 1, + ) ) + matched_candidate = matching_candidates[0] if matching_candidates else None if matched_candidate is None: _record_failure( item_log, @@ -414,6 +437,9 @@ def validate_contestation_items( continue item_log["item_na_fatura"] = True item_log["item_confirmado"] = True + item_log["item_fatura_resolvido"] = str(matched_candidate.get("name", "") or "") + item_log["secao_fatura"] = str(matched_candidate.get("section", "") or "") + item_log["tipo_fatura"] = str(matched_candidate.get("source_type", "") or "") classe = str(matched_candidate.get("classe", "")).strip().lower() is_strategic = ( diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/__init__.cpython-313.pyc index 0884551..7c5d9de 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/_context.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/_context.cpython-313.pyc index 7a1b447..9698354 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/_context.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/_context.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ausencia_oferta_proativa.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ausencia_oferta_proativa.cpython-313.pyc index c9e6e18..8af6d66 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ausencia_oferta_proativa.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ausencia_oferta_proativa.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/coerencia.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/coerencia.cpython-313.pyc new file mode 100644 index 0000000..a03ef27 Binary files /dev/null and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/coerencia.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_in.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_in.cpython-313.pyc index 2bd01ff..c9e4fd7 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_in.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_in.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_out.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_out.cpython-313.pyc index 11dd10d..b358a98 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_out.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/dlex_out.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/fallback.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/fallback.cpython-313.pyc index 1132393..c94d019 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/fallback.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/fallback.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/fraseologia.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/fraseologia.cpython-313.pyc new file mode 100644 index 0000000..3ce0003 Binary files /dev/null and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/fraseologia.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/out_of_scope.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/out_of_scope.cpython-313.pyc index 905ecd1..d5528f0 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/out_of_scope.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/out_of_scope.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/pinj.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/pinj.cpython-313.pyc index b5413c1..c6cb457 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/pinj.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/pinj.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ragsec.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ragsec.cpython-313.pyc index 4911908..2571043 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ragsec.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/ragsec.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/revprec.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/revprec.cpython-313.pyc index 4554b51..126e47f 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/revprec.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/revprec.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/tox.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/tox.cpython-313.pyc index 4baa1eb..7c9f875 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/tox.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/tox.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/toxicidade_output.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/toxicidade_output.cpython-313.pyc index 00322c0..cee57ac 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/toxicidade_output.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/prompts/__pycache__/toxicidade_output.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/__init__.cpython-313.pyc index 7c5189f..70d57ee 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/alcada.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/alcada.cpython-313.pyc index 5b34ba6..bef8c28 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/alcada.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/alcada.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/anatel.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/anatel.cpython-313.pyc index 0346dc6..a6955f3 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/anatel.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/anatel.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/confirmation.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/confirmation.cpython-313.pyc index 0574b75..7db49c3 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/confirmation.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/confirmation.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_in.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_in.cpython-313.pyc index ad49474..17e3369 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_in.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_in.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_out.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_out.cpython-313.pyc index efe66e0..fc27262 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_out.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/dlex_out.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/ragsec.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/ragsec.cpython-313.pyc index cbb1164..3ecaadc 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/ragsec.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/ragsec.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/revprec.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/revprec.cpython-313.pyc index 1e25c61..35c858f 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/revprec.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/revprec.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/tox.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/tox.cpython-313.pyc index 07441ae..df3ae4b 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/tox.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rails/__pycache__/tox.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/__init__.cpython-313.pyc index 4e813ef..bec637a 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/alcada.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/alcada.cpython-313.pyc index 4934703..8035625 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/alcada.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/alcada.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/pinj_patterns.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/pinj_patterns.cpython-313.pyc index 587b3d8..1f8f177 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/pinj_patterns.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/pinj_patterns.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/tox_blocklist.cpython-313.pyc b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/tox_blocklist.cpython-313.pyc index daddf1d..f150fb0 100644 Binary files a/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/tox_blocklist.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/guardrails/calibrated/rules/__pycache__/tox_blocklist.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/guardrails/rails.py b/libs/agent_framework/src/agent_framework/guardrails/rails.py index 810e694..87f4d73 100644 --- a/libs/agent_framework/src/agent_framework/guardrails/rails.py +++ b/libs/agent_framework/src/agent_framework/guardrails/rails.py @@ -328,47 +328,6 @@ class ProactiveOfferRail(Guardrail): ) -def _sanitize_low_risk_phraseology(text: str, reason: str) -> str | None: - """Remove apenas fechamentos/redirecionamentos de baixo risco. - - FRASEOLOGIA continua fail-closed para conteúdo material. Para B4 e ofertas - genéricas de continuação, porém, bloquear toda uma resposta grounded piora a - UX; nesses casos removemos somente a sentença ofensora. - """ - normalized_reason = (reason or "").casefold() - low_risk = any(token in normalized_reason for token in ( - "viola b4", "outro canal", "atendimento especializado", - "realizar alguma ação", "oferta de ação", "orienta o cliente", - )) - if not low_risk: - return None - - forbidden = ( - "entre em contato", "fale com um atendente", "procure uma loja", - "acesse o app", "acesse o site", "atendimento especializado", - "área de planos", "area de planos", "é só me avisar", - "e so me avisar", "realizar alguma ação", "realizar alguma acao", - "gerenciar esses serviços", "gerenciar esses servicos", - ) - sentences = re.split(r"(?<=[.!?])\s+", (text or "").strip()) - kept: list[str] = [] - removed = False - for sentence in sentences: - normalized = sentence.casefold() - proactive = ( - ("se quiser" in normalized or "caso queira" in normalized or "se desejar" in normalized) - and any(token in normalized for token in ("realizar", "gerenciar", "cancelar", "contratar", "alterar", "ação", "acao")) - ) - if proactive or any(token in normalized for token in forbidden): - removed = True - continue - kept.append(sentence.strip()) - sanitized = " ".join(x for x in kept if x).strip() - if removed and sanitized: - return sanitized - return None - - class PhraseologyRail(Guardrail): """FRASEOLOGIA calibrado: bloqueia fraseados proibidos do agente.""" code = "FRASEOLOGIA" @@ -380,26 +339,9 @@ class PhraseologyRail(Guardrail): _llm(ctx), "FRASEOLOGIA", {"text": text or "", "context": ctx}, profile_name="grl", component_name="guardrail.fraseologia", generation_name="guardrail.fraseologia", ) - allowed = bool(out.get("allowed", True)) - reason = str(out.get("reason") or out.get("label") or "FRASEOLOGIA avaliado") - if not allowed: - sanitized = _sanitize_low_risk_phraseology(text or "", reason) - if sanitized: - return RailDecision( - code=self.code, - allowed=True, - reason=f"FRASEOLOGIA sanitizada: {reason}", - sanitized_text=sanitized, - metadata={ - "mechanism": "llm_rail+deterministic_sanitize", - "data": out, - "calibrated": True, - "original_allowed": False, - }, - ) return RailDecision( - code=self.code, allowed=allowed, - reason=reason, + code=self.code, allowed=bool(out.get("allowed", True)), + reason=str(out.get("reason") or out.get("label") or "FRASEOLOGIA avaliado"), sanitized_text=text, metadata={"mechanism": "llm_rail", "data": out, "calibrated": True}, ) diff --git a/libs/agent_framework/src/agent_framework/identity/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/identity/__pycache__/__init__.cpython-313.pyc index c6acc34..2770326 100644 Binary files a/libs/agent_framework/src/agent_framework/identity/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/identity/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/identity/__pycache__/mcp_mapper.cpython-313.pyc b/libs/agent_framework/src/agent_framework/identity/__pycache__/mcp_mapper.cpython-313.pyc index 4c687e4..669dd27 100644 Binary files a/libs/agent_framework/src/agent_framework/identity/__pycache__/mcp_mapper.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/identity/__pycache__/mcp_mapper.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/identity/__pycache__/models.cpython-313.pyc b/libs/agent_framework/src/agent_framework/identity/__pycache__/models.cpython-313.pyc index b476d05..39d33a3 100644 Binary files a/libs/agent_framework/src/agent_framework/identity/__pycache__/models.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/identity/__pycache__/models.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/identity/__pycache__/resolver.cpython-313.pyc b/libs/agent_framework/src/agent_framework/identity/__pycache__/resolver.cpython-313.pyc index 20ca015..0cf4b81 100644 Binary files a/libs/agent_framework/src/agent_framework/identity/__pycache__/resolver.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/identity/__pycache__/resolver.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/__pycache__/__init__.cpython-313.pyc index 953c1f9..b02a300 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/__pycache__/judge.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/__pycache__/judge.cpython-313.pyc index c31ebd7..085b315 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/__pycache__/judge.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/__pycache__/judge.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/__init__.cpython-313.pyc index 8819c51..609ab11 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/llm_client.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/llm_client.cpython-313.pyc index d932194..7d13d56 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/llm_client.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/__pycache__/llm_client.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/__init__.cpython-313.pyc index cedce74..b087b79 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/aluc.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/aluc.cpython-313.pyc index cab6b13..d2052d5 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/aluc.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/aluc.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/csi.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/csi.cpython-313.pyc index 579652e..4f6fcb1 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/csi.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/csi.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/fallback.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/fallback.cpython-313.pyc index a7a3013..9587d8d 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/fallback.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/fallback.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/rqlt.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/rqlt.cpython-313.pyc index 8983a27..5f5be04 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/rqlt.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/rqlt.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/vctn.cpython-313.pyc b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/vctn.cpython-313.pyc index c4f3c1a..2be23c0 100644 Binary files a/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/vctn.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/judges/calibrated/prompts/__pycache__/vctn.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/llm/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/llm/__pycache__/__init__.cpython-313.pyc index 6448078..b929ed7 100644 Binary files a/libs/agent_framework/src/agent_framework/llm/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/llm/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/llm/__pycache__/base.cpython-313.pyc b/libs/agent_framework/src/agent_framework/llm/__pycache__/base.cpython-313.pyc index 6483934..bd6c705 100644 Binary files a/libs/agent_framework/src/agent_framework/llm/__pycache__/base.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/llm/__pycache__/base.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/llm/__pycache__/profile_resolver.cpython-313.pyc b/libs/agent_framework/src/agent_framework/llm/__pycache__/profile_resolver.cpython-313.pyc index 842b813..ce8be98 100644 Binary files a/libs/agent_framework/src/agent_framework/llm/__pycache__/profile_resolver.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/llm/__pycache__/profile_resolver.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/llm/__pycache__/providers.cpython-313.pyc b/libs/agent_framework/src/agent_framework/llm/__pycache__/providers.cpython-313.pyc index a13608b..49cf8e7 100644 Binary files a/libs/agent_framework/src/agent_framework/llm/__pycache__/providers.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/llm/__pycache__/providers.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/mcp/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/mcp/__pycache__/__init__.cpython-313.pyc index efaa09e..5565b3c 100644 Binary files a/libs/agent_framework/src/agent_framework/mcp/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/mcp/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/mcp/__pycache__/client.cpython-313.pyc b/libs/agent_framework/src/agent_framework/mcp/__pycache__/client.cpython-313.pyc index ccc9304..8bf7996 100644 Binary files a/libs/agent_framework/src/agent_framework/mcp/__pycache__/client.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/mcp/__pycache__/client.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/mcp/__pycache__/models.cpython-313.pyc b/libs/agent_framework/src/agent_framework/mcp/__pycache__/models.cpython-313.pyc index ab6c024..237181e 100644 Binary files a/libs/agent_framework/src/agent_framework/mcp/__pycache__/models.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/mcp/__pycache__/models.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/mcp/__pycache__/registry.cpython-313.pyc b/libs/agent_framework/src/agent_framework/mcp/__pycache__/registry.cpython-313.pyc index 10dd069..0dc48c1 100644 Binary files a/libs/agent_framework/src/agent_framework/mcp/__pycache__/registry.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/mcp/__pycache__/registry.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_policy.cpython-313.pyc b/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_policy.cpython-313.pyc index 7995057..db288d4 100644 Binary files a/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_policy.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_policy.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_router.cpython-313.pyc b/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_router.cpython-313.pyc index 823bf00..8a43c7a 100644 Binary files a/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_router.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/mcp/__pycache__/tool_router.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/mcp/models.py b/libs/agent_framework/src/agent_framework/mcp/models.py index 98f1529..97046c3 100644 --- a/libs/agent_framework/src/agent_framework/mcp/models.py +++ b/libs/agent_framework/src/agent_framework/mcp/models.py @@ -28,6 +28,11 @@ class MCPToolConfig(BaseModel): execution_policy: dict[str, Any] = Field(default_factory=dict) selection_keywords: list[str] = Field(default_factory=list) + # Política declarativa opcional de apresentação da resposta da tool. + # Para novos projetos prefira mode=renderer + renderer=. + # O framework resolve o nome no registry; a regra de negócio fica na aplicação. + response: dict[str, Any] = Field(default_factory=dict) + # Política declarativa de cache da tool, lida diretamente de config/tools.yaml. # Exemplo: # cache: diff --git a/libs/agent_framework/src/agent_framework/mcp/registry.py b/libs/agent_framework/src/agent_framework/mcp/registry.py index 6ac4308..b37efc8 100644 --- a/libs/agent_framework/src/agent_framework/mcp/registry.py +++ b/libs/agent_framework/src/agent_framework/mcp/registry.py @@ -70,6 +70,7 @@ class MCPRegistry: "confirmation_required": tool.confirmation_required, "execution_policy": tool.execution_policy, "selection_keywords": tool.selection_keywords, + "response": tool.response, "cache": tool.cache, }) return out diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/__init__.cpython-313.pyc index 0a0f164..de31105 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_extractor.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_extractor.cpython-313.pyc index b7442fc..63ffd96 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_extractor.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_extractor.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_memory.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_memory.cpython-313.pyc index e86f110..b43fee8 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_memory.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_memory.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_models.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_models.cpython-313.pyc index d327111..6afd231 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_models.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_models.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_store.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_store.cpython-313.pyc index 77ac2c2..4ccb771 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_store.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/long_term_store.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/message_history.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/message_history.cpython-313.pyc index d6c0550..478cfda 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/message_history.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/message_history.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_memory.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_memory.cpython-313.pyc index 49b62d8..23a63b2 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_memory.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_memory.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_store.cpython-313.pyc b/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_store.cpython-313.pyc index 12d798c..5e3c682 100644 Binary files a/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_store.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/memory/__pycache__/summary_store.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/models/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/models/__pycache__/__init__.cpython-313.pyc index 6dbf7ed..0d18e5e 100644 Binary files a/libs/agent_framework/src/agent_framework/models/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/models/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/models/__pycache__/identity.cpython-313.pyc b/libs/agent_framework/src/agent_framework/models/__pycache__/identity.cpython-313.pyc index c2b0f6f..df67cd4 100644 Binary files a/libs/agent_framework/src/agent_framework/models/__pycache__/identity.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/models/__pycache__/identity.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/models/__pycache__/session.cpython-313.pyc b/libs/agent_framework/src/agent_framework/models/__pycache__/session.cpython-313.pyc index b08fe68..51f483b 100644 Binary files a/libs/agent_framework/src/agent_framework/models/__pycache__/session.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/models/__pycache__/session.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/__init__.cpython-313.pyc index b0ef011..8f32787 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/context.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/context.cpython-313.pyc index 68ac915..46068d0 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/context.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/context.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/event_bus.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/event_bus.cpython-313.pyc index cec5a48..de174b9 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/event_bus.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/event_bus.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/guardrail_events.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/guardrail_events.cpython-313.pyc index 02de7c7..a76205e 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/guardrail_events.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/guardrail_events.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/ic_events.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/ic_events.cpython-313.pyc index 17816e5..5c37f19 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/ic_events.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/ic_events.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/judge_events.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/judge_events.cpython-313.pyc index 1609099..475de22 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/judge_events.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/judge_events.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/langgraph_telemetry.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/langgraph_telemetry.cpython-313.pyc index f621496..9081464 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/langgraph_telemetry.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/langgraph_telemetry.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/llm_advisors.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/llm_advisors.cpython-313.pyc index 1ae15bf..ead586d 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/llm_advisors.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/llm_advisors.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_contract.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_contract.cpython-313.pyc index bf06b29..41a4393 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_contract.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_contract.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_otel.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_otel.cpython-313.pyc index 2b64d41..bb7269a 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_otel.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/noc_otel.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/observer.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/observer.cpython-313.pyc index f2a759b..2f400d1 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/observer.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/observer.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/otel.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/otel.cpython-313.pyc index f3ae6de..78aa6db 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/otel.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/otel.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/streaming_events.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/streaming_events.cpython-313.pyc index 33c3b73..f32b12e 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/streaming_events.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/streaming_events.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/telemetry.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/telemetry.cpython-313.pyc index e9cbe6a..b28731e 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/telemetry.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/telemetry.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/token_cost.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/token_cost.cpython-313.pyc index 760aea3..b684fe4 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/token_cost.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/token_cost.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/observability/__pycache__/workflow_events.cpython-313.pyc b/libs/agent_framework/src/agent_framework/observability/__pycache__/workflow_events.cpython-313.pyc index 258d9ab..693bcfc 100644 Binary files a/libs/agent_framework/src/agent_framework/observability/__pycache__/workflow_events.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/observability/__pycache__/workflow_events.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/oci/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/oci/__pycache__/__init__.cpython-313.pyc index 1030172..23dbf2f 100644 Binary files a/libs/agent_framework/src/agent_framework/oci/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/oci/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/oci/__pycache__/auth.cpython-313.pyc b/libs/agent_framework/src/agent_framework/oci/__pycache__/auth.cpython-313.pyc index 6e1dabf..7cb6d9c 100644 Binary files a/libs/agent_framework/src/agent_framework/oci/__pycache__/auth.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/oci/__pycache__/auth.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/persistence/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/persistence/__pycache__/__init__.cpython-313.pyc index 2fbd9df..297b860 100644 Binary files a/libs/agent_framework/src/agent_framework/persistence/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/persistence/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/persistence/__pycache__/oracle_store.cpython-313.pyc b/libs/agent_framework/src/agent_framework/persistence/__pycache__/oracle_store.cpython-313.pyc index 3ba9e42..fa8709d 100644 Binary files a/libs/agent_framework/src/agent_framework/persistence/__pycache__/oracle_store.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/persistence/__pycache__/oracle_store.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/persistence/__pycache__/sqlite_store.cpython-313.pyc b/libs/agent_framework/src/agent_framework/persistence/__pycache__/sqlite_store.cpython-313.pyc index e200c5c..04a15a1 100644 Binary files a/libs/agent_framework/src/agent_framework/persistence/__pycache__/sqlite_store.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/persistence/__pycache__/sqlite_store.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/presentation/__init__.py b/libs/agent_framework/src/agent_framework/presentation/__init__.py new file mode 100644 index 0000000..a96f24f --- /dev/null +++ b/libs/agent_framework/src/agent_framework/presentation/__init__.py @@ -0,0 +1,15 @@ +from .renderers import ( + ToolResponseRenderer, + ToolResponseRendererRegistry, + register_tool_response_renderer, + render_tool_response, + tool_response_renderers, +) + +__all__ = [ + "ToolResponseRenderer", + "ToolResponseRendererRegistry", + "register_tool_response_renderer", + "render_tool_response", + "tool_response_renderers", +] diff --git a/libs/agent_framework/src/agent_framework/presentation/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/presentation/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..3f10a11 Binary files /dev/null and b/libs/agent_framework/src/agent_framework/presentation/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/presentation/__pycache__/renderers.cpython-313.pyc b/libs/agent_framework/src/agent_framework/presentation/__pycache__/renderers.cpython-313.pyc new file mode 100644 index 0000000..777eefb Binary files /dev/null and b/libs/agent_framework/src/agent_framework/presentation/__pycache__/renderers.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/presentation/renderers.py b/libs/agent_framework/src/agent_framework/presentation/renderers.py new file mode 100644 index 0000000..528359a --- /dev/null +++ b/libs/agent_framework/src/agent_framework/presentation/renderers.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from collections.abc import Callable +from threading import RLock +from typing import Any, Protocol + + +class ToolResponseRenderer(Protocol): + def __call__( + self, + *, + tool_name: str, + result: dict[str, Any], + state: dict[str, Any], + agent_label: str, + ) -> str | None: ... + + +class ToolResponseRendererRegistry: + """Thread-safe registry for application/domain response renderers. + + The framework stores only symbolic renderer names. Business-specific + formatting lives in the application that registers the renderer. + """ + + def __init__(self) -> None: + self._renderers: dict[str, ToolResponseRenderer] = {} + self._lock = RLock() + + def register( + self, + name: str, + renderer: ToolResponseRenderer, + *, + replace: bool = True, + ) -> None: + key = str(name or "").strip() + if not key: + raise ValueError("renderer name must not be empty") + if not callable(renderer): + raise TypeError("renderer must be callable") + with self._lock: + if not replace and key in self._renderers: + raise KeyError(f"renderer already registered: {key}") + self._renderers[key] = renderer + + def get(self, name: str | None) -> ToolResponseRenderer | None: + key = str(name or "").strip() + if not key: + return None + with self._lock: + return self._renderers.get(key) + + def render( + self, + name: str | None, + *, + tool_name: str, + result: dict[str, Any], + state: dict[str, Any], + agent_label: str, + ) -> str | None: + renderer = self.get(name) + if renderer is None: + return None + value = renderer( + tool_name=tool_name, + result=result, + state=state, + agent_label=agent_label, + ) + if value is None: + return None + text = str(value).strip() + return text or None + + +tool_response_renderers = ToolResponseRendererRegistry() + + +def register_tool_response_renderer( + name: str, + renderer: ToolResponseRenderer, + *, + replace: bool = True, +) -> None: + tool_response_renderers.register(name, renderer, replace=replace) + + +def render_tool_response( + name: str | None, + *, + tool_name: str, + result: dict[str, Any], + state: dict[str, Any], + agent_label: str, +) -> str | None: + return tool_response_renderers.render( + name, + tool_name=tool_name, + result=result, + state=state, + agent_label=agent_label, + ) diff --git a/libs/agent_framework/src/agent_framework/rag/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/rag/__pycache__/__init__.cpython-313.pyc index 2f70874..5a34028 100644 Binary files a/libs/agent_framework/src/agent_framework/rag/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/rag/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/rag/__pycache__/embedding_provider.cpython-313.pyc b/libs/agent_framework/src/agent_framework/rag/__pycache__/embedding_provider.cpython-313.pyc index 616fe07..de46d97 100644 Binary files a/libs/agent_framework/src/agent_framework/rag/__pycache__/embedding_provider.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/rag/__pycache__/embedding_provider.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/rag/__pycache__/graph_store.cpython-313.pyc b/libs/agent_framework/src/agent_framework/rag/__pycache__/graph_store.cpython-313.pyc index 78e3a3a..1a276ee 100644 Binary files a/libs/agent_framework/src/agent_framework/rag/__pycache__/graph_store.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/rag/__pycache__/graph_store.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/rag/__pycache__/ingest.cpython-313.pyc b/libs/agent_framework/src/agent_framework/rag/__pycache__/ingest.cpython-313.pyc index b056e8c..6297b7f 100644 Binary files a/libs/agent_framework/src/agent_framework/rag/__pycache__/ingest.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/rag/__pycache__/ingest.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/rag/__pycache__/rag_service.cpython-313.pyc b/libs/agent_framework/src/agent_framework/rag/__pycache__/rag_service.cpython-313.pyc index cb2b2be..6899d36 100644 Binary files a/libs/agent_framework/src/agent_framework/rag/__pycache__/rag_service.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/rag/__pycache__/rag_service.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/rag/__pycache__/vector_store.cpython-313.pyc b/libs/agent_framework/src/agent_framework/rag/__pycache__/vector_store.cpython-313.pyc index 40da196..48c6444 100644 Binary files a/libs/agent_framework/src/agent_framework/rag/__pycache__/vector_store.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/rag/__pycache__/vector_store.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/repositories/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/repositories/__pycache__/__init__.cpython-313.pyc index ab5a21f..a750b2a 100644 Binary files a/libs/agent_framework/src/agent_framework/repositories/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/repositories/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/repositories/__pycache__/session_repository.cpython-313.pyc b/libs/agent_framework/src/agent_framework/repositories/__pycache__/session_repository.cpython-313.pyc index ae7bc63..878b296 100644 Binary files a/libs/agent_framework/src/agent_framework/repositories/__pycache__/session_repository.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/repositories/__pycache__/session_repository.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/routing/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/routing/__pycache__/__init__.cpython-313.pyc index 17174f6..525c7c7 100644 Binary files a/libs/agent_framework/src/agent_framework/routing/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/routing/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/routing/__pycache__/config_loader.cpython-313.pyc b/libs/agent_framework/src/agent_framework/routing/__pycache__/config_loader.cpython-313.pyc index 6b3d5e7..37b9707 100644 Binary files a/libs/agent_framework/src/agent_framework/routing/__pycache__/config_loader.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/routing/__pycache__/config_loader.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/routing/__pycache__/continuity.cpython-313.pyc b/libs/agent_framework/src/agent_framework/routing/__pycache__/continuity.cpython-313.pyc index 1655f49..6fbe55a 100644 Binary files a/libs/agent_framework/src/agent_framework/routing/__pycache__/continuity.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/routing/__pycache__/continuity.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/routing/__pycache__/enterprise_router.cpython-313.pyc b/libs/agent_framework/src/agent_framework/routing/__pycache__/enterprise_router.cpython-313.pyc index f636bad..dde408b 100644 Binary files a/libs/agent_framework/src/agent_framework/routing/__pycache__/enterprise_router.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/routing/__pycache__/enterprise_router.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/routing/__pycache__/models.cpython-313.pyc b/libs/agent_framework/src/agent_framework/routing/__pycache__/models.cpython-313.pyc index e6d1791..9e67e6f 100644 Binary files a/libs/agent_framework/src/agent_framework/routing/__pycache__/models.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/routing/__pycache__/models.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/runtime/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/runtime/__pycache__/__init__.cpython-313.pyc index e1a0424..99da663 100644 Binary files a/libs/agent_framework/src/agent_framework/runtime/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/runtime/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/runtime/__pycache__/agent_runtime.cpython-313.pyc b/libs/agent_framework/src/agent_framework/runtime/__pycache__/agent_runtime.cpython-313.pyc index c5673e3..cac260c 100644 Binary files a/libs/agent_framework/src/agent_framework/runtime/__pycache__/agent_runtime.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/runtime/__pycache__/agent_runtime.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/runtime/agent_runtime.py b/libs/agent_framework/src/agent_framework/runtime/agent_runtime.py index 2580f43..af6c569 100644 --- a/libs/agent_framework/src/agent_framework/runtime/agent_runtime.py +++ b/libs/agent_framework/src/agent_framework/runtime/agent_runtime.py @@ -4,6 +4,7 @@ import hashlib import json import logging import re +import uuid from dataclasses import dataclass, field from typing import Any, Iterable, Mapping @@ -15,6 +16,21 @@ logger = logging.getLogger(__name__) _EMPTY_VALUES = (None, "", {}, []) +_ACTIVE_TRANSACTION_STATUSES = { + "COLLECTING_PARAMETERS", + "AWAITING_CONFIRMATION", + "WORKFLOW_PAUSED", + "TOOL_RESULT_CLARIFICATION", + "EXECUTING", +} +_TERMINAL_TRANSACTION_STATUSES = { + "COMPLETED", + "FAILED", + "CANCELLED", + "BLOCKED", + "OUT_OF_SCOPE", +} + @dataclass(slots=True) class RuntimeContext: @@ -519,11 +535,42 @@ class AgentRuntimeMixin: return str(response.get("content") or response.get("text") or response.get("answer") or "") return str(getattr(response, "content", None) or getattr(response, "text", None) or response) + def _drop_stale_message_extracted_arguments( + self, + tool_name: str, + arguments: dict[str, Any], + *, + explicit_fields: Iterable[str] = (), + ) -> dict[str, Any]: + """Remove valores herdados para campos cujo contrato diz ``from: message``. + + Em uma NOVA transação, ``context.tool_arguments`` pode ainda carregar + parâmetros de uma operação anterior. Campos declarados pelo mapper como + extraídos da mensagem corrente não podem nascer desse contexto antigo. + Valores explicitamente extraídos deterministicamente do turno atual são + preservados. Durante coleta incremental este helper não é usado. + """ + router = getattr(self, "tool_router", None) + if not router or not hasattr(router, "parameter_extract_rules"): + return dict(arguments or {}) + rules = router.parameter_extract_rules(tool_name) or {} + explicit = {str(name) for name in explicit_fields} + cleaned = dict(arguments or {}) + for field_name, rule in rules.items(): + if ( + str(rule.get("from") or "message").lower() == "message" + and str(field_name) not in explicit + ): + cleaned.pop(str(field_name), None) + return cleaned + async def _extract_mcp_parameters( self, tool_name: str, arguments: dict[str, Any], state: dict[str, Any], + *, + overwrite_from_message: bool = False, ) -> dict[str, Any]: """Executa regras ``extract`` declaradas para a tool escolhida. @@ -544,9 +591,13 @@ class AgentRuntimeMixin: llm = getattr(self, "llm", None) for field_name, rule in rules.items(): - if resolved.get(field_name) not in _EMPTY_VALUES: + from_message = str(rule.get("from") or "message").lower() == "message" + if not from_message: continue - if str(rule.get("from") or "message").lower() != "message": + # Em uma nova transação, a mensagem atual prevalece para campos + # declarados como ``from: message``. Durante COLLECTING_PARAMETERS + # o default permanece False para congelar valores já coletados. + if resolved.get(field_name) not in _EMPTY_VALUES and not overwrite_from_message: continue strategy = str(rule.get("strategy") or "llm").lower() value: Any = None @@ -1167,19 +1218,13 @@ class AgentRuntimeMixin: return None def _select_transactional_tool(self, tools: list[str], text: str) -> str | None: - """Seleciona a ação transacional da intent atual. - - O match por ``selection_keywords`` continua tendo precedência. Porém, depois - que o EnterpriseRouter já restringiu ``tools`` às capabilities da intent, - uma única tool transacional é uma escolha determinística e segura. Isso - evita perder frases naturais como ``quero cancelar TIM Fashion Mensal`` ou - ``não contratei esse serviço`` só porque elas não repetem literalmente uma - keyword de ``tools.yaml``. - """ matched = self._transactional_action_match(text, tools) if matched: return matched + # Generic fallback: once routing has constrained the allowlist, a single + # transactional capability is unambiguous even when the user's wording + # does not contain one of the tool-specific selection keywords. transactional = [ tool for tool in tools @@ -1348,12 +1393,112 @@ class AgentRuntimeMixin: state["transaction_status"] = "COMPLETED" if result.get("ok") else "FAILED" return result + @staticmethod + def _transaction_is_active(state: dict[str, Any]) -> bool: + return str(state.get("transaction_status") or "") in _ACTIVE_TRANSACTION_STATUSES + + @staticmethod + def _transaction_is_terminal(state: dict[str, Any]) -> bool: + return str(state.get("transaction_status") or "") in _TERMINAL_TRANSACTION_STATUSES + + def _active_transaction(self, state: dict[str, Any]) -> dict[str, Any] | None: + """Return only the operationally active transaction. + + Closed transactions are history and must never provide tool/arguments for + a later turn. For backward compatibility, an old checkpoint that has the + legacy selected/pending fields but an ACTIVE status is lazily hydrated into + ``active_transaction``. + """ + if not self._transaction_is_active(state): + return None + current = state.get("active_transaction") + if isinstance(current, dict) and current.get("tool_name"): + return current + legacy = state.get("pending_tool_call") or state.get("selected_tool_call") or {} + if not isinstance(legacy, dict) or not legacy.get("tool_name"): + return None + current = { + "transaction_id": str(uuid.uuid4()), + "tool_name": legacy.get("tool_name"), + "arguments": dict(legacy.get("arguments") or {}), + "status": state.get("transaction_status"), + "started_from_intent": state.get("intent"), + } + state["active_transaction"] = current + return current + + def _set_active_transaction( + self, + state: dict[str, Any], + *, + tool_name: str, + arguments: dict[str, Any], + status: str, + transaction_id: str | None = None, + ) -> dict[str, Any]: + current = state.get("active_transaction") if isinstance(state.get("active_transaction"), dict) else {} + txid = transaction_id or current.get("transaction_id") or str(uuid.uuid4()) + tx = { + "transaction_id": txid, + "tool_name": tool_name, + "arguments": dict(arguments or {}), + "status": status, + "started_from_intent": current.get("started_from_intent") or state.get("intent"), + } + state["active_transaction"] = tx + return tx + + def _finish_active_transaction(self, state: dict[str, Any], status: str) -> None: + """Close the active transaction without leaving operational state behind.""" + active = self._active_transaction(state) + if isinstance(active, dict): + state["last_transaction"] = { + **active, + "status": status, + } + state["active_transaction"] = None + state["selected_tool_call"] = {} + state["pending_tool_call"] = {} + state["missing_parameters"] = [] + state["confirmation_required"] = False + state["confirmation_received"] = status == "COMPLETED" + state["next_state"] = None + state["transaction_status"] = status + + def _normalize_transaction_lifecycle(self, state: dict[str, Any]) -> None: + """Ensure closed transactions cannot leak into a later user turn.""" + if self._transaction_is_terminal(state): + # Preserve a compact audit snapshot, but remove every operational latch. + active = state.get("active_transaction") + if not isinstance(active, dict): + legacy = state.get("pending_tool_call") or state.get("selected_tool_call") + if isinstance(legacy, dict) and legacy.get("tool_name"): + active = { + "transaction_id": str(uuid.uuid4()), + "tool_name": legacy.get("tool_name"), + "arguments": dict(legacy.get("arguments") or {}), + "status": state.get("transaction_status"), + "started_from_intent": state.get("intent"), + } + if isinstance(active, dict): + state["last_transaction"] = {**active, "status": state.get("transaction_status")} + state["active_transaction"] = None + state["selected_tool_call"] = {} + state["pending_tool_call"] = {} + state["missing_parameters"] = [] + state["confirmation_required"] = False + state["confirmation_received"] = False + state["next_state"] = None + return + if self._transaction_is_active(state): + self._active_transaction(state) + def transaction_state_patch(self, state: dict[str, Any]) -> dict[str, Any]: keys = ( "available_mcp_tools", "selected_tool_call", "pending_tool_call", "transaction_status", "confirmation_required", "confirmation_received", "tool_policy_result", "missing_parameters", "next_state", "pending_domain_workflow", "pending_tool_clarification", - "business_workflows_executed", + "business_workflows_executed", "active_transaction", "last_transaction", ) return {key: state.get(key) for key in keys if key in state} @@ -1411,6 +1556,9 @@ class AgentRuntimeMixin: "next_state": collecting_state, "tool_policy_result": {**policy, "tool_name": tool_name, "action": "collecting_parameters"}, }) + self._set_active_transaction( + state, tool_name=tool_name, arguments=arguments, status="COLLECTING_PARAMETERS" + ) def transaction_confirmation_message(self, state: dict[str, Any]) -> str | None: if state.get("transaction_status") != "AWAITING_CONFIRMATION": @@ -1446,6 +1594,185 @@ class AgentRuntimeMixin: matches.append(name) return matches or available_tools[:1] + @staticmethod + def _response_path_get(data: Any, path: str | None) -> Any: + """Resolve caminho simples ``a.b.c`` em dicts sem conhecer o domínio.""" + if not path: + return data + current = data + for part in str(path).split("."): + if isinstance(current, Mapping): + current = current.get(part) + else: + return None + return current + + @staticmethod + def _response_format_value(value: Any, formatter: str | None) -> Any: + """Formatadores genéricos permitidos pela política declarativa de resposta.""" + if formatter in (None, "", "raw"): + return value + if formatter == "decimal_2_comma": + try: + return f"{float(value):.2f}".replace(".", ",") + except (TypeError, ValueError): + return value + if formatter == "decimal_2": + try: + return f"{float(value):.2f}" + except (TypeError, ValueError): + return value + if formatter == "str": + return "" if value is None else str(value) + return value + + @classmethod + def _response_template(cls, template: str, data: Mapping[str, Any], formats: Mapping[str, Any] | None = None) -> str | None: + """Renderiza template somente se todos os placeholders existirem. + + Isso evita respostas como ``None`` quando o contrato da tool não corresponde + à configuração. Nesse caso o runtime cai no fallback legado/LLM. + """ + formats = formats or {} + names = set(re.findall(r"\{([A-Za-z_][A-Za-z0-9_]*)\}", str(template))) + values: dict[str, Any] = {} + for name in names: + if name not in data or data.get(name) is None: + return None + values[name] = cls._response_format_value(data.get(name), formats.get(name)) + try: + return str(template).format(**values) + except Exception: + return None + + def _render_declared_tool_response(self, tool_name: str | None, data: dict[str, Any], *, agent_label: str, state: dict[str, Any] | None = None) -> str | None: + """Renderiza resposta MCP por configuração, sem regras de negócio no core. + + A configuração vive em ``tools.yaml`` e suporta primitives genéricas: + ``template``, ``list`` e ``lines``. Se não houver política, retorna ``None`` + para preservar integralmente o comportamento legado. + """ + router = getattr(self, "tool_router", None) + registry = getattr(router, "registry", None) + cfg = registry.get_tool(str(tool_name)) if registry and tool_name else None + policy = dict(getattr(cfg, "response", None) or {}) if cfg else {} + if not policy: + return None + + mode = str(policy.get("mode") or "").strip().lower() + + # Extensão preferencial: o core conhece apenas um nome simbólico. + # O código do renderer é registrado pela aplicação/domínio. + if mode == "renderer": + renderer_name = str(policy.get("renderer") or "").strip() + if not renderer_name: + return None + try: + from agent_framework.presentation import render_tool_response + + return render_tool_response( + renderer_name, + tool_name=str(tool_name or ""), + result=data, + state=state or {}, + agent_label=agent_label, + ) + except Exception: + # Compatibilidade/fail-open: renderer ausente ou com erro não quebra + # agentes legados; o fluxo continua para o fallback existente. + return None + + # Modos declarativos da versão anterior são preservados apenas por + # compatibilidade. Novos projetos devem usar mode=renderer. + base: dict[str, Any] = {**data, "agent_label": agent_label, "result": data} + + if mode == "template": + template = policy.get("template") + if not template: + return None + # ``result`` pode ser usado para debug/compatibilidade; demais campos + # precisam existir para impedir None em texto de cliente. + if "{result}" in str(template): + try: + return str(template).replace("{result}", str(data)).replace("{agent_label}", agent_label) + except Exception: + return None + return self._response_template(str(template), base, policy.get("formats")) + + if mode == "list": + items = self._response_path_get(data, policy.get("source")) + if not isinstance(items, list) or not items: + return str(policy.get("empty_message") or "").strip() or None + rendered_items: list[str] = [] + item_template = str(policy.get("item_template") or "{item}") + item_formats = policy.get("item_formats") or {} + for raw in items: + if isinstance(raw, Mapping): + item_data = dict(raw) + else: + item_data = {"item": raw} + item_data["agent_label"] = agent_label + line = self._response_template(item_template, item_data, item_formats) + if line: + rendered_items.append(line) + if not rendered_items: + return None + count = len(rendered_items) + heading_template = policy.get("heading_singular") if count == 1 else policy.get("heading_plural") + heading = None + if heading_template: + heading = self._response_template( + str(heading_template), + {"agent_label": agent_label, "count": count}, + ) + sep = str(policy.get("separator") or "\n") + body = sep.join(rendered_items) + return f"{heading}\n{body}" if heading else body + + if mode == "lines": + lines: list[str] = [] + for spec in policy.get("lines") or []: + if not isinstance(spec, Mapping): + continue + kind = str(spec.get("kind") or "template") + if kind == "template": + when = spec.get("when_present") + if when and self._response_path_get(data, str(when)) is None: + continue + line = self._response_template(str(spec.get("template") or ""), base, spec.get("formats")) + if line: + lines.append(line) + elif kind == "list": + values = self._response_path_get(data, spec.get("source")) + if not isinstance(values, list) or not values: + continue + fields = list(spec.get("item_fields") or ["item"]) + rendered: list[str] = [] + for value in values: + if isinstance(value, Mapping): + chosen = next((value.get(f) for f in fields if value.get(f) not in _EMPTY_VALUES), None) + else: + chosen = value + if chosen not in _EMPTY_VALUES: + rendered.append(str(chosen)) + if rendered: + lines.append( + str(spec.get("prefix") or "") + + str(spec.get("separator") or "; ").join(rendered) + + str(spec.get("suffix") or "") + ) + if not lines: + return None + return str(policy.get("joiner") or " ").join(lines) + + if mode == "field": + value = self._response_path_get(data, policy.get("field")) + return str(value).strip() if value not in _EMPTY_VALUES else None + + if mode in {"llm", "none"}: + return None + return None + def build_direct_mcp_answer(self, state: dict[str, Any], mcp_results: list[dict[str, Any]], *, agent_label: str) -> str | None: """Resposta determinística para consultas estruturadas simples.""" requires_rag, _ = self._mcp_rag_directive(mcp_results) @@ -1475,6 +1802,14 @@ class AgentRuntimeMixin: return None tool = ok[0].get("tool_name") data = ok[0]["result"] + + # Primeiro tenta o contrato genérico e declarativo de apresentação. + # Se a aplicação não o configurou, preserva exatamente o fallback legado + # abaixo para não quebrar projetos existentes. + declared = self._render_declared_tool_response(tool, data, agent_label=agent_label, state=state) + if declared is not None: + return declared + if tool == "consultar_pedido": oid=data.get("order_id"); status=data.get("status"); total=data.get("valor_total") lines=[f"[{agent_label}] Pedido {oid}: status {status}."] @@ -1509,6 +1844,7 @@ class AgentRuntimeMixin: available_tools = list(tools if tools is not None else (state.get("mcp_tools") or [])) state["available_mcp_tools"] = available_tools text = state.get("sanitized_input") or state.get("user_text") or "" + self._normalize_transaction_lifecycle(state) # Clarificação de resultado de tool tem precedência: reutiliza a mesma tool # e argumentos, alterando apenas o parâmetro escolhido pelo usuário. @@ -1524,7 +1860,7 @@ class AgentRuntimeMixin: # Antes de confirmar, complete os parâmetros obrigatórios da ação. if state.get("transaction_status") == "COLLECTING_PARAMETERS": - selected = dict(state.get("selected_tool_call") or {}) + selected = dict(self._active_transaction(state) or state.get("selected_tool_call") or {}) tool_name = selected.get("tool_name") if tool_name: previous_args = dict(selected.get("arguments") or {}) @@ -1535,14 +1871,20 @@ class AgentRuntimeMixin: aliases=aliases, extra_args=self._extract_action_arguments(text), ) - arguments = { - **previous_args, - **{k: v for k, v in new_args.items() if v not in (None, "", [], {})}, - } - # Execute parameter extraction before deciding whether the workflow - # must enter COLLECTING_PARAMETERS. Otherwise parameters declared - # with strategy=llm in mcp_parameter_mapping.yaml are invisible to - # the deterministic transaction state machine. + # Durante coleta incremental, valores de contexto podem ainda conter + # parâmetros de uma operação anterior. O que já foi coletado para a + # transação pendente prevalece; o turno atual só preenche lacunas. + non_empty_new = {k: v for k, v in new_args.items() if v not in (None, "", [], {})} + arguments = {**non_empty_new, **previous_args} + + # Campos de envelope pertencem ao turno corrente e devem permanecer + # atualizados, mesmo quando os parâmetros de negócio ficam congelados. + for per_turn_key in ("query", "operator_instructions", "interaction_key"): + if non_empty_new.get(per_turn_key) not in (None, "", [], {}): + arguments[per_turn_key] = non_empty_new[per_turn_key] + + # Reutiliza o contrato declarativo para preencher somente os campos + # ainda faltantes; campos previamente coletados não são sobrescritos. arguments = await self._extract_mcp_parameters(tool_name, arguments, state) policy = self._resolve_tool_execution_policy(tool_name, arguments) missing = self._missing_required_arguments(policy, arguments) @@ -1562,6 +1904,9 @@ class AgentRuntimeMixin: selected = {"tool_name": tool_name, "arguments": arguments} state["selected_tool_call"] = selected + self._set_active_transaction( + state, tool_name=tool_name, arguments=arguments, status="COLLECTING_PARAMETERS" + ) state["missing_parameters"] = [] if policy.get("require_confirmation"): waiting_state = self._waiting_state_name(state) @@ -1573,6 +1918,9 @@ class AgentRuntimeMixin: "next_state": waiting_state, "tool_policy_result": {**policy, "tool_name": tool_name}, }) + self._set_active_transaction( + state, tool_name=tool_name, arguments=arguments, status="AWAITING_CONFIRMATION" + ) return [{ "ok": True, "executed": False, @@ -1586,27 +1934,29 @@ class AgentRuntimeMixin: result = await self._call_mcp_tool(tool_name, arguments, state) self._capture_pending_domain_workflow(state, result) self._capture_pending_tool_clarification(state, result, tool_name=tool_name, arguments=arguments) - state.update({ - "transaction_status": ("WORKFLOW_PAUSED" if state.get("pending_domain_workflow") else ("TOOL_RESULT_CLARIFICATION" if state.get("pending_tool_clarification") else ("COMPLETED" if result.get("ok") else "FAILED"))), - "confirmation_required": False, - "confirmation_received": True, - "pending_tool_call": {}, - "missing_parameters": [], - }) + final_status = ("WORKFLOW_PAUSED" if state.get("pending_domain_workflow") else ("TOOL_RESULT_CLARIFICATION" if state.get("pending_tool_clarification") else ("COMPLETED" if result.get("ok") else "FAILED"))) + if final_status in _TERMINAL_TRANSACTION_STATUSES: + self._finish_active_transaction(state, final_status) + else: + state.update({ + "transaction_status": final_status, + "confirmation_required": False, + "confirmation_received": True, + "pending_tool_call": {}, + "missing_parameters": [], + }) + self._set_active_transaction( + state, tool_name=tool_name, arguments=arguments, status=final_status + ) return [result] - pending = state.get("pending_tool_call") or {} + active_tx = self._active_transaction(state) + pending = (active_tx if isinstance(active_tx, dict) and active_tx.get("status") == "AWAITING_CONFIRMATION" else state.get("pending_tool_call")) or {} if pending: decision = self._confirmation_decision(text) if decision == "reject": - state.update({ - "transaction_status": "CANCELLED", - "confirmation_received": False, - "confirmation_required": False, - "selected_tool_call": pending, - "pending_tool_call": {}, - "tool_policy_result": {"action": "cancelled", "tool_name": pending.get("tool_name")}, - }) + state["tool_policy_result"] = {"action": "cancelled", "tool_name": pending.get("tool_name")} + self._finish_active_transaction(state, "CANCELLED") return [{"ok": True, "tool_name": pending.get("tool_name"), "transaction_status": "CANCELLED", "cancelled": True}] if decision == "confirm": tool_name = pending.get("tool_name") @@ -1616,17 +1966,26 @@ class AgentRuntimeMixin: result = await self._call_mcp_tool(tool_name, arguments, state) self._capture_pending_domain_workflow(state, result) self._capture_pending_tool_clarification(state, result, tool_name=tool_name, arguments=arguments) - state.update({ - "transaction_status": ("WORKFLOW_PAUSED" if state.get("pending_domain_workflow") else ("TOOL_RESULT_CLARIFICATION" if state.get("pending_tool_clarification") else ("COMPLETED" if result.get("ok") else "FAILED"))), - "confirmation_required": False, - "selected_tool_call": pending, - "pending_tool_call": {}, - "tool_policy_result": {"action": "executed_after_confirmation", "tool_name": tool_name}, - }) + final_status = ("WORKFLOW_PAUSED" if state.get("pending_domain_workflow") else ("TOOL_RESULT_CLARIFICATION" if state.get("pending_tool_clarification") else ("COMPLETED" if result.get("ok") else "FAILED"))) + state["tool_policy_result"] = {"action": "executed_after_confirmation", "tool_name": tool_name} + if final_status in _TERMINAL_TRANSACTION_STATUSES: + self._finish_active_transaction(state, final_status) + else: + state.update({ + "transaction_status": final_status, + "confirmation_required": False, + "pending_tool_call": {}, + }) + self._set_active_transaction( + state, tool_name=tool_name, arguments=arguments, status=final_status + ) results.append(result) return results state["transaction_status"] = "AWAITING_CONFIRMATION" state["confirmation_required"] = True + self._set_active_transaction( + state, tool_name=str(pending.get("tool_name") or ""), arguments=dict(pending.get("arguments") or {}), status="AWAITING_CONFIRMATION" + ) return [{"ok": False, "tool_name": pending.get("tool_name"), "awaiting_confirmation": True, "transaction_status": "AWAITING_CONFIRMATION"}] read_only_tools = [ @@ -1669,19 +2028,30 @@ class AgentRuntimeMixin: if not selected_action: return results + explicit_action_args = self._extract_action_arguments(text) action_args = self.build_tool_arguments( state, tool_name=selected_action, intent=state.get("intent"), aliases=aliases, - extra_args=self._extract_action_arguments(text), + extra_args=explicit_action_args, + ) + # Nova transação: parâmetros declarados ``from: message`` não podem ser + # herdados de context.tool_arguments de uma operação anterior. + action_args = self._drop_stale_message_extracted_arguments( + selected_action, action_args, explicit_fields=explicit_action_args.keys() + ) + # A mensagem atual é a fonte de verdade para esses campos no primeiro + # turno transacional. + action_args = await self._extract_mcp_parameters( + selected_action, action_args, state, overwrite_from_message=True ) - # Extract parameters (including LLM-declared extraction rules) before - # validating required fields and before persisting the pending call. - action_args = await self._extract_mcp_parameters(selected_action, action_args, state) policy = self._resolve_tool_execution_policy(selected_action, action_args) selected = {"tool_name": selected_action, "arguments": action_args} state["selected_tool_call"] = selected + self._set_active_transaction( + state, tool_name=selected_action, arguments=action_args, status="COLLECTING_PARAMETERS" + ) state["tool_policy_result"] = {**policy, "tool_name": selected_action} missing = self._missing_required_arguments(policy, action_args) @@ -1718,6 +2088,9 @@ class AgentRuntimeMixin: "confirmation_required": True, "confirmation_received": False, }) + self._set_active_transaction( + state, tool_name=selected_action, arguments=action_args, status="AWAITING_CONFIRMATION" + ) state["next_state"] = self._waiting_state_name(state) if emit_events: await self._emit_ic("IC.TRANSACTION_CONFIRMATION_REQUIRED", state, {"tool_name": selected_action, **policy}, component="agent_runtime.tool_policy") @@ -1727,12 +2100,19 @@ class AgentRuntimeMixin: action_args["confirmed"] = True result = await self._call_mcp_tool(selected_action, action_args, state) self._capture_pending_domain_workflow(state, result) - state.update({ - "transaction_status": ("WORKFLOW_PAUSED" if state.get("pending_domain_workflow") else ("TOOL_RESULT_CLARIFICATION" if state.get("pending_tool_clarification") else ("COMPLETED" if result.get("ok") else "FAILED"))), - "confirmation_required": False, - "confirmation_received": True, - "pending_tool_call": {}, - }) + final_status = ("WORKFLOW_PAUSED" if state.get("pending_domain_workflow") else ("TOOL_RESULT_CLARIFICATION" if state.get("pending_tool_clarification") else ("COMPLETED" if result.get("ok") else "FAILED"))) + if final_status in _TERMINAL_TRANSACTION_STATUSES: + self._finish_active_transaction(state, final_status) + else: + state.update({ + "transaction_status": final_status, + "confirmation_required": False, + "confirmation_received": True, + "pending_tool_call": {}, + }) + self._set_active_transaction( + state, tool_name=selected_action, arguments=action_args, status=final_status + ) results.append(result) return results diff --git a/libs/agent_framework/src/agent_framework/sse/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/sse/__pycache__/__init__.cpython-313.pyc index 2e67dad..f70e366 100644 Binary files a/libs/agent_framework/src/agent_framework/sse/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/sse/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/sse/__pycache__/events.cpython-313.pyc b/libs/agent_framework/src/agent_framework/sse/__pycache__/events.cpython-313.pyc index fed8b22..a97b0b6 100644 Binary files a/libs/agent_framework/src/agent_framework/sse/__pycache__/events.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/sse/__pycache__/events.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/supervisor/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/supervisor/__pycache__/__init__.cpython-313.pyc index c1bda3d..3bfad3b 100644 Binary files a/libs/agent_framework/src/agent_framework/supervisor/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/supervisor/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/supervisor/__pycache__/supervisor.cpython-313.pyc b/libs/agent_framework/src/agent_framework/supervisor/__pycache__/supervisor.cpython-313.pyc index b928242..2f7705a 100644 Binary files a/libs/agent_framework/src/agent_framework/supervisor/__pycache__/supervisor.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/supervisor/__pycache__/supervisor.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/__pycache__/__init__.cpython-313.pyc b/libs/agent_framework/src/agent_framework/workflows/__pycache__/__init__.cpython-313.pyc index 536364c..2ea8042 100644 Binary files a/libs/agent_framework/src/agent_framework/workflows/__pycache__/__init__.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/workflows/__pycache__/__init__.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/__pycache__/graph.cpython-313.pyc b/libs/agent_framework/src/agent_framework/workflows/__pycache__/graph.cpython-313.pyc new file mode 100644 index 0000000..ca8c8f0 Binary files /dev/null and b/libs/agent_framework/src/agent_framework/workflows/__pycache__/graph.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/__pycache__/models.cpython-313.pyc b/libs/agent_framework/src/agent_framework/workflows/__pycache__/models.cpython-313.pyc index 08349f9..7cd96e2 100644 Binary files a/libs/agent_framework/src/agent_framework/workflows/__pycache__/models.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/workflows/__pycache__/models.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/__pycache__/registry.cpython-313.pyc b/libs/agent_framework/src/agent_framework/workflows/__pycache__/registry.cpython-313.pyc index 2a96f3a..20e524d 100644 Binary files a/libs/agent_framework/src/agent_framework/workflows/__pycache__/registry.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/workflows/__pycache__/registry.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/__pycache__/repository.cpython-313.pyc b/libs/agent_framework/src/agent_framework/workflows/__pycache__/repository.cpython-313.pyc index 60b2dd2..accb9fd 100644 Binary files a/libs/agent_framework/src/agent_framework/workflows/__pycache__/repository.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/workflows/__pycache__/repository.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/__pycache__/runtime.cpython-313.pyc b/libs/agent_framework/src/agent_framework/workflows/__pycache__/runtime.cpython-313.pyc index 206eb3e..353244b 100644 Binary files a/libs/agent_framework/src/agent_framework/workflows/__pycache__/runtime.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/workflows/__pycache__/runtime.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/__pycache__/tool_executor.cpython-313.pyc b/libs/agent_framework/src/agent_framework/workflows/__pycache__/tool_executor.cpython-313.pyc index 9428e45..f6f7842 100644 Binary files a/libs/agent_framework/src/agent_framework/workflows/__pycache__/tool_executor.cpython-313.pyc and b/libs/agent_framework/src/agent_framework/workflows/__pycache__/tool_executor.cpython-313.pyc differ diff --git a/libs/agent_framework/src/agent_framework/workflows/runtime.py b/libs/agent_framework/src/agent_framework/workflows/runtime.py index bc8a1b6..f818233 100644 --- a/libs/agent_framework/src/agent_framework/workflows/runtime.py +++ b/libs/agent_framework/src/agent_framework/workflows/runtime.py @@ -434,15 +434,11 @@ class WorkflowRuntime: "current_node": None, } config = {"configurable": {"thread_id": eid}} - # Explicit offline-regression mode. When enabled, always use the - # deterministic backend, regardless of whether LangGraph happens to be - # installed in the current environment. This keeps regression results - # reproducible across developer machines and CI while production - # (the default) continues to require/use LangGraph. if self.allow_deterministic_fallback: - return await self._run_fallback( - definition, initial, start_node=definition.start, execution_id=eid - ) + try: + import langgraph # noqa: F401 + except ModuleNotFoundError: + return await self._run_fallback(definition, initial, start_node=definition.start, execution_id=eid) try: graph = self._compile(definition) state = await graph.ainvoke(initial, config=config) @@ -503,9 +499,10 @@ class WorkflowRuntime: definition = self.repository.get_version(name, version) if version else self.repository.get_active(name) config = {"configurable": {"thread_id": execution_id}} if self.allow_deterministic_fallback: - return await self._resume_fallback( - name, execution_id, resume_value, version=version - ) + try: + import langgraph # noqa: F401 + except ModuleNotFoundError: + return await self._resume_fallback(name, execution_id, resume_value, version=version) try: from langgraph.types import Command except ModuleNotFoundError as exc: diff --git a/templates/agent_template_backend/app/agents/runtime.py b/templates/agent_template_backend/app/agents/runtime.py index e6429c4..7a1a9be 100644 --- a/templates/agent_template_backend/app/agents/runtime.py +++ b/templates/agent_template_backend/app/agents/runtime.py @@ -3,5 +3,8 @@ from __future__ import annotations # Compatibilidade local do template/backend. # A implementação oficial agora fica no framework para evitar duplicação entre agentes. from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext +from app.presentation import register_tool_renderers + +register_tool_renderers() __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] diff --git a/templates/agent_template_backend/app/presentation/__init__.py b/templates/agent_template_backend/app/presentation/__init__.py new file mode 100644 index 0000000..c0eba0d --- /dev/null +++ b/templates/agent_template_backend/app/presentation/__init__.py @@ -0,0 +1,3 @@ +from .tool_renderers import register_tool_renderers + +__all__ = ["register_tool_renderers"] diff --git a/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc b/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc new file mode 100644 index 0000000..32e74b9 Binary files /dev/null and b/templates/agent_template_backend/app/presentation/__pycache__/tool_renderers.cpython-313.pyc differ diff --git a/templates/agent_template_backend/app/presentation/tool_renderers.py b/templates/agent_template_backend/app/presentation/tool_renderers.py new file mode 100644 index 0000000..f77c47a --- /dev/null +++ b/templates/agent_template_backend/app/presentation/tool_renderers.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any + +from agent_framework.presentation import register_tool_response_renderer + + +def _money_brl(value: Any) -> str: + try: + return f"{float(value):.2f}".replace(".", ",") + except (TypeError, ValueError): + return str(value) + + +def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + return f"[{agent_label}] Fatura consultada: {result}." + + +def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + plano = result.get("plano") + if plano is None: + return None + parts = [f"[{agent_label}] Seu plano é {plano}"] + internet_gb = result.get("internet_gb") + status = result.get("status") + if internet_gb is not None: + parts.append(f"com {internet_gb} GB") + if status is not None: + parts.append(f"status {status}") + return ", ".join(parts) + "." + + +def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + status = result.get("status") + if order_id is None or status is None: + return None + lines = [f"[{agent_label}] Pedido {order_id}: status {status}."] + total = result.get("valor_total") + if total is not None: + lines.append(f"Valor total: R$ {_money_brl(total)}.") + items = result.get("itens") or [] + rendered_items: list[str] = [] + if isinstance(items, list): + for item in items: + if isinstance(item, dict): + value = item.get("descricao") or item.get("nome") or item.get("sku") + else: + value = item + if value not in (None, ""): + rendered_items.append(str(value)) + if rendered_items: + lines.append("Itens: " + "; ".join(rendered_items) + ".") + return " ".join(lines) + + +def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None: + order_id = result.get("order_id") + transportadora = result.get("transportadora") + codigo = result.get("codigo_rastreio") + previsao = result.get("previsao_entrega") + if any(v is None for v in (order_id, transportadora, codigo, previsao)): + return None + return ( + f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, " + f"rastreio {codigo}, previsão {previsao}." + ) + + +def register_tool_renderers() -> None: + register_tool_response_renderer("telecom.invoice", render_telecom_invoice) + register_tool_response_renderer("telecom.plan", render_telecom_plan) + register_tool_response_renderer("retail.order", render_retail_order) + register_tool_response_renderer("retail.delivery", render_retail_delivery) diff --git a/templates/agent_template_backend/config/tools.yaml b/templates/agent_template_backend/config/tools.yaml index d85fae1..6273371 100644 --- a/templates/agent_template_backend/config/tools.yaml +++ b/templates/agent_template_backend/config/tools.yaml @@ -10,6 +10,9 @@ tools: - fatura - conta - boleto + response: + mode: renderer + renderer: telecom.invoice consultar_pagamentos: description: Consulta histórico de pagamentos do cliente. mcp_server: telecom @@ -28,6 +31,9 @@ tools: asset_id: string selection_keywords: - plano + response: + mode: renderer + renderer: telecom.plan listar_servicos: description: Lista serviços ativos e adicionais VAS. mcp_server: telecom @@ -49,6 +55,9 @@ tools: - consultar pedido - status do pedido - pedido + response: + mode: renderer + renderer: retail.order consultar_entrega: description: Consulta entrega e rastreamento do pedido. mcp_server: retail @@ -61,6 +70,9 @@ tools: - rastreamento - transportadora - previsão + response: + mode: renderer + renderer: retail.delivery solicitar_troca: description: Simula abertura de solicitação de troca. mcp_server: retail diff --git a/tests/__pycache__/conftest.cpython-313-pytest-9.0.2.pyc b/tests/__pycache__/conftest.cpython-313-pytest-9.0.2.pyc index db53f3f..dff3d68 100644 Binary files a/tests/__pycache__/conftest.cpython-313-pytest-9.0.2.pyc and b/tests/__pycache__/conftest.cpython-313-pytest-9.0.2.pyc differ diff --git a/tests/__pycache__/test_generic_tool_response_presentation.cpython-313-pytest-9.0.2.pyc b/tests/__pycache__/test_generic_tool_response_presentation.cpython-313-pytest-9.0.2.pyc new file mode 100644 index 0000000..fccf00c Binary files /dev/null and b/tests/__pycache__/test_generic_tool_response_presentation.cpython-313-pytest-9.0.2.pyc differ diff --git a/tests/__pycache__/test_mcp_parameter_extraction_runtime.cpython-313-pytest-9.0.2.pyc b/tests/__pycache__/test_mcp_parameter_extraction_runtime.cpython-313-pytest-9.0.2.pyc new file mode 100644 index 0000000..2c07d30 Binary files /dev/null and b/tests/__pycache__/test_mcp_parameter_extraction_runtime.cpython-313-pytest-9.0.2.pyc differ diff --git a/tests/__pycache__/test_transactional_tool_flow.cpython-313-pytest-9.0.2.pyc b/tests/__pycache__/test_transactional_tool_flow.cpython-313-pytest-9.0.2.pyc new file mode 100644 index 0000000..5bff15e Binary files /dev/null and b/tests/__pycache__/test_transactional_tool_flow.cpython-313-pytest-9.0.2.pyc differ diff --git a/tests/test_generic_tool_response_presentation.py b/tests/test_generic_tool_response_presentation.py new file mode 100644 index 0000000..f57feaa --- /dev/null +++ b/tests/test_generic_tool_response_presentation.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from types import SimpleNamespace + +from agent_framework.presentation import register_tool_response_renderer +from agent_framework.runtime.agent_runtime import AgentRuntimeMixin + + +class _Registry: + def __init__(self, responses): + self.responses = responses + + def get_tool(self, name): + response = self.responses.get(name) + if response is None: + return None + return SimpleNamespace(response=response) + + +class _Runtime(AgentRuntimeMixin): + def __init__(self, responses): + self.tool_router = SimpleNamespace(registry=_Registry(responses)) + + def _mcp_rag_directive(self, results): + return False, None + + def _mcp_llm_composition_directive(self, results): + return False, None + + def _transactional_action_match(self, text): + return None + + def _workflow_payload_from_tool_result(self, item): + return None + + +def _result(tool, data): + return [{"tool_name": tool, "ok": True, "result": data}] + + +def test_renderer_mode_uses_application_registered_renderer(): + def renderer(*, tool_name, result, state, agent_label): + return f"[{agent_label}] {result['name']} / {state['intent']}" + + register_tool_response_renderer("test.entity", renderer) + rt = _Runtime({"consultar_algo": {"mode": "renderer", "renderer": "test.entity"}}) + answer = rt.build_direct_mcp_answer( + {"user_text": "consulta", "intent": "test_intent"}, + _result("consultar_algo", {"name": "OK"}), + agent_label="TestAgent", + ) + assert answer == "[TestAgent] OK / test_intent" + + +def test_missing_renderer_falls_back_without_breaking_runtime(): + rt = _Runtime({"consultar_plano": {"mode": "renderer", "renderer": "missing.renderer"}}) + answer = rt.build_direct_mcp_answer( + {"user_text": "qual meu plano"}, + _result("consultar_plano", {"plano": "Controle", "internet_gb": 50, "status": "ATIVO"}), + agent_label="ProductAgent", + ) + assert answer == "[ProductAgent] Seu plano é Controle, com 50 GB e status ATIVO." + + +def test_no_declared_response_keeps_legacy_fallback(): + rt = _Runtime({}) + answer = rt.build_direct_mcp_answer( + {"user_text": "qual meu plano"}, + _result("consultar_plano", {"plano": "Controle", "internet_gb": 50, "status": "ATIVO"}), + agent_label="ProductAgent", + ) + assert answer == "[ProductAgent] Seu plano é Controle, com 50 GB e status ATIVO." diff --git a/tests/test_mcp_parameter_extraction_runtime.py b/tests/test_mcp_parameter_extraction_runtime.py index a70c57e..86b8618 100644 --- a/tests/test_mcp_parameter_extraction_runtime.py +++ b/tests/test_mcp_parameter_extraction_runtime.py @@ -59,3 +59,54 @@ async def test_runtime_extracts_order_id_from_current_message(): ) assert result["order_id"] == "123" assert result["contract_key"] == "3000131180" + +class _ContestExtractLLM: + async def ainvoke(self, messages, **kwargs): + prompt = messages[0]["content"] + if "Campo: subject" in prompt: + return {"content": '{"subject": "TIM CTRL Redes Sociais 8.0"}'} + if "Campo: valor" in prompt: + return {"content": '{"valor": null}'} + return {"content": '{}'} + + +class _ContestExtractRouter: + def parameter_extract_rules(self, tool_name): + return { + "subject": { + "from": "message", + "strategy": "llm", + "type": "string", + "description": "Extraia o item contestado.", + }, + "valor": { + "from": "message", + "strategy": "llm", + "type": "number", + "description": "Extraia o valor explicitamente informado.", + }, + } + + +class _ContestExtractRuntime(AgentRuntimeMixin): + def __init__(self): + self.tool_router = _ContestExtractRouter() + self.llm = _ContestExtractLLM() + + +@pytest.mark.asyncio +async def test_new_transaction_current_message_overrides_stale_subject_from_context(): + runtime = _ContestExtractRuntime() + result = await runtime._extract_mcp_parameters( + "contestar_cobranca", + {"subject": "TIM Fashion Mensal", "valor": 10.0}, + { + "user_text": "nao contratei TIM CTRL Redes Sociais 8.0", + "sanitized_input": "nao contratei TIM CTRL Redes Sociais 8.0", + }, + overwrite_from_message=True, + ) + assert result["subject"] == "TIM CTRL Redes Sociais 8.0" + # null extraction does not destroy a pre-existing value; transaction start + # sanitization is about explicit current-message evidence, not blind clearing. + assert result["valor"] == 10.0 diff --git a/tests/test_transactional_tool_flow.py b/tests/test_transactional_tool_flow.py index f292bec..e2597ec 100644 --- a/tests/test_transactional_tool_flow.py +++ b/tests/test_transactional_tool_flow.py @@ -88,3 +88,202 @@ async def test_transaction_waits_then_executes_after_confirmation(): assert runtime.calls[-1][0] == "solicitar_devolucao" assert runtime.calls[-1][1]["confirmed"] is True assert second[-1]["ok"] is True + +class _ContestPolicyRouter: + def __init__(self): + from types import SimpleNamespace + self.registry = SimpleNamespace( + tools={"contestar_cobranca": object()}, + get_tool=lambda name: SimpleNamespace(selection_keywords=["contestar", "não contratei", "nao contratei"]), + ) + + def resolve_execution_policy(self, tool_name, arguments=None): + return { + "operation_type": "transactional", + "require_confirmation": True, + "requires": ["subject", "valor"], + "policy_source": "test", + } + + def validate_execution_policy(self, tool_name, arguments=None): + policy = self.resolve_execution_policy(tool_name, arguments) + return True, None, policy + + +class _ContestRuntime(AgentRuntimeMixin): + def __init__(self): + self.tool_router = _ContestPolicyRouter() + self.calls = [] + + async def _call_mcp_tool(self, tool_name, arguments, state): + self.calls.append((tool_name, dict(arguments))) + return {"ok": True, "tool_name": tool_name, "result": {"status": "OPENED"}} + + +@pytest.mark.asyncio +async def test_collecting_parameters_does_not_replace_collected_subject_with_stale_context(): + """A later value-only turn must not replace an already collected subject. + + Regression reproduced from Contas: subject was collected as TIM CTRL, while + context/tool_arguments still exposed TIM Fashion from another transaction. + When the user supplied only R$ 71,99, the stale context used to overwrite + the collected subject before confirmation. + """ + runtime = _ContestRuntime() + state = { + "user_text": "R$ 71,99", + "sanitized_input": "R$ 71,99", + "route": "contestacao_agent", + "intent": "state:COLLECTING_CONTESTACAO_PARAMETERS", + "transaction_status": "COLLECTING_PARAMETERS", + "selected_tool_call": { + "tool_name": "contestar_cobranca", + "arguments": { + "subject": "TIM CTRL Redes Sociais 8.0", + "motivo": "não contratei", + }, + }, + # Simulates stale contextual arguments left by another action/session turn. + "context": { + "tool_arguments": { + "subject": "TIM Fashion Mensal", + "valor": 71.99, + } + }, + } + + result = await runtime.execute_tools_for_intent(state, tools=[]) + + assert result[-1]["transaction_status"] == "AWAITING_CONFIRMATION" + assert state["pending_tool_call"]["arguments"]["subject"] == "TIM CTRL Redes Sociais 8.0" + assert state["pending_tool_call"]["arguments"]["valor"] == 71.99 + assert state["pending_tool_call"]["arguments"]["motivo"] == "não contratei" + assert state["pending_tool_call"]["arguments"]["query"] == "R$ 71,99" + assert runtime.calls == [] + +class _InitialContestLLM: + async def ainvoke(self, messages, **kwargs): + prompt = messages[0]["content"] + if "Campo: subject" in prompt: + return {"content": '{"subject": "TIM CTRL Redes Sociais 8.0"}'} + if "Campo: valor" in prompt: + return {"content": '{"valor": null}'} + if "Campo: motivo" in prompt: + return {"content": '{"motivo": "não contratei"}'} + return {"content": '{}'} + + +class _InitialContestRouter(_ContestPolicyRouter): + def resolve_execution_policy(self, tool_name, arguments=None): + return { + "operation_type": "transactional", + "require_confirmation": True, + "requires": ["subject"], + "policy_source": "test", + } + + def parameter_extract_rules(self, tool_name): + return { + "subject": {"from": "message", "strategy": "llm", "type": "string", "description": "item"}, + "valor": {"from": "message", "strategy": "llm", "type": "number", "description": "valor"}, + "motivo": {"from": "message", "strategy": "llm", "type": "string", "description": "motivo"}, + } + + +class _InitialContestRuntime(AgentRuntimeMixin): + def __init__(self): + self.tool_router = _InitialContestRouter() + self.llm = _InitialContestLLM() + self.calls = [] + + async def _call_mcp_tool(self, tool_name, arguments, state): + self.calls.append((tool_name, dict(arguments))) + return {"ok": True, "tool_name": tool_name, "result": {"status": "OPENED"}} + + +@pytest.mark.asyncio +async def test_new_contestation_does_not_inherit_subject_or_value_from_previous_transaction(): + runtime = _InitialContestRuntime() + state = { + "user_text": "nao contratei TIM CTRL Redes Sociais 8.0", + "sanitized_input": "nao contratei TIM CTRL Redes Sociais 8.0", + "mcp_tools": ["contestar_cobranca"], + "route": "contestacao_agent", + "intent": "contas_contestation", + "context": { + "tool_arguments": { + "subject": "TIM Fashion Mensal", + "valor": 10.0, + "motivo": "contestação antiga", + } + }, + } + + result = await runtime.execute_tools_for_intent(state) + pending = state["pending_tool_call"]["arguments"] + assert result[-1]["transaction_status"] == "AWAITING_CONFIRMATION" + assert pending["subject"] == "TIM CTRL Redes Sociais 8.0" + assert pending["motivo"] == "não contratei" + assert "valor" not in pending + assert runtime.calls == [] + +@pytest.mark.asyncio +async def test_closed_transaction_is_not_operational_context_for_next_turn(): + runtime = _InitialContestRuntime() + state = { + "user_text": "nao contratei TIM CTRL Redes Sociais 8.0", + "sanitized_input": "nao contratei TIM CTRL Redes Sociais 8.0", + "mcp_tools": ["contestar_cobranca"], + "route": "contestacao_agent", + "intent": "contas_contestation", + # Historical/closed transaction must never feed the new one. + "transaction_status": "COMPLETED", + "selected_tool_call": { + "tool_name": "cancelar_vas_avulso", + "arguments": {"subject": "TIM Fashion Mensal", "valor": 10.0}, + }, + "pending_tool_call": {}, + "context": { + "tool_arguments": { + "subject": "TIM Fashion Mensal", + "valor": 10.0, + } + }, + } + + result = await runtime.execute_tools_for_intent(state) + + assert result[-1]["transaction_status"] == "AWAITING_CONFIRMATION" + assert state["active_transaction"]["tool_name"] == "contestar_cobranca" + assert state["active_transaction"]["arguments"]["subject"] == "TIM CTRL Redes Sociais 8.0" + assert state["pending_tool_call"]["tool_name"] == "contestar_cobranca" + assert state["pending_tool_call"]["arguments"]["subject"] == "TIM CTRL Redes Sociais 8.0" + assert state["last_transaction"]["tool_name"] == "cancelar_vas_avulso" + assert state["last_transaction"]["arguments"]["subject"] == "TIM Fashion Mensal" + + +@pytest.mark.asyncio +async def test_terminal_confirmation_closes_active_transaction_and_clears_latches(): + runtime = _Runtime() + state = { + "user_text": "Quero devolver o pedido 123 porque me arrependi", + "sanitized_input": "Quero devolver o pedido 123 porque me arrependi", + "mcp_tools": ["consultar_pedido", "solicitar_devolucao"], + "route": "support_agent", + "intent": "retail_support_exchange_return", + } + await runtime.execute_tools_for_intent(state) + assert state["active_transaction"]["status"] == "AWAITING_CONFIRMATION" + + state["user_text"] = "sim" + state["sanitized_input"] = "sim" + await runtime.execute_tools_for_intent(state) + + assert state["transaction_status"] == "COMPLETED" + assert state["active_transaction"] is None + assert state["selected_tool_call"] == {} + assert state["pending_tool_call"] == {} + assert state["missing_parameters"] == [] + assert state["next_state"] is None + assert state["last_transaction"]["tool_name"] == "solicitar_devolucao" + assert state["last_transaction"]["status"] == "COMPLETED" diff --git a/tests/unit/__pycache__/test_langgraph_checkpoint_saver.cpython-313-pytest-9.0.2.pyc b/tests/unit/__pycache__/test_langgraph_checkpoint_saver.cpython-313-pytest-9.0.2.pyc new file mode 100644 index 0000000..3fdd435 Binary files /dev/null and b/tests/unit/__pycache__/test_langgraph_checkpoint_saver.cpython-313-pytest-9.0.2.pyc differ diff --git a/tests/unit/__pycache__/test_resilient_checkpointer.cpython-313-pytest-9.0.2.pyc b/tests/unit/__pycache__/test_resilient_checkpointer.cpython-313-pytest-9.0.2.pyc new file mode 100644 index 0000000..8453472 Binary files /dev/null and b/tests/unit/__pycache__/test_resilient_checkpointer.cpython-313-pytest-9.0.2.pyc differ