mirror of
https://github.com/hoshikawa2/agent_platform_oci.git
synced 2026-11-06 11:24:13 +00:00
Compare commits
70 Commits
e517f5e6a3
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 01b456fdc5 | |||
| f035580c21 | |||
| ddd9d9a0d4 | |||
|
|
0d986e025a | ||
|
|
ccf509dd21 | ||
| 4ca6c8a274 | |||
| 6a511b9005 | |||
| 1916e49c45 | |||
| b2d5cc09b2 | |||
| e3bd48cf4b | |||
|
|
1942f78df8 | ||
|
|
b4a1a43eee | ||
|
|
6c5fb33c08 | ||
| 20a891b1d7 | |||
| 42e1720d1c | |||
| 5149fb9a5e | |||
| a03c6fd325 | |||
| d986b9751f | |||
| 50e7db4666 | |||
| 63810ab5c7 | |||
| edf46f9429 | |||
| 6f859a991a | |||
| db16d478ba | |||
| 3cb970d8ab | |||
| b7d68317ca | |||
| a2fe158d62 | |||
| e6bc243cf7 | |||
| c9eb71af32 | |||
| ab0aa5bc11 | |||
| a2c7a946c8 | |||
| a5f24dac3f | |||
| d535ec2a16 | |||
| f97714ac40 | |||
| d5fd41a40c | |||
| dd40662776 | |||
| cd07ad079c | |||
| 39ff42806c | |||
| a9bb79d59a | |||
|
|
2e5ec5cace | ||
|
|
b24df5abdc | ||
| ca2dceda4e | |||
| ea6d278ef8 | |||
| 75e8bec89c | |||
| 04493c3364 | |||
| 7a749cb93b | |||
| 535f7c0e1a | |||
| e8c7b591a8 | |||
| c120b96bf8 | |||
|
|
2a9d9001b0 | ||
| 5a06eeef24 | |||
| d5a671cf57 | |||
|
|
279489efb4 | ||
|
|
4717ebedb3 | ||
| 330b43c36f | |||
| c2e511f6ec | |||
| b0f5633132 | |||
| f43cc65809 | |||
| d4d16889f7 | |||
| 479ceb9b7a | |||
| 9402e1d70c | |||
| a30ca76433 | |||
| fde9465a0e | |||
| 66a67cb503 | |||
| adfe585807 | |||
| 84513764cf | |||
| f128d8870c | |||
| 5de39f274d | |||
| e7bba0ec0b | |||
| 59edc85b26 | |||
| a9e4fa042a |
32
.env.example
32
.env.example
@@ -207,3 +207,35 @@ 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
|
||||
|
||||
# Optional agent/deployment observability contract mapping.
|
||||
# Keep disabled in the generic framework; agents may enable their own YAML mapping.
|
||||
OBSERVABILITY_CODE_MAPPING_ENABLED=false
|
||||
OBSERVABILITY_CODE_MAPPING_PATH=
|
||||
|
||||
###############################################################################
|
||||
# RAG provider selection (mutually exclusive at runtime)
|
||||
###############################################################################
|
||||
# standard = RAG original do agent_framework_oci (default, backward compatible)
|
||||
# kbdb = KBDB enterprise via PKG_KB_SERVING.SEARCH_KNOWLEDGE_BASE
|
||||
RAG_PROVIDER=standard
|
||||
|
||||
# Somente usados quando RAG_PROVIDER=kbdb. Se vazios, credenciais caem para ADB_*.
|
||||
KBDB_DB_USER=
|
||||
KBDB_DB_PASSWORD=
|
||||
KBDB_DB_DSN=
|
||||
KBDB_DB_WALLET_LOCATION=
|
||||
KBDB_DB_WALLET_PASSWORD=
|
||||
KBDB_SEARCH_TYPE=hybrid
|
||||
KBDB_NODE_EXPANSION=true
|
||||
KBDB_NODE_MAX_RELATED=8
|
||||
KBDB_GRAPH_CROSS_REF=false
|
||||
KBDB_MAX_CROSS_REF_HOPS=1
|
||||
KBDB_DOCUMENT_TYPE=customer_safe
|
||||
KBDB_METADATA_JSON=
|
||||
KBDB_MIN_SCORE=
|
||||
|
||||
# Framework vocabulary and standard responses: pt-BR | en
|
||||
AGENT_LOCALE=pt-BR
|
||||
# Optional directory containing complete pt-BR.json and en.json catalogs.
|
||||
# AGENT_LOCALES_DIR=./config/locales
|
||||
|
||||
56
.env.jev.example
Normal file
56
.env.jev.example
Normal file
@@ -0,0 +1,56 @@
|
||||
# Copy these settings into the .env loaded by the running backend/gateway.
|
||||
# Existing feature flags (ENABLE_LLM_ROUTER, ENABLE_ROUTE_STICKINESS, etc.) still apply.
|
||||
# Global default; each individual setting below takes precedence.
|
||||
DECISION_PROVIDER=current
|
||||
DECISION_FALLBACK_TO_CURRENT=true
|
||||
JEV_ENDPOINT=https://api.typesafe.ai/v1/systemone
|
||||
AI_GATEWAY_API_KEY=
|
||||
JEV_MODEL=jev-latest
|
||||
JEV_TIMEOUT_SECONDS=15
|
||||
JEV_MIN_CONFIDENCE=0.7
|
||||
JEV_DECISION_DIAGNOSTICS=true
|
||||
|
||||
# All options: current | jev. No existing behavior changes by default.
|
||||
DECISION_ROUTE_CONTINUITY_PROVIDER=current
|
||||
DECISION_ROUTER_PROVIDER=current
|
||||
DECISION_WORKFLOW_EXPECTED_INPUT_PROVIDER=current
|
||||
DECISION_WORKFLOW_REENTRY_PROVIDER=current
|
||||
DECISION_TRANSACTION_CONFIRMATION_PROVIDER=current
|
||||
DECISION_TRANSACTION_PARAMETER_RELEVANCE_PROVIDER=current
|
||||
DECISION_TRANSACTION_INTENT_SHIFT_PROVIDER=current
|
||||
DECISION_MULTI_INTENT_PROVIDER=current
|
||||
DECISION_TRANSACTION_PARAMETER_RECONCILIATION_PROVIDER=current
|
||||
DECISION_GLOBAL_SUPERVISOR_PROVIDER=current
|
||||
DECISION_PROCESSING_INTERRUPTION_PROVIDER=current
|
||||
|
||||
# Generic LLM guardrail and output supervisor (existing profile names).
|
||||
DECISION_GUARDRAIL_GUARDRAIL_PROVIDER=current
|
||||
DECISION_GUARDRAIL_GRL_PROVIDER=current
|
||||
# Calibrated guardrails, independently by task.
|
||||
DECISION_GUARDRAIL_PINJ_PROVIDER=current
|
||||
DECISION_GUARDRAIL_COER_PROVIDER=current
|
||||
DECISION_GUARDRAIL_TOX_PROVIDER=current
|
||||
DECISION_GUARDRAIL_REVPREC_PROVIDER=current
|
||||
DECISION_GUARDRAIL_AOFERTA_PROVIDER=current
|
||||
DECISION_GUARDRAIL_OOS_PROVIDER=current
|
||||
DECISION_GUARDRAIL_FRASEOLOGIA_PROVIDER=current
|
||||
DECISION_GUARDRAIL_RAGSEC_PROVIDER=current
|
||||
DECISION_GUARDRAIL_DLEX_IN_PROVIDER=current
|
||||
DECISION_GUARDRAIL_DLEX_OUT_PROVIDER=current
|
||||
|
||||
# Calibrated judges, by task; generic judges, by configured name.
|
||||
DECISION_JUDGE_CSI_PROVIDER=current
|
||||
DECISION_JUDGE_VCTN_PROVIDER=current
|
||||
DECISION_JUDGE_ALUC_PROVIDER=current
|
||||
DECISION_JUDGE_RQLT_PROVIDER=current
|
||||
DECISION_JUDGE_LLM_JUDGE_PROVIDER=current
|
||||
|
||||
# Optional threshold per point, independent from the provider choice.
|
||||
# DECISION_ROUTE_CONTINUITY_MIN_CONFIDENCE=0.90
|
||||
# DECISION_TRANSACTION_CONFIRMATION_MIN_CONFIDENCE=0.95
|
||||
|
||||
# Named calibrated judge overrides its task group (optional).
|
||||
# DECISION_JUDGE_GROUNDEDNESS_PROVIDER=jev
|
||||
# DECISION_JUDGE_RESPONSE_QUALITY_PROVIDER=current
|
||||
# Optional individual guardrail recheck override.
|
||||
# DECISION_GUARDRAIL_DLEX_OUT_PROTOCOL_AUTHORIZATION_RECHECK_PROVIDER=jev
|
||||
139
.idea/workspace.xml
generated
139
.idea/workspace.xml
generated
@@ -4,7 +4,9 @@
|
||||
<option name="autoReloadType" value="SELECTIVE" />
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="30a0e1d8-9d7d-469b-b241-f300911cee8a" name="Changes" comment="Ajustes na documentação e remanejamento dos folders" />
|
||||
<list default="true" id="30a0e1d8-9d7d-469b-b241-f300911cee8a" name="Changes" comment="Ajustes na documentação e remanejamento dos folders">
|
||||
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
||||
</list>
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
@@ -45,31 +47,113 @@
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent"><![CDATA[{
|
||||
"keyToString": {
|
||||
"ASKED_SHARE_PROJECT_CONFIGURATION_FILES": "true",
|
||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"RunOnceActivity.git.unshallow": "true",
|
||||
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
|
||||
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
|
||||
"git-widget-placeholder": "master",
|
||||
"kotlin-language-version-configured": "true",
|
||||
"last_opened_file_path": "D:/Dropbox/ORACLE/TIM/FY27/Wave_2/Ajuste para manter o agente atual ou voltar ao roteamento/agent_framework_oci",
|
||||
"node.js.detected.package.eslint": "true",
|
||||
"node.js.detected.package.tslint": "true",
|
||||
"node.js.selected.package.eslint": "(autodetect)",
|
||||
"node.js.selected.package.tslint": "(autodetect)",
|
||||
"nodejs_package_manager_path": "npm",
|
||||
"settings.editor.selected.configurable": "configurable.group.appearance",
|
||||
"vue.rearranger.settings.migration": "true"
|
||||
<component name="PropertiesComponent">{
|
||||
"keyToString": {
|
||||
"ASKED_SHARE_PROJECT_CONFIGURATION_FILES": "true",
|
||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager": "true",
|
||||
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
||||
"RunOnceActivity.git.unshallow": "true",
|
||||
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
|
||||
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
|
||||
"Shell Script.agent_frontend.executor": "Run",
|
||||
"Shell Script.agent_template_backend.executor": "Run",
|
||||
"Shell Script.mcp_gateway.executor": "Run",
|
||||
"Shell Script.mcp_server.executor": "Run",
|
||||
"git-widget-placeholder": "main",
|
||||
"kotlin-language-version-configured": "true",
|
||||
"last_opened_file_path": "D:/Dropbox/ORACLE/TIM/FY27/Commits/agent_platform_oci",
|
||||
"node.js.detected.package.eslint": "true",
|
||||
"node.js.detected.package.tslint": "true",
|
||||
"node.js.selected.package.eslint": "(autodetect)",
|
||||
"node.js.selected.package.tslint": "(autodetect)",
|
||||
"nodejs_package_manager_path": "npm",
|
||||
"project.structure.last.edited": "Project",
|
||||
"project.structure.proportion": "0.15",
|
||||
"project.structure.side.proportion": "0.2",
|
||||
"settings.editor.selected.configurable": "advanced.settings",
|
||||
"vue.rearranger.settings.migration": "true"
|
||||
}
|
||||
}]]></component>
|
||||
}</component>
|
||||
<component name="RecentsManager">
|
||||
<key name="CopyFile.RECENT_KEYS">
|
||||
<recent name="C:\Asus_Projects\kbdb\agent_framework_oci\templates\agent_template_backend" />
|
||||
</key>
|
||||
</component>
|
||||
<component name="RunManager" selected="Shell Script.agent_template_backend">
|
||||
<configuration name="agent_frontend" type="ShConfigurationType">
|
||||
<option name="SCRIPT_TEXT" value="wsl bash -lc "source .venv/bin/activate && cd apps/agent_frontend && python -m http.server 5173"" />
|
||||
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||
<option name="SCRIPT_PATH" value="" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||
<option name="INTERPRETER_PATH" value="powershell.exe" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||
<option name="EXECUTE_SCRIPT_FILE" value="false" />
|
||||
<envs />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="agent_template_backend" type="ShConfigurationType">
|
||||
<option name="SCRIPT_TEXT" value="wsl bash -lc "source .venv/bin/activate && cd templates/agent_template_backend && python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload"" />
|
||||
<option name="INDEPENDENT_SCRIPT_PATH" value="false" />
|
||||
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/templates/agent_template_backend/app" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="false" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||
<option name="INTERPRETER_PATH" value="powershell.exe" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||
<option name="EXECUTE_SCRIPT_FILE" value="false" />
|
||||
<envs />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="mcp_gateway" type="ShConfigurationType">
|
||||
<option name="SCRIPT_TEXT" value="wsl bash -lc "source .venv/bin/activate && cd scripts && bash run_mcp_gateway.sh"" />
|
||||
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||
<option name="SCRIPT_PATH" value="" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||
<option name="INTERPRETER_PATH" value="powershell.exe" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||
<option name="EXECUTE_SCRIPT_FILE" value="false" />
|
||||
<envs />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="mcp_server" type="ShConfigurationType">
|
||||
<option name="SCRIPT_TEXT" value="wsl bash -lc "source .venv/bin/activate && cd scripts && bash run_mcp_servers.sh"" />
|
||||
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||
<option name="SCRIPT_PATH" value="" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||
<option name="INTERPRETER_PATH" value="powershell.exe" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||
<option name="EXECUTE_SCRIPT_FILE" value="false" />
|
||||
<envs />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<list>
|
||||
<item itemvalue="Shell Script.agent_template_backend" />
|
||||
<item itemvalue="Shell Script.mcp_gateway" />
|
||||
<item itemvalue="Shell Script.mcp_server" />
|
||||
<item itemvalue="Shell Script.agent_frontend" />
|
||||
</list>
|
||||
</component>
|
||||
<component name="SharedIndexes">
|
||||
<attachedChunks>
|
||||
<set>
|
||||
<option value="bundled-jdk-9823dce3aa75-fbdcb00ec9e3-intellij.indexing.shared.core-IU-251.29188.36" />
|
||||
<option value="bundled-js-predefined-d6986cc7102b-09060db00ec0-JavaScript-IU-251.29188.36" />
|
||||
<option value="bundled-jdk-30f59d01ecdd-cffe25b9f5b3-intellij.indexing.shared.core-IU-253.28294.334" />
|
||||
<option value="bundled-js-predefined-d6986cc7102b-c7e53b3be11b-JavaScript-IU-253.28294.334" />
|
||||
</set>
|
||||
</attachedChunks>
|
||||
</component>
|
||||
@@ -89,9 +173,14 @@
|
||||
<workItem from="1785245181314" duration="79000" />
|
||||
<workItem from="1785245608367" duration="670000" />
|
||||
<workItem from="1785326458404" duration="86000" />
|
||||
<workItem from="1785414225783" duration="148000" />
|
||||
<workItem from="1785414447653" duration="704000" />
|
||||
<workItem from="1785630146329" duration="316000" />
|
||||
<workItem from="1785405876905" duration="1300000" />
|
||||
<workItem from="1785409583147" duration="1561000" />
|
||||
<workItem from="1785452072692" duration="784000" />
|
||||
<workItem from="1785453511270" duration="1006000" />
|
||||
<workItem from="1792665278602" duration="734000" />
|
||||
<workItem from="1793193595355" duration="436000" />
|
||||
<workItem from="1793194079956" duration="5443000" />
|
||||
<workItem from="1793271962068" duration="758000" />
|
||||
</task>
|
||||
<task id="LOCAL-00001" summary="Ajustes na documentação e remanejamento dos folders">
|
||||
<option name="closed" value="true" />
|
||||
|
||||
57
ATUALIZACAO_TESTES.md
Normal file
57
ATUALIZACAO_TESTES.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# Atualização dos testes após mudanças de contrato
|
||||
|
||||
Esta revisão mantém os quatro nomes de arquivo e a quantidade de testes. Oito
|
||||
testes foram atualizados, sem `skip`, `xfail` ou alterações no runtime para
|
||||
acomodar as expectativas antigas. Os nomes de sete funções foram ajustados para
|
||||
descrever o comportamento atual. Os comentários nos testes registram o histórico.
|
||||
|
||||
## Histórico verificado no Git do pacote original
|
||||
|
||||
- `1711575`, 2026-09-07, `bugfix reconciliation extractor`: removeu
|
||||
`field_evidence_views`, a construção de candidatos estruturais e partes da
|
||||
reconciliação anterior.
|
||||
- `82636ec`, 2026-09-08, `bugfix: extractor cases 8 and 16`: consolidou a coleta
|
||||
de parâmetros no `single_extractor`, com contexto e pré-validação autoritativa.
|
||||
- `36f9781`, 2026-09-18, `new feature: transaction interruption for same intent replacement`:
|
||||
também adicionou sanitização e reavaliação ao DLEX_OUT e passou a usar
|
||||
`sanitized_text` somente quando há um texto substituto.
|
||||
|
||||
## O que os testes passam a verificar
|
||||
|
||||
| Arquivo | Contrato coberto |
|
||||
|---|---|
|
||||
| `tests/test_transactional_tool_flow.py` | Após `NEEDS_PARAMETER`, o fluxo aguarda nova informação; a nova validação ocorre no turno seguinte e a operação não executa antes da confirmação. |
|
||||
| `tests/test_transaction_parameter_llm_precedence.py` | O reconciliador recebe schema e contexto, aceita o campo resolvido e respeita `preserve` sem sobrescrever o valor conhecido. |
|
||||
| `tests/test_transaction_explicit_abandonment_and_structural_candidate.py` | Campo indefinido continua pendente; extração contextual bem-sucedida passa pela validação antes da confirmação; `clear` não inventa um valor nem apaga os demais campos. |
|
||||
| `tests/test_dlex_out_expected_protocol_authorization.py` | Protocolo autorizado não exige substituição do texto; credencial é removida e a resposta é reavaliada; outra violação mantém o bloqueio. |
|
||||
|
||||
Os simuladores deixaram de depender de frases específicas do prompt, como
|
||||
“FOCO PRINCIPAL DA RECONCILIAÇÃO”. Eles devolvem saídas compatíveis com o contrato
|
||||
da chamada. A identificação semântica por um modelo real não é comprovada por
|
||||
esses testes unitários: os testes verificam como o framework utiliza suas saídas.
|
||||
|
||||
## Verificações realizadas
|
||||
|
||||
- 160 testes selecionados aprovados no pacote atualizado, incluindo os 41 testes
|
||||
de localização e os quatro arquivos desta revisão.
|
||||
- Os 66 testes dos quatro arquivos também foram executados usando a biblioteca
|
||||
original do ZIP: todos aprovados. Assim, a atualização dos testes não depende
|
||||
da alteração de idiomas para passar.
|
||||
- Contagem mantida por arquivo: 31, 13, 17 e 5 testes, respectivamente.
|
||||
- Nenhuma chamada a OCI, modelos remotos ou ferramentas reais de negócio.
|
||||
- Esta revisão não afirma que a suíte completa do repositório foi executada.
|
||||
|
||||
## Aplicar ao repositório
|
||||
|
||||
O ZIP completo inclui a localização em `pt-BR` e `en` entregue anteriormente e
|
||||
esta revisão dos testes. Copie o conteúdo da pasta `agent_platform_oci` para a
|
||||
raiz do repositório, preservando a pasta `.git` que já existe no seu checkout.
|
||||
|
||||
Se a localização já estiver aplicada, o ZIP complementar de testes contém apenas
|
||||
os quatro arquivos atualizados e esta documentação. Não é preciso usar ambos.
|
||||
|
||||
Sugestão de mensagem de commit para a revisão dos testes:
|
||||
|
||||
```text
|
||||
test: align transaction and DLEX_OUT tests with current contracts
|
||||
```
|
||||
64
Documentacao/IMPLEMENTACAO_WORKFLOWS_TRANSACIONAIS.md
Normal file
64
Documentacao/IMPLEMENTACAO_WORKFLOWS_TRANSACIONAIS.md
Normal file
@@ -0,0 +1,64 @@
|
||||
# Implementação — workflows transacionais determinísticos
|
||||
|
||||
## Entrega
|
||||
|
||||
Foi adicionada ao `agent_framework_oci` uma capacidade opcional para executar transações multi-etapas como workflows determinísticos compilados em LangGraph.
|
||||
|
||||
### Módulo novo
|
||||
|
||||
`libs/agent_framework/src/agent_framework/workflows/`
|
||||
|
||||
- `models.py`: contratos Pydantic e validação estrutural;
|
||||
- `repository.py`: resolução de versão ativa e leitura de YAML imutável;
|
||||
- `registry.py`: registro desacoplado de actions sync/async;
|
||||
- `runtime.py`: compilação, cache e execução do StateGraph;
|
||||
- `tool_executor.py`: integração com a política da tool;
|
||||
- `__init__.py`: API pública.
|
||||
|
||||
### Política expandida
|
||||
|
||||
`ToolPolicy` agora aceita:
|
||||
|
||||
```yaml
|
||||
execution:
|
||||
mode: direct_tool | workflow | agent
|
||||
workflow: nome_do_workflow
|
||||
version: active | 1
|
||||
```
|
||||
|
||||
O default permanece `direct_tool`, preservando compatibilidade.
|
||||
|
||||
### Configuração
|
||||
|
||||
Foram adicionados:
|
||||
|
||||
- `ENABLE_TRANSACTIONAL_WORKFLOWS=false`;
|
||||
- `WORKFLOWS_PATH=./workflows`.
|
||||
|
||||
### Template
|
||||
|
||||
Inclui um exemplo completo de devolução de pedido com:
|
||||
|
||||
- confirmação e campos obrigatórios pela política;
|
||||
- workflow YAML versionado;
|
||||
- actions de domínio no backend;
|
||||
- bifurcação determinística baseada no resultado da validação.
|
||||
|
||||
## Validação realizada
|
||||
|
||||
- `tests/unit/test_tool_policies.py`: 4 testes aprovados;
|
||||
- compilação Python de framework, template e novos testes: aprovada;
|
||||
- o teste funcional novo do LangGraph foi criado, mas não pôde ser executado neste container porque `langgraph` não está instalado no ambiente. A dependência já está declarada no `pyproject.toml` do framework.
|
||||
|
||||
## Escopo e segurança
|
||||
|
||||
Esta entrega cria o motor e a integração de política. Para operações críticas em produção ainda é necessário conectar:
|
||||
|
||||
- execution store persistente;
|
||||
- idempotência de negócio nas actions/APIs;
|
||||
- autorização por escopo;
|
||||
- telemetria IC/NOC específica de workflow;
|
||||
- compensação/Saga quando aplicável;
|
||||
- estratégia corporativa de timeout e retry.
|
||||
|
||||
Esses itens foram explicitamente documentados para evitar a falsa impressão de que retry por si só garante segurança transacional.
|
||||
987
Documentacao/Implementando_Basic_Auth.md
Normal file
987
Documentacao/Implementando_Basic_Auth.md
Normal file
@@ -0,0 +1,987 @@
|
||||
# Implementando Basic Auth
|
||||
|
||||
Para validar **todo o circuito com Basic Auth**, você precisa configurar três relações distintas:
|
||||
|
||||
```text
|
||||
Cliente de teste
|
||||
└─ Basic Auth A ─► Agent Gateway :8010
|
||||
└─ Basic Auth B ─► Agent Backend :8000
|
||||
└─ Basic Auth C ─► MCP Gateway :8300
|
||||
```
|
||||
|
||||
Há um detalhe importante: no pacote atual, a autenticação Basic já funciona para chamadas **de entrada**, mas os clientes internos ainda não enviam Basic Auth:
|
||||
|
||||
* `Agent Gateway → Agent Backend` não envia credencial;
|
||||
* `Agent Backend → MCP Gateway` envia apenas Bearer Token.
|
||||
|
||||
Portanto, para testar o circuito inteiro com Basic Auth, faça os dois pequenos ajustes de código descritos abaixo.
|
||||
|
||||
---
|
||||
|
||||
# 1. Preparar o ambiente
|
||||
|
||||
Considere que o ZIP foi extraído em:
|
||||
|
||||
```bash
|
||||
cd agent_framework_oci_authentication_v2_1
|
||||
```
|
||||
|
||||
Crie um único ambiente virtual para facilitar o teste:
|
||||
|
||||
```bash
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
```
|
||||
|
||||
No Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\Activate.ps1
|
||||
```
|
||||
|
||||
Instale o framework e as dependências dos três componentes:
|
||||
|
||||
```bash
|
||||
pip install -U pip
|
||||
|
||||
pip install -e ./libs/agent_framework
|
||||
|
||||
pip install \
|
||||
-r ./Tuning-Performance/Authentication/agent_template_backend_authentication/requirements.txt \
|
||||
-r ./apps/agent_gateway/requirements.txt \
|
||||
-r ./apps/mcp_gateway/requirements.txt
|
||||
```
|
||||
|
||||
Confirme a importação:
|
||||
|
||||
```bash
|
||||
python -c "from agent_framework.security import install_authentication; print('framework ok')"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 2. Criar três pares de Client ID e Secret
|
||||
|
||||
Use credenciais diferentes para cada trecho. Para teste local:
|
||||
|
||||
| Fluxo | Client ID | Secret de teste |
|
||||
| ----------------------- | -------------------- | --------------------------- |
|
||||
| Cliente → Agent Gateway | `tia-test` | `TiaGateway-Test-2026!` |
|
||||
| Agent Gateway → Backend | `agent-gateway-test` | `GatewayBackend-Test-2026!` |
|
||||
| Backend → MCP Gateway | `agent-backend-test` | `BackendMcp-Test-2026!` |
|
||||
|
||||
Esses valores são apenas para ambiente local. Não os reutilize em produção.
|
||||
|
||||
## Gerar os hashes
|
||||
|
||||
O script está em:
|
||||
|
||||
```text
|
||||
Tuning-Performance/Authentication/
|
||||
agent_template_backend_authentication/
|
||||
scripts/generate_secret_hash.py
|
||||
```
|
||||
|
||||
Execute:
|
||||
|
||||
```bash
|
||||
python Tuning-Performance/Authentication/agent_template_backend_authentication/scripts/generate_secret_hash.py \
|
||||
--secret 'TiaGateway-Test-2026!'
|
||||
```
|
||||
|
||||
Depois:
|
||||
|
||||
```bash
|
||||
python Tuning-Performance/Authentication/agent_template_backend_authentication/scripts/generate_secret_hash.py \
|
||||
--secret 'GatewayBackend-Test-2026!'
|
||||
```
|
||||
|
||||
E:
|
||||
|
||||
```bash
|
||||
python Tuning-Performance/Authentication/agent_template_backend_authentication/scripts/generate_secret_hash.py \
|
||||
--secret 'BackendMcp-Test-2026!'
|
||||
```
|
||||
|
||||
Você receberá três valores semelhantes a:
|
||||
|
||||
```text
|
||||
pbkdf2_sha256:310000:<salt>:<digest>
|
||||
```
|
||||
|
||||
Guarde-os temporariamente:
|
||||
|
||||
```bash
|
||||
HASH_CLIENT_GATEWAY='pbkdf2_sha256:310000:...'
|
||||
HASH_GATEWAY_BACKEND='pbkdf2_sha256:310000:...'
|
||||
HASH_BACKEND_MCP='pbkdf2_sha256:310000:...'
|
||||
```
|
||||
|
||||
O hash muda a cada execução porque o salt é aleatório. Isso é esperado.
|
||||
|
||||
---
|
||||
|
||||
# 3. Configurar o Agent Gateway
|
||||
|
||||
Entre no diretório:
|
||||
|
||||
```bash
|
||||
cd apps/agent_gateway
|
||||
```
|
||||
|
||||
Copie o exemplo:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Adicione ao final do `.env`:
|
||||
|
||||
```env
|
||||
# Entrada: cliente/TIA -> Agent Gateway
|
||||
AGENT_GATEWAY_AUTH_ENABLED=true
|
||||
AGENT_GATEWAY_AUTH_MODE=basic
|
||||
AGENT_GATEWAY_AUTH_BASIC_CLIENT_ID=tia-test
|
||||
AGENT_GATEWAY_AUTH_BASIC_SECRET_HASH=COLE_AQUI_HASH_CLIENT_GATEWAY
|
||||
AGENT_GATEWAY_AUTH_BASIC_REALM=agent-gateway
|
||||
|
||||
AGENT_GATEWAY_AUTH_PUBLIC_PATHS=/health,/docs,/openapi.json,/redoc
|
||||
AGENT_GATEWAY_AUTH_PUBLIC_PREFIXES=
|
||||
|
||||
# Saída: Agent Gateway -> Agent Backend
|
||||
BACKEND_AUTH_MODE=basic
|
||||
BACKEND_AUTH_CLIENT_ID=agent-gateway-test
|
||||
BACKEND_AUTH_SECRET=GatewayBackend-Test-2026!
|
||||
```
|
||||
|
||||
Não coloque aspas no `.env`:
|
||||
|
||||
```env
|
||||
BACKEND_AUTH_SECRET=GatewayBackend-Test-2026!
|
||||
```
|
||||
|
||||
O arquivo de backends já aponta o backend Contas para:
|
||||
|
||||
```yaml
|
||||
contas:
|
||||
url: http://localhost:8000
|
||||
```
|
||||
|
||||
Arquivo:
|
||||
|
||||
```text
|
||||
apps/agent_gateway/config/backends.yaml
|
||||
```
|
||||
|
||||
Para este teste, mantenha apenas o backend `contas` ou force o backend no payload. Caso contrário, pedidos sobre ofertas e suporte podem ser roteados para portas em que nenhum backend está rodando.
|
||||
|
||||
---
|
||||
|
||||
# 4. Fazer o Agent Gateway enviar Basic Auth ao backend
|
||||
|
||||
Abra:
|
||||
|
||||
```text
|
||||
libs/agent_framework/src/agent_framework/global_supervisor/client.py
|
||||
```
|
||||
|
||||
Substitua a classe `BackendClient` por uma versão que aceite autenticação Basic.
|
||||
|
||||
No início do arquivo, adicione:
|
||||
|
||||
```python
|
||||
import os
|
||||
```
|
||||
|
||||
Altere o construtor:
|
||||
|
||||
```python
|
||||
class BackendClient:
|
||||
def __init__(
|
||||
self,
|
||||
timeout_seconds: float = 120.0,
|
||||
basic_client_id: str | None = None,
|
||||
basic_secret: str | None = None,
|
||||
):
|
||||
self.timeout_seconds = timeout_seconds
|
||||
self.basic_client_id = basic_client_id
|
||||
self.basic_secret = basic_secret
|
||||
|
||||
def _auth(self) -> httpx.BasicAuth | None:
|
||||
if self.basic_client_id and self.basic_secret:
|
||||
return httpx.BasicAuth(
|
||||
username=self.basic_client_id,
|
||||
password=self.basic_secret,
|
||||
)
|
||||
return None
|
||||
```
|
||||
|
||||
No método `call_message`, troque:
|
||||
|
||||
```python
|
||||
resp = await client.post(url, json=payload)
|
||||
```
|
||||
|
||||
por:
|
||||
|
||||
```python
|
||||
resp = await client.post(
|
||||
url,
|
||||
json=payload,
|
||||
auth=self._auth(),
|
||||
)
|
||||
```
|
||||
|
||||
No método `health`, você pode manter `/health` público. Caso queira enviar autenticação também, use:
|
||||
|
||||
```python
|
||||
resp = await client.get(url, auth=self._auth())
|
||||
```
|
||||
|
||||
Agora abra:
|
||||
|
||||
```text
|
||||
apps/agent_gateway/app/main.py
|
||||
```
|
||||
|
||||
Adicione:
|
||||
|
||||
```python
|
||||
import os
|
||||
```
|
||||
|
||||
Troque:
|
||||
|
||||
```python
|
||||
backend_client = BackendClient(
|
||||
timeout_seconds=settings.BACKEND_TIMEOUT_SECONDS
|
||||
)
|
||||
```
|
||||
|
||||
por:
|
||||
|
||||
```python
|
||||
backend_client = BackendClient(
|
||||
timeout_seconds=settings.BACKEND_TIMEOUT_SECONDS,
|
||||
basic_client_id=os.getenv("BACKEND_AUTH_CLIENT_ID"),
|
||||
basic_secret=os.getenv("BACKEND_AUTH_SECRET"),
|
||||
)
|
||||
```
|
||||
|
||||
Isso implementa:
|
||||
|
||||
```text
|
||||
Agent Gateway → Agent Backend
|
||||
Authorization: Basic base64(agent-gateway-test:GatewayBackend-Test-2026!)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 5. Configurar o Agent Backend autenticado
|
||||
|
||||
Entre no diretório:
|
||||
|
||||
```bash
|
||||
cd Tuning-Performance/Authentication/agent_template_backend_authentication
|
||||
```
|
||||
|
||||
Copie o exemplo:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Ajuste a seção de autenticação:
|
||||
|
||||
```env
|
||||
# Entrada: Agent Gateway -> Agent Backend
|
||||
AGENT_AUTH_ENABLED=true
|
||||
AGENT_AUTH_MODE=basic
|
||||
AGENT_AUTH_BASIC_CLIENT_ID=agent-gateway-test
|
||||
AGENT_AUTH_BASIC_SECRET_HASH=COLE_AQUI_HASH_GATEWAY_BACKEND
|
||||
AGENT_AUTH_BASIC_REALM=agent-contas
|
||||
|
||||
AGENT_AUTH_PUBLIC_PATHS=/health,/docs,/openapi.json,/redoc
|
||||
AGENT_AUTH_PUBLIC_PREFIXES=
|
||||
```
|
||||
|
||||
Para usar o MCP Gateway:
|
||||
|
||||
```env
|
||||
MCP_GATEWAY_ENABLED=true
|
||||
MCP_GATEWAY_URL=http://localhost:8300
|
||||
MCP_GATEWAY_TIMEOUT_SECONDS=60
|
||||
|
||||
# Saída: Agent Backend -> MCP Gateway
|
||||
MCP_GATEWAY_AUTH_MODE=basic
|
||||
MCP_GATEWAY_BASIC_CLIENT_ID=agent-backend-test
|
||||
MCP_GATEWAY_BASIC_SECRET=BackendMcp-Test-2026!
|
||||
```
|
||||
|
||||
Para evitar dependências externas durante o primeiro teste, configure também:
|
||||
|
||||
```env
|
||||
LLM_PROVIDER=mock
|
||||
ENABLE_LANGFUSE=false
|
||||
ENABLE_ANALYTICS=false
|
||||
|
||||
SESSION_REPOSITORY_PROVIDER=memory
|
||||
MEMORY_REPOSITORY_PROVIDER=memory
|
||||
CHECKPOINT_REPOSITORY_PROVIDER=memory
|
||||
CACHE_PROVIDER=memory
|
||||
USAGE_REPOSITORY_PROVIDER=memory
|
||||
```
|
||||
|
||||
Os nomes exatos de alguns providers podem depender do arquivo de configuração atual do framework. Caso o `.env.example` já contenha valores locais ou mock, preserve-os.
|
||||
|
||||
---
|
||||
|
||||
# 6. Fazer o Backend enviar Basic Auth ao MCP Gateway
|
||||
|
||||
Abra:
|
||||
|
||||
```text
|
||||
libs/agent_framework/src/agent_framework/gateways/mcp_gateway_client.py
|
||||
```
|
||||
|
||||
Substitua a implementação por:
|
||||
|
||||
```python
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
|
||||
class MCPGatewayClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
token: str | None = None,
|
||||
timeout_seconds: int = 60,
|
||||
auth_mode: str | None = None,
|
||||
basic_client_id: str | None = None,
|
||||
basic_secret: str | None = None,
|
||||
):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.token = token
|
||||
self.timeout_seconds = timeout_seconds
|
||||
self.auth_mode = (auth_mode or "").strip().lower()
|
||||
self.basic_client_id = basic_client_id
|
||||
self.basic_secret = basic_secret
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if (
|
||||
self.auth_mode == "basic"
|
||||
and self.basic_client_id
|
||||
and self.basic_secret
|
||||
):
|
||||
raw = f"{self.basic_client_id}:{self.basic_secret}".encode("utf-8")
|
||||
encoded = base64.b64encode(raw).decode("ascii")
|
||||
return {"Authorization": f"Basic {encoded}"}
|
||||
|
||||
if self.token:
|
||||
return {"Authorization": f"Bearer {self.token}"}
|
||||
|
||||
return {}
|
||||
|
||||
async def list_tools(self) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=self.timeout_seconds
|
||||
) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/v1/tools",
|
||||
headers=self._headers(),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def invoke_tool(
|
||||
self,
|
||||
*,
|
||||
tenant_id: str,
|
||||
agent_id: str,
|
||||
channel: str | None,
|
||||
tool_name: str,
|
||||
arguments: dict[str, Any] | None = None,
|
||||
business_context: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
payload = {
|
||||
"tenant_id": tenant_id,
|
||||
"agent_id": agent_id,
|
||||
"channel": channel,
|
||||
"tool_name": tool_name,
|
||||
"arguments": arguments or {},
|
||||
"business_context": business_context or {},
|
||||
"metadata": metadata or {},
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=self.timeout_seconds
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"{self.base_url}/v1/tools/{tool_name}/invoke",
|
||||
json=payload,
|
||||
headers=self._headers(),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
```
|
||||
|
||||
Agora abra:
|
||||
|
||||
```text
|
||||
libs/agent_framework/src/agent_framework/mcp/tool_router.py
|
||||
```
|
||||
|
||||
Localize:
|
||||
|
||||
```python
|
||||
MCPGatewayClient(
|
||||
base_url=getattr(
|
||||
settings,
|
||||
"MCP_GATEWAY_URL",
|
||||
"http://localhost:8300",
|
||||
),
|
||||
token=getattr(settings, "MCP_GATEWAY_TOKEN", None),
|
||||
timeout_seconds=getattr(
|
||||
settings,
|
||||
"MCP_GATEWAY_TIMEOUT_SECONDS",
|
||||
settings.MCP_TOOL_TIMEOUT_SECONDS,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
Altere para:
|
||||
|
||||
```python
|
||||
MCPGatewayClient(
|
||||
base_url=getattr(
|
||||
settings,
|
||||
"MCP_GATEWAY_URL",
|
||||
"http://localhost:8300",
|
||||
),
|
||||
token=getattr(settings, "MCP_GATEWAY_TOKEN", None),
|
||||
timeout_seconds=getattr(
|
||||
settings,
|
||||
"MCP_GATEWAY_TIMEOUT_SECONDS",
|
||||
settings.MCP_TOOL_TIMEOUT_SECONDS,
|
||||
),
|
||||
auth_mode=getattr(
|
||||
settings,
|
||||
"MCP_GATEWAY_AUTH_MODE",
|
||||
None,
|
||||
),
|
||||
basic_client_id=getattr(
|
||||
settings,
|
||||
"MCP_GATEWAY_BASIC_CLIENT_ID",
|
||||
None,
|
||||
),
|
||||
basic_secret=getattr(
|
||||
settings,
|
||||
"MCP_GATEWAY_BASIC_SECRET",
|
||||
None,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
Adicione estes campos em:
|
||||
|
||||
```text
|
||||
libs/agent_framework/src/agent_framework/config/settings.py
|
||||
```
|
||||
|
||||
Próximo das configurações existentes de MCP Gateway:
|
||||
|
||||
```python
|
||||
MCP_GATEWAY_AUTH_MODE: str | None = None
|
||||
MCP_GATEWAY_BASIC_CLIENT_ID: str | None = None
|
||||
MCP_GATEWAY_BASIC_SECRET: str | None = None
|
||||
```
|
||||
|
||||
Há também uma factory local em:
|
||||
|
||||
```text
|
||||
Tuning-Performance/Authentication/
|
||||
agent_template_backend_authentication/
|
||||
app/mcp_gateway_client_factory.py
|
||||
```
|
||||
|
||||
Ajuste para:
|
||||
|
||||
```python
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from agent_framework.gateways import MCPGatewayClient
|
||||
|
||||
|
||||
def build_mcp_gateway_client() -> MCPGatewayClient | None:
|
||||
if os.getenv("MCP_GATEWAY_ENABLED", "true").lower() != "true":
|
||||
return None
|
||||
|
||||
return MCPGatewayClient(
|
||||
base_url=os.getenv(
|
||||
"MCP_GATEWAY_URL",
|
||||
"http://localhost:8300",
|
||||
),
|
||||
token=os.getenv("MCP_GATEWAY_TOKEN") or None,
|
||||
timeout_seconds=int(
|
||||
os.getenv("MCP_GATEWAY_TIMEOUT_SECONDS", "60")
|
||||
),
|
||||
auth_mode=os.getenv("MCP_GATEWAY_AUTH_MODE"),
|
||||
basic_client_id=os.getenv(
|
||||
"MCP_GATEWAY_BASIC_CLIENT_ID"
|
||||
),
|
||||
basic_secret=os.getenv(
|
||||
"MCP_GATEWAY_BASIC_SECRET"
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 7. Configurar o MCP Gateway
|
||||
|
||||
Entre no diretório:
|
||||
|
||||
```bash
|
||||
cd apps/mcp_gateway
|
||||
```
|
||||
|
||||
Crie `.env`:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Adicione:
|
||||
|
||||
```env
|
||||
# Entrada: Agent Backend -> MCP Gateway
|
||||
MCP_GATEWAY_AUTH_ENABLED=true
|
||||
MCP_GATEWAY_AUTH_MODE=basic
|
||||
MCP_GATEWAY_AUTH_BASIC_CLIENT_ID=agent-backend-test
|
||||
MCP_GATEWAY_AUTH_BASIC_SECRET_HASH=COLE_AQUI_HASH_BACKEND_MCP
|
||||
MCP_GATEWAY_AUTH_BASIC_REALM=mcp-gateway
|
||||
|
||||
MCP_GATEWAY_AUTH_PUBLIC_PATHS=/health,/ready,/docs,/openapi.json,/redoc
|
||||
MCP_GATEWAY_AUTH_PUBLIC_PREFIXES=
|
||||
|
||||
MCP_GATEWAY_CONFIG_PATH=config/mcp_gateway.yaml
|
||||
```
|
||||
|
||||
## Desabilitar o mecanismo Bearer legado
|
||||
|
||||
O MCP Gateway ainda possui um segundo mecanismo antigo, configurado dentro de:
|
||||
|
||||
```text
|
||||
apps/mcp_gateway/config/mcp_gateway.yaml
|
||||
```
|
||||
|
||||
Localize a seção:
|
||||
|
||||
```yaml
|
||||
auth:
|
||||
enabled: true
|
||||
```
|
||||
|
||||
Altere para:
|
||||
|
||||
```yaml
|
||||
auth:
|
||||
enabled: false
|
||||
```
|
||||
|
||||
Isso é necessário porque o novo middleware já faz a autenticação Basic. Caso o `auth_check()` legado continue habilitado, a requisição passará pelo Basic e depois será rejeitada por não possuir Bearer Token.
|
||||
|
||||
---
|
||||
|
||||
# 8. Subir os componentes
|
||||
|
||||
Use quatro terminais.
|
||||
|
||||
## Terminal 1 — MCP Servers
|
||||
|
||||
O MCP Gateway precisa ter pelo menos um servidor MCP disponível para demonstrar uma chamada real.
|
||||
|
||||
Na raiz do projeto:
|
||||
|
||||
```bash
|
||||
source .venv/bin/activate
|
||||
```
|
||||
|
||||
Suba o servidor telecom:
|
||||
|
||||
```bash
|
||||
uvicorn mcp.servers.telecom_mcp_server.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8100 \
|
||||
--reload
|
||||
```
|
||||
|
||||
Em outro terminal, caso queira também o retail:
|
||||
|
||||
```bash
|
||||
uvicorn mcp.servers.retail_mcp_server.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8200 \
|
||||
--reload
|
||||
```
|
||||
|
||||
Confira as URLs configuradas em:
|
||||
|
||||
```text
|
||||
apps/mcp_gateway/config/mcp_gateway.yaml
|
||||
```
|
||||
|
||||
Para execução local, devem apontar para:
|
||||
|
||||
```yaml
|
||||
url: http://localhost:8100
|
||||
```
|
||||
|
||||
e:
|
||||
|
||||
```yaml
|
||||
url: http://localhost:8200
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Terminal 2 — MCP Gateway
|
||||
|
||||
```bash
|
||||
cd apps/mcp_gateway
|
||||
source ../../.venv/bin/activate
|
||||
```
|
||||
|
||||
Suba usando `--env-file`. Isso é importante porque o middleware lê variáveis com `os.getenv()`:
|
||||
|
||||
```bash
|
||||
uvicorn app.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8300 \
|
||||
--reload \
|
||||
--env-file .env
|
||||
```
|
||||
|
||||
Teste a saúde pública:
|
||||
|
||||
```bash
|
||||
curl http://localhost:8300/health
|
||||
```
|
||||
|
||||
Teste um endpoint protegido sem credencial:
|
||||
|
||||
```bash
|
||||
curl -i http://localhost:8300/v1/tools
|
||||
```
|
||||
|
||||
Esperado:
|
||||
|
||||
```text
|
||||
HTTP/1.1 401 Unauthorized
|
||||
```
|
||||
|
||||
Teste com Basic Auth:
|
||||
|
||||
```bash
|
||||
curl -i \
|
||||
-u 'agent-backend-test:BackendMcp-Test-2026!' \
|
||||
http://localhost:8300/v1/tools
|
||||
```
|
||||
|
||||
Esperado:
|
||||
|
||||
```text
|
||||
HTTP/1.1 200 OK
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Terminal 3 — Agent Backend
|
||||
|
||||
```bash
|
||||
cd Tuning-Performance/Authentication/agent_template_backend_authentication
|
||||
source ../../../.venv/bin/activate
|
||||
```
|
||||
|
||||
Suba:
|
||||
|
||||
```bash
|
||||
uvicorn app.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8000 \
|
||||
--reload \
|
||||
--env-file .env
|
||||
```
|
||||
|
||||
Teste saúde:
|
||||
|
||||
```bash
|
||||
curl http://localhost:8000/health
|
||||
```
|
||||
|
||||
Teste endpoint protegido sem credencial:
|
||||
|
||||
```bash
|
||||
curl -i http://localhost:8000/agents
|
||||
```
|
||||
|
||||
Esperado:
|
||||
|
||||
```text
|
||||
HTTP/1.1 401 Unauthorized
|
||||
```
|
||||
|
||||
Teste com a credencial usada pelo Agent Gateway:
|
||||
|
||||
```bash
|
||||
curl -i \
|
||||
-u 'agent-gateway-test:GatewayBackend-Test-2026!' \
|
||||
http://localhost:8000/agents
|
||||
```
|
||||
|
||||
Esperado:
|
||||
|
||||
```text
|
||||
HTTP/1.1 200 OK
|
||||
```
|
||||
|
||||
Teste mensagem diretamente:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8000/gateway/message \
|
||||
-u 'agent-gateway-test:GatewayBackend-Test-2026!' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"channel": "web",
|
||||
"agent_id": "telecom_contas",
|
||||
"tenant_id": "default",
|
||||
"payload": {
|
||||
"text": "Quero consultar minha fatura",
|
||||
"session_id": "teste-backend-001",
|
||||
"user_id": "user-001",
|
||||
"customer_id": "12345",
|
||||
"message_id": "msg-001"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Terminal 4 — Agent Gateway
|
||||
|
||||
```bash
|
||||
cd apps/agent_gateway
|
||||
source ../../.venv/bin/activate
|
||||
```
|
||||
|
||||
Suba:
|
||||
|
||||
```bash
|
||||
uvicorn app.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8010 \
|
||||
--reload \
|
||||
--env-file .env
|
||||
```
|
||||
|
||||
Teste saúde:
|
||||
|
||||
```bash
|
||||
curl http://localhost:8010/health
|
||||
```
|
||||
|
||||
Teste endpoint protegido sem credencial:
|
||||
|
||||
```bash
|
||||
curl -i http://localhost:8010/backends
|
||||
```
|
||||
|
||||
Esperado:
|
||||
|
||||
```text
|
||||
HTTP/1.1 401 Unauthorized
|
||||
```
|
||||
|
||||
Teste com a credencial externa:
|
||||
|
||||
```bash
|
||||
curl -i \
|
||||
-u 'tia-test:TiaGateway-Test-2026!' \
|
||||
http://localhost:8010/backends
|
||||
```
|
||||
|
||||
Esperado:
|
||||
|
||||
```text
|
||||
HTTP/1.1 200 OK
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 9. Validar o circuito completo
|
||||
|
||||
Force o backend `contas` para evitar que o roteador selecione um backend não iniciado:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8010/gateway/message \
|
||||
-u 'tia-test:TiaGateway-Test-2026!' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"channel": "web",
|
||||
"backend_id": "contas",
|
||||
"tenant_id": "default",
|
||||
"agent_id": "telecom_contas",
|
||||
"session_id": "circuito-basic-001",
|
||||
"payload": {
|
||||
"text": "Quero consultar minha fatura",
|
||||
"session_id": "circuito-basic-001",
|
||||
"user_id": "user-001",
|
||||
"customer_id": "12345",
|
||||
"message_id": "msg-circuito-001"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
O circuito esperado é:
|
||||
|
||||
```text
|
||||
curl
|
||||
│ Basic tia-test
|
||||
▼
|
||||
Agent Gateway :8010
|
||||
│ Basic agent-gateway-test
|
||||
▼
|
||||
Agent Backend :8000
|
||||
│ Basic agent-backend-test
|
||||
▼
|
||||
MCP Gateway :8300
|
||||
▼
|
||||
MCP Server :8100 ou :8200
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 10. Como comprovar cada autenticação
|
||||
|
||||
Faça testes negativos em cada trecho.
|
||||
|
||||
## Secret externo incorreto
|
||||
|
||||
```bash
|
||||
curl -i \
|
||||
-u 'tia-test:senha-errada' \
|
||||
http://localhost:8010/backends
|
||||
```
|
||||
|
||||
Resultado esperado:
|
||||
|
||||
```text
|
||||
401 Unauthorized
|
||||
```
|
||||
|
||||
## Secret do gateway para backend incorreto
|
||||
|
||||
Altere temporariamente no `apps/agent_gateway/.env`:
|
||||
|
||||
```env
|
||||
BACKEND_AUTH_SECRET=senha-errada
|
||||
```
|
||||
|
||||
Reinicie o Agent Gateway e envie uma mensagem.
|
||||
|
||||
O gateway deverá retornar erro de backend, normalmente:
|
||||
|
||||
```text
|
||||
502 Bad Gateway
|
||||
```
|
||||
|
||||
O erro interno será originado por um:
|
||||
|
||||
```text
|
||||
401 Unauthorized
|
||||
```
|
||||
|
||||
do Agent Backend.
|
||||
|
||||
## Secret do backend para MCP incorreto
|
||||
|
||||
Altere temporariamente:
|
||||
|
||||
```env
|
||||
MCP_GATEWAY_BASIC_SECRET=senha-errada
|
||||
```
|
||||
|
||||
Reinicie o backend e execute uma frase que acione uma ferramenta MCP.
|
||||
|
||||
O backend deverá registrar falha na chamada ao MCP Gateway com:
|
||||
|
||||
```text
|
||||
401 Unauthorized
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 11. Verificação rápida de portas
|
||||
|
||||
No Linux ou WSL:
|
||||
|
||||
```bash
|
||||
ss -lntp | grep -E ':8000|:8010|:8100|:8200|:8300'
|
||||
```
|
||||
|
||||
No Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
Get-NetTCPConnection -State Listen |
|
||||
Where-Object LocalPort -in 8000,8010,8100,8200,8300 |
|
||||
Sort-Object LocalPort
|
||||
```
|
||||
|
||||
Você deverá ver:
|
||||
|
||||
```text
|
||||
8000 Agent Backend
|
||||
8010 Agent Gateway
|
||||
8100 Telecom MCP Server
|
||||
8200 Retail MCP Server
|
||||
8300 MCP Gateway
|
||||
```
|
||||
|
||||
## Observação importante
|
||||
|
||||
O segredo original precisa existir no componente cliente:
|
||||
|
||||
```text
|
||||
TIA ou curl:
|
||||
TiaGateway-Test-2026!
|
||||
|
||||
Agent Gateway:
|
||||
GatewayBackend-Test-2026!
|
||||
|
||||
Agent Backend:
|
||||
BackendMcp-Test-2026!
|
||||
```
|
||||
|
||||
Os componentes servidores armazenam apenas os hashes:
|
||||
|
||||
```text
|
||||
Agent Gateway:
|
||||
hash de TiaGateway-Test-2026!
|
||||
|
||||
Agent Backend:
|
||||
hash de GatewayBackend-Test-2026!
|
||||
|
||||
MCP Gateway:
|
||||
hash de BackendMcp-Test-2026!
|
||||
```
|
||||
|
||||
Em produção, os segredos originais e hashes devem vir de Vault ou Kubernetes Secret, não de arquivos `.env`.
|
||||
@@ -77,3 +77,12 @@ No compose, o backend usa `config/mcp_servers.docker.yaml` para apontar para `te
|
||||
## Operações read-only e transacionais
|
||||
|
||||
Use `config/tool_policies.yaml` no backend para classificar somente as operações que precisam de tratamento adicional. A validação é aplicada no roteador central antes do MCP Gateway/Server. O arquivo é opcional e templates antigos continuam usando as políticas já presentes em `tools.yaml`. A configuração completa e o roteiro de migração estão em [README_TOOL_POLICIES.md](README_TOOL_POLICIES.md).
|
||||
|
||||
|
||||
## Chamadas MCP multi-item
|
||||
|
||||
Para operações com listas de produtos, pedidos, ativos ou outros recursos, **não implemente loops de chamadas MCP dentro do agente**. O framework possui contrato genérico para parâmetros `array/list`, pre-validation, confirmação e resultado por item (`SUCCESS`, `PARTIAL_SUCCESS`, `FAILED`).
|
||||
|
||||
Guia completo: [MCP Multi-item — Guia do Desenvolvedor](../docs/MCP_MULTI_ITEM_DEVELOPER_GUIDE.md).
|
||||
|
||||
A tool primária deve retornar `results[]` com `success` ou `ok` booleano por item. Em workflows, use preferencialmente `output[tool_name].results`.
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Release Notes — Generic Deterministic Intent Shift v15
|
||||
|
||||
## Problema corrigido
|
||||
|
||||
A Route Stickiness podia preservar a intent anterior quando a nova mensagem correspondia a uma intent configurada no `routing.yaml`, mas a frase do usuário omitia conectores curtos presentes na keyword configurada.
|
||||
|
||||
Exemplo real de configuração:
|
||||
|
||||
- keyword: `qual é o meu plano`
|
||||
- mensagem: `qual o meu plano`
|
||||
|
||||
A classificação determinística não reconhecia a nova intent e a continuity acabava mantendo a intent anterior.
|
||||
|
||||
## Correção
|
||||
|
||||
O `EnterpriseRouter` continua usando, nesta ordem:
|
||||
|
||||
1. match exato;
|
||||
2. sequência completa de tokens com palavras inseridas (`ordered_tokens`);
|
||||
3. sequência de tokens informativos tolerando a omissão de conectores curtos presentes na keyword (`ordered_content_tokens`).
|
||||
|
||||
A terceira estratégia ignora, somente no lado da keyword, tokens de até dois caracteres e exige pelo menos dois tokens informativos. Não há nomes de intents, agentes, domínios ou verbos de negócio hardcoded.
|
||||
|
||||
Assim, a solução é dirigida integralmente pelas intents carregadas do `routing.yaml` da aplicação.
|
||||
|
||||
## Precedência sobre Route Stickiness
|
||||
|
||||
Quando o candidato determinístico encontrado é diferente da intent ativa, ele preempta a stickiness e retorna:
|
||||
|
||||
- `route_stickiness_preempted: true`
|
||||
- `previous_agent`
|
||||
- `previous_intent`
|
||||
- `keyword_match_strategy`
|
||||
|
||||
A continuity LLM não é chamada nesse caminho.
|
||||
|
||||
## Casos cobertos
|
||||
|
||||
### Mesmo agente, nova intent
|
||||
|
||||
`retail_order_tracking` -> `quero cancelar meu pedido` -> `retail_order_cancel`
|
||||
|
||||
### Mesmo agente, tools diferentes
|
||||
|
||||
`contas_invoice_query` -> `qual o meu plano` -> `contas_plan_information`
|
||||
|
||||
Mesmo que ambas as intents usem `faturas_agent`, as tools mudam de `consultar_faturas` para `consultar_plano`.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Route Stickiness — deterministic intent shift (v14)
|
||||
|
||||
## Problema corrigido
|
||||
|
||||
Uma keyword multi-token como `cancelar pedido` não era reconhecida em frases como `quero cancelar meu pedido`. O match legado usava substring literal; assim, a keyword genérica `pedido` podia manter `retail_order_tracking` e a continuidade reutilizava a intent anterior.
|
||||
|
||||
## Correção
|
||||
|
||||
O `EnterpriseRouter` agora possui um segundo estágio determinístico para keywords multi-token: ordered-token matching com até três tokens intermediários. Não há chamada adicional de LLM.
|
||||
|
||||
Exemplos reconhecidos pela keyword configurada `cancelar pedido`:
|
||||
|
||||
- `quero cancelar meu pedido`
|
||||
- `quero cancelar o meu pedido`
|
||||
- `pode cancelar esse pedido`
|
||||
- `gostaria de cancelar meu pedido`
|
||||
|
||||
Quando esse match identifica uma intent diferente da ativa, ele preempta a route stickiness antes do LLM de continuidade.
|
||||
|
||||
Metadados de auditoria esperados:
|
||||
|
||||
```json
|
||||
{
|
||||
"method": "keyword",
|
||||
"intent": "retail_order_cancel",
|
||||
"metadata": {
|
||||
"matched_keyword": "cancelar pedido",
|
||||
"keyword_match_strategy": "ordered_tokens",
|
||||
"route_stickiness_preempted": true,
|
||||
"previous_intent": "retail_order_tracking"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Custo de LLM
|
||||
|
||||
Para mudança explícita reconhecida deterministicamente, o classificador LLM de continuity não é chamado. Para mensagens sem sinal explícito, a Route Stickiness continua com o comportamento configurado.
|
||||
|
||||
## Regressão
|
||||
|
||||
Testes cobrem mudança `retail_order_tracking -> retail_order_cancel` no mesmo `orders_agent`, inclusive com palavras intermediárias. A suíte relacionada passou com 18 testes.
|
||||
30
FIX_TRANSACTION_INTENT_LOOP.md
Normal file
30
FIX_TRANSACTION_INTENT_LOOP.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Correção: escape de estado transacional / mudança de intenção
|
||||
|
||||
Correção aplicada em 2026-08-20 para impedir que uma sessão fique presa em `COLLECTING_PARAMETERS` ou `AWAITING_CONFIRMATION` quando o usuário muda explicitamente de assunto.
|
||||
|
||||
## Comportamento corrigido
|
||||
|
||||
Antes:
|
||||
|
||||
1. uma transação entrava em `COLLECTING_PARAMETERS`;
|
||||
2. `next_state` forçava o mesmo agente via `state_policies`;
|
||||
3. toda mensagem seguinte era tratada como tentativa de preencher o parâmetro faltante;
|
||||
4. uma nova intenção como `quais sao meus servicos` permanecia presa no fluxo anterior.
|
||||
|
||||
Agora:
|
||||
|
||||
- o `EnterpriseRouter` verifica mudança explícita de intenção antes de aplicar o lock de estado;
|
||||
- keyword explícita tem prioridade;
|
||||
- quando necessário, o LLM router pode detectar mudança com confiança >= `router.confidence_threshold`;
|
||||
- a decisão recebe `metadata.transaction_interruption=intent_shift`;
|
||||
- o runtime encerra a transação pendente como `CANCELLED`, limpa `next_state`, parâmetros e latches, e prossegue com a nova intent;
|
||||
- cancelamentos explícitos como `cancele essa operação anterior` funcionam também durante `COLLECTING_PARAMETERS`.
|
||||
|
||||
## Testes adicionados
|
||||
|
||||
- mudança de intent durante `COLLECTING_PARAMETERS`;
|
||||
- resposta curta/baixa confiança permanece na transação;
|
||||
- cancelamento explícito durante coleta de parâmetros;
|
||||
- limpeza do estado transacional antes de executar a nova intent.
|
||||
|
||||
Testes focados: 19 passed.
|
||||
102
FIX_TRANSACTION_PARAMETER_PRECEDENCE.md
Normal file
102
FIX_TRANSACTION_PARAMETER_PRECEDENCE.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# Precedência transacional + extração LLM de parâmetros
|
||||
|
||||
Esta correção remove a extração textual hardcoded de parâmetros transacionais e faz a coleta de `policy.requires` por um extrator LLM genérico.
|
||||
|
||||
## Regra de precedência
|
||||
|
||||
Enquanto existir uma transação ativa, o framework trata o turno nesta ordem:
|
||||
|
||||
```text
|
||||
ACTIVE_TRANSACTION
|
||||
|
|
||||
+-- COLLECTING_PARAMETERS
|
||||
| |
|
||||
| +-- LLM tenta extrair SOMENTE os parâmetros ainda pendentes
|
||||
| |
|
||||
| +-- extraiu >= 1 ?
|
||||
| |
|
||||
| +-- SIM -> continua a transação; NÃO avalia intent_shift
|
||||
| |
|
||||
| +-- NÃO -> libera EnterpriseRouter para avaliar intent_shift
|
||||
|
|
||||
+-- AWAITING_CONFIRMATION
|
||||
|
|
||||
+-- reconhece confirmação/rejeição explícita
|
||||
|
|
||||
+-- reconheceu ?
|
||||
|
|
||||
+-- SIM -> continua/cancela a transação; NÃO avalia intent_shift
|
||||
|
|
||||
+-- NÃO -> libera EnterpriseRouter para avaliar intent_shift
|
||||
```
|
||||
|
||||
## TransactionParameterExtractor
|
||||
|
||||
Novo componente:
|
||||
|
||||
`libs/agent_framework/src/agent_framework/runtime/transaction_parameters.py`
|
||||
|
||||
A extração textual dos parâmetros de negócio é feita exclusivamente por LLM. O componente recebe:
|
||||
|
||||
- nome da tool/transação ativa;
|
||||
- parâmetros atualmente pendentes;
|
||||
- argumentos já conhecidos;
|
||||
- schema/tipos declarados em `tools.yaml` quando disponíveis;
|
||||
- descrição da tool;
|
||||
- mensagem atual do usuário.
|
||||
|
||||
Ele não conhece nomes de domínio como `order_id`, `reason`, `subject`, `valor`, TIM ou retail. Não há regex de entidades de negócio.
|
||||
|
||||
A LLM pode interpretar, por exemplo:
|
||||
|
||||
- `PED-1001` quando só há um parâmetro compatível pendente;
|
||||
- `o pedido é PED-1001`;
|
||||
- `PED-1001, desisti da compra` preenchendo dois parâmetros no mesmo turno;
|
||||
- respostas com o nome do parâmetro seguido do valor;
|
||||
- respostas apenas com o valor, quando semanticamente inequívocas.
|
||||
|
||||
Em caso de dúvida, o prompt manda retornar `null`. Uma nova solicitação não deve ser transformada em valor de parâmetro.
|
||||
|
||||
## Separação de responsabilidades
|
||||
|
||||
`tool_policies.yaml` continua sendo a fonte de verdade para `requires`.
|
||||
|
||||
`tools.yaml` pode fornecer tipos via `args_schema` e descrição da tool para melhorar a interpretação sem introduzir código específico de domínio.
|
||||
|
||||
`mcp_parameter_mapping.yaml` continua responsável pelos parâmetros auxiliares/contrato MCP. As strategies do mapper são explicitamente excluídas dos campos presentes em `policy.requires`, para não misturar extração MCP com coleta transacional.
|
||||
|
||||
O `EnterpriseRouter` usa o mesmo extrator LLM apenas como *probe* de precedência. Se pelo menos um parâmetro pendente for encontrado, o turno permanece no estado transacional. Os valores extraídos são colocados no metadata da decisão e reutilizados pelo runtime, evitando uma segunda chamada LLM no mesmo turno.
|
||||
|
||||
## Profile LLM
|
||||
|
||||
Foi adicionado aos templates:
|
||||
|
||||
```yaml
|
||||
transaction_parameter_extraction:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1-mini
|
||||
temperature: 0
|
||||
max_tokens: 500
|
||||
timeout_seconds: 8
|
||||
```
|
||||
|
||||
Generation/component:
|
||||
|
||||
- `llm.transaction_parameter_extraction`
|
||||
- `transaction_parameter_extraction`
|
||||
|
||||
## Limpeza de estado
|
||||
|
||||
Em `intent_shift`, `transaction_pre_validation` da transação abandonada é removido para não contaminar a nova transação. O resultado de pre-validation continua preservado enquanto pertence à própria transação para auditoria.
|
||||
|
||||
## Testes adicionados
|
||||
|
||||
`tests/test_transaction_parameter_llm_precedence.py`
|
||||
|
||||
Cobertura:
|
||||
|
||||
1. dois parâmetros extraídos no mesmo turno;
|
||||
2. um parâmetro preenchido ganha precedência sobre keyword que indicaria outra intent;
|
||||
3. nenhum parâmetro encontrado libera `intent_shift`;
|
||||
4. ausência do antigo `_extract_action_arguments()` hardcoded;
|
||||
5. confirmação `sim` ganha precedência sobre intent shift.
|
||||
84
JEV_INTEGRATION.md
Normal file
84
JEV_INTEGRATION.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# Seleção individual de decisões: modelo atual ou JEV
|
||||
|
||||
Implementação opt-in para o projeto do ZIP de 03/11/2026. O padrão continua sendo `current`; nenhum modelo foi ativado e nenhuma chave foi incluída.
|
||||
|
||||
## Configuração
|
||||
|
||||
Copie as variáveis de `.env.jev.example` para o `.env` utilizado pelo processo. Se usar contêiner/Kubernetes, passe as variáveis também para o ambiente do processo e guarde a chave no mecanismo de secrets do ambiente. Reinicie o serviço após alterar a configuração. Substitua os arquivos de código e refaça o build/redeploy caso o framework esteja instalado em pacote ou imagem; reiniciar sem atualizar o pacote instalado não aplica mudanças de código.
|
||||
|
||||
Exemplo: ativar somente continuidade e intenção, mantendo o restante atual:
|
||||
|
||||
```dotenv
|
||||
DECISION_PROVIDER=current
|
||||
DECISION_ROUTE_CONTINUITY_PROVIDER=jev
|
||||
DECISION_ROUTER_PROVIDER=jev
|
||||
AI_GATEWAY_API_KEY=<sua chave>
|
||||
JEV_MODEL=typesafe-ai/jev
|
||||
DECISION_FALLBACK_TO_CURRENT=true
|
||||
JEV_MIN_CONFIDENCE=0.7
|
||||
DECISION_ROUTE_CONTINUITY_MIN_CONFIDENCE=0.90
|
||||
```
|
||||
|
||||
A variável individual prevalece sobre `DECISION_PROVIDER`. Uma variável individual ausente herda o padrão global. Como o exemplo define todas como `current`, mudar somente a variável global não altera os pontos explicitamente definidos. Os valores válidos são `current` e `jev`.
|
||||
|
||||
A seleção não habilita funcionalidades desativadas: `ENABLE_LLM_ROUTER`, `ENABLE_ROUTE_STICKINESS`, configuração de semantic classifiers e configuração dos guardrails/judges continuam controlando se cada ponto é executado. Para não tornar `current` incompatível, não foram alteradas as regras determinísticas nem os controles de execução.
|
||||
|
||||
## Pontos disponíveis
|
||||
|
||||
Cada sufixo abaixo corresponde a `DECISION_<SUFIXO>_PROVIDER`:
|
||||
|
||||
| Sufixo | Função |
|
||||
|---|---|
|
||||
| ROUTE_CONTINUITY | CONTINUE, ROUTE, HUMAN_HANDOFF, END_SESSION; inclui sondagem de controles globais que usa o mesmo classificador |
|
||||
| ROUTER | Intenção semântica; agente, domínio e ferramentas derivados do catálogo local |
|
||||
| WORKFLOW_EXPECTED_INPUT | Opção permitida para retomada de workflow; opção sem correspondência não retoma |
|
||||
| WORKFLOW_REENTRY | REENTER ou RESUME |
|
||||
| TRANSACTION_CONFIRMATION | Confirmação semântica, usando as opções configuradas; parser explícito permanece |
|
||||
| TRANSACTION_PARAMETER_RELEVANCE | RELEVANT ou NOT_RELEVANT |
|
||||
| TRANSACTION_INTENT_SHIFT | CONTINUE, REPLACE, SHIFT ou ABANDON e intenção de destino |
|
||||
| MULTI_INTENT | Intenção de cada objetivo extraído, com preservação de ordem e trechos literais |
|
||||
| TRANSACTION_PARAMETER_RECONCILIATION | resolved, preserve, clear ou unresolved por parâmetro |
|
||||
| GLOBAL_SUPERVISOR | Backend permitido no registro do supervisor global |
|
||||
| PROCESSING_INTERRUPTION | Regenerar resposta de voz ou repetir |
|
||||
| GUARDRAIL_GUARDRAIL / GUARDRAIL_GRL | Guardrails LLM genéricos com os perfis padrão; perfis personalizados usam GUARDRAIL_<PERFIL> |
|
||||
| GUARDRAIL_PINJ, COER, TOX, REVPREC, AOFERTA, OOS, FRASEOLOGIA, RAGSEC, DLEX_IN, DLEX_OUT | Cada tarefa calibrada tem sua própria variável GUARDRAIL_<TAREFA> |
|
||||
| JUDGE_CSI, JUDGE_VCTN, JUDGE_ALUC, JUDGE_RQLT | Cada tarefa de judge calibrado, como padrão de grupo |
|
||||
| JUDGE_<NOME> | Judge genérico, usando seu `name`; o padrão é JUDGE_LLM_JUDGE |
|
||||
|
||||
Um judge calibrado também aceita `DECISION_JUDGE_<NOME_CONFIGURADO>_PROVIDER`, que prevalece sobre o grupo da tarefa (por exemplo `DECISION_JUDGE_GROUNDEDNESS_PROVIDER` prevalece sobre `DECISION_JUDGE_ALUC_PROVIDER`). Rechecagens de guardrail aceitam o nome completo do componente, por exemplo `DECISION_GUARDRAIL_DLEX_OUT_PROTOCOL_AUTHORIZATION_RECHECK_PROVIDER`, prevalecendo sobre `DECISION_GUARDRAIL_DLEX_OUT_PROVIDER`.
|
||||
|
||||
Caracteres diferentes de letras/números são convertidos em `_`, com nome em maiúsculas. O mesmo ponto pode definir `DECISION_<SUFIXO>_MIN_CONFIDENCE`; esse valor é independente dos limites já existentes no componente. Os limites existentes continuam sendo aplicados depois da integração.
|
||||
|
||||
## O que é híbrido
|
||||
|
||||
- Multi-intenção: o modelo atual extrai os objetivos e seus trechos, mantendo a ordem. O JEV escolhe a intenção de cada objetivo. Não há geração de trechos pelo JEV; trechos não literais são rejeitados. Isso pode custar mais que uma chamada atual isolada, por ser uma etapa adicional.
|
||||
- Reconciliação: o modelo atual extrai candidatos e proveniência. JEV decide o tratamento de cada campo. A decisão não inventa valores e não substitui validação de negócio.
|
||||
- Geração final, extração livre, resumos, RAG rewrite/compression, TOXOUT e FALLBACK de texto seguem no provedor atual. Autorização, alçadas, idempotência, pré-validação de negócio e execução seguem nas implementações existentes.
|
||||
- Guardrail LLM genérico no JEV avalia se o texto original pode passar sem alteração. Se precisar de sanitização, deve bloquear; o JEV não fornece `sanitized_text` ou instruções textuais de reescrita. Reescritas já separadas no fluxo continuam generativas.
|
||||
- Judges JEV não inventam rótulos ou justificativas de prosa: o retorno contém os campos necessários à decisão e motivo técnico fixo. RQLT/CSI usam score 0–10; judge genérico converte para 0–1. Os limites precisam de calibração antes de produção.
|
||||
|
||||
## Transporte, falhas e observabilidade
|
||||
|
||||
O cliente usa `POST https://ai-gateway.vercel.sh/v1/decisions` com `typesafe-ai/jev`, API key em `Authorization`, timeout de 15 segundos por padrão e perguntas choice/predicate/score. Usa a biblioteca padrão do Python; não adiciona dependências de produção. A chamada bloqueante roda em thread para não bloquear o event loop.
|
||||
|
||||
Respostas incompletas, tipos incompatíveis, opções não declaradas, números inválidos, confiança abaixo do limite e erros de transporte acionam o provedor atual uma vez quando `DECISION_FALLBACK_TO_CURRENT=true`. Sem fallback, a exceção chega ao tratamento de falha já existente do componente; isso não redefine automaticamente cada política fail-open/fail-closed. Confiança ausente em choice/score é zero e aciona fallback no limite padrão. Para predicates usa-se a probabilidade do resultado selecionado. Para várias perguntas usa-se o mínimo das confianças.
|
||||
|
||||
O custo de uma chamada JEV seguida de fallback inclui ambas as etapas. Respostas recebidas são contabilizadas no repositório de uso e no evento `decision.jev` quando o provedor original oferece esses recursos, mesmo quando a validação rejeita a resposta. Logs registram ponto, modelo, duração, uso e falha/fallback, sem imprimir prompts, chave ou corpo de erro HTTP. Não há geração Langfuse de chat para chamadas JEV; a integração publica evento de decisão.
|
||||
|
||||
## Validação
|
||||
|
||||
Teste isolado, sem dependências do projeto ou API real:
|
||||
|
||||
```sh
|
||||
python3 tests/test_jev_transport_standalone.py
|
||||
```
|
||||
|
||||
Testes adicionais de integração em ambiente com dependências instaladas:
|
||||
|
||||
```sh
|
||||
PYTHONPATH=libs/agent_framework/src python -m pytest tests/test_jev_decisions.py tests/test_expected_input_semantic_classifier.py tests/unit/test_semantic_route_stickiness.py
|
||||
```
|
||||
|
||||
O teste isolado cobre contratos, seleção, precedência de configuração, fallback, erros, confiança, transporte e análise sintática dos módulos. Resultado local: 17 testes isolados passaram, incluindo execução dos corpos reais de continuidade, roteamento, reconciliação e judge calibrado com transporte simulado. A suíte completa não foi executada: as dependências do projeto não estavam disponíveis e a tentativa de instalação não conseguiu obtê-las. A suíte completa e a qualidade/latência do modelo real precisam ser verificadas no ambiente de execução. Não foi feita chamada real ao JEV.
|
||||
|
||||
Fontes de protocolo consultadas: https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-decisions e https://vercel.com/ai-gateway/models/jev.
|
||||
264
LICENSE.txt
Normal file
264
LICENSE.txt
Normal file
@@ -0,0 +1,264 @@
|
||||
The Universal Permissive License (UPL), Version 1.0
|
||||
This page provides a copy of and also attempts to answer some frequently asked questions about the Universal Permissive License version 1.0. The UPL was first drafted by Oracle in the Spring of 2014, was revised several times after extensive consultation with the Java Community Process Executive Committee and through the Open Source Initiative review process, and was finally approved by the Open Source Initiative in February 2015.
|
||||
|
||||
To begin with, this is the final approved text of the Universal Permissive License v 1.0:
|
||||
|
||||
Copyright (c) [year] [copyright holders]
|
||||
|
||||
The Universal Permissive License (UPL), Version 1.0
|
||||
|
||||
Subject to the condition set forth below, permission is hereby granted to any
|
||||
person obtaining a copy of this software, associated documentation and/or data
|
||||
(collectively the "Software"), free of charge and under any and all copyright
|
||||
rights in the Software, and any and all patent rights owned or freely
|
||||
licensable by each licensor hereunder covering either (i) the unmodified
|
||||
Software as contributed to or provided by such licensor, or (ii) the Larger
|
||||
Works (as defined below), to deal in both
|
||||
|
||||
(a) the Software, and
|
||||
(b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
|
||||
one is included with the Software (each a "Larger Work" to which the Software
|
||||
is contributed by such licensors),
|
||||
|
||||
without restriction, including without limitation the rights to copy, create
|
||||
derivative works of, display, perform, and distribute the Software and make,
|
||||
use, sell, offer for sale, import, export, have made, and have sold the
|
||||
Software and the Larger Work(s), and to sublicense the foregoing rights on
|
||||
either these or other terms.
|
||||
|
||||
This license is subject to the following condition:
|
||||
The above copyright notice and either this complete permission notice or at
|
||||
a minimum a reference to the UPL must be included in all copies or
|
||||
substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
When referring to the license, you may link to it at https://oss.oracle.com/licenses/upl or you may also find a copy on the Open Source Initiative web site at https://opensource.org/licenses/UPL.
|
||||
|
||||
Frequently Asked Questions
|
||||
What is the UPL and why did you create it?
|
||||
What are the most important features of the UPL?
|
||||
Can you point to some concrete problems the UPL solves that you could not have addressed with the MIT, BSD or Apache licenses?
|
||||
So why is the absence of an express patent license in the MIT or BSD licenses a problem - isn't the implied license enough?
|
||||
Why didn't you include a defensive patent termination provision?
|
||||
I heard this licenses our entire patent portfolio to Oracle, is that right?
|
||||
How should I apply the UPL to my code?
|
||||
What goes in the Larger Works file and what should it look like?
|
||||
Can someone else change my Larger Works file and license my patents for other things?
|
||||
What is the UPL and why did you create it?
|
||||
The UPL is a highly permissive license, including both copyright and patent licenses, which permits use and relicensing under both copyleft and commercial terms, and also facilitates use as a contributor license agreement.
|
||||
|
||||
It was originally borne out of a discussion in the Java Community Process around what it would take to permit collaboration on JSR reference implementations in open source forges without the necessity of collaborators signing the JSPA or an Oracle Contributor Agreement. In order to accommodate the broadest possible use case, the license needed to include an express patent license and to be broadly agreed to be GPLv2, GPLv2+Classpath Exception, CDDL, and commercial license compatible, including the ability to cut and paste code between modules, and while it is almost universally agreed among those knowledgeable in FOSS licensing that license proliferation is something to be avoided without good cause, since a license meeting these relatively simple and obvious criteria did not exist, it was decided to draft one.
|
||||
|
||||
Drafting started with the MIT license, and after a lot of discussion with other open source lawyers, developers, members of the Java Community Process Executive Committee, and reviewers and board members of the Open Source Initiative, and several rounds of revision, finally arrived at the vetted license text you see here. The license was approved by the OSI as conforming with the Open Source Definition and non-duplicative of existing permissive licenses in February 2015.
|
||||
|
||||
Return to FAQ.
|
||||
|
||||
What are the most important features of the UPL?
|
||||
The most important features and things to understand about the UPL are the following:
|
||||
|
||||
Clear patent protection. The UPL is a broad permissive license including both a copyright license and an express patent license, covering at least a version licensed by someone under the license (for example a distributor) and/or a version someone contributed to even if they never distribute the whole. (The reason the latter is needed is discussed below.) By virtue of the unambiguous patent license, the UPL is materially clearer with respect to the rights licensed and likely broader than either the MIT or BSD licenses.
|
||||
Clear & simplified relicensing. The UPL expressly permits sublicensing under either the UPL or under other terms, which clearly allows someone to relicense code received under the UPL either on copyleft terms, on proprietary terms, or otherwise, thus permitting maximum flexibility in reuse.
|
||||
Reduced overhead in source files. The UPL expressly permits use of the license without including a full copy of the text, which is useful for JavaScript or other cases where minimizing space consumed by licenses is desired - see below for our recommendation of how to apply the license or include proper attribution without the full text.
|
||||
It can be used as a contributor agreement. Finally, the UPL may be used as a contributor license agreement licensing both the software itself and also contributor patents for use in one or more "Larger Works." The Larger Works licensed in this fashion are designated by the use of a separate file accompanying the license, akin to the NOTICE file that accompanies the Apache License, Version 2.0. The Larger Works file can be used to control for both contributions to other works (for example, we could specify MySQL in a Larger Works file for a work, which would then license contributor patents for MySQL as well as the contribution), to set patent license scope for specific versions (for example, we could specify the approved reference implementation of JSR-xxx including Maintenance Releases to ensure that all contributors to an RI are licensing both the final version of the RI and qualified updates under the JCP program), or both.
|
||||
Return to FAQ.
|
||||
|
||||
Can you point to some concrete problems the UPL solves that you could not have addressed with the MIT, BSD or Apache licenses?
|
||||
The most important problem the UPL solves is the inclusion of an express patent license in a license that is both broadly agreed to be uniformly copyleft compatible and also permits the software to be freely used in commercially licensed software (i.e., without concerns about reciprocal license obligations).
|
||||
|
||||
The MIT and BSD licenses do not include express patent licenses, and while many argue that there is an implied patent license, there is nontrivial debate about the existence & scope of any such implied license. This is addressed in some more detail below. The Apache license, on the other hand, is argued by some not to be GPLv2 compatible, which makes it tricky to use in connection with GPLv2 licensed code - the GPLv2 is still by far the most popular open source license, and unambiguous, undisputed GPL compatibility was a crucial qualifier for any license considered for use in the JCP. (Even the BSD license has been argued not to be GPL compatible - while this need not be addressed here, and it is not the conclusion of the FSF or most others, by virtue of expressly permitting relicensing on other terms, the UPL is definitively and fully GPLv2 compatible.)
|
||||
|
||||
Another problem solved with the UPL, which seems like a small thing but adds compliance and clarity, is that licensors and distributors are expressly permitted to reference the UPL rather than including a complete copy of the text in each item. What is the license solving for here? The MIT and BSD licenses expressly require that you include a complete copy of the license in each piece of source code. This means that if you have 50 different JavaScript files being downloaded from a page, each one should be giving you a complete copy of the license - you may be using as much bandwidth for licenses as you do for the actual code! And if you do not include a complete copy of the license, as some folks do not, merely referring to the license by URL or name, then you are not really applying the license in the intended manner and are in fact suggesting that downstream recipients not strictly follow those terms either.
|
||||
|
||||
Finally, the inclusion of the Larger Works concept facilitates use as a contributor license agreement (CLA), with contributors granting a patent license to the works to which they're contributing, and therefore creating a common & safe platform for collaboration where no one is going to assert infringement by the same project in which they're an active participant.
|
||||
|
||||
Return to FAQ.
|
||||
|
||||
So why is the absence of an express patent license in the MIT or BSD licenses a problem - isn't the implied license enough?
|
||||
Some authorities think it is enough, but not everyone agrees on this point. To begin with, it has been suggested that in some jurisdictions there may be no implied license at all, or only a license to people to whom a licensor directly distributed the software.
|
||||
|
||||
But even if one were to take the position that a patent license covering any contribution is implied, and further that it covers the entirety of a work you distribute, in our world of cloud offerings, many contributors may never distribute the entirety of the work at all. This may reduce the likelihood that a court would find them to have granted an implied license for the whole of the work.
|
||||
|
||||
The UPL attempts to solve these problems by having each party that either contributes to the project or distributes it under the UPL expressly license all patents that they own or can freely license that cover the work - thus, e.g., licensing the whole even from contributors who never distribute the whole.
|
||||
|
||||
Return to FAQ.
|
||||
|
||||
Why isn't there a defensive patent termination provision?
|
||||
A defensive patent termination provision may sound like a great idea at first, especially for a pure open source project, but does not really work for contributions to software that is also licensed on commercial terms.
|
||||
|
||||
Why? A company that takes on commercial obligations with respect to a piece of code needs to retain the ability to keep supporting and shipping that code. A defensive patent termination provision allows someone who makes a contribution and then breaches the project license to the project to then potentially effectively block infringement suits against them, even when they have willfully and flagrantly disregarded community norms and IP rights in the project. Such a provision is therefore in reality as much of a sword as it is a shield.
|
||||
|
||||
Say, for example, that a fictional company WidgetCo were to make a contribution to fictional company GadgetCo's product GadgetX under a license with a patent termination provision. Now, WidgetCo decides to violate GadgetCo's terms and distribute GadgetX without a license. GadgetCo's options for stopping the violation would ordinarily include both copyright and also patent infringement claims for any patents covering GadgetX. If, on the other hand, WidgetCo has made patent covered contributions under an agreement with a so-called defensive termination clause, GadgetCo's ability to stop WidgetCo from violating the license may be significantly compromised because it can no longer bring patent claims without risking losing its own license to the patents on the contributions, which therefore might require it to stop shipping GadgetX immediately and stop supporting versions that customers are relying on.
|
||||
|
||||
As a commercial distributor of software, GadgetCo's customers rely on it to have the rights it needs to be able to continue to deliver and support the software, and defensive patent termination rights in contributions are inconsistent with those obligations. Defensive patent termination only helps someone who may be subject to infringement litigation by someone who is using the code - it won't stop patent trolls, who aren't normally using the code to begin with. So who does it stop, in reality? Someone who is using the code but has IP rights that someone else using the code is infringing. Now, it may be reasonable to tell someone who has no relationship to a community that they cannot simultaneously expect to be able to use the code and also sue for its use - thus making such provisions at least not entirely crazy for a pure FOSS project that no one is signing up to develop or support on a commercial basis, and which is rarely if ever going to need to enforce its rights anyway. But for anyone who both actually expects to need to enforce its license and also wants to take contributions, this makes no sense - you need to be able to enforce your rights in the project without needing to stop shipping or using it, and accepting contributions under terms with a patent termination provision does not satisfy this basic need.
|
||||
|
||||
Return to FAQ.
|
||||
|
||||
I heard this licenses our entire patent portfolio to Oracle, is that right?
|
||||
No, it is not, this is simply untrue except in odd and contrived circumstances that would apply to other FOSS licenses as well. If your entire patent portfolio happens to read on a UPL licensed project that you have distributed on those terms or contributed to, or its designated Larger Works, then yes, it would all be licensed for use in that Software and those specified Larger Works, not just to Oracle but to all licensees under the UPL, just as it would all be licensed for a project under the Apache Software License or Eclipse Public License if your entire portfolio read on a project under the ASL or EPL. Patents that do not read on the project as you contributed to or distributed it or the specified Larger Works are not licensed, there is no magic here.
|
||||
|
||||
The patent scope is not really all that complicated. It covers your contributions, the project you contributed to in the state it existed when you contributed, and anything specified in the Larger Works file (which may be another application, it may be other or later versions, it may be a piece of hardware, or any combination of those things - or, just as importantly, it may be none of those things, since many projects may have no Larger Works file at all, in which case the patent license is little different than the express patent license in the Apache license, only without the so-called defensive termination provision).
|
||||
|
||||
Return to FAQ.
|
||||
|
||||
How should I apply the UPL to my code?
|
||||
It is best to insert a copyright notice and a copy of the license at the top of each source file, and if there is a package of numerous files, to also insert a LICENSE file including a copy of the UPL in the root of the distribution. Here is an example:
|
||||
|
||||
/*
|
||||
** MyWidget version 1.0.
|
||||
**
|
||||
** Copyright (c) 2015 WidgetCo, Inc.
|
||||
**
|
||||
** The Universal Permissive License (UPL), Version 1.0
|
||||
**
|
||||
** Subject to the condition set forth below, permission is hereby granted to any
|
||||
** person obtaining a copy of this software, associated documentation and/or data
|
||||
** (collectively the "Software"), free of charge and under any and all copyright
|
||||
** rights in the Software, and any and all patent rights owned or freely
|
||||
** licensable by each licensor hereunder covering either (i) the unmodified
|
||||
** Software as contributed to or provided by such licensor, or (ii) the Larger
|
||||
** Works (as defined below), to deal in both
|
||||
**
|
||||
** (a) the Software, and
|
||||
** (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
|
||||
** one is included with the Software (each a "Larger Work" to which the Software
|
||||
** is contributed by such licensors),
|
||||
**
|
||||
** without restriction, including without limitation the rights to copy, create
|
||||
** derivative works of, display, perform, and distribute the Software and make,
|
||||
** use, sell, offer for sale, import, export, have made, and have sold the
|
||||
** Software and the Larger Work(s), and to sublicense the foregoing rights on
|
||||
** either these or other terms.
|
||||
**
|
||||
** This license is subject to the following condition:
|
||||
** The above copyright notice and either this complete permission notice or at
|
||||
** a minimum a reference to the UPL must be included in all copies or
|
||||
** substantial portions of the Software.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
** SOFTWARE.
|
||||
*/
|
||||
If using the UPL for JavaScript or other circumstances in which space is at a premium, you may use a reference to the license rather than a full copy (though a full copy is always preferred if there's room and you won't be transmitting a bunch of copies to the same user). If you want to use just a short reference, you should still insert a copyright notice, and along with it, a statement that the file is licensed under the UPL, and may link to it at https://oss.oracle.com/licenses/upl or on the Open Source Initiative web site at https://opensource.org/licenses/UPL.
|
||||
|
||||
Here is an example header with a short reference for use in source code:
|
||||
|
||||
/*
|
||||
** MyWidget version 1.0.
|
||||
**
|
||||
** Copyright (c) 2015 WidgetCo, Inc.
|
||||
** Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
|
||||
*/
|
||||
Return to FAQ.
|
||||
|
||||
What goes in the Larger Works file and what should it look like?
|
||||
To begin with, we should note that the Larger Works concept will be irrelevant to many people and to be clear, there is no need to license any Larger Works at all in order to use the UPL on your code - this is still advantageous versus other permissive licenses because licensees can count on a patent license of unambiguous scope from each contributor, can freely relicense the code as necessary for their needs, and can abbreviate the license notice if appropriate.
|
||||
|
||||
The purpose of the Larger Works addition to the license is to allow you to use the UPL as a contributor license agreement, commonly referred to as a CLA, licensing patents for a specified larger work or set of works with which contributions may be used. If you desire to use the UPL as a CLA, in addition to including the UPL and/or references to it in your source, you should insert a lrgrwrks.txt file in the root of the distribution specifying the licensed Larger Works. You will name the licensed project/product there, and if appropriate, specify what versions are covered. In theory you could use a single word naming a product, which would be effective, but some slightly prettier examples are as follows.
|
||||
|
||||
Here is what we are hoping to use in connection with JCP Reference Implementations:
|
||||
|
||||
/* Larger Works File for JSR-xxx
|
||||
**
|
||||
** Licensed Larger Works: The Reference Implementation for JSR-xxx Including Maintenance Releases
|
||||
** as defined in the JCP Procedures documentation.
|
||||
*/
|
||||
So what is the intent here? We are not expanding the scope of the licensed project beyond the RI, however, we want to make sure that the RI is fully covered such that an early contributor who stops adding new code still licenses the RI as a whole, including Maintenance Releases down the line.
|
||||
|
||||
A somewhat broader example is as follows:
|
||||
|
||||
/* Larger Works File for MyWidget
|
||||
**
|
||||
** Larger Works: MyApp
|
||||
*/
|
||||
Here, someone has set up the Larger Works file to act as a CLA for the application MyApp. The licensors of MyWidget are also licensing their patents for use in MyApp, and because there is no version restriction, this is presumably true for future versions of MyApp as well as the current version. If they wanted to license only the current version, they could have said:
|
||||
|
||||
/* Larger Works File for MyWidget
|
||||
**
|
||||
** Larger Works: MyApp 1.0
|
||||
*/
|
||||
Or if Company A wanted to use the UPL with a Larger Works file as a CLA for all of their products, they could use one of the following:
|
||||
|
||||
/* Larger Works File for Contributions to Company A Projects
|
||||
**
|
||||
** Larger Works: All Software Authored or Distributed by Company A
|
||||
*/
|
||||
or
|
||||
|
||||
/* Larger Works File for Contributions to Company A Projects
|
||||
**
|
||||
** Larger Works: All Company A Products and Projects
|
||||
*/
|
||||
If the Apache Software Foundation wanted to use the UPL as a CLA, they could use the following:
|
||||
|
||||
/* Larger Works File for Contributions to ASF Projects
|
||||
**
|
||||
** Larger Works: All Apache Software Foundation Projects
|
||||
*/
|
||||
or even more broadly, to include dependencies that are not ASF projects:
|
||||
|
||||
/* Larger Works File for Contributions to ASF projects
|
||||
**
|
||||
** Larger Works: All Apache Software Foundation projects and their dependencies
|
||||
*/
|
||||
or they could make it project specific, for single or multiple Projects:
|
||||
|
||||
/* Larger Works File for Contributions to Apache Ant & Maven
|
||||
**
|
||||
** Larger Works: Apache Ant and Apache Maven and their subprojects
|
||||
*/
|
||||
or project and version specific:
|
||||
|
||||
/* Larger Works File for Contributions to Cassandra
|
||||
**
|
||||
** Larger Works: Apache Cassandra 2.0.15 and updates other than major version updates
|
||||
*/
|
||||
or subject area specific:
|
||||
|
||||
/* Larger Works File for Contributions to Build Tools
|
||||
**
|
||||
** Larger Works: All Apache Software Foundation projects pertaining to software builds and related processes, including without
|
||||
** limitation Ant, Ant Libraries, Ivy, IvyDE, EasyAnt, Maven and other software for controlling build processes tools
|
||||
*/
|
||||
As you can see, the intent of the Larger Works file is to permit nearly infinite flexibility in what is being licensed beyond the Software itself, as every company and FOSS project has different needs. Note that while a comment format has been used for these examples, since this is not executable code, this isn't strictly necessary, it was done as a matter of habit and in case someone imports one of the files into some executable code.
|
||||
|
||||
Return to FAQ.
|
||||
|
||||
Can someone else change my Larger Works file and license my patents for other things?
|
||||
To begin with, a party who alters the Larger Works file cannot alter the scope of the license someone else granted, any more than they could alter the license text of the UPL, the GPL, or any other license and assert that the original licensors are bound by their changes. So no one can offer a broader license to your patents than the one you declared. The only power they have is to sublicense downstream recipients on different terms under whatever IP rights they have.
|
||||
|
||||
And on the flip side, what happens if someone simply removes the Larger Works file from a code base and then redistributes without it? Then they are sublicensing the code to a downstream recipient on other terms, without any Larger Works being licensed under their own patents, though the license from the original licensors would still survive on those terms as to people who receive the Software from other sources.
|
||||
|
||||
Similarly, if someone alters the Larger Works file and then distributes the code to new recipients themselves under the UPL, then that new distributor is granting a license of a different scope than the one granted by the original authors, which they are permitted to do, just as they would be permitted to grant their own license to the code under the GPL or a commercial license. However, the polite thing to do in this case would be to address the altered scope of their license in the Larger Works file while leaving intact the Larger Works designation from prior licensors. Let's say, for example, we start off with a Larger Works file that looks like this, covering all of Java:
|
||||
|
||||
/* Larger Works File for Contributions to Project X
|
||||
**
|
||||
** Larger Works: All Oracle Java implementations including without limitation Oracle Java EE, Java SE, Java ME, and OpenJDK
|
||||
*/
|
||||
This would grant a license to all of Java from each contributor on those terms. Now let's say Company A only wants to license a particular JSR, not all of Java. They would ideally add separate license and Larger Works files that travel with their contributions calling out only that JSR, most effectively by placing them in a separate directly clearly demarcating what is under that license. (Separating these things out is always a trick when you try to commingle source in the same file, but if you keep files separate, this is not generally difficult.)
|
||||
|
||||
In the alternative, if the contributions were not easily separable from the larger project in another directory, and for some reason they could not add a separate directory just for the license either, and therefore absolutely needed a way to combine their own, distinct Larger Works designation with that from others, they could in theory also add their own declaration to the existing Larger Works file without purporting to change the license from others as follows:
|
||||
|
||||
/* Larger Works File for Contributions to Project X
|
||||
**
|
||||
** Larger Works: All Oracle Java implementations including without limitation Oracle Java EE, Java SE, Java ME, and OpenJDK
|
||||
**
|
||||
** Exception: Company A licenses only the following Larger Works: The Reference Implementation for JSR-xxx including
|
||||
** Maintenance Releases as defined in the JCP Procedures documentation
|
||||
*/
|
||||
This would therefore clearly inform a recipient that only the RI was licensed under Company A's patents, but leave intact the reference to the broader license from other contributors.
|
||||
|
||||
There are certainly other possibilities for accommodating multiple Larger Works scopes as well, about which your counsel can advise you.
|
||||
|
||||
Return to FAQ.
|
||||
|
||||
Return to top.
|
||||
133
LOCALIZACAO.md
Normal file
133
LOCALIZACAO.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# Termos e frases configuráveis — pt-BR e en
|
||||
|
||||
Esta distribuição inclui dois catálogos completos, em JSON UTF-8:
|
||||
|
||||
- `libs/agent_framework/src/agent_framework/locales/pt-BR.json`
|
||||
- `libs/agent_framework/src/agent_framework/locales/en.json`
|
||||
|
||||
Cada arquivo reúne termos reconhecidos, mensagens padronizadas, instruções de
|
||||
recuperação de guardrails e padrões de extração. JSON permite editar o catálogo
|
||||
sem uma dependência adicional no carregador. Os dois arquivos usam as mesmas chaves.
|
||||
|
||||
## Selecionar o idioma
|
||||
|
||||
No `.env` do backend:
|
||||
|
||||
```dotenv
|
||||
AGENT_LOCALE=en
|
||||
```
|
||||
|
||||
Para português, use `AGENT_LOCALE=pt-BR` ou omita a variável. Também são aceitos
|
||||
`pt`, `pt_BR`, `en-US` e `en-GB`. Uma opção inexistente gera erro; não há troca
|
||||
silenciosa para português quando o idioma solicitado não está disponível.
|
||||
|
||||
O idioma é o padrão do backend. Os prompts e as configurações de negócio dos
|
||||
agentes continuam sendo definidos pelo projeto; use prompts e descrições no
|
||||
idioma desejado. Esta alteração não traduz automaticamente conteúdos de RAG,
|
||||
respostas dos servidores MCP, mensagens declaradas por um workflow, arquivos de
|
||||
exemplo, regras de negócio ou textos personalizados do aplicativo/frontend.
|
||||
Prompts internos de classificação podem continuar em português: as decisões são
|
||||
estruturadas. As instruções de recuperação que impunham português foram separadas
|
||||
nos catálogos, incluindo sua variante em inglês.
|
||||
|
||||
## Personalizar sem alterar a biblioteca
|
||||
|
||||
Copie os catálogos para um diretório da aplicação e configure:
|
||||
|
||||
```dotenv
|
||||
AGENT_LOCALE=en
|
||||
AGENT_LOCALES_DIR=./config/locales
|
||||
```
|
||||
|
||||
Nesse exemplo, o arquivo usado será `./config/locales/en.json`. O catálogo é
|
||||
completo, e não um arquivo de alterações parciais. Preserve as chaves e os campos
|
||||
como `{action}`, `{target}`, `{options}` e `{subject}` ao traduzir as frases.
|
||||
Não é necessário manter a mesma quantidade de termos nas listas.
|
||||
|
||||
Reinicie o backend após editar os arquivos: o carregador mantém os catálogos em
|
||||
cache. Na inicialização, ele verifica a estrutura, os campos das mensagens, a
|
||||
sintaxe dos padrões e conflitos entre confirmação e recusa.
|
||||
|
||||
As principais seções são:
|
||||
|
||||
| Seção | Conteúdo |
|
||||
|---|---|
|
||||
| `terms.confirmation` | Confirmações e recusas explícitas de transações |
|
||||
| `terms.workflow` | Respostas de compatibilidade para checkpoints antigos |
|
||||
| `terms.multi_intent` | Conjunções, verbos e prefixos de confirmação |
|
||||
| `terms.global_router` | Termos de continuidade e encerramento |
|
||||
| `terms.groundedness` | Indícios de especificidade e incerteza |
|
||||
| `terms.mock` | Termos dos classificadores locais usados em testes/desenvolvimento |
|
||||
| `messages` | Frases de confirmação, nova tentativa, esclarecimento e fallback |
|
||||
| `prompts.fallback` | Instruções de reescrita e regeneração por guardrail |
|
||||
| `prompts.judge_rewrite` | Instruções de recuperação dos judges |
|
||||
| `memory` | Padrões para extração de memória de longo prazo |
|
||||
| `protocol` | Dígitos, letras e nomes usados na vocalização de protocolos |
|
||||
| `safety` | Padrões determinísticos de segurança e escopo |
|
||||
| `legacy_extraction` | Padrões do extrator legado de pedido/motivo |
|
||||
|
||||
## Decisões internas e contratos de workflow
|
||||
|
||||
Os códigos internos permanecem estáveis: `confirm`, `reject`, `SIM`, `NAO`,
|
||||
`OUTRO` e nomes de estados não devem ser traduzidos em arquivos existentes.
|
||||
O catálogo trata as palavras reconhecidas e os textos apresentados.
|
||||
|
||||
Um workflow que declara `expected_input`, `reprompt` ou mensagens próprias
|
||||
continua tendo precedência. Para aceitar `YES` e `NO` em um contrato enumerado,
|
||||
configure essas opções no workflow e ajuste suas transições, ou mantenha os
|
||||
códigos atuais e use seu classificador semântico para mapear as respostas.
|
||||
O dicionário global não substitui silenciosamente o contrato de um fluxo.
|
||||
|
||||
As listas de confirmação transacional usam correspondência da frase completa,
|
||||
ignorando maiúsculas, espaços repetidos e pontuação final simples. Não inclua
|
||||
frases ambíguas como “entendi”/“understood” nessas listas: compreender uma
|
||||
explicação não equivale a autorizar uma operação. O fallback semântico existente
|
||||
continua disponível para respostas que não constam do catálogo.
|
||||
|
||||
Os padrões de segurança mantêm cobertura em português e inglês nos dois arquivos.
|
||||
Nomes de concorrentes presentes em `safety` preservam a configuração original de
|
||||
telecom; adapte essas regras quando mudar o domínio da aplicação.
|
||||
|
||||
## Vários idiomas no mesmo processo
|
||||
|
||||
Para aplicações que selecionam o idioma por agente ou atendimento, envolva a
|
||||
execução completa (roteamento, runtime e guardrails) no contexto correspondente:
|
||||
|
||||
```python
|
||||
from agent_framework.localization import use_locale
|
||||
|
||||
with use_locale("en"):
|
||||
# Execute aqui o roteamento, o agente e seus guardrails.
|
||||
result = await handle_turn(...)
|
||||
```
|
||||
|
||||
`handle_turn` representa o ponto de entrada da sua aplicação; não é uma nova API
|
||||
do framework. O contexto usa `ContextVar`, é isolado entre tarefas assíncronas e
|
||||
restaura o idioma anterior ao sair. Não altere `os.environ` a cada atendimento.
|
||||
O idioma da conversa não é detectado automaticamente.
|
||||
|
||||
## Validação desta entrega
|
||||
|
||||
- 41 testes novos de localização aprovados.
|
||||
- 160 testes selecionados aprovados após a atualização de oito testes antigos.
|
||||
- As oito expectativas antigas estavam desalinhadas com mudanças de contrato
|
||||
anteriores à localização. Histórico, escopo e validação estão em
|
||||
`ATUALIZACAO_TESTES.md`. Os 66 testes dos quatro arquivos atualizados também
|
||||
passaram com a biblioteca original do ZIP.
|
||||
- As verificações incluem execução/cancelamento real do runtime com ferramentas
|
||||
simuladas, confirmação determinística no roteador sem LLM, múltiplas intenções,
|
||||
retomada de workflows, memória, protocolos, segurança, concorrência e catálogo
|
||||
personalizado.
|
||||
- Não foram feitas chamadas a modelos remotos, OCI ou ferramentas reais de negócio.
|
||||
|
||||
Os testes novos estão em `tests/test_locale_catalogs.py`. Para executá-los em um
|
||||
ambiente com as dependências do projeto e pytest/pytest-asyncio:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=libs/agent_framework/src pytest -q tests/test_locale_catalogs.py
|
||||
```
|
||||
|
||||
O pacote de entrega conserva os arquivos do projeto e remove metadados do macOS,
|
||||
cache de bytecode, builds antigos e diretórios de Git/IDE. As fontes corrigidas
|
||||
ficam em `libs/agent_framework/src`. As variantes de demonstração em
|
||||
`Tuning-Performance` mantêm suas configurações de domínio originais.
|
||||
1920
MANUAL_REGRAS_AGENT_TEMPLATE_BACKEND.md
Normal file
1920
MANUAL_REGRAS_AGENT_TEMPLATE_BACKEND.md
Normal file
File diff suppressed because it is too large
Load Diff
1917
MANUAL_RULES_AGENT_TEMPLATE_BACKEND_EN.md
Normal file
1917
MANUAL_RULES_AGENT_TEMPLATE_BACKEND_EN.md
Normal file
File diff suppressed because it is too large
Load Diff
29
MULTI_ITEM_FRAMEWORK_FIX_20260918.md
Normal file
29
MULTI_ITEM_FRAMEWORK_FIX_20260918.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Multi-item result preservation fix
|
||||
|
||||
## Objective
|
||||
Preserve the terminal outcome of each item executed by the primary transactional tool. A failure in a later auxiliary/composite step must not erase successful item outcomes or turn an already-completed multi-item operation into a total failure.
|
||||
|
||||
## Framework-only change
|
||||
No agent/template business logic is required for this fix. The runtime now recognizes an explicit structural contract on the requested tool: a `results` array with two or more entries carrying boolean `success` or `ok` fields.
|
||||
|
||||
For workflow-backed tools the authoritative source is preferentially:
|
||||
|
||||
`workflow.output[tool_name].results`
|
||||
|
||||
The framework derives one of:
|
||||
- `SUCCESS`
|
||||
- `PARTIAL_SUCCESS`
|
||||
- `FAILED`
|
||||
|
||||
and publishes a generic `metadata.multi_item` summary with item counts.
|
||||
|
||||
When one or more primary items completed successfully but the outer wrapper is `ok=false` because a later auxiliary/post-processing step failed, the normalized result preserves the original failure as `original_ok=false` / `secondary_error` while exposing the requested operation as operationally successful (`ok=true`).
|
||||
|
||||
The LLM context also receives an explicit generic instruction that successful per-item terminal evidence cannot be overwritten by a secondary error and that mixed outcomes must be reported individually.
|
||||
|
||||
## Regression tests
|
||||
Added `tests/test_multi_item_result_normalization.py` covering:
|
||||
- 2 success + 1 failure -> `PARTIAL_SUCCESS`;
|
||||
- all primary items successful + later secondary failure -> primary `SUCCESS` preserved;
|
||||
- single-item behavior unchanged;
|
||||
- unrelated nested tool results cannot override failure of the requested primary tool.
|
||||
17
OBSERVABILITY_FIX_NOTES.md
Normal file
17
OBSERVABILITY_FIX_NOTES.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Observability severity patch
|
||||
|
||||
- Central `severity_policy.py` classifies explicit MCP failures, guardrail blocks, judge rejections, RAG failures and memory/cache errors.
|
||||
- `Telemetry.event()` accepts `level` and `status_message` and preserves WARNING/ERROR events as individual observations in compact mode.
|
||||
- `Telemetry.span()` handle supports `set_status(level, message)`; failed MCP results mark their span ERROR without raising exceptions.
|
||||
- Long-term-memory read/write failures emit telemetry while preserving existing fallback behavior.
|
||||
- Guardrail blocked and negative judge evaluation emit WARNING when these helper methods are invoked.
|
||||
- Normal cache misses and empty RAG results are not automatically failures.
|
||||
|
||||
## Scope / limitations
|
||||
- Existing call sites must invoke `GuardrailTelemetry.blocked` for guardrail blocking events; this patch does not rewrite every pipeline call site.
|
||||
- Redis cache currently has no injected Telemetry instance, so its existing logger errors are not yet Langfuse observations. A separate dependency-injection change is required to cover that path safely.
|
||||
- RAG database connection errors that are caught by external KBDB integrations without emitting a telemetry event cannot be classified automatically.
|
||||
- No live Langfuse ingestion test was possible in this environment. Verify both compact and verbose modes against your server.
|
||||
|
||||
## Validation
|
||||
`PYTHONPATH=libs/agent_framework/src python -m pytest -q tests/test_observability_severity_policy.py`
|
||||
11084
README_en.md
11084
README_en.md
File diff suppressed because it is too large
Load Diff
11900
README_pt.md
Normal file
11900
README_pt.md
Normal file
File diff suppressed because it is too large
Load Diff
38
SECURITY.md
Normal file
38
SECURITY.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Reporting security vulnerabilities
|
||||
|
||||
Oracle values the independent security research community and believes that
|
||||
responsible disclosure of security vulnerabilities helps us ensure the security
|
||||
and privacy of all our users.
|
||||
|
||||
Please do NOT raise a GitHub Issue to report a security vulnerability. If you
|
||||
believe you have found a security vulnerability, please submit a report to
|
||||
[secalert_us@oracle.com][1] preferably with a proof of concept. Please review
|
||||
some additional information on [how to report security vulnerabilities to Oracle][2].
|
||||
We encourage people who contact Oracle Security to use email encryption using
|
||||
[our encryption key][3].
|
||||
|
||||
We ask that you do not use other channels or contact the project maintainers
|
||||
directly.
|
||||
|
||||
Non-vulnerability related security issues including ideas for new or improved
|
||||
security features are welcome on GitHub Issues.
|
||||
|
||||
## Security updates, alerts and bulletins
|
||||
|
||||
Security updates will be released on a regular cadence. Many of our projects
|
||||
will typically release security fixes in conjunction with the
|
||||
Oracle Critical Patch Update program. Additional
|
||||
information, including past advisories, is available on our [security alerts][4]
|
||||
page.
|
||||
|
||||
## Security-related information
|
||||
|
||||
We will provide security related information such as a threat model, considerations
|
||||
for secure use, or any known security issues in our documentation. Please note
|
||||
that labs and sample code are intended to demonstrate a concept and may not be
|
||||
sufficiently hardened for production use.
|
||||
|
||||
[1]: mailto:secalert_us@oracle.com
|
||||
[2]: https://www.oracle.com/corporate/security-practices/assurance/vulnerability/reporting.html
|
||||
[3]: https://www.oracle.com/security-alerts/encryptionkey.html
|
||||
[4]: https://www.oracle.com/security-alerts/
|
||||
@@ -37,3 +37,27 @@ AGENT_AUTH_BASIC_REALM=agent-contas
|
||||
# AGENT_AUTH_PROXY_SUBJECT_HEADER=x-authenticated-subject
|
||||
# AGENT_AUTH_PROXY_SHARED_SECRET_HEADER=x-internal-auth
|
||||
# AGENT_AUTH_PROXY_SHARED_SECRET_HASH=sha256:replace-hex
|
||||
|
||||
|
||||
# RAG / KBDB
|
||||
# RAG provider: standard (local) ou kbdb (PKG_KB_SERVING.SEARCH_KNOWLEDGE_BASE)
|
||||
RAG_PROVIDER=standard
|
||||
# KBDB usa credenciais próprias; não há fallback para ADB_*.
|
||||
KBDB_DB_USER=
|
||||
KBDB_DB_PASSWORD=
|
||||
KBDB_DB_DSN=
|
||||
KBDB_DB_WALLET_LOCATION=
|
||||
KBDB_DB_WALLET_PASSWORD=
|
||||
KBDB_SEARCH_TYPE=hybrid
|
||||
KBDB_NODE_EXPANSION=true
|
||||
KBDB_NODE_MAX_RELATED=8
|
||||
KBDB_GRAPH_CROSS_REF=false
|
||||
KBDB_MAX_CROSS_REF_HOPS=1
|
||||
KBDB_DOCUMENT_TYPE=customer_safe
|
||||
KBDB_METADATA_JSON=
|
||||
KBDB_MIN_SCORE=
|
||||
KBDB_IDENTIFY_DOCUMENT=true
|
||||
KBDB_STORE_QUERY=true
|
||||
KBDB_IDENTIFY_TOP_N=3
|
||||
RAG_GROUNDED_ONLY=false
|
||||
KBDB_GROUNDED_ONLY=true
|
||||
|
||||
@@ -108,6 +108,14 @@ class BillingAgent(AgentRuntimeMixin):
|
||||
"next_state": "BILLING_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
@@ -108,6 +108,14 @@ class OrdersAgent(AgentRuntimeMixin):
|
||||
"next_state": "ORDER_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
@@ -108,6 +108,14 @@ class ProductAgent(AgentRuntimeMixin):
|
||||
"next_state": "PRODUCT_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -108,6 +108,14 @@ class SupportAgent(AgentRuntimeMixin):
|
||||
"next_state": "SUPPORT_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
@@ -369,9 +369,12 @@ async def _process_gateway_message(req: GatewayRequest, emit_sse: bool = False)
|
||||
"route": result.get("route"),
|
||||
"intent": result.get("intent"),
|
||||
"route_decision": result.get("route_decision"),
|
||||
"supervisor_results": result.get("supervisor_results") or [],
|
||||
"agent_responses": result.get("agent_responses") or result.get("supervisor_results") or [],
|
||||
"domain": result.get("domain"),
|
||||
"mcp_tools": result.get("mcp_tools"),
|
||||
"mcp_results": result.get("mcp_results"),
|
||||
"rag_results": result.get("rag_results"),
|
||||
"business_context": business_context.model_dump(),
|
||||
"identity_missing": missing_identity_keys,
|
||||
"judges": result.get("judge_results"),
|
||||
|
||||
@@ -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)
|
||||
@@ -23,9 +23,12 @@ class AgentState(TypedDict, total=False):
|
||||
domain: str
|
||||
mcp_tools: list[str]
|
||||
mcp_results: list[dict[str, Any]]
|
||||
rag_results: list[dict[str, Any]]
|
||||
available_mcp_tools: list[str]
|
||||
selected_tool_call: dict[str, Any]
|
||||
pending_tool_call: dict[str, Any]
|
||||
active_transaction: dict[str, Any]
|
||||
last_transaction: dict[str, Any]
|
||||
transaction_status: str
|
||||
confirmation_required: bool
|
||||
confirmation_received: bool
|
||||
@@ -33,6 +36,11 @@ class AgentState(TypedDict, total=False):
|
||||
missing_parameters: list[str]
|
||||
supervisor_plan: dict[str, Any]
|
||||
supervisor_results: list[dict[str, Any]]
|
||||
agent_responses: list[dict[str, Any]]
|
||||
pending_topics: list[dict[str, Any]]
|
||||
handled_topics: list[dict[str, Any]]
|
||||
operation_results: dict[str, dict[str, Any]]
|
||||
multi_intent_plan: dict[str, Any]
|
||||
active_agent: str
|
||||
route_bypassed: bool
|
||||
continuity_signal: dict[str, Any]
|
||||
|
||||
Binary file not shown.
@@ -7,6 +7,7 @@ from agent_framework.guardrails.rail_action import RailAction
|
||||
from agent_framework.guardrails.rail_result import RailResult
|
||||
from agent_framework.judges.judge import JudgePipeline
|
||||
from agent_framework.routing.enterprise_router import EnterpriseRouter
|
||||
from agent_framework.routing.pending_topics import drain_pending_topics
|
||||
from agent_framework.supervisor.supervisor import Supervisor
|
||||
from agent_framework.observability.workflow_events import WorkflowTelemetry
|
||||
from agent_framework.observability.guardrail_events import GuardrailTelemetry
|
||||
@@ -109,7 +110,6 @@ class AgentWorkflow:
|
||||
fail_fast=bool(getattr(settings, "GUARDRAILS_FAIL_FAST", True)),
|
||||
)
|
||||
self.judges = JudgePipeline()
|
||||
self.supervisor = Supervisor()
|
||||
self.workflow_telemetry = WorkflowTelemetry(telemetry)
|
||||
self.guardrail_telemetry = GuardrailTelemetry(telemetry)
|
||||
self.judge_telemetry = JudgeTelemetry(telemetry)
|
||||
@@ -118,6 +118,14 @@ class AgentWorkflow:
|
||||
self.embedding_provider = create_embedding_provider(settings)
|
||||
self.rag_service = RagService(settings, embedding_provider=self.embedding_provider, telemetry=telemetry)
|
||||
self.router = EnterpriseRouter(settings, llm=llm, telemetry=telemetry)
|
||||
self.supervisor = Supervisor(
|
||||
routing_rules=[
|
||||
(intent.name, intent.agent, list(intent.keywords))
|
||||
for intent in self.router.intents
|
||||
if intent.enabled
|
||||
],
|
||||
fallback_agent=self.router.fallback_agent,
|
||||
)
|
||||
agent_kwargs = {"telemetry": telemetry, "tool_router": getattr(self, "tool_router", None), "rag_service": self.rag_service, "cache": self.cache, "settings": settings, "observer": self.observer, "memory": memory, "summary_memory": summary_memory}
|
||||
self.billing = BillingAgent(llm, **agent_kwargs)
|
||||
self.product = ProductAgent(llm, **agent_kwargs)
|
||||
@@ -160,7 +168,7 @@ class AgentWorkflow:
|
||||
builder.add_conditional_edges(
|
||||
"input_guardrails",
|
||||
self._after_input_guardrails,
|
||||
{"blocked": "persist", "continue": "load_long_term_memory"},
|
||||
{"blocked": "output_guardrails", "continue": "load_long_term_memory"},
|
||||
)
|
||||
builder.add_edge("load_long_term_memory", "routing_decision")
|
||||
builder.add_conditional_edges(
|
||||
@@ -197,6 +205,31 @@ class AgentWorkflow:
|
||||
def _after_input_guardrails(self, state):
|
||||
return "blocked" if state.get("blocked") else "continue"
|
||||
|
||||
@staticmethod
|
||||
def _input_guardrail_user_message(decisions, state, sanitized_text):
|
||||
# Keep the technical guardrail reason in telemetry, but expose only a
|
||||
# safe, actionable message to the end user. The message is intentionally
|
||||
# routed through output_guardrails before persistence/delivery.
|
||||
blocked = [d for d in decisions if not getattr(d, "allowed", True)]
|
||||
first = blocked[0] if blocked else None
|
||||
code = str(getattr(first, "code", "") or "").upper()
|
||||
if code == "COER":
|
||||
return (
|
||||
"Não consegui entender sua última mensagem porque ela parece "
|
||||
"incompleta ou ambígua. Pode reformular ou completar o que você quis dizer?"
|
||||
)
|
||||
if code == "INPUT_SIZE":
|
||||
return "Sua mensagem ficou muito longa para eu processar de uma vez. Pode resumir ou dividir em partes?"
|
||||
if code == "DLEX_IN":
|
||||
return "Não posso usar essa informação da forma solicitada. Reformule o pedido sem incluir dados ou conteúdo restrito."
|
||||
if code == "PINJ":
|
||||
return "Não posso seguir instruções que tentem alterar as regras do atendimento. Posso continuar ajudando com a sua solicitação."
|
||||
if code == "TOX":
|
||||
return "Não consegui prosseguir com essa mensagem. Pode reformular o pedido para continuarmos o atendimento?"
|
||||
if code == "CMP":
|
||||
return "Não posso prosseguir com essa solicitação dessa forma. Posso ajudar com uma alternativa permitida."
|
||||
return "Não consegui processar essa mensagem. Pode reformular para eu continuar o atendimento?"
|
||||
|
||||
async def input_guardrails(self, state):
|
||||
if state.get("session_ended") is True:
|
||||
answer = str(getattr(
|
||||
@@ -222,6 +255,28 @@ class AgentWorkflow:
|
||||
input=state.get("user_text"),
|
||||
):
|
||||
history_texts = [m.get("content", "") for m in state.get("history", [])]
|
||||
guardrail_active_transaction = (
|
||||
state.get("active_transaction")
|
||||
if isinstance(state.get("active_transaction"), dict)
|
||||
else {}
|
||||
)
|
||||
guardrail_transaction_status = str(
|
||||
guardrail_active_transaction.get("status")
|
||||
or state.get("transaction_status")
|
||||
or ""
|
||||
).strip().upper()
|
||||
pending_call = state.get("pending_tool_call") if isinstance(state.get("pending_tool_call"), dict) else {}
|
||||
if state.get("confirmation_required") and pending_call.get("tool_name"):
|
||||
guardrail_transaction_status = "AWAITING_CONFIRMATION"
|
||||
elif state.get("missing_parameters") and pending_call.get("tool_name"):
|
||||
guardrail_transaction_status = "COLLECTING_PARAMETERS"
|
||||
for mcp_result in reversed(list(state.get("mcp_results") or [])):
|
||||
if not isinstance(mcp_result, dict):
|
||||
continue
|
||||
mcp_status = str(mcp_result.get("transaction_status") or "").strip().upper()
|
||||
if mcp_status in {"COLLECTING_PARAMETERS", "AWAITING_CONFIRMATION"}:
|
||||
guardrail_transaction_status = mcp_status
|
||||
break
|
||||
await self.observer.emit_grl(
|
||||
"001",
|
||||
{
|
||||
@@ -240,6 +295,10 @@ class AgentWorkflow:
|
||||
"tenant_id": state.get("tenant_id"),
|
||||
"agent_id": state.get("agent_id"),
|
||||
"agent_profile": state.get("agent_profile") or {},
|
||||
"transaction_status": guardrail_transaction_status,
|
||||
"missing_parameters": list(state.get("missing_parameters") or []),
|
||||
"active_transaction": guardrail_active_transaction,
|
||||
"mcp_results": list(state.get("mcp_results") or []),
|
||||
},
|
||||
)
|
||||
for _decision in decisions:
|
||||
@@ -281,12 +340,33 @@ class AgentWorkflow:
|
||||
component="workflow.input_guardrails.final",
|
||||
)
|
||||
if any(not d.allowed for d in decisions):
|
||||
# A blocking input guardrail stops the turn before routing/tools.
|
||||
# Clear turn-local routing/tool state so stale data from a prior
|
||||
# turn cannot appear as if it was executed after the block.
|
||||
user_message = self._input_guardrail_user_message(decisions, state, sanitized)
|
||||
return {
|
||||
"sanitized_input": sanitized,
|
||||
"answer": "Não consegui seguir com essa mensagem por regra de segurança.",
|
||||
"final_answer": "Não consegui seguir com essa mensagem por regra de segurança.",
|
||||
"answer": user_message,
|
||||
"final_answer": None,
|
||||
"guardrail_decisions": [d.model_dump() for d in decisions],
|
||||
"route": "blocked",
|
||||
"intent": "input_guardrail_blocked",
|
||||
"route_decision": {
|
||||
"route": "blocked",
|
||||
"agent": None,
|
||||
"intent": "input_guardrail_blocked",
|
||||
"confidence": 1.0,
|
||||
"reason": "Entrada interrompida por guardrail antes do roteamento.",
|
||||
"method": "guardrail",
|
||||
"next_state": state.get("next_state"),
|
||||
"handoff": False,
|
||||
"metadata": {},
|
||||
"domain": state.get("domain"),
|
||||
"mcp_tools": [],
|
||||
},
|
||||
"mcp_tools": [],
|
||||
"mcp_results": [],
|
||||
"judge_results": [],
|
||||
"blocked": True,
|
||||
}
|
||||
return {
|
||||
@@ -363,6 +443,18 @@ class AgentWorkflow:
|
||||
"reason": decision.reason if decision.method == "continuity" else None,
|
||||
"profile": (decision.metadata or {}).get("continuity_profile"),
|
||||
} if decision.method == "continuity" else {},
|
||||
"pending_topics": (
|
||||
(decision.metadata or {}).get("multi_intent_plan", {}).get("operations", [])[1:]
|
||||
if (decision.metadata or {}).get("multi_intent_plan")
|
||||
else list(state.get("pending_topics") or [])
|
||||
),
|
||||
# Durable correlation for the primary operation. route_decision
|
||||
# is replaced by state routing on confirmation/resume turns.
|
||||
"multi_intent_plan": (
|
||||
(decision.metadata or {}).get("multi_intent_plan")
|
||||
or state.get("multi_intent_plan")
|
||||
or {}
|
||||
),
|
||||
}
|
||||
|
||||
async def billing_agent(self, state):
|
||||
@@ -439,6 +531,7 @@ class AgentWorkflow:
|
||||
return {
|
||||
"answer": answer,
|
||||
"supervisor_results": partials,
|
||||
"agent_responses": partials,
|
||||
"mcp_results": mcp_results,
|
||||
"next_state": "SUPERVISOR_ACTIVE",
|
||||
}
|
||||
@@ -501,16 +594,51 @@ class AgentWorkflow:
|
||||
agente gerar `answer` e antes dos judges/persistência, produzindo campos
|
||||
supervisor_* no state e eventos GRL.001..GRL.009 via AgentObserver.
|
||||
"""
|
||||
drained = await drain_pending_topics(
|
||||
state,
|
||||
str(state.get("answer") or ""),
|
||||
{
|
||||
"billing_agent": self.billing.run,
|
||||
"product_agent": self.product.run,
|
||||
"orders_agent": self.orders.run,
|
||||
"support_agent": self.support.run,
|
||||
},
|
||||
)
|
||||
candidate = drained.answer
|
||||
if not bool(getattr(self.settings, "ENABLE_OUTPUT_SUPERVISOR", True)):
|
||||
return {
|
||||
"answer": candidate,
|
||||
"final_answer": candidate,
|
||||
"pending_topics": drained.pending_topics,
|
||||
"handled_topics": drained.handled_topics,
|
||||
"agent_responses": drained.agent_responses,
|
||||
"operation_results": drained.operation_results,
|
||||
"mcp_results": drained.mcp_results,
|
||||
"rag_results": drained.rag_results,
|
||||
"output_guardrails_already_applied": False,
|
||||
"supervisor_action": "disabled",
|
||||
"supervisor_attempt": int(state.get("supervisor_attempt", 0)),
|
||||
**drained.state_patch,
|
||||
}
|
||||
|
||||
candidate = state.get("answer") or ""
|
||||
context = {
|
||||
**(state.get("context") or {}),
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"tenant_id": state.get("tenant_id"),
|
||||
"agent_id": state.get("agent_id"),
|
||||
"session_id": state.get("conversation_key") or state.get("session_id"),
|
||||
@@ -577,6 +705,13 @@ class AgentWorkflow:
|
||||
for r in decision.results
|
||||
],
|
||||
"output_guardrails_already_applied": True,
|
||||
"pending_topics": drained.pending_topics,
|
||||
"handled_topics": drained.handled_topics,
|
||||
"agent_responses": drained.agent_responses,
|
||||
"operation_results": drained.operation_results,
|
||||
"mcp_results": drained.mcp_results,
|
||||
"rag_results": drained.rag_results,
|
||||
**drained.state_patch,
|
||||
"guardrail_decisions": state.get("guardrail_decisions", [])
|
||||
+ [item for r in decision.results for item in (r.metadata or {}).get("legacy_decisions", [])],
|
||||
}
|
||||
@@ -803,6 +938,7 @@ class AgentWorkflow:
|
||||
"judges": state.get("judge_results", []),
|
||||
"mcp_tools": state.get("mcp_tools", []),
|
||||
"mcp_results": state.get("mcp_results", []),
|
||||
"rag_results": state.get("rag_results", []),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -60,6 +60,18 @@ mcp_parameter_mapping:
|
||||
mensagem.
|
||||
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
|
||||
group: 1
|
||||
cancelar_pedido:
|
||||
map:
|
||||
session_key: session_id
|
||||
extract:
|
||||
order_id:
|
||||
from: message
|
||||
type: string
|
||||
strategy: hybrid
|
||||
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
|
||||
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
|
||||
group: 1
|
||||
|
||||
solicitar_troca:
|
||||
map:
|
||||
session_key: session_id
|
||||
|
||||
@@ -7,6 +7,35 @@ router:
|
||||
confidence_threshold: 0.65
|
||||
allow_handoff: true
|
||||
|
||||
transaction_confirmation:
|
||||
# Explicit yes/no stays deterministic. Only inconclusive replies use this LLM fallback.
|
||||
semantic_fallback:
|
||||
enabled: true
|
||||
allowed_values: [SIM, NAO, CONTINUAR]
|
||||
confirm_values: [SIM]
|
||||
reject_values: [NAO]
|
||||
continue_values: [CONTINUAR]
|
||||
include_relevant_context: true
|
||||
profile_name: router
|
||||
prompt: |
|
||||
Você classifica a resposta do cliente a uma confirmação transacional pendente.
|
||||
Considere a pergunta pendente, somente o histórico recente relacionado ao mesmo tema e a fala atual.
|
||||
Não execute a ação e não invente fatos.
|
||||
|
||||
Classes permitidas: {{ allowed_values }}
|
||||
- SIM: confirmação/aceite inequívoco, inclusive equivalentes como "isso mesmo", "pode confirmar", "é isso" quando o contexto tornar o aceite claro.
|
||||
- NAO: recusa/cancelamento inequívoco da ação pendente.
|
||||
- CONTINUAR: qualquer resposta que não confirme nem rejeite inequivocamente, incluindo pergunta adicional, correção, novo dado, ambiguidade ou possível mudança de assunto.
|
||||
|
||||
Pergunta pendente:
|
||||
{{ pending_prompt }}
|
||||
|
||||
Histórico relevante:
|
||||
{{ relevant_conversation_context }}
|
||||
|
||||
Resposta atual do cliente:
|
||||
{{ user_input }}
|
||||
|
||||
state_policies:
|
||||
- state: WAITING_BILLING_CONFIRMATION
|
||||
agent: billing_agent
|
||||
@@ -79,6 +108,25 @@ intents:
|
||||
- Quero saber sobre meu pacote de internet.
|
||||
- Tenho roaming internacional?
|
||||
|
||||
|
||||
- name: retail_order_cancel
|
||||
domain: retail
|
||||
agent: orders_agent
|
||||
description: Cancelamento explícito de pedido ou compra.
|
||||
priority: 20
|
||||
mcp_tools:
|
||||
- consultar_pedido
|
||||
- cancelar_pedido
|
||||
keywords:
|
||||
- cancelar pedido
|
||||
- cancelamento do pedido
|
||||
- cancelar a compra
|
||||
- cancelar compra
|
||||
examples:
|
||||
- Quero cancelar meu pedido.
|
||||
- Cancele o pedido.
|
||||
- Quero cancelar a compra.
|
||||
|
||||
- name: retail_order_tracking
|
||||
domain: retail
|
||||
agent: orders_agent
|
||||
|
||||
@@ -7,6 +7,12 @@ defaults:
|
||||
require_confirmation: false
|
||||
|
||||
tool_policies:
|
||||
cancelar_pedido:
|
||||
operation_type: transactional
|
||||
require_confirmation: true
|
||||
requires: [order_id]
|
||||
|
||||
|
||||
solicitar_troca:
|
||||
operation_type: transactional
|
||||
require_confirmation: true
|
||||
|
||||
@@ -4,18 +4,33 @@ tools:
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
invoice_id: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
invoice_id:
|
||||
type: string
|
||||
label: o identificador da fatura
|
||||
description: Identificador da fatura que o cliente deseja consultar.
|
||||
user_prompt: Informe o identificador da fatura que deseja consultar.
|
||||
selection_keywords:
|
||||
- fatura
|
||||
- conta
|
||||
- boleto
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: telecom.invoice
|
||||
consultar_pagamentos:
|
||||
description: Consulta histórico de pagamentos do cliente.
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
selection_keywords:
|
||||
- pagamento
|
||||
- pagamentos
|
||||
@@ -24,16 +39,31 @@ tools:
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
asset_id: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
asset_id:
|
||||
type: string
|
||||
label: o identificador do plano ou ativo
|
||||
description: Identificador do plano ou ativo comercial associado ao cliente.
|
||||
user_prompt: Informe o identificador do plano ou ativo que deseja consultar.
|
||||
selection_keywords:
|
||||
- plano
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: telecom.plan
|
||||
listar_servicos:
|
||||
description: Lista serviços ativos e adicionais VAS.
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
selection_keywords:
|
||||
- serviços
|
||||
- servicos
|
||||
@@ -43,24 +73,63 @@ tools:
|
||||
mcp_server: retail
|
||||
enabled: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
customer_id: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido que o cliente deseja consultar.
|
||||
user_prompt: Informe o número do pedido que deseja consultar.
|
||||
customer_id:
|
||||
type: string
|
||||
label: a identificação do cliente
|
||||
description: Identificador do cliente associado ao pedido de varejo.
|
||||
user_prompt: Informe a identificação do cliente.
|
||||
selection_keywords:
|
||||
- consultar pedido
|
||||
- status do pedido
|
||||
- pedido
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: retail.order
|
||||
consultar_entrega:
|
||||
description: Consulta entrega e rastreamento do pedido.
|
||||
mcp_server: retail
|
||||
enabled: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido cuja entrega ou rastreamento será consultado.
|
||||
user_prompt: Informe o número do pedido que deseja rastrear.
|
||||
selection_keywords:
|
||||
- entrega
|
||||
- rastreio
|
||||
- rastreamento
|
||||
- transportadora
|
||||
- previsão
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: retail.delivery
|
||||
cancelar_pedido:
|
||||
description: Simula o cancelamento de um pedido de varejo.
|
||||
mcp_server: retail
|
||||
enabled: true
|
||||
tool_type: action
|
||||
requires:
|
||||
- order_id
|
||||
confirmation_required: true
|
||||
args_schema:
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido que o cliente deseja cancelar.
|
||||
user_prompt: Informe o número do pedido que deseja cancelar.
|
||||
selection_keywords:
|
||||
- cancelar pedido
|
||||
- cancelamento do pedido
|
||||
- cancelar compra
|
||||
- cancelar a compra
|
||||
|
||||
|
||||
solicitar_troca:
|
||||
description: Simula abertura de solicitação de troca.
|
||||
mcp_server: retail
|
||||
@@ -71,8 +140,16 @@ tools:
|
||||
- reason
|
||||
confirmation_required: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
reason: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido para o qual o cliente deseja solicitar troca.
|
||||
user_prompt: Informe o número do pedido que deseja trocar.
|
||||
reason:
|
||||
type: string
|
||||
label: o motivo da troca
|
||||
description: Motivo informado pelo cliente para solicitar a troca do pedido.
|
||||
user_prompt: Qual é o motivo da troca?
|
||||
selection_keywords:
|
||||
- solicitar troca
|
||||
- trocar
|
||||
@@ -89,8 +166,16 @@ tools:
|
||||
- reason
|
||||
confirmation_required: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
reason: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido para o qual o cliente deseja solicitar devolução.
|
||||
user_prompt: Informe o número do pedido que deseja devolver.
|
||||
reason:
|
||||
type: string
|
||||
label: o motivo da devolução
|
||||
description: Motivo informado pelo cliente para solicitar a devolução do pedido.
|
||||
user_prompt: Qual é o motivo da devolução?
|
||||
selection_keywords:
|
||||
- solicitar devolução
|
||||
- solicitar devolucao
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Confirmação Transacional Semântica
|
||||
|
||||
Este template suporta confirmação transacional em duas camadas: primeiro um parser determinístico para `sim`/`não` e equivalentes explícitos; somente quando ele não consegue decidir, o framework usa um classificador semântico configurado em `config/routing.yaml`.
|
||||
|
||||
A configuração `router.transaction_confirmation.semantic_fallback` usa três classes: `SIM`, `NAO` e `CONTINUAR`. O prompt pode usar `{{ pending_prompt }}`, `{{ relevant_conversation_context }}`, `{{ user_input }}` e `{{ allowed_values }}`. O histórico injetado é apenas contexto de interpretação; não substitui validação de negócio ou evidência MCP.
|
||||
|
||||
Exemplo: após `Você confirma o cancelamento do serviço Tamboro Mensal?`, a frase `isso mesmo, pode confirmar` pode ser classificada como `SIM`. Já `mas qual é o valor?` deve ser `CONTINUAR`, portanto não executa a ação por confirmação.
|
||||
|
||||
Entradas explícitas já suportadas continuam no caminho determinístico e não geram custo adicional de LLM. Em observabilidade, o fallback usa `transaction.confirmation.semantic_classifier` e o `route_decision.metadata` informa `transaction_confirmation_source: semantic`.
|
||||
|
||||
Consulte `docs/developer/pt/03_transaction_workflows_and_state.md` do framework para o contrato completo e exemplos.
|
||||
@@ -15,11 +15,17 @@ profiles:
|
||||
temperature: 0
|
||||
max_tokens: 80
|
||||
timeout_seconds: 5
|
||||
processing_interruption_classifier:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1-mini
|
||||
temperature: 0
|
||||
max_tokens: 8
|
||||
timeout_seconds: 5
|
||||
router:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1
|
||||
temperature: 0
|
||||
max_tokens: 500
|
||||
max_tokens: 768
|
||||
guardrail:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1
|
||||
@@ -78,3 +84,10 @@ profiles:
|
||||
temperature: 0
|
||||
max_tokens: 80
|
||||
timeout_seconds: 5
|
||||
|
||||
transaction_parameter_extraction:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1-mini
|
||||
temperature: 0
|
||||
max_tokens: 500
|
||||
timeout_seconds: 8
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
###############################################################################
|
||||
# AI AGENT PLATFORM - CONFIGURAÇÃO ÚNICA
|
||||
# Este arquivo é lido por Pydantic Settings no framework e no backend template.
|
||||
###############################################################################
|
||||
|
||||
APP_NAME=ai-agent-template
|
||||
APP_ENV=local
|
||||
LOG_LEVEL=INFO
|
||||
API_HOST=0.0.0.0
|
||||
API_PORT=8000
|
||||
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
|
||||
|
||||
###############################################################################
|
||||
# LLM - OCI Generative AI como provider principal
|
||||
###############################################################################
|
||||
# Opções: mock, oci_openai, oci_sdk, openai_compatible
|
||||
LLM_PROVIDER=oci_sdk
|
||||
LLM_TEMPERATURE=0.2
|
||||
LLM_MAX_TOKENS=2048
|
||||
LLM_TIMEOUT_SECONDS=120
|
||||
|
||||
# OCI OpenAI-compatible endpoint
|
||||
OCI_GENAI_BASE_URL=https://inference.generativeai.us-chicago-1.oci.oraclecloud.com
|
||||
OCI_GENAI_MODEL=openai.gpt-4.1
|
||||
OCI_GENAI_API_KEY=sk-ph3FgX6iP3fxAQCXb9IpPIDTadkeeYAWntUWhzcWysIM6zsS
|
||||
OCI_GENAI_PROJECT_OCID=
|
||||
|
||||
#OCI_GENAI_BASE_URL=https://pegruagntaiatenddev.pe.inference.generativeai.sa-saopaulo-1.oci.oraclecloud.com
|
||||
#OCI_GENAI_MODEL=openai.gpt-4.1
|
||||
#OCI_GENAI_API_KEY=
|
||||
#OCI_GENAI_PROJECT_OCID=
|
||||
|
||||
|
||||
# OCI_AUTH_MODE=config_file|instance_principal|resource_principal
|
||||
OCI_AUTH_MODE=config_file
|
||||
# OCI SDK / signer / profiles
|
||||
OCI_CONFIG_FILE=~/.oci/config
|
||||
OCI_PROFILE=LATINOAMERICA-Chicago
|
||||
OCI_COMPARTMENT_ID=ocid1.compartment.oc1..aaaaaaaaexpiw4a7dio64mkfv2t273s2hgdl6mgfvvyv7tycalnjlvpvfl3q
|
||||
OCI_REGION=us-chicago-1
|
||||
|
||||
###############################################################################
|
||||
# Persistência
|
||||
###############################################################################
|
||||
# Opções: memory, autonomous, mongodb
|
||||
SESSION_REPOSITORY_PROVIDER=autonomous
|
||||
MEMORY_REPOSITORY_PROVIDER=autonomous
|
||||
CHECKPOINT_REPOSITORY_PROVIDER=autonomous
|
||||
|
||||
# Autonomous Database
|
||||
ADB_USER=admin
|
||||
ADB_PASSWORD=Moniquinha19721972
|
||||
ADB_DSN=oradb23ai_high
|
||||
ADB_WALLET_LOCATION=/mnt/d/Dropbox/ORACLE/LatinoAmerica/Wallet_ORADB23ai
|
||||
ADB_WALLET_PASSWORD=Moniquinha1972
|
||||
ADB_TABLE_PREFIX=AGENTFW
|
||||
|
||||
# MongoDB - também pode representar Autonomous usando API compatível com Mongo, se habilitada no ambiente
|
||||
MONGODB_URI=mongodb://mongo:mongopassword@localhost:27017
|
||||
MONGODB_DATABASE=agent_platform
|
||||
|
||||
# Redis
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
ENABLE_REDIS_CACHE=false
|
||||
|
||||
###############################################################################
|
||||
# RAG / Vector / Graph
|
||||
###############################################################################
|
||||
VECTOR_STORE_PROVIDER=autonomous
|
||||
GRAPH_STORE_PROVIDER=autonomous
|
||||
RAG_TOP_K=5
|
||||
EMBEDDING_PROVIDER=oci
|
||||
OCI_EMBEDDING_MODEL=cohere.embed-multilingual-v3.0
|
||||
RAG_FILE_GLOBS=*.md,*.txt,*.yaml,*.yml,*.json
|
||||
|
||||
###############################################################################
|
||||
# Observabilidade
|
||||
###############################################################################
|
||||
ENABLE_LANGFUSE=true
|
||||
# Opcional: verbose, compact
|
||||
LANGFUSE_TRACE_MODE=compact
|
||||
# Nome customizado do trace pai, ex.: backoffice.checklist.workflow ou backoffice.emulador.workflow
|
||||
LANGFUSE_COMPACT_VISIBLE_EVENT_PREFIXES=AGA.,NOC., IC.
|
||||
LANGFUSE_COMPACT_SUPPRESSED_PREFIXES=llm.chat_completion
|
||||
LANGFUSE_IGNORE_HEALTHCHECKS=true
|
||||
LANGFUSE_IGNORED_PATHS=/health,/ready,/metrics
|
||||
LANGFUSE_PUBLIC_KEY=pk-lf-4a1e3921-5158-4fd3-a16d-7a77549fb312
|
||||
LANGFUSE_SECRET_KEY=sk-lf-efc6fd59-c5ec-4858-b6ec-4aa129734915
|
||||
LANGFUSE_HOST=http://localhost:3005
|
||||
ENABLE_OTEL=false
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=
|
||||
OTEL_SERVICE_NAME=ai-agent-template
|
||||
ENABLE_LANGFUSE_OPENAI_AUTO_INSTRUMENTATION=true
|
||||
ENABLE_LANGFUSE_ANALYTICS_PUBLISHER=false
|
||||
|
||||
###############################################################################
|
||||
# Analytics / Observer corporativo
|
||||
###############################################################################
|
||||
# Quando true, AgentObserver publica eventos IC.*, NOC.* e GRL.* nos providers abaixo.
|
||||
ENABLE_ANALYTICS=false
|
||||
# Providers aceitos: oci_streaming,pubsub,noop
|
||||
ANALYTICS_PROVIDERS=oci_streaming
|
||||
# Compatibilidade FIRST/TIM: pode informar AGENT_PUBSUB_TOPIC diretamente.
|
||||
AGENT_PUBSUB_TOPIC=
|
||||
GCP_PUBSUB_TOPIC_PATH=
|
||||
GCP_PROJECT_ID=
|
||||
GCP_PUBSUB_TOPIC=
|
||||
GCP_PUBSUB_TIMEOUT_SECONDS=30
|
||||
# Credencial GCP segue padrão Google:
|
||||
# GOOGLE_APPLICATION_CREDENTIALS=/secrets/gcp-service-account.json
|
||||
|
||||
###############################################################################
|
||||
# OCI Streaming
|
||||
###############################################################################
|
||||
ENABLE_OCI_STREAMING=false
|
||||
OCI_STREAM_ENDPOINT=
|
||||
OCI_STREAM_OCID=
|
||||
OCI_STREAM_PARTITION_KEY=agent-events
|
||||
|
||||
###############################################################################
|
||||
# Guardrails, Judges, Supervisor
|
||||
###############################################################################
|
||||
ENABLE_INPUT_GUARDRAILS=true
|
||||
ENABLE_OUTPUT_GUARDRAILS=true
|
||||
ENABLE_JUDGES=true
|
||||
ENABLE_SUPERVISOR=true
|
||||
ENABLE_OUTPUT_SUPERVISOR=true
|
||||
ENABLE_PARALLEL_GUARDRAILS=true
|
||||
GUARDRAILS_FAIL_FAST=true
|
||||
OUTPUT_SUPERVISOR_MAX_RETRIES=3
|
||||
GUARDRAILS_CONFIG_PATH=./config/guardrails.yaml
|
||||
JUDGES_CONFIG_PATH=./config/judges.yaml
|
||||
PROMPT_POLICY_PATH=./config/prompt_policy.yaml
|
||||
|
||||
###############################################################################
|
||||
# Gateway de canais
|
||||
###############################################################################
|
||||
DEFAULT_CHANNEL=web
|
||||
# embedded = backend may parse simple/native channel payloads.
|
||||
# external = backend only accepts GatewayRequest normalized by an external Channel Gateway.
|
||||
FRAMEWORK_CHANNEL_INPUT_MODE=embedded
|
||||
ENABLE_VOICE_ADAPTER=true
|
||||
ENABLE_WHATSAPP_ADAPTER=true
|
||||
ENABLE_TEXT_ADAPTER=true
|
||||
|
||||
#################################################
|
||||
# ENTERPRISE ROUTING
|
||||
#################################################
|
||||
# Arquivo YAML com intents, keywords, políticas de estado e fallback.
|
||||
ROUTING_CONFIG_PATH=./config/routing.yaml
|
||||
# true = usa LLM para classificar quando keywords/estado não resolverem.
|
||||
# Em produção, costuma ser útil; em desenvolvimento, false evita custo e latência.
|
||||
ENABLE_LLM_ROUTER=true
|
||||
|
||||
# Semantic route stickiness (optional).
|
||||
# Uses a lightweight LLM profile to decide only CONTINUE vs ROUTE.
|
||||
# There are no regexes or deterministic language rules.
|
||||
ENABLE_ROUTE_STICKINESS=true
|
||||
ROUTE_STICKINESS_LLM_PROFILE=route_continuity
|
||||
ROUTE_STICKINESS_CONFIDENCE_THRESHOLD=0.90
|
||||
ROUTE_STICKINESS_HISTORY_TURNS=2
|
||||
ROUTE_STICKINESS_MAX_TOKENS=80
|
||||
HUMAN_HANDOFF_MESSAGE=Vou encaminhar seu atendimento para uma pessoa.
|
||||
END_SESSION_MESSAGE=Atendimento encerrado. Obrigado pelo contato.
|
||||
ENABLE_TRANSACTIONAL_WORKFLOWS=true
|
||||
WORKFLOWS_PATH=./workflows
|
||||
|
||||
###############################################################################
|
||||
# MCP / Tools
|
||||
###############################################################################
|
||||
ENABLE_MCP_TOOLS=true
|
||||
MCP_SERVERS_CONFIG_PATH=./config/mcp_servers.yaml
|
||||
TOOLS_CONFIG_PATH=./config/tools.yaml
|
||||
MCP_TOOL_TIMEOUT_SECONDS=30
|
||||
|
||||
# router = EnterpriseRouter seleciona um agente; supervisor = pode acionar múltiplos agentes
|
||||
ROUTING_MODE=router
|
||||
|
||||
# Usage/cost accounting
|
||||
USAGE_REPOSITORY_PROVIDER=autonomous
|
||||
IDENTITY_CONFIG_PATH=./config/identity.yaml
|
||||
MCP_PARAMETER_MAPPING_PATH=./config/mcp_parameter_mapping.yaml
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# ConversationSummaryMemory / compressão de contexto conversacional
|
||||
# -----------------------------------------------------------------------------
|
||||
ENABLE_CONVERSATION_SUMMARY_MEMORY=true
|
||||
MEMORY_CONTEXT_STRATEGY=summary
|
||||
MEMORY_HISTORY_LIMIT=80
|
||||
MEMORY_RECENT_MESSAGES_LIMIT=8
|
||||
MEMORY_SUMMARY_TRIGGER_MESSAGES=20
|
||||
MEMORY_MAX_SUMMARY_CHARS=6000
|
||||
MEMORY_SUMMARY_USE_LLM=true
|
||||
MEMORY_INJECT_RECENT_MESSAGES=true
|
||||
MEMORY_INJECT_SUMMARY=true
|
||||
|
||||
###############################################################################
|
||||
# LONG-TERM MEMORY
|
||||
###############################################################################
|
||||
ENABLE_LONG_TERM_MEMORY=true
|
||||
LONG_TERM_MEMORY_PROVIDER=sqlite
|
||||
LONG_TERM_MEMORY_SQLITE_PATH=./data/agent_framework.db
|
||||
LONG_TERM_MEMORY_TABLE=agentfw_long_term_memory
|
||||
# For Autonomous/Oracle, defaults to ${ADB_TABLE_PREFIX}_LONG_TERM_MEMORY
|
||||
# LONG_TERM_MEMORY_ORACLE_TABLE=AGENTFW_LONG_TERM_MEMORY
|
||||
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
|
||||
ENABLE_TRANSACTIONAL_WORKFLOWS=true
|
||||
WORKFLOWS_PATH=./workflows
|
||||
@@ -0,0 +1,235 @@
|
||||
###############################################################################
|
||||
# AI AGENT PLATFORM - CONFIGURAÇÃO ÚNICA
|
||||
# Este arquivo é lido por Pydantic Settings no framework e no backend template.
|
||||
###############################################################################
|
||||
|
||||
APP_NAME=ai-agent-template
|
||||
APP_ENV=local
|
||||
LOG_LEVEL=INFO
|
||||
API_HOST=0.0.0.0
|
||||
API_PORT=8000
|
||||
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
|
||||
|
||||
###############################################################################
|
||||
# LLM - OCI Generative AI como provider principal
|
||||
###############################################################################
|
||||
# Opções: mock, oci_openai, oci_sdk, openai_compatible
|
||||
LLM_PROVIDER=oci_openai
|
||||
LLM_TEMPERATURE=0.2
|
||||
LLM_MAX_TOKENS=2048
|
||||
LLM_TIMEOUT_SECONDS=120
|
||||
|
||||
# OCI OpenAI-compatible endpoint
|
||||
OCI_GENAI_BASE_URL=https://inference.generativeai.us-chicago-1.oci.oraclecloud.com/openai/v1
|
||||
OCI_GENAI_MODEL=openai.gpt-4.1
|
||||
OCI_GENAI_API_KEY=sk-ph3FgX6ph3FgX6ph3FgX6ph3FgX6ph3FgX6ph3FgX6
|
||||
OCI_GENAI_PROJECT_OCID=
|
||||
|
||||
# OCI_AUTH_MODE=config_file|instance_principal|resource_principal
|
||||
OCI_AUTH_MODE=config_file
|
||||
# OCI SDK / signer / profiles
|
||||
OCI_CONFIG_FILE=~/.oci/config
|
||||
OCI_PROFILE=DEFAULT
|
||||
OCI_COMPARTMENT_ID=ocid1.compartment.oc1..aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
OCI_REGION=us-chicago-1
|
||||
|
||||
###############################################################################
|
||||
# Persistência
|
||||
###############################################################################
|
||||
# Opções: memory, autonomous, mongodb
|
||||
SESSION_REPOSITORY_PROVIDER=autonomous
|
||||
MEMORY_REPOSITORY_PROVIDER=autonomous
|
||||
CHECKPOINT_REPOSITORY_PROVIDER=autonomous
|
||||
|
||||
# Autonomous Database
|
||||
ADB_USER=admin
|
||||
ADB_PASSWORD=fjhsdf04954hf
|
||||
ADB_DSN=oradb23aidev_high
|
||||
ADB_WALLET_LOCATION=/ORACLE/DEFAULT/Wallet_ORADB23aiDev
|
||||
ADB_WALLET_PASSWORD=fjhsdf04954hf
|
||||
ADB_TABLE_PREFIX=AGENTFW
|
||||
|
||||
# MongoDB - também pode representar Autonomous usando API compatível com Mongo, se habilitada no ambiente
|
||||
MONGODB_URI=mongodb://mongo:mongopassword@localhost:27017
|
||||
MONGODB_DATABASE=agent_platform
|
||||
|
||||
# Redis
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
ENABLE_REDIS_CACHE=false
|
||||
|
||||
###############################################################################
|
||||
# RAG / Vector / Graph
|
||||
###############################################################################
|
||||
VECTOR_STORE_PROVIDER=memory
|
||||
GRAPH_STORE_PROVIDER=memory
|
||||
RAG_TOP_K=5
|
||||
EMBEDDING_PROVIDER=mock
|
||||
OCI_EMBEDDING_MODEL=cohere.embed-multilingual-v3.0
|
||||
RAG_FILE_GLOBS=*.md,*.txt,*.yaml,*.yml,*.json
|
||||
|
||||
|
||||
# RAG / KBDB
|
||||
# RAG provider: standard (local) ou kbdb (PKG_KB_SERVING.SEARCH_KNOWLEDGE_BASE)
|
||||
RAG_PROVIDER=standard
|
||||
# KBDB usa credenciais próprias; não há fallback para ADB_*.
|
||||
KBDB_DB_USER=
|
||||
KBDB_DB_PASSWORD=
|
||||
KBDB_DB_DSN=
|
||||
KBDB_DB_WALLET_LOCATION=
|
||||
KBDB_DB_WALLET_PASSWORD=
|
||||
KBDB_SEARCH_TYPE=hybrid
|
||||
KBDB_NODE_EXPANSION=true
|
||||
KBDB_NODE_MAX_RELATED=8
|
||||
KBDB_GRAPH_CROSS_REF=false
|
||||
KBDB_MAX_CROSS_REF_HOPS=1
|
||||
KBDB_DOCUMENT_TYPE=customer_safe
|
||||
KBDB_METADATA_JSON=
|
||||
KBDB_MIN_SCORE=
|
||||
KBDB_IDENTIFY_DOCUMENT=true
|
||||
KBDB_STORE_QUERY=true
|
||||
KBDB_IDENTIFY_TOP_N=3
|
||||
RAG_GROUNDED_ONLY=false
|
||||
KBDB_GROUNDED_ONLY=true
|
||||
|
||||
###############################################################################
|
||||
# Observabilidade
|
||||
###############################################################################
|
||||
ENABLE_LANGFUSE=true
|
||||
LANGFUSE_TRACE_MODE=verbose # Opcional: verbose, compact
|
||||
LANGFUSE_ROOT_SPAN_NAME=agent.gateway_message
|
||||
LANGFUSE_LEGACY_IO_FALLBACK=true
|
||||
LANGFUSE_PUBLIC_KEY=pk-lf-bd9b0c7e-2b8b-4e5b-a382-284a9b4413b3
|
||||
LANGFUSE_SECRET_KEY=sk-lf-5f5cc18d-0bb5-424e-b5d0-cb3664d58c20
|
||||
LANGFUSE_HOST=http://localhost:3005
|
||||
ENABLE_OTEL=false
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=
|
||||
OTEL_SERVICE_NAME=ai-agent-template
|
||||
ENABLE_LANGFUSE_OPENAI_AUTO_INSTRUMENTATION=true
|
||||
|
||||
###############################################################################
|
||||
# Analytics / Observer corporativo
|
||||
###############################################################################
|
||||
# Quando true, AgentObserver publica eventos IC.*, NOC.* e GRL.* nos providers abaixo.
|
||||
ENABLE_ANALYTICS=false
|
||||
# Providers aceitos: oci_streaming,pubsub,noop
|
||||
ANALYTICS_PROVIDERS=pubsub
|
||||
# Compatibilidade FIRST/TIM: pode informar AGENT_PUBSUB_TOPIC diretamente.
|
||||
AGENT_PUBSUB_TOPIC=
|
||||
GCP_PUBSUB_TOPIC_PATH=
|
||||
GCP_PROJECT_ID=
|
||||
GCP_PUBSUB_TOPIC=
|
||||
GCP_PUBSUB_TIMEOUT_SECONDS=30
|
||||
# Credencial GCP segue padrão Google:
|
||||
# GOOGLE_APPLICATION_CREDENTIALS=/secrets/gcp-service-account.json
|
||||
|
||||
###############################################################################
|
||||
# OCI Streaming
|
||||
###############################################################################
|
||||
ENABLE_OCI_STREAMING=false
|
||||
OCI_STREAM_ENDPOINT=
|
||||
OCI_STREAM_OCID=
|
||||
OCI_STREAM_PARTITION_KEY=agent-events
|
||||
|
||||
###############################################################################
|
||||
# Guardrails, Judges, Supervisor
|
||||
###############################################################################
|
||||
ENABLE_INPUT_GUARDRAILS=true
|
||||
ENABLE_OUTPUT_GUARDRAILS=true
|
||||
ENABLE_JUDGES=true
|
||||
ENABLE_SUPERVISOR=true
|
||||
ENABLE_OUTPUT_SUPERVISOR=true
|
||||
ENABLE_PARALLEL_GUARDRAILS=true
|
||||
GUARDRAILS_FAIL_FAST=true
|
||||
OUTPUT_SUPERVISOR_MAX_RETRIES=3
|
||||
GUARDRAILS_CONFIG_PATH=./config/guardrails.yaml
|
||||
JUDGES_CONFIG_PATH=./config/judges.yaml
|
||||
PROMPT_POLICY_PATH=./config/prompt_policy.yaml
|
||||
|
||||
###############################################################################
|
||||
# Gateway de canais
|
||||
###############################################################################
|
||||
DEFAULT_CHANNEL=web
|
||||
# embedded = backend may parse simple/native channel payloads.
|
||||
# external = backend only accepts GatewayRequest normalized by an external Channel Gateway.
|
||||
FRAMEWORK_CHANNEL_INPUT_MODE=embedded
|
||||
ENABLE_VOICE_ADAPTER=true
|
||||
ENABLE_WHATSAPP_ADAPTER=true
|
||||
ENABLE_TEXT_ADAPTER=true
|
||||
|
||||
#################################################
|
||||
# ENTERPRISE ROUTING
|
||||
#################################################
|
||||
# Arquivo YAML com intents, keywords, políticas de estado e fallback.
|
||||
ROUTING_CONFIG_PATH=./config/routing.yaml
|
||||
# true = usa LLM para classificar quando keywords/estado não resolverem.
|
||||
# Em produção, costuma ser útil; em desenvolvimento, false evita custo e latência.
|
||||
ENABLE_LLM_ROUTER=true
|
||||
|
||||
# Semantic route stickiness (optional).
|
||||
# Uses a lightweight LLM profile to decide only CONTINUE vs ROUTE.
|
||||
# There are no regexes or deterministic language rules.
|
||||
ENABLE_ROUTE_STICKINESS=true
|
||||
ROUTE_STICKINESS_LLM_PROFILE=route_continuity
|
||||
ROUTE_STICKINESS_CONFIDENCE_THRESHOLD=0.90
|
||||
ROUTE_STICKINESS_HISTORY_TURNS=2
|
||||
ROUTE_STICKINESS_MAX_TOKENS=80
|
||||
HUMAN_HANDOFF_MESSAGE=Vou encaminhar seu atendimento para uma pessoa.
|
||||
END_SESSION_MESSAGE=Atendimento encerrado. Obrigado pelo contato.
|
||||
ENABLE_TRANSACTIONAL_WORKFLOWS=true
|
||||
WORKFLOWS_PATH=./workflows
|
||||
|
||||
###############################################################################
|
||||
# MCP / Tools
|
||||
###############################################################################
|
||||
ENABLE_MCP_TOOLS=true
|
||||
MCP_SERVERS_CONFIG_PATH=./config/mcp_servers.yaml
|
||||
TOOLS_CONFIG_PATH=./config/tools.yaml
|
||||
TOOL_POLICIES_PATH=./config/tool_policies.yaml
|
||||
MCP_TOOL_TIMEOUT_SECONDS=30
|
||||
|
||||
# router = EnterpriseRouter seleciona um agente; supervisor = pode acionar múltiplos agentes
|
||||
ROUTING_MODE=router
|
||||
|
||||
# Usage/cost accounting
|
||||
USAGE_REPOSITORY_PROVIDER=autonomous
|
||||
IDENTITY_CONFIG_PATH=./config/identity.yaml
|
||||
MCP_PARAMETER_MAPPING_PATH=./config/mcp_parameter_mapping.yaml
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# ConversationSummaryMemory / compressão de contexto conversacional
|
||||
# -----------------------------------------------------------------------------
|
||||
ENABLE_CONVERSATION_SUMMARY_MEMORY=true
|
||||
MEMORY_CONTEXT_STRATEGY=summary
|
||||
MEMORY_HISTORY_LIMIT=80
|
||||
MEMORY_RECENT_MESSAGES_LIMIT=8
|
||||
MEMORY_SUMMARY_TRIGGER_MESSAGES=20
|
||||
MEMORY_MAX_SUMMARY_CHARS=6000
|
||||
MEMORY_SUMMARY_USE_LLM=true
|
||||
MEMORY_INJECT_RECENT_MESSAGES=true
|
||||
MEMORY_INJECT_SUMMARY=true
|
||||
|
||||
###############################################################################
|
||||
# MCP Gateway
|
||||
###############################################################################
|
||||
# true = framework routes tool calls to the dedicated MCP Gateway.
|
||||
# false = framework calls MCP servers directly from mcp_servers.yaml.
|
||||
MCP_GATEWAY_ENABLED=true
|
||||
MCP_GATEWAY_URL=http://localhost:8300
|
||||
MCP_GATEWAY_TIMEOUT_SECONDS=60
|
||||
# MCP_GATEWAY_TOKEN=
|
||||
MCP_GATEWAY_AGENT_ID=telecom_contas
|
||||
MCP_GATEWAY_TENANT_ID=default
|
||||
|
||||
###############################################################################
|
||||
# LONG-TERM MEMORY
|
||||
###############################################################################
|
||||
ENABLE_LONG_TERM_MEMORY=true
|
||||
LONG_TERM_MEMORY_PROVIDER=sqlite
|
||||
LONG_TERM_MEMORY_SQLITE_PATH=./data/agent_framework.db
|
||||
LONG_TERM_MEMORY_TABLE=agentfw_long_term_memory
|
||||
# For Autonomous/Oracle, defaults to ${ADB_TABLE_PREFIX}_LONG_TERM_MEMORY
|
||||
# LONG_TERM_MEMORY_ORACLE_TABLE=AGENTFW_LONG_TERM_MEMORY
|
||||
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
|
||||
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.
@@ -108,6 +108,14 @@ class BillingAgent(AgentRuntimeMixin):
|
||||
"next_state": "BILLING_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
@@ -108,6 +108,14 @@ class OrdersAgent(AgentRuntimeMixin):
|
||||
"next_state": "ORDER_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
@@ -108,6 +108,14 @@ class ProductAgent(AgentRuntimeMixin):
|
||||
"next_state": "PRODUCT_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
@@ -108,6 +108,14 @@ class SupportAgent(AgentRuntimeMixin):
|
||||
"next_state": "SUPPORT_ACTIVE",
|
||||
"mcp_results": tool_context,
|
||||
"rag": rag_metadata,
|
||||
"rag_context": rag_context,
|
||||
"rag_results": [{
|
||||
"intent": state.get("intent"),
|
||||
"agent": self.name,
|
||||
"source_text": str(state.get("sanitized_input") or state.get("user_text") or ""),
|
||||
"metadata": rag_metadata,
|
||||
**({"context": rag_context} if rag_context else {}),
|
||||
}],
|
||||
"memory_context_metadata": state.get("memory_context_metadata"),
|
||||
**self.transaction_state_patch(state),
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -363,9 +363,12 @@ async def _process_gateway_message(req: GatewayRequest, emit_sse: bool = False)
|
||||
"route": result.get("route"),
|
||||
"intent": result.get("intent"),
|
||||
"route_decision": result.get("route_decision"),
|
||||
"supervisor_results": result.get("supervisor_results") or [],
|
||||
"agent_responses": result.get("agent_responses") or result.get("supervisor_results") or [],
|
||||
"domain": result.get("domain"),
|
||||
"mcp_tools": result.get("mcp_tools"),
|
||||
"mcp_results": result.get("mcp_results"),
|
||||
"rag_results": result.get("rag_results"),
|
||||
"business_context": business_context.model_dump(),
|
||||
"identity_missing": missing_identity_keys,
|
||||
"judges": result.get("judge_results"),
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
from .tool_renderers import register_tool_renderers
|
||||
|
||||
__all__ = ["register_tool_renderers"]
|
||||
Binary file not shown.
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)
|
||||
@@ -23,9 +23,12 @@ class AgentState(TypedDict, total=False):
|
||||
domain: str
|
||||
mcp_tools: list[str]
|
||||
mcp_results: list[dict[str, Any]]
|
||||
rag_results: list[dict[str, Any]]
|
||||
available_mcp_tools: list[str]
|
||||
selected_tool_call: dict[str, Any]
|
||||
pending_tool_call: dict[str, Any]
|
||||
active_transaction: dict[str, Any]
|
||||
last_transaction: dict[str, Any]
|
||||
transaction_status: str
|
||||
confirmation_required: bool
|
||||
confirmation_received: bool
|
||||
@@ -33,6 +36,11 @@ class AgentState(TypedDict, total=False):
|
||||
missing_parameters: list[str]
|
||||
supervisor_plan: dict[str, Any]
|
||||
supervisor_results: list[dict[str, Any]]
|
||||
agent_responses: list[dict[str, Any]]
|
||||
pending_topics: list[dict[str, Any]]
|
||||
handled_topics: list[dict[str, Any]]
|
||||
operation_results: dict[str, dict[str, Any]]
|
||||
multi_intent_plan: dict[str, Any]
|
||||
active_agent: str
|
||||
route_bypassed: bool
|
||||
continuity_signal: dict[str, Any]
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -7,6 +7,7 @@ from agent_framework.guardrails.rail_action import RailAction
|
||||
from agent_framework.guardrails.rail_result import RailResult
|
||||
from agent_framework.judges.judge import JudgePipeline
|
||||
from agent_framework.routing.enterprise_router import EnterpriseRouter
|
||||
from agent_framework.routing.pending_topics import drain_pending_topics
|
||||
from agent_framework.supervisor.supervisor import Supervisor
|
||||
from agent_framework.observability.workflow_events import WorkflowTelemetry
|
||||
from agent_framework.observability.guardrail_events import GuardrailTelemetry
|
||||
@@ -109,7 +110,6 @@ class AgentWorkflow:
|
||||
fail_fast=bool(getattr(settings, "GUARDRAILS_FAIL_FAST", True)),
|
||||
)
|
||||
self.judges = JudgePipeline()
|
||||
self.supervisor = Supervisor()
|
||||
self.workflow_telemetry = WorkflowTelemetry(telemetry)
|
||||
self.guardrail_telemetry = GuardrailTelemetry(telemetry)
|
||||
self.judge_telemetry = JudgeTelemetry(telemetry)
|
||||
@@ -118,6 +118,14 @@ class AgentWorkflow:
|
||||
self.embedding_provider = create_embedding_provider(settings)
|
||||
self.rag_service = RagService(settings, embedding_provider=self.embedding_provider, telemetry=telemetry)
|
||||
self.router = EnterpriseRouter(settings, llm=llm, telemetry=telemetry)
|
||||
self.supervisor = Supervisor(
|
||||
routing_rules=[
|
||||
(intent.name, intent.agent, list(intent.keywords))
|
||||
for intent in self.router.intents
|
||||
if intent.enabled
|
||||
],
|
||||
fallback_agent=self.router.fallback_agent,
|
||||
)
|
||||
agent_kwargs = {"telemetry": telemetry, "tool_router": getattr(self, "tool_router", None), "rag_service": self.rag_service, "cache": self.cache, "settings": settings, "observer": self.observer, "memory": memory, "summary_memory": summary_memory}
|
||||
self.billing = BillingAgent(llm, **agent_kwargs)
|
||||
self.product = ProductAgent(llm, **agent_kwargs)
|
||||
@@ -160,7 +168,7 @@ class AgentWorkflow:
|
||||
builder.add_conditional_edges(
|
||||
"input_guardrails",
|
||||
self._after_input_guardrails,
|
||||
{"blocked": "persist", "continue": "load_long_term_memory"},
|
||||
{"blocked": "output_guardrails", "continue": "load_long_term_memory"},
|
||||
)
|
||||
builder.add_edge("load_long_term_memory", "routing_decision")
|
||||
builder.add_conditional_edges(
|
||||
@@ -197,6 +205,31 @@ class AgentWorkflow:
|
||||
def _after_input_guardrails(self, state):
|
||||
return "blocked" if state.get("blocked") else "continue"
|
||||
|
||||
@staticmethod
|
||||
def _input_guardrail_user_message(decisions, state, sanitized_text):
|
||||
# Keep the technical guardrail reason in telemetry, but expose only a
|
||||
# safe, actionable message to the end user. The message is intentionally
|
||||
# routed through output_guardrails before persistence/delivery.
|
||||
blocked = [d for d in decisions if not getattr(d, "allowed", True)]
|
||||
first = blocked[0] if blocked else None
|
||||
code = str(getattr(first, "code", "") or "").upper()
|
||||
if code == "COER":
|
||||
return (
|
||||
"Não consegui entender sua última mensagem porque ela parece "
|
||||
"incompleta ou ambígua. Pode reformular ou completar o que você quis dizer?"
|
||||
)
|
||||
if code == "INPUT_SIZE":
|
||||
return "Sua mensagem ficou muito longa para eu processar de uma vez. Pode resumir ou dividir em partes?"
|
||||
if code == "DLEX_IN":
|
||||
return "Não posso usar essa informação da forma solicitada. Reformule o pedido sem incluir dados ou conteúdo restrito."
|
||||
if code == "PINJ":
|
||||
return "Não posso seguir instruções que tentem alterar as regras do atendimento. Posso continuar ajudando com a sua solicitação."
|
||||
if code == "TOX":
|
||||
return "Não consegui prosseguir com essa mensagem. Pode reformular o pedido para continuarmos o atendimento?"
|
||||
if code == "CMP":
|
||||
return "Não posso prosseguir com essa solicitação dessa forma. Posso ajudar com uma alternativa permitida."
|
||||
return "Não consegui processar essa mensagem. Pode reformular para eu continuar o atendimento?"
|
||||
|
||||
async def input_guardrails(self, state):
|
||||
if state.get("session_ended") is True:
|
||||
answer = str(getattr(
|
||||
@@ -222,6 +255,28 @@ class AgentWorkflow:
|
||||
input=state.get("user_text"),
|
||||
):
|
||||
history_texts = [m.get("content", "") for m in state.get("history", [])]
|
||||
guardrail_active_transaction = (
|
||||
state.get("active_transaction")
|
||||
if isinstance(state.get("active_transaction"), dict)
|
||||
else {}
|
||||
)
|
||||
guardrail_transaction_status = str(
|
||||
guardrail_active_transaction.get("status")
|
||||
or state.get("transaction_status")
|
||||
or ""
|
||||
).strip().upper()
|
||||
pending_call = state.get("pending_tool_call") if isinstance(state.get("pending_tool_call"), dict) else {}
|
||||
if state.get("confirmation_required") and pending_call.get("tool_name"):
|
||||
guardrail_transaction_status = "AWAITING_CONFIRMATION"
|
||||
elif state.get("missing_parameters") and pending_call.get("tool_name"):
|
||||
guardrail_transaction_status = "COLLECTING_PARAMETERS"
|
||||
for mcp_result in reversed(list(state.get("mcp_results") or [])):
|
||||
if not isinstance(mcp_result, dict):
|
||||
continue
|
||||
mcp_status = str(mcp_result.get("transaction_status") or "").strip().upper()
|
||||
if mcp_status in {"COLLECTING_PARAMETERS", "AWAITING_CONFIRMATION"}:
|
||||
guardrail_transaction_status = mcp_status
|
||||
break
|
||||
await self.observer.emit_grl(
|
||||
"001",
|
||||
{
|
||||
@@ -240,6 +295,10 @@ class AgentWorkflow:
|
||||
"tenant_id": state.get("tenant_id"),
|
||||
"agent_id": state.get("agent_id"),
|
||||
"agent_profile": state.get("agent_profile") or {},
|
||||
"transaction_status": guardrail_transaction_status,
|
||||
"missing_parameters": list(state.get("missing_parameters") or []),
|
||||
"active_transaction": guardrail_active_transaction,
|
||||
"mcp_results": list(state.get("mcp_results") or []),
|
||||
},
|
||||
)
|
||||
for _decision in decisions:
|
||||
@@ -281,12 +340,33 @@ class AgentWorkflow:
|
||||
component="workflow.input_guardrails.final",
|
||||
)
|
||||
if any(not d.allowed for d in decisions):
|
||||
# A blocking input guardrail stops the turn before routing/tools.
|
||||
# Clear turn-local routing/tool state so stale data from a prior
|
||||
# turn cannot appear as if it was executed after the block.
|
||||
user_message = self._input_guardrail_user_message(decisions, state, sanitized)
|
||||
return {
|
||||
"sanitized_input": sanitized,
|
||||
"answer": "Não consegui seguir com essa mensagem por regra de segurança.",
|
||||
"final_answer": "Não consegui seguir com essa mensagem por regra de segurança.",
|
||||
"answer": user_message,
|
||||
"final_answer": None,
|
||||
"guardrail_decisions": [d.model_dump() for d in decisions],
|
||||
"route": "blocked",
|
||||
"intent": "input_guardrail_blocked",
|
||||
"route_decision": {
|
||||
"route": "blocked",
|
||||
"agent": None,
|
||||
"intent": "input_guardrail_blocked",
|
||||
"confidence": 1.0,
|
||||
"reason": "Entrada interrompida por guardrail antes do roteamento.",
|
||||
"method": "guardrail",
|
||||
"next_state": state.get("next_state"),
|
||||
"handoff": False,
|
||||
"metadata": {},
|
||||
"domain": state.get("domain"),
|
||||
"mcp_tools": [],
|
||||
},
|
||||
"mcp_tools": [],
|
||||
"mcp_results": [],
|
||||
"judge_results": [],
|
||||
"blocked": True,
|
||||
}
|
||||
return {
|
||||
@@ -363,6 +443,18 @@ class AgentWorkflow:
|
||||
"reason": decision.reason if decision.method == "continuity" else None,
|
||||
"profile": (decision.metadata or {}).get("continuity_profile"),
|
||||
} if decision.method == "continuity" else {},
|
||||
"pending_topics": (
|
||||
(decision.metadata or {}).get("multi_intent_plan", {}).get("operations", [])[1:]
|
||||
if (decision.metadata or {}).get("multi_intent_plan")
|
||||
else list(state.get("pending_topics") or [])
|
||||
),
|
||||
# Durable correlation for the primary operation. route_decision
|
||||
# is replaced by state routing on confirmation/resume turns.
|
||||
"multi_intent_plan": (
|
||||
(decision.metadata or {}).get("multi_intent_plan")
|
||||
or state.get("multi_intent_plan")
|
||||
or {}
|
||||
),
|
||||
}
|
||||
|
||||
async def billing_agent(self, state):
|
||||
@@ -439,6 +531,7 @@ class AgentWorkflow:
|
||||
return {
|
||||
"answer": answer,
|
||||
"supervisor_results": partials,
|
||||
"agent_responses": partials,
|
||||
"mcp_results": mcp_results,
|
||||
"next_state": "SUPERVISOR_ACTIVE",
|
||||
}
|
||||
@@ -501,16 +594,51 @@ class AgentWorkflow:
|
||||
agente gerar `answer` e antes dos judges/persistência, produzindo campos
|
||||
supervisor_* no state e eventos GRL.001..GRL.009 via AgentObserver.
|
||||
"""
|
||||
drained = await drain_pending_topics(
|
||||
state,
|
||||
str(state.get("answer") or ""),
|
||||
{
|
||||
"billing_agent": self.billing.run,
|
||||
"product_agent": self.product.run,
|
||||
"orders_agent": self.orders.run,
|
||||
"support_agent": self.support.run,
|
||||
},
|
||||
)
|
||||
candidate = drained.answer
|
||||
if not bool(getattr(self.settings, "ENABLE_OUTPUT_SUPERVISOR", True)):
|
||||
return {
|
||||
"answer": candidate,
|
||||
"final_answer": candidate,
|
||||
"pending_topics": drained.pending_topics,
|
||||
"handled_topics": drained.handled_topics,
|
||||
"agent_responses": drained.agent_responses,
|
||||
"operation_results": drained.operation_results,
|
||||
"mcp_results": drained.mcp_results,
|
||||
"rag_results": drained.rag_results,
|
||||
"output_guardrails_already_applied": False,
|
||||
"supervisor_action": "disabled",
|
||||
"supervisor_attempt": int(state.get("supervisor_attempt", 0)),
|
||||
**drained.state_patch,
|
||||
}
|
||||
|
||||
candidate = state.get("answer") or ""
|
||||
context = {
|
||||
**(state.get("context") or {}),
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"evidence": (list(drained.mcp_results) + list(drained.rag_results)) or (state.get("context") or {}).get("evidence"),
|
||||
"tool_result": drained.mcp_results or (state.get("context") or {}).get("tool_result"),
|
||||
"tool_executed": any(isinstance(item, dict) and item.get("ok") for item in drained.mcp_results),
|
||||
"mcp_results": drained.mcp_results,
|
||||
"tenant_id": state.get("tenant_id"),
|
||||
"agent_id": state.get("agent_id"),
|
||||
"session_id": state.get("conversation_key") or state.get("session_id"),
|
||||
@@ -577,6 +705,13 @@ class AgentWorkflow:
|
||||
for r in decision.results
|
||||
],
|
||||
"output_guardrails_already_applied": True,
|
||||
"pending_topics": drained.pending_topics,
|
||||
"handled_topics": drained.handled_topics,
|
||||
"agent_responses": drained.agent_responses,
|
||||
"operation_results": drained.operation_results,
|
||||
"mcp_results": drained.mcp_results,
|
||||
"rag_results": drained.rag_results,
|
||||
**drained.state_patch,
|
||||
"guardrail_decisions": state.get("guardrail_decisions", [])
|
||||
+ [item for r in decision.results for item in (r.metadata or {}).get("legacy_decisions", [])],
|
||||
}
|
||||
@@ -803,6 +938,7 @@ class AgentWorkflow:
|
||||
"judges": state.get("judge_results", []),
|
||||
"mcp_tools": state.get("mcp_tools", []),
|
||||
"mcp_results": state.get("mcp_results", []),
|
||||
"rag_results": state.get("rag_results", []),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -60,6 +60,18 @@ mcp_parameter_mapping:
|
||||
mensagem.
|
||||
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
|
||||
group: 1
|
||||
cancelar_pedido:
|
||||
map:
|
||||
session_key: session_id
|
||||
extract:
|
||||
order_id:
|
||||
from: message
|
||||
type: string
|
||||
strategy: hybrid
|
||||
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
|
||||
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
|
||||
group: 1
|
||||
|
||||
solicitar_troca:
|
||||
map:
|
||||
session_key: session_id
|
||||
|
||||
@@ -7,6 +7,35 @@ router:
|
||||
confidence_threshold: 0.65
|
||||
allow_handoff: true
|
||||
|
||||
transaction_confirmation:
|
||||
# Explicit yes/no stays deterministic. Only inconclusive replies use this LLM fallback.
|
||||
semantic_fallback:
|
||||
enabled: true
|
||||
allowed_values: [SIM, NAO, CONTINUAR]
|
||||
confirm_values: [SIM]
|
||||
reject_values: [NAO]
|
||||
continue_values: [CONTINUAR]
|
||||
include_relevant_context: true
|
||||
profile_name: router
|
||||
prompt: |
|
||||
Você classifica a resposta do cliente a uma confirmação transacional pendente.
|
||||
Considere a pergunta pendente, somente o histórico recente relacionado ao mesmo tema e a fala atual.
|
||||
Não execute a ação e não invente fatos.
|
||||
|
||||
Classes permitidas: {{ allowed_values }}
|
||||
- SIM: confirmação/aceite inequívoco, inclusive equivalentes como "isso mesmo", "pode confirmar", "é isso" quando o contexto tornar o aceite claro.
|
||||
- NAO: recusa/cancelamento inequívoco da ação pendente.
|
||||
- CONTINUAR: qualquer resposta que não confirme nem rejeite inequivocamente, incluindo pergunta adicional, correção, novo dado, ambiguidade ou possível mudança de assunto.
|
||||
|
||||
Pergunta pendente:
|
||||
{{ pending_prompt }}
|
||||
|
||||
Histórico relevante:
|
||||
{{ relevant_conversation_context }}
|
||||
|
||||
Resposta atual do cliente:
|
||||
{{ user_input }}
|
||||
|
||||
state_policies:
|
||||
- state: WAITING_BILLING_CONFIRMATION
|
||||
agent: billing_agent
|
||||
@@ -79,6 +108,25 @@ intents:
|
||||
- Quero saber sobre meu pacote de internet.
|
||||
- Tenho roaming internacional?
|
||||
|
||||
|
||||
- name: retail_order_cancel
|
||||
domain: retail
|
||||
agent: orders_agent
|
||||
description: Cancelamento explícito de pedido ou compra.
|
||||
priority: 20
|
||||
mcp_tools:
|
||||
- consultar_pedido
|
||||
- cancelar_pedido
|
||||
keywords:
|
||||
- cancelar pedido
|
||||
- cancelamento do pedido
|
||||
- cancelar a compra
|
||||
- cancelar compra
|
||||
examples:
|
||||
- Quero cancelar meu pedido.
|
||||
- Cancele o pedido.
|
||||
- Quero cancelar a compra.
|
||||
|
||||
- name: retail_order_tracking
|
||||
domain: retail
|
||||
agent: orders_agent
|
||||
|
||||
@@ -7,6 +7,12 @@ defaults:
|
||||
require_confirmation: false
|
||||
|
||||
tool_policies:
|
||||
cancelar_pedido:
|
||||
operation_type: transactional
|
||||
require_confirmation: true
|
||||
requires: [order_id]
|
||||
|
||||
|
||||
solicitar_troca:
|
||||
operation_type: transactional
|
||||
require_confirmation: true
|
||||
|
||||
@@ -4,18 +4,33 @@ tools:
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
invoice_id: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
invoice_id:
|
||||
type: string
|
||||
label: o identificador da fatura
|
||||
description: Identificador da fatura que o cliente deseja consultar.
|
||||
user_prompt: Informe o identificador da fatura que deseja consultar.
|
||||
selection_keywords:
|
||||
- fatura
|
||||
- conta
|
||||
- boleto
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: telecom.invoice
|
||||
consultar_pagamentos:
|
||||
description: Consulta histórico de pagamentos do cliente.
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
selection_keywords:
|
||||
- pagamento
|
||||
- pagamentos
|
||||
@@ -24,16 +39,31 @@ tools:
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
asset_id: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
asset_id:
|
||||
type: string
|
||||
label: o identificador do plano ou ativo
|
||||
description: Identificador do plano ou ativo comercial associado ao cliente.
|
||||
user_prompt: Informe o identificador do plano ou ativo que deseja consultar.
|
||||
selection_keywords:
|
||||
- plano
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: telecom.plan
|
||||
listar_servicos:
|
||||
description: Lista serviços ativos e adicionais VAS.
|
||||
mcp_server: telecom
|
||||
enabled: true
|
||||
args_schema:
|
||||
msisdn: string
|
||||
msisdn:
|
||||
type: string
|
||||
label: o número da linha
|
||||
description: Número da linha do cliente (MSISDN) usado para consultar informações de telecom.
|
||||
user_prompt: Informe o número da linha que deseja consultar.
|
||||
selection_keywords:
|
||||
- serviços
|
||||
- servicos
|
||||
@@ -43,24 +73,63 @@ tools:
|
||||
mcp_server: retail
|
||||
enabled: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
customer_id: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido que o cliente deseja consultar.
|
||||
user_prompt: Informe o número do pedido que deseja consultar.
|
||||
customer_id:
|
||||
type: string
|
||||
label: a identificação do cliente
|
||||
description: Identificador do cliente associado ao pedido de varejo.
|
||||
user_prompt: Informe a identificação do cliente.
|
||||
selection_keywords:
|
||||
- consultar pedido
|
||||
- status do pedido
|
||||
- pedido
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: retail.order
|
||||
consultar_entrega:
|
||||
description: Consulta entrega e rastreamento do pedido.
|
||||
mcp_server: retail
|
||||
enabled: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido cuja entrega ou rastreamento será consultado.
|
||||
user_prompt: Informe o número do pedido que deseja rastrear.
|
||||
selection_keywords:
|
||||
- entrega
|
||||
- rastreio
|
||||
- rastreamento
|
||||
- transportadora
|
||||
- previsão
|
||||
response:
|
||||
mode: renderer
|
||||
renderer: retail.delivery
|
||||
cancelar_pedido:
|
||||
description: Simula o cancelamento de um pedido de varejo.
|
||||
mcp_server: retail
|
||||
enabled: true
|
||||
tool_type: action
|
||||
requires:
|
||||
- order_id
|
||||
confirmation_required: true
|
||||
args_schema:
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido que o cliente deseja cancelar.
|
||||
user_prompt: Informe o número do pedido que deseja cancelar.
|
||||
selection_keywords:
|
||||
- cancelar pedido
|
||||
- cancelamento do pedido
|
||||
- cancelar compra
|
||||
- cancelar a compra
|
||||
|
||||
|
||||
solicitar_troca:
|
||||
description: Simula abertura de solicitação de troca.
|
||||
mcp_server: retail
|
||||
@@ -71,8 +140,16 @@ tools:
|
||||
- reason
|
||||
confirmation_required: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
reason: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido para o qual o cliente deseja solicitar troca.
|
||||
user_prompt: Informe o número do pedido que deseja trocar.
|
||||
reason:
|
||||
type: string
|
||||
label: o motivo da troca
|
||||
description: Motivo informado pelo cliente para solicitar a troca do pedido.
|
||||
user_prompt: Qual é o motivo da troca?
|
||||
selection_keywords:
|
||||
- solicitar troca
|
||||
- trocar
|
||||
@@ -89,8 +166,16 @@ tools:
|
||||
- reason
|
||||
confirmation_required: true
|
||||
args_schema:
|
||||
order_id: string
|
||||
reason: string
|
||||
order_id:
|
||||
type: string
|
||||
label: o número do pedido
|
||||
description: Identificador do pedido para o qual o cliente deseja solicitar devolução.
|
||||
user_prompt: Informe o número do pedido que deseja devolver.
|
||||
reason:
|
||||
type: string
|
||||
label: o motivo da devolução
|
||||
description: Motivo informado pelo cliente para solicitar a devolução do pedido.
|
||||
user_prompt: Qual é o motivo da devolução?
|
||||
selection_keywords:
|
||||
- solicitar devolução
|
||||
- solicitar devolucao
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Confirmação Transacional Semântica
|
||||
|
||||
Este template suporta confirmação transacional em duas camadas: primeiro um parser determinístico para `sim`/`não` e equivalentes explícitos; somente quando ele não consegue decidir, o framework usa um classificador semântico configurado em `config/routing.yaml`.
|
||||
|
||||
A configuração `router.transaction_confirmation.semantic_fallback` usa três classes: `SIM`, `NAO` e `CONTINUAR`. O prompt pode usar `{{ pending_prompt }}`, `{{ relevant_conversation_context }}`, `{{ user_input }}` e `{{ allowed_values }}`. O histórico injetado é apenas contexto de interpretação; não substitui validação de negócio ou evidência MCP.
|
||||
|
||||
Exemplo: após `Você confirma o cancelamento do serviço Tamboro Mensal?`, a frase `isso mesmo, pode confirmar` pode ser classificada como `SIM`. Já `mas qual é o valor?` deve ser `CONTINUAR`, portanto não executa a ação por confirmação.
|
||||
|
||||
Entradas explícitas já suportadas continuam no caminho determinístico e não geram custo adicional de LLM. Em observabilidade, o fallback usa `transaction.confirmation.semantic_classifier` e o `route_decision.metadata` informa `transaction_confirmation_source: semantic`.
|
||||
|
||||
Consulte `docs/developer/pt/03_transaction_workflows_and_state.md` do framework para o contrato completo e exemplos.
|
||||
@@ -15,11 +15,17 @@ profiles:
|
||||
temperature: 0
|
||||
max_tokens: 80
|
||||
timeout_seconds: 5
|
||||
processing_interruption_classifier:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1-mini
|
||||
temperature: 0
|
||||
max_tokens: 8
|
||||
timeout_seconds: 5
|
||||
router:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1
|
||||
temperature: 0
|
||||
max_tokens: 500
|
||||
max_tokens: 768
|
||||
guardrail:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1
|
||||
@@ -78,3 +84,10 @@ profiles:
|
||||
temperature: 0
|
||||
max_tokens: 80
|
||||
timeout_seconds: 5
|
||||
|
||||
transaction_parameter_extraction:
|
||||
provider: oci_openai
|
||||
model: openai.gpt-4.1-mini
|
||||
temperature: 0
|
||||
max_tokens: 500
|
||||
timeout_seconds: 8
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Domain Requested LLM Composition
|
||||
|
||||
## Objetivo
|
||||
|
||||
Permitir que uma tool/workflow de domínio informe que o resultado operacional não deve ser devolvido diretamente ao usuário e precisa ser redigido pelo LLM oficial do agente, sem criar um gateway LLM dentro do domínio.
|
||||
|
||||
## Contrato
|
||||
|
||||
A tool pode devolver, em qualquer nível do resultado:
|
||||
|
||||
```json
|
||||
{
|
||||
"requires_llm_composition": true,
|
||||
"response_instruction": "Explique ao cliente a forma de devolução usando apenas os dados do workflow."
|
||||
}
|
||||
```
|
||||
|
||||
Também é aceito `response_instructions` como lista.
|
||||
|
||||
O `AgentRuntimeMixin` percorre recursivamente o resultado MCP. Quando a flag está ativa, `build_direct_mcp_answer()` retorna `None`; a resposta segue pelo LLM configurado no framework e recebe as evidências MCP no contexto normal do agente.
|
||||
|
||||
## Por que isso existe
|
||||
|
||||
Algumas operações, como pró-rata, possuem resultado determinístico e efeitos já concluídos, mas precisam de linguagem natural adequada ao canal. Antes, o domínio Contas possuía um gateway LLM próprio. Agora o domínio só declara a necessidade e a instrução; execução, credenciais, profiles, tracing e custos continuam no `agent_framework_oci`.
|
||||
|
||||
## Regras
|
||||
|
||||
- Não usar para decidir se uma transação deve ocorrer.
|
||||
- Não usar para inventar valores ou protocolos.
|
||||
- A instrução deve exigir que o LLM use somente as evidências retornadas pela tool/workflow.
|
||||
- Pode coexistir com `requires_rag`; nesse caso o framework também executa RAG antes da composição.
|
||||
51
Tuning-Performance/Domain_Requested_RAG/README.md
Normal file
51
Tuning-Performance/Domain_Requested_RAG/README.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Domain-Requested RAG
|
||||
|
||||
## Objetivo
|
||||
|
||||
Permitir que uma tool/workflow de domínio declare que o resultado MCP **não é suficiente** para produzir a resposta final e que o agente deve recuperar conhecimento usando o `RagService` oficial do `agent_framework_oci`.
|
||||
|
||||
O domínio não instancia banco vetorial, embeddings, LLM ou cliente RAG. Ele apenas devolve no resultado:
|
||||
|
||||
```json
|
||||
{
|
||||
"requires_rag": true,
|
||||
"rag_queries": [
|
||||
"Como cancelar o serviço Paramount+ no parceiro? Procedimento oficial de cancelamento."
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Fluxo
|
||||
|
||||
```text
|
||||
Workflow/tool de domínio
|
||||
|
|
||||
| requires_rag + rag_queries
|
||||
v
|
||||
AgentRuntimeMixin
|
||||
|
|
||||
+-- impede direct MCP answer
|
||||
+-- ignora SKIP_RAG_WHEN_MCP_SUFFICIENT para este resultado
|
||||
+-- usa rag_query/rag_queries como query override
|
||||
v
|
||||
RagService
|
||||
v
|
||||
Vector/Graph store configurado no framework
|
||||
v
|
||||
LLM do agente com MCP evidence + RAG evidence
|
||||
```
|
||||
|
||||
## Regras
|
||||
|
||||
1. `requires_rag=false` ou ausente mantém o comportamento padrão.
|
||||
2. `SKIP_RAG_WHEN_MCP_SUFFICIENT=true` continua válido para tools normais.
|
||||
3. Quando `requires_rag=true`, o framework não usa `build_direct_mcp_answer()`.
|
||||
4. `rag_query` aceita uma query; `rag_queries` aceita várias queries, preservadas e deduplicadas em ordem.
|
||||
5. O domínio nunca executa `RagService` diretamente.
|
||||
6. Guardrails de retrieval (`RAGSEC`, `RET_REL` etc.) continuam executando normalmente sobre o contexto recuperado.
|
||||
|
||||
## Exemplo Contas
|
||||
|
||||
No fluxo VAS Estratégico, após o cliente rejeitar a explicação e pedir cancelamento, a action devolve queries específicas por parceiro. O `VasAgent` usa o `RagService` do framework para recuperar o procedimento oficial e compor a resposta.
|
||||
|
||||
Isso substitui o comportamento legado em que o backend Contas possuía uma busca RAG própria dentro de `vas_strategic()`.
|
||||
16
Tuning-Performance/External_Guardrails_Judges/README.md
Normal file
16
Tuning-Performance/External_Guardrails_Judges/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# External Guardrails / Judges
|
||||
|
||||
Este cenário de tuning mede extensões de política do agente. Antes de interpretar os resultados, implemente e valide o contrato descrito no [guia completo](../../docs/EXTERNAL_GUARDRAILS_JUDGES.md).
|
||||
|
||||
O cenário deve comparar, no mínimo, latência p50/p95/p99, taxa de allow/deny/sanitize, erros e timeouts, custo de judges com LLM e comportamento fail-open/fail-closed. Separe resultados por código/nome e estágio, sem registrar prompts, PII ou payloads financeiros.
|
||||
|
||||
Cuidados de leitura:
|
||||
|
||||
- `type: external` afeta apenas o componente declarado;
|
||||
- implementação síncrona usa worker thread e implementação `async` usa o event loop;
|
||||
- judges executam concorrentemente, então meça contenção do provedor e do pool;
|
||||
- compare a mesma carga com extensão desligada para obter o overhead incremental;
|
||||
- execute casos transacionais separadamente, pois `always_run_for_transactional` ignora a amostragem;
|
||||
- no template corrente os pipelines são globais; caminhos por agente não implicam isolamento automático.
|
||||
|
||||
Antes do benchmark, rode `pytest -q tests/test_external_guardrails_judges_documentation.py` para provar que os exemplos do manual ainda carregam e executam.
|
||||
@@ -66,6 +66,30 @@ EMBEDDING_PROVIDER=mock
|
||||
OCI_EMBEDDING_MODEL=cohere.embed-multilingual-v3.0
|
||||
RAG_FILE_GLOBS=*.md,*.txt,*.yaml,*.yml,*.json
|
||||
|
||||
|
||||
# RAG / KBDB
|
||||
# RAG provider: standard (local) ou kbdb (PKG_KB_SERVING.SEARCH_KNOWLEDGE_BASE)
|
||||
RAG_PROVIDER=standard
|
||||
# KBDB usa credenciais próprias; não há fallback para ADB_*.
|
||||
KBDB_DB_USER=
|
||||
KBDB_DB_PASSWORD=
|
||||
KBDB_DB_DSN=
|
||||
KBDB_DB_WALLET_LOCATION=
|
||||
KBDB_DB_WALLET_PASSWORD=
|
||||
KBDB_SEARCH_TYPE=hybrid
|
||||
KBDB_NODE_EXPANSION=true
|
||||
KBDB_NODE_MAX_RELATED=8
|
||||
KBDB_GRAPH_CROSS_REF=false
|
||||
KBDB_MAX_CROSS_REF_HOPS=1
|
||||
KBDB_DOCUMENT_TYPE=customer_safe
|
||||
KBDB_METADATA_JSON=
|
||||
KBDB_MIN_SCORE=
|
||||
KBDB_IDENTIFY_DOCUMENT=true
|
||||
KBDB_STORE_QUERY=true
|
||||
KBDB_IDENTIFY_TOP_N=3
|
||||
RAG_GROUNDED_ONLY=false
|
||||
KBDB_GROUNDED_ONLY=true
|
||||
|
||||
###############################################################################
|
||||
# Observabilidade
|
||||
###############################################################################
|
||||
@@ -0,0 +1,6 @@
|
||||
FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
COPY agent_framework /agent_framework
|
||||
COPY agent_template_backend /app
|
||||
RUN pip install --no-cache-dir -e /agent_framework -r requirements.txt
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,54 @@
|
||||
# Agent Template Backend Enterprise
|
||||
|
||||
Este folder é uma cópia completa do `agent_template_backend`, sem cortes de
|
||||
arquitetura. Ele mantém workflow, router, output supervisor, guardrails,
|
||||
analytics, observer, MCP, memória, checkpoints e configurações.
|
||||
|
||||
A diferença é que a lógica de negócio dos agentes de exemplo foi removida da
|
||||
execução e preservada comentada nos próprios arquivos:
|
||||
|
||||
- `app/agents/billing_agent.py`
|
||||
- `app/agents/product_agent.py`
|
||||
- `app/agents/orders_agent.py`
|
||||
- `app/agents/support_agent.py`
|
||||
|
||||
## O que o desenvolvedor deve alterar
|
||||
|
||||
1. Escolher ou criar um agente em `app/agents/`.
|
||||
2. Implementar o método `run()`.
|
||||
3. Ajustar prompts e tools, se necessário.
|
||||
4. Emitir ICs de negócio relevantes para a jornada.
|
||||
5. Manter NOC/GRL nos pontos operacionais e de guardrails.
|
||||
|
||||
## O que já está integrado
|
||||
|
||||
- `AgentObserver`
|
||||
- `observer.emit_ic()`
|
||||
- `observer.emit_noc()`
|
||||
- `observer.emit_grl()`
|
||||
- `AnalyticsPublisher`
|
||||
- OCI Streaming
|
||||
- GCP Pub/Sub
|
||||
- OutputSupervisor
|
||||
- GuardrailPipeline com suporte a execução paralela/fail-fast no framework
|
||||
- MCP Tool Router
|
||||
- LangGraph
|
||||
- Memory
|
||||
- Checkpoint
|
||||
- Langfuse / OpenTelemetry
|
||||
|
||||
## Exemplos adicionados
|
||||
|
||||
Veja `app/examples/`:
|
||||
|
||||
- `ic_examples.py`
|
||||
- `noc_examples.py`
|
||||
- `grl_examples.py`
|
||||
- `mcp_examples.py`
|
||||
- `observer_examples.py`
|
||||
|
||||
## Convenção rápida
|
||||
|
||||
- IC = evento de negócio / curadoria / informacional.
|
||||
- NOC = evento operacional / saúde técnica.
|
||||
- GRL = evento de guardrail / segurança / validação.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,15 @@
|
||||
# Agentes do Template Backend Enterprise
|
||||
|
||||
Os arquivos desta pasta preservam a estrutura real esperada pelo workflow, mas
|
||||
não executam lógica de negócio pronta.
|
||||
|
||||
Cada agente mostra:
|
||||
|
||||
- como emitir IC;
|
||||
- como emitir NOC;
|
||||
- como emitir GRL;
|
||||
- como coletar MCP via `_collect_tool_context()`;
|
||||
- como recuperar RAG via `_retrieve_rag_context()`;
|
||||
- onde chamar LLM/cache.
|
||||
|
||||
A implementação original do exemplo está comentada no fim de cada arquivo.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
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