mirror of
https://github.com/hoshikawa2/agent_platform_oci.git
synced 2026-09-07 18:23:46 +00:00
bugfixes: transaction parameter collector, generic formatting messages, guardrails, prompts. Testing contas
This commit is contained in:
@@ -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"]
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .tool_renderers import register_tool_renderers
|
||||
|
||||
__all__ = ["register_tool_renderers"]
|
||||
Binary file not shown.
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .tool_renderers import register_tool_renderers
|
||||
|
||||
__all__ = ["register_tool_renderers"]
|
||||
Binary file not shown.
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .tool_renderers import register_tool_renderers
|
||||
|
||||
__all__ = ["register_tool_renderers"]
|
||||
Binary file not shown.
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .tool_renderers import register_tool_renderers
|
||||
|
||||
__all__ = ["register_tool_renderers"]
|
||||
Binary file not shown.
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .tool_renderers import register_tool_renderers
|
||||
|
||||
__all__ = ["register_tool_renderers"]
|
||||
Binary file not shown.
@@ -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)
|
||||
@@ -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
|
||||
|
||||
165
docs/features/01_authentication.md
Normal file
165
docs/features/01_authentication.md
Normal file
@@ -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/`
|
||||
183
docs/features/02_deterministic_transactional_workflow.md
Normal file
183
docs/features/02_deterministic_transactional_workflow.md
Normal file
@@ -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/`
|
||||
157
docs/features/03_domain_requested_llm_composition.md
Normal file
157
docs/features/03_domain_requested_llm_composition.md
Normal file
@@ -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/`
|
||||
167
docs/features/04_domain_requested_rag.md
Normal file
167
docs/features/04_domain_requested_rag.md
Normal file
@@ -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/`
|
||||
167
docs/features/05_long_term_memory.md
Normal file
167
docs/features/05_long_term_memory.md
Normal file
@@ -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/`
|
||||
163
docs/features/06_offline_workflow_regression.md
Normal file
163
docs/features/06_offline_workflow_regression.md
Normal file
@@ -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/`
|
||||
165
docs/features/07_pause_resume_workflow.md
Normal file
165
docs/features/07_pause_resume_workflow.md
Normal file
@@ -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/`
|
||||
151
docs/features/08_route_stickiness.md
Normal file
151
docs/features/08_route_stickiness.md
Normal file
@@ -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/`
|
||||
153
docs/features/09_voice_interruption_replay.md
Normal file
153
docs/features/09_voice_interruption_replay.md
Normal file
@@ -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/`
|
||||
167
docs/features/10_workflow_error_recovery.md
Normal file
167
docs/features/10_workflow_error_recovery.md
Normal file
@@ -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/`
|
||||
169
docs/features/11_clarification.md
Normal file
169
docs/features/11_clarification.md
Normal file
@@ -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/`
|
||||
163
docs/features/12_durable_idempotency.md
Normal file
163
docs/features/12_durable_idempotency.md
Normal file
@@ -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/`
|
||||
157
docs/features/13_dynamic_transaction_states.md
Normal file
157
docs/features/13_dynamic_transaction_states.md
Normal file
@@ -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_<PREFIX>_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_<PREFIX>_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/`
|
||||
159
docs/features/14_post_finalization_replay.md
Normal file
159
docs/features/14_post_finalization_replay.md
Normal file
@@ -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/`
|
||||
171
docs/features/15_retrieval_tool_guardrails.md
Normal file
171
docs/features/15_retrieval_tool_guardrails.md
Normal file
@@ -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/`
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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(
|
||||
(
|
||||
matching_candidates = [
|
||||
candidate
|
||||
for candidate in candidates
|
||||
if _is_same_plan_name(candidate.get("name", ""), item_name)
|
||||
),
|
||||
None,
|
||||
]
|
||||
# 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 = (
|
||||
|
||||
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user