Ajustes na documentação e remanejamento dos folders

This commit is contained in:
2026-06-21 10:32:26 -03:00
parent fe194a9f2a
commit 853c286313
8 changed files with 318 additions and 230 deletions

16
.idea/agent_platform_oci.iml generated Normal file
View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
</module>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/agent_platform_oci.iml" filepath="$PROJECT_DIR$/.idea/agent_platform_oci.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

23
.idea/workspace.xml generated
View File

@@ -5,17 +5,10 @@
</component> </component>
<component name="ChangeListManager"> <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$/.env.example" beforeDir="false" afterPath="$PROJECT_DIR$/.env.example" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" /> <change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
<change beforePath="$PROJECT_DIR$/README_en.md" beforeDir="false" afterPath="$PROJECT_DIR$/README_en.md" afterDir="false" /> <change beforePath="$PROJECT_DIR$/README_en.md" beforeDir="false" afterPath="$PROJECT_DIR$/README_en.md" afterDir="false" />
<change beforePath="$PROJECT_DIR$/apps/agent_gateway/config/backends.yaml" beforeDir="false" afterPath="$PROJECT_DIR$/apps/agent_gateway/config/backends.yaml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/specs/SPEC-003-AI-Gateway.md" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/apps/mcp_gateway/app/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/apps/mcp_gateway/app/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/apps/mcp_gateway/config/mcp_gateway.yaml" beforeDir="false" afterPath="$PROJECT_DIR$/apps/mcp_gateway/config/mcp_gateway.yaml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/mcp/servers/retail_mcp_server/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/mcp/servers/retail_mcp_server/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/mcp/servers/telecom_mcp_server/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/mcp/servers/telecom_mcp_server/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/specs/SPEC-001-Architecture.md" beforeDir="false" afterPath="$PROJECT_DIR$/specs/SPEC-001-Architecture.md" afterDir="false" />
<change beforePath="$PROJECT_DIR$/templates/agent_template_backend/.env" beforeDir="false" afterPath="$PROJECT_DIR$/templates/agent_template_backend/.env" afterDir="false" />
<change beforePath="$PROJECT_DIR$/templates/agent_template_backend_day_zero/.env" beforeDir="false" afterPath="$PROJECT_DIR$/templates/agent_template_backend_day_zero/.env" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -92,6 +85,8 @@
<workItem from="1781996091031" duration="1242000" /> <workItem from="1781996091031" duration="1242000" />
<workItem from="1782038604623" duration="6486000" /> <workItem from="1782038604623" duration="6486000" />
<workItem from="1782047166074" duration="27000" /> <workItem from="1782047166074" duration="27000" />
<workItem from="1782047194363" duration="961000" />
<workItem from="1782048494672" duration="230000" />
</task> </task>
<task id="LOCAL-00001" summary="Ajustes na documentação e remanejamento dos folders"> <task id="LOCAL-00001" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" /> <option name="closed" value="true" />
@@ -109,7 +104,15 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1782045265085</updated> <updated>1782045265085</updated>
</task> </task>
<option name="localTasksCounter" value="3" /> <task id="LOCAL-00003" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" />
<created>1782048304579</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1782048304579</updated>
</task>
<option name="localTasksCounter" value="4" />
<servers /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">

View File

@@ -33,7 +33,7 @@ Define a arquitetura geral da plataforma, seus componentes principais, estrutura
Descreve o runtime de execução conversacional dos agentes, incluindo LangGraph, estado, memória, checkpoints, roteamento, supervisor, BusinessContext, integração com MCP, RAG, eventos e tratamento de erros. Descreve o runtime de execução conversacional dos agentes, incluindo LangGraph, estado, memória, checkpoints, roteamento, supervisor, BusinessContext, integração com MCP, RAG, eventos e tratamento de erros.
### [SPEC-003 — AI Gateway](specs/SPEC-003-AI-Gateway.md) ### [SPEC-003 — Agent Gateway](specs/SPEC-003-Agent-Gateway.md)
Especifica o gateway responsável por centralizar chamadas de LLM e embeddings, incluindo contratos de request/response, profiles, providers, autenticação OCI, fallback, rate limit, métricas, segurança e observabilidade. Especifica o gateway responsável por centralizar chamadas de LLM e embeddings, incluindo contratos de request/response, profiles, providers, autenticação OCI, fallback, rate limit, métricas, segurança e observabilidade.

View File

@@ -32,7 +32,7 @@ Defines the overall platform architecture, its main components, repository struc
Describes the conversational execution runtime for agents, including LangGraph, state management, memory, checkpoints, routing, supervisor, BusinessContext, MCP integration, RAG, events, and error handling. Describes the conversational execution runtime for agents, including LangGraph, state management, memory, checkpoints, routing, supervisor, BusinessContext, MCP integration, RAG, events, and error handling.
### [SPEC-003 — AI Gateway](specs/SPEC-003-AI-Gateway.md) ### [SPEC-003 — Agent Gateway](specs/SPEC-003-Agent-Gateway.md)
Specifies the gateway responsible for centralizing LLM and embedding calls, including request/response contracts, profiles, providers, OCI authentication, fallback, rate limiting, metrics, security, and observability. Specifies the gateway responsible for centralizing LLM and embedding calls, including request/response contracts, profiles, providers, OCI authentication, fallback, rate limiting, metrics, security, and observability.

View File

@@ -1,218 +0,0 @@
# SPEC-003 — AI Gateway
## Escopo
O AI Gateway executa chamadas de inferência e embedding por contrato padronizado. Ele centraliza provider, modelo, profile, política, fallback, uso, custo, latência e telemetria.
## Endpoints
| Método | Endpoint | Descrição |
|---|---|---|
| `POST` | `/v1/chat/completions` | Geração de texto/chat. |
| `POST` | `/v1/embeddings` | Geração de embeddings. |
| `GET` | `/v1/models` | Lista modelos disponíveis. |
| `GET` | `/v1/profiles` | Lista profiles configurados. |
| `GET` | `/health` | Health check. |
| `GET` | `/ready` | Readiness check. |
## LLMRequest
```json
{
"tenant_id": "default",
"agent_id": "telecom_contas",
"profile": "judge",
"component": "judge",
"operation": "chat_completion",
"messages": [
{"role": "system", "content": "Você é um avaliador."},
{"role": "user", "content": "Avalie a resposta."}
],
"parameters": {
"temperature": 0,
"max_tokens": 800
},
"metadata": {
"request_id": "req-001",
"trace_id": "trace-001",
"session_id": "default:telecom_contas:session-001"
}
}
```
## LLMResponse
```json
{
"provider": "oci_openai",
"model": "openai.gpt-4.1",
"profile": "judge",
"content": "Resultado da geração.",
"usage": {
"input_tokens": 1200,
"output_tokens": 300,
"total_tokens": 1500
},
"latency_ms": 820,
"finish_reason": "stop",
"metadata": {
"fallback_used": false
}
}
```
## Profiles
```yaml
profiles:
default:
provider: oci_openai
model: openai.gpt-4.1
temperature: 0.2
max_tokens: 2048
supervisor:
provider: oci_openai
model: openai.gpt-4.1
temperature: 0
max_tokens: 700
router:
provider: oci_openai
model: openai.gpt-4.1
temperature: 0
max_tokens: 500
guardrail:
provider: oci_openai
model: openai.gpt-4.1
temperature: 0
max_tokens: 600
judge:
provider: oci_openai
model: openai.gpt-4.1
temperature: 0
max_tokens: 800
rag_generation:
provider: oci_openai
model: openai.gpt-4.1
temperature: 0.1
max_tokens: 1800
```
## Providers
| Provider | Autenticação | Uso |
|---|---|---|
| `mock` | Nenhuma | Testes locais. |
| `oci_openai` | API Key / endpoint compatible | OCI GenAI OpenAI-Compatible. |
| `oci_sdk` | OCI Auth Mode | SDK nativo OCI. |
| `openai_compatible` | API Key | Endpoint compatível OpenAI. |
## OCI Authentication
| Variável | Valores |
|---|---|
| `LLM_PROVIDER` | `mock`, `oci_openai`, `oci_sdk`, `openai_compatible` |
| `OCI_AUTH_MODE` | `config_file`, `instance_principal`, `resource_principal`, `workload_identity` |
| `OCI_GENAI_API_KEY` | API key para provider compatível |
## Fallback
```yaml
fallback:
enabled: true
policies:
default:
chain:
- profile: default
- profile: default_low_cost
judge:
enabled: false
```
## Rate Limit
```yaml
rate_limits:
default:
requests_per_minute: 600
tokens_per_minute: 1000000
agents:
telecom_contas:
requests_per_minute: 120
```
## Eventos
| Evento | Descrição |
|---|---|
| `ai.request.received` | Requisição recebida. |
| `ai.profile.resolved` | Profile resolvido. |
| `ai.provider.selected` | Provider selecionado. |
| `ai.completion.started` | Chamada iniciada. |
| `ai.completion.completed` | Chamada concluída. |
| `ai.fallback.used` | Fallback utilizado. |
| `ai.request.failed` | Falha de inferência. |
## Métricas
| Métrica | Dimensões |
|---|---|
| `ai_requests_total` | provider, model, profile, tenant, agent, status |
| `ai_latency_ms` | provider, model, profile |
| `ai_tokens_total` | provider, model, input/output |
| `ai_cost_estimated` | provider, model, tenant, agent |
| `ai_fallback_total` | source_profile, fallback_profile |
## Segurança
- API keys não são gravadas em logs.
- Prompts podem ser mascarados conforme política.
- Providers são autorizados por tenant.
- Workload Identity é usada em Kubernetes quando configurada.
- Modelos bloqueados por política retornam erro controlado.
## Requisitos Não Funcionais
| Categoria | Requisito |
|---|---|
| Disponibilidade | Componentes deployáveis expõem `/health` e `/ready`. |
| Escalabilidade | Apps stateless escalam horizontalmente. Estado conversacional fica em repositórios externos. |
| Segurança | Segredos são fornecidos por secret store ou Kubernetes Secrets. |
| Observabilidade | Logs, métricas e traces usam correlação por request_id, trace_id, session_id, tenant_id e agent_id. |
| Auditabilidade | Decisões de rota, guardrail, judge, MCP e LLM são rastreáveis. |
| Portabilidade | Execução suportada em local, Docker Compose e Kubernetes/OKE. |
| Configuração | Comportamento variável é controlado por `.env` e YAML versionado. |
## Critérios de Aceite
- [ ] Endpoint de chat completion aceita LLMRequest.
- [ ] Endpoint de embeddings aceita EmbeddingRequest.
- [ ] Profiles são resolvidos por `llm_profiles.yaml`.
- [ ] Provider/model/profile aparecem em logs e traces.
- [ ] Fallback é explícito e rastreável.
- [ ] Rate limit é aplicado por tenant/agente.
- [ ] OCI Auth funciona por ambiente.
- [ ] Modelo não autorizado é rejeitado.
- [ ] Uso de tokens é registrado.
- [ ] Erros retornam payload padronizado.
## Glossário
| Termo | Definição |
|---|---|
| Agent Platform | Plataforma composta por runtime, gateways, evaluator, templates, contratos e componentes operacionais. |
| Agent Framework | Biblioteca/core reutilizável com contratos, guardrails, judges, memória, telemetria, providers e utilitários. |
| Agent Runtime | Motor de execução de agentes baseado em LangGraph, estado, sessão, memória, checkpoints, roteamento e ciclo de vida. |
| Agent Gateway | Aplicação deployável de entrada, roteamento e orquestração entre backends/agentes. |
| Channel Gateway | Aplicação ou módulo de normalização de payloads de canais para GatewayRequest. |
| AI Gateway | Aplicação de governança, roteamento e abstração de chamadas LLM/embedding. |
| MCP Gateway | Aplicação de governança e roteamento de tools MCP. |
| Evaluator | Camada de avaliação online/offline, regressão e certificação. |
| Business Context | Conjunto de chaves canônicas de negócio: customer_key, contract_key, interaction_key, account_key, resource_key e session_key. |

View File

@@ -0,0 +1,273 @@
# SPEC-003 — Agent Gateway
## Escopo
O Agent Gateway é o ponto único de entrada da plataforma para canais e consumidores externos.
Sua responsabilidade é receber mensagens, gerenciar sessões globais, resolver o backend/agente responsável, executar roteamento, realizar handoff entre agentes/backends e encaminhar eventos SSE.
O Agent Gateway não executa inferência LLM nem embeddings. Essas capacidades pertencem ao Runtime e ao Agent Framework.
---
## Responsabilidades
### Entrada Única da Plataforma
```text
Web
WhatsApp
Voice
Teams
Slack
|
v
Agent Gateway
|
+--> Agent Backend A
|
+--> Agent Backend B
|
+--> Agent Backend C
```
### Gerenciamento de Sessões
Responsável por:
- Criação de sessões
- Recuperação de sessões
- Atualização de contexto global
- Persistência de metadados de sessão
- Correlação de requisições
Exemplo:
```json
{
"session_id": "default:telecom_contas:123",
"tenant_id": "default",
"active_backend": "telecom_contas",
"active_agent": "telecom_contas",
"turn_count": 12,
"metadata": {}
}
```
---
## Backend Routing
Resolve qual backend deve processar a mensagem.
Exemplo:
```yaml
backends:
telecom_contas:
url: http://backend-contas:8000
telecom_ofertas:
url: http://backend-ofertas:8000
```
Critérios possíveis:
- Backend padrão
- Regras YAML
- Intenção detectada
- Contexto da sessão
- Router LLM (opcional)
---
## Handoff
Permite transferência entre agentes ou backends.
Exemplo:
```text
Contas
|
+--> Ofertas
|
+--> Retenção
```
O handoff deve preservar:
- session_id
- conversation_key
- business context
- histórico da conversa
- metadados de correlação
---
## SSE Proxy
Responsável por encaminhar eventos de streaming para clientes.
### Endpoints
| Método | Endpoint |
|----------|----------|
| POST | /gateway/message |
| POST | /gateway/message/sse |
| GET | /gateway/events/{session_id} |
Eventos SSE suportados:
- connected
- workflow.started
- message.responded
- workflow.completed
- flow.end
- error
---
## Backend Discovery
Pode operar com catálogo estático ou descoberta dinâmica.
### Catálogo Estático
```yaml
backends:
telecom_contas:
url: http://contas:8000
telecom_ofertas:
url: http://ofertas:8000
```
### Descoberta Dinâmica
```yaml
service_discovery:
enabled: true
```
Capacidades:
- Registro automático
- Health check periódico
- Atualização de catálogo
- Sincronização de metadados
---
## Health e Operação
### Endpoints
| Método | Endpoint |
|----------|----------|
| GET | /health |
| GET | /ready |
| GET | /backends |
| GET | /debug/sessions |
---
## Contrato GatewayRequest
```json
{
"tenant_id": "default",
"agent_id": "telecom_contas",
"session_id": "default:telecom_contas:123",
"message": "Quero consultar minha fatura",
"business_context": {
"customer_key": "11999999999"
},
"metadata": {
"request_id": "req-001",
"trace_id": "trace-001"
}
}
```
---
## Contrato GatewayResponse
```json
{
"session_id": "default:telecom_contas:123",
"backend": "telecom_contas",
"agent": "telecom_contas",
"message": "Sua fatura está disponível.",
"metadata": {
"request_id": "req-001"
}
}
```
---
## Eventos
| Evento | Descrição |
|----------|----------|
| agent.gateway.request.received | Requisição recebida |
| agent.gateway.session.created | Sessão criada |
| agent.gateway.backend.selected | Backend selecionado |
| agent.gateway.handoff.started | Handoff iniciado |
| agent.gateway.handoff.completed | Handoff concluído |
| agent.gateway.sse.connected | Cliente SSE conectado |
| agent.gateway.request.failed | Falha de processamento |
---
## Métricas
| Métrica | Dimensões |
|----------|----------|
| gateway_requests_total | tenant, backend, agent, status |
| gateway_sessions_active | tenant |
| gateway_backend_selection_total | backend |
| gateway_handoff_total | origem, destino |
| gateway_latency_ms | backend |
| gateway_sse_connections | backend |
---
## Segurança
- Autenticação obrigatória quando configurada.
- Propagação de identidade entre gateways.
- Máscara de dados sensíveis em logs.
- Correlação por request_id, trace_id e session_id.
- Controle de acesso por tenant.
---
## Requisitos Não Funcionais
| Categoria | Requisito |
|----------|----------|
| Disponibilidade | Expor /health e /ready |
| Escalabilidade | Stateless com escala horizontal |
| Observabilidade | Logs, métricas e traces |
| Auditabilidade | Todas as decisões de roteamento rastreáveis |
| Segurança | Segredos externos e mascaramento |
| Portabilidade | Local, Docker e Kubernetes |
| Configuração | YAML e variáveis de ambiente |
---
## Critérios de Aceite
- [ ] Recebe mensagens de múltiplos canais.
- [ ] Seleciona backend corretamente.
- [ ] Mantém sessão global.
- [ ] Encaminha SSE.
- [ ] Executa handoff.
- [ ] Preserva Business Context.
- [ ] Suporta múltiplos backends.
- [ ] Permite descoberta dinâmica.
- [ ] Expõe health e readiness.
- [ ] Gera métricas e telemetria.