@polymorphism-tech/morph-spec 7.0.0 → 7.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +368 -368
- package/claude-plugin.json +14 -14
- package/docs/CHEATSHEET.md +199 -199
- package/docs/QUICKSTART.md +200 -200
- package/framework/CLAUDE.md +1 -1
- package/framework/MORPH.md +4 -1
- package/framework/agents.json +132 -127
- package/framework/rubrics/backend.json +41 -36
- package/framework/rules/ai-agents-standards.md +45 -15
- package/framework/rules/neon-standards.md +25 -26
- package/framework/skills/core/morph-brainstorming/SKILL.md +1 -1
- package/framework/skills/core/morph-plan/SKILL.md +3 -1
- package/framework/skills/core/morph-stack-scan/SKILL.md +3 -3
- package/framework/standards/STANDARDS.json +1729 -1133
- package/framework/standards/ai-agents/agent-session.md +160 -0
- package/framework/standards/ai-agents/batching.md +193 -0
- package/framework/standards/ai-agents/context-providers.md +188 -0
- package/framework/standards/ai-agents/mcp-server.md +250 -0
- package/framework/standards/ai-agents/mcp-tools.md +197 -0
- package/framework/standards/ai-agents/middleware-patterns.md +207 -0
- package/framework/standards/ai-agents/modalities-image-gen.md +173 -0
- package/framework/standards/ai-agents/modalities-speech-to-text.md +171 -0
- package/framework/standards/ai-agents/modalities-text-to-speech.md +181 -0
- package/framework/standards/ai-agents/modalities-vision.md +201 -0
- package/framework/standards/ai-agents/multi-agent-patterns.md +155 -0
- package/framework/standards/ai-agents/production.md +114 -258
- package/framework/standards/ai-agents/prompts-in-db.md +214 -0
- package/framework/standards/ai-agents/providers/model-registry.md +158 -0
- package/framework/standards/ai-agents/rag-custom-pgvector.md +243 -0
- package/framework/standards/ai-agents/service-tier-flex.md +135 -0
- package/framework/standards/ai-agents/setup.md +142 -316
- package/framework/standards/ai-agents/structured-output.md +249 -0
- package/framework/standards/ai-agents/sweet-spot.md +109 -0
- package/framework/standards/ai-agents/workflows.md +114 -284
- package/framework/standards/architecture/vertical-slice/vertical-slice.md +439 -429
- package/framework/standards/backend/api/validation.md +92 -88
- package/framework/standards/backend/database/postgresql/database.md +336 -332
- package/framework/standards/backend/database/vector-search-rag.md +599 -541
- package/framework/standards/backend/dotnet/fluent-validation-vsa.md +4 -0
- package/framework/standards/backend/dotnet/result-pattern.md +4 -0
- package/framework/standards/backend/dotnet/scalar-ui.md +176 -172
- package/framework/standards/backend/dotnet/scrutor.md +4 -0
- package/framework/standards/backend/dotnet/vsa-handler-patterns.md +310 -274
- package/framework/standards/backend/integrations/asaas/asaas-api.md +260 -216
- package/framework/standards/backend/integrations/hangfire/hangfire-jobs.md +354 -350
- package/framework/standards/backend/integrations/neon-auth/neon-auth.md +30 -19
- package/framework/standards/backend/integrations/resend/resend-email.md +400 -385
- package/framework/standards/data/nosql/cache/redis.md +106 -97
- package/framework/standards/data/nosql/cosmos-db.md +127 -118
- package/framework/standards/data/vector-search/rag-chunking.md +113 -104
- package/framework/standards/frontend/design-system/ai-image-generation.md +4 -0
- package/framework/standards/frontend/design-system/animations.md +164 -160
- package/framework/standards/frontend/design-system/naming.md +68 -64
- package/framework/standards/frontend/gsap/gsap-core.md +14 -8
- package/framework/standards/frontend/gsap/gsap-plugins.md +26 -21
- package/framework/standards/frontend/gsap/gsap-scrolltrigger.md +9 -7
- package/framework/standards/frontend/nextjs/app-router.md +127 -123
- package/framework/standards/frontend/nextjs/components.md +136 -132
- package/framework/standards/frontend/nextjs/data-fetching.md +130 -126
- package/framework/standards/frontend/nextjs/forms.md +134 -128
- package/framework/standards/frontend/nextjs/motion-patterns.md +328 -322
- package/framework/standards/frontend/nextjs/naming-conventions.md +71 -67
- package/framework/standards/frontend/nextjs/nextjs-patterns.md +229 -225
- package/framework/standards/frontend/nextjs/project-structure.md +106 -102
- package/framework/standards/frontend/nextjs/state-management.md +76 -72
- package/framework/standards/frontend/nextjs/testing.md +115 -111
- package/framework/standards/infrastructure/docker/easypanel-deploy.md +196 -192
- package/framework/standards/infrastructure/neon/neon-pgrag.md +6 -2
- package/framework/standards/infrastructure/neon/neon-pgvector.md +4 -0
- package/framework/standards/infrastructure/neon/neon-setup.md +5 -1
- package/framework/standards/integration/mcp/mcp-tools.md +471 -462
- package/framework/templates/CLAUDE.md.core.template +1 -1
- package/framework/templates/REGISTRY.json +1745 -1239
- package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +39 -0
- package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +68 -0
- package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +117 -0
- package/framework/templates/code/dotnet/ai-agents/PromptRepository.cs.template +95 -0
- package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +61 -0
- package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +107 -0
- package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +58 -0
- package/framework/templates/code/dotnet/backend/repository.cs +3 -10
- package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +58 -0
- package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +91 -0
- package/package.json +89 -83
- package/src/core/templates/template-registry.js +289 -256
- package/src/lib/generators/context-generator.js +516 -518
- package/src/lib/generators/scaffold-generator.js +23 -26
- package/framework/standards/infrastructure/neon/neon-semantic-kernel.md +0 -310
- package/framework/templates/integrations/semantic-kernel-neon.cs +0 -125
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# Structured Output — Typed agent responses
|
|
2
|
+
|
|
3
|
+
> **Scope:** stacks=["dotnet"]
|
|
4
|
+
> **Layer:** 0 (always-load via persona maf-expert)
|
|
5
|
+
> **Keywords:** structured output, typed response, response format, schema validated output, record output, JSON schema agent, RunAsync generic
|
|
6
|
+
> **Read by Claude in:** implement (sempre que um agente produz saída consumida por outro sistema)
|
|
7
|
+
|
|
8
|
+
**Verified against:** MAF 1.0 GA. Last-verified: 2026-05-19.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Por que sempre Structured Output
|
|
13
|
+
|
|
14
|
+
Texto livre de LLM é não-determinístico. Dois runs da mesma prompt podem retornar formatações diferentes, campos com nomes diferentes, ou dados em posições diferentes. Você não consegue plugar isso num pipeline downstream de forma confiável.
|
|
15
|
+
|
|
16
|
+
Um `sealed record` tipado é um contrato: o front-end, o banco, o próximo agente sabem exatamente a shape. O runtime MAF gera o JSON Schema a partir do tipo, envia para o modelo, e deserializa o retorno automaticamente. Se o modelo devolver algo fora do schema, a call falha rápido e com mensagem clara — muito melhor que descobrir um bug de parsing em produção.
|
|
17
|
+
|
|
18
|
+
**Regra prática:** 90%+ das chamadas a LLM em produção precisam de structured output. A única exceção é saída puramente textual para display final (ex: resposta de chatbot para o usuário). Se a saída vai ser lida por código, use `RunAsync<T>`.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## A API (MAF 1.0 GA)
|
|
23
|
+
|
|
24
|
+
### Form 1 — `RunAsync<T>` (recomendada)
|
|
25
|
+
|
|
26
|
+
```csharp
|
|
27
|
+
AgentResponse<CityInfo> response = await agent.RunAsync<CityInfo>("Provide information about Tokyo.");
|
|
28
|
+
CityInfo tokyo = response.Result;
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
O runtime MAF:
|
|
32
|
+
1. Gera o JSON Schema a partir de `T` automaticamente.
|
|
33
|
+
2. Seta `ResponseFormat` na chamada ao modelo.
|
|
34
|
+
3. Deserializa a resposta JSON diretamente em `.Result`.
|
|
35
|
+
|
|
36
|
+
**Use Form 1 por default.** É a forma mais simples e a que menos expõe detalhes de provider.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
### Form 2 — `ChatResponseFormat.ForJsonSchema<T>()` (quando precisar de ChatOptions)
|
|
41
|
+
|
|
42
|
+
```csharp
|
|
43
|
+
AIAgent agent = _modelRegistry.GetChatClient("text-heavy").AsAIAgent(new ChatClientAgentOptions
|
|
44
|
+
{
|
|
45
|
+
Name = "ProposalAgent",
|
|
46
|
+
ChatOptions = new()
|
|
47
|
+
{
|
|
48
|
+
Instructions = "You are a commercial proposal specialist.",
|
|
49
|
+
ResponseFormat = ChatResponseFormat.ForJsonSchema<ProposalDraft>()
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
AgentResponse response = await agent.RunAsync("Draft a proposal for a SaaS migration project.");
|
|
54
|
+
ProposalDraft draft = response.Deserialize<ProposalDraft>(JsonSerializerOptions.Web);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Use Form 2 quando:**
|
|
58
|
+
- Você precisa setar `ResponseFormat` junto com outras `ChatOptions` (ex: temperatura, system prompt por invocação).
|
|
59
|
+
- Você quer reusar o mesmo agente para múltiplos tipos de saída, trocando o format por chamada via `ChatClientAgentRunOptions`.
|
|
60
|
+
|
|
61
|
+
**Setando ResponseFormat por invocação (sem recriar o agente):**
|
|
62
|
+
|
|
63
|
+
```csharp
|
|
64
|
+
var runOptions = new ChatClientAgentRunOptions
|
|
65
|
+
{
|
|
66
|
+
ChatOptions = new() { ResponseFormat = ChatResponseFormat.ForJsonSchema<ProposalDraft>() }
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
AgentResponse response = await agent.RunAsync("Draft a proposal.", runOptions);
|
|
70
|
+
ProposalDraft draft = response.Deserialize<ProposalDraft>(JsonSerializerOptions.Web);
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Definindo o tipo de saída
|
|
76
|
+
|
|
77
|
+
Use `sealed class` ou `sealed record`. Regras:
|
|
78
|
+
|
|
79
|
+
1. `[Description("...")]` **na classe/record** — descreve ao modelo o que o objeto representa. Sem isso, o modelo depende só do nome do tipo.
|
|
80
|
+
2. `[JsonPropertyName("snake_case")]` **em CADA propriedade** — sem isso, o modelo pode retornar `camelCase`, `PascalCase`, ou `snake_case` dependendo do provider e da versão. Quando o provider muda, o desserializador quebra silenciosamente.
|
|
81
|
+
3. Tipos de propriedade devem ser **nullable** (`string?`, `int?`) em classes; em records posicionais use nullable quando o campo pode estar ausente.
|
|
82
|
+
4. Para listas: `IReadOnlyList<T>` — imutável por padrão, previne mutação acidental após desserialização.
|
|
83
|
+
|
|
84
|
+
**Exemplo realista — `ProposalDraft`:**
|
|
85
|
+
|
|
86
|
+
```csharp
|
|
87
|
+
using System.ComponentModel;
|
|
88
|
+
using System.Text.Json.Serialization;
|
|
89
|
+
|
|
90
|
+
[Description("A structured commercial proposal draft")]
|
|
91
|
+
public sealed record ProposalDraft(
|
|
92
|
+
[property: JsonPropertyName("headline")] string Headline,
|
|
93
|
+
[property: JsonPropertyName("client_pain_point")] string ClientPainPoint,
|
|
94
|
+
[property: JsonPropertyName("sections")] IReadOnlyList<DeliverableSection> Sections,
|
|
95
|
+
[property: JsonPropertyName("total_price")] decimal TotalPrice,
|
|
96
|
+
[property: JsonPropertyName("validity_days")] int ValidityDays);
|
|
97
|
+
|
|
98
|
+
[Description("One deliverable section of a proposal")]
|
|
99
|
+
public sealed record DeliverableSection(
|
|
100
|
+
[property: JsonPropertyName("title")] string Title,
|
|
101
|
+
[property: JsonPropertyName("description")] string Description);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
> Prefer `record` sobre `class` para tipos de saída — imutável, `==` por valor, `ToString()` útil para logs. Use `class` somente se o tipo precisar de lógica de mutação pós-desserialização.
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## Exemplo C# completo
|
|
109
|
+
|
|
110
|
+
Um agente que recebe dados de cliente e retorna um `ProposalDraft` usando Form 1 (`RunAsync<T>`):
|
|
111
|
+
|
|
112
|
+
```csharp
|
|
113
|
+
using System.ComponentModel;
|
|
114
|
+
using System.Text.Json.Serialization;
|
|
115
|
+
using Microsoft.Agents.AI;
|
|
116
|
+
using Microsoft.Extensions.AI;
|
|
117
|
+
|
|
118
|
+
// --- Tipos de saída ---
|
|
119
|
+
|
|
120
|
+
[Description("A structured commercial proposal draft")]
|
|
121
|
+
public sealed record ProposalDraft(
|
|
122
|
+
[property: JsonPropertyName("headline")] string Headline,
|
|
123
|
+
[property: JsonPropertyName("client_pain_point")] string ClientPainPoint,
|
|
124
|
+
[property: JsonPropertyName("sections")] IReadOnlyList<DeliverableSection> Sections,
|
|
125
|
+
[property: JsonPropertyName("total_price")] decimal TotalPrice,
|
|
126
|
+
[property: JsonPropertyName("validity_days")] int ValidityDays);
|
|
127
|
+
|
|
128
|
+
[Description("One deliverable section of a proposal")]
|
|
129
|
+
public sealed record DeliverableSection(
|
|
130
|
+
[property: JsonPropertyName("title")] string Title,
|
|
131
|
+
[property: JsonPropertyName("description")] string Description);
|
|
132
|
+
|
|
133
|
+
// --- Agente ---
|
|
134
|
+
|
|
135
|
+
public sealed class ProposalDraftingAgent
|
|
136
|
+
{
|
|
137
|
+
private readonly AIAgent _agent;
|
|
138
|
+
|
|
139
|
+
public ProposalDraftingAgent(ModelRegistry modelRegistry)
|
|
140
|
+
{
|
|
141
|
+
_agent = modelRegistry.GetChatClient("text-heavy").AsAIAgent(new ChatClientAgentOptions
|
|
142
|
+
{
|
|
143
|
+
Name = "ProposalDraftingAgent",
|
|
144
|
+
ChatOptions = new()
|
|
145
|
+
{
|
|
146
|
+
Instructions = """
|
|
147
|
+
You are a senior commercial proposal specialist.
|
|
148
|
+
Always produce a structured proposal based on the client context provided.
|
|
149
|
+
The total_price must reflect realistic market pricing for the scope described.
|
|
150
|
+
validity_days must be between 15 and 90.
|
|
151
|
+
"""
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
public async Task<ProposalDraft> DraftAsync(string clientContext, CancellationToken ct = default)
|
|
157
|
+
{
|
|
158
|
+
AgentResponse<ProposalDraft> response = await _agent.RunAsync<ProposalDraft>(
|
|
159
|
+
$"Draft a commercial proposal for the following client context:\n\n{clientContext}",
|
|
160
|
+
cancellationToken: ct);
|
|
161
|
+
|
|
162
|
+
return response.Result;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
**Consumindo `.Result`:**
|
|
168
|
+
|
|
169
|
+
```csharp
|
|
170
|
+
var agent = new ProposalDraftingAgent(modelRegistry);
|
|
171
|
+
ProposalDraft draft = await agent.DraftAsync("Client: RetailCo. Need: Migrate 5 legacy Java services to .NET 10.");
|
|
172
|
+
|
|
173
|
+
Console.WriteLine(draft.Headline); // ex: "Modernization of RetailCo's Core Services"
|
|
174
|
+
Console.WriteLine(draft.TotalPrice); // ex: 87500.00
|
|
175
|
+
Console.WriteLine(draft.Sections.Count); // ex: 4
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
> **Model Registry alias `"text-heavy"`:** resolves to the project's configured high-quality model (ex: `gpt-4o`, `gemini-1.5-pro`, `claude-opus-4-5`). Nunca hardcode o nome do modelo — veja `ai-agents-providers-model-registry`.
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## Validação pós-call
|
|
183
|
+
|
|
184
|
+
O JSON schema garante a **shape** da resposta, não a **semântica**. O modelo pode retornar um `TotalPrice` de `0` ou `ValidityDays` de `-1` e ainda conformar ao schema.
|
|
185
|
+
|
|
186
|
+
**Sempre valide regras de negócio depois de `RunAsync<T>`:**
|
|
187
|
+
|
|
188
|
+
```csharp
|
|
189
|
+
public async Task<Result<ProposalDraft>> DraftValidatedAsync(string clientContext, CancellationToken ct = default)
|
|
190
|
+
{
|
|
191
|
+
AgentResponse<ProposalDraft> response = await _agent.RunAsync<ProposalDraft>(
|
|
192
|
+
$"Draft a commercial proposal for:\n\n{clientContext}",
|
|
193
|
+
cancellationToken: ct);
|
|
194
|
+
|
|
195
|
+
ProposalDraft draft = response.Result;
|
|
196
|
+
|
|
197
|
+
// Validação semântica — schema não cobre isso
|
|
198
|
+
if (draft.TotalPrice <= 0)
|
|
199
|
+
return Result.Failure<ProposalDraft>("Agent returned zero or negative price.");
|
|
200
|
+
|
|
201
|
+
if (draft.ValidityDays is < 15 or > 90)
|
|
202
|
+
return Result.Failure<ProposalDraft>($"ValidityDays {draft.ValidityDays} is out of range [15, 90].");
|
|
203
|
+
|
|
204
|
+
if (draft.Sections is null || draft.Sections.Count == 0)
|
|
205
|
+
return Result.Failure<ProposalDraft>("Agent returned proposal with no deliverable sections.");
|
|
206
|
+
|
|
207
|
+
if (string.IsNullOrWhiteSpace(draft.Headline))
|
|
208
|
+
return Result.Failure<ProposalDraft>("Agent returned proposal with empty headline.");
|
|
209
|
+
|
|
210
|
+
return Result.Success(draft);
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
> Se a validação falhar, você pode re-prompt com o erro como contexto, ou retornar um domain error para o caller decidir. Nunca lance exception como fluxo de controle — use `Result<T>` ou equivalente.
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
## Anti-patterns
|
|
219
|
+
|
|
220
|
+
| Anti-pattern | Por quê é errado | Jeito certo |
|
|
221
|
+
|--------------|-----------------|-------------|
|
|
222
|
+
| Retornar texto livre e parsear com regex | LLM output é não-determinístico; regex quebra quando o modelo muda a formatação | Use `RunAsync<T>` com um `sealed record` tipado |
|
|
223
|
+
| Usar `dynamic` ou `JsonNode` em vez de um record tipado | Perde type-safety, IntelliSense e validação em compile time; erros surgem em runtime em produção | Defina um `sealed record` com `[JsonPropertyName]` em cada propriedade |
|
|
224
|
+
| Tipo de saída sem `[JsonPropertyName]` em cada propriedade | Quando o provider muda de versão ou o casing da resposta varia, `JsonSerializer` silenciosamente atribui `null` sem erro | Decore CADA propriedade com `[JsonPropertyName("snake_case")]` |
|
|
225
|
+
| Confiar apenas no JSON schema para garantir corretude | Schema valida shape, não semântica — `TotalPrice = 0` e `ValidityDays = -1` são válidos no schema | Sempre valide regras de negócio após `RunAsync<T>` e retorne `Result<T>` em caso de falha |
|
|
226
|
+
| Criar o `ChatClient` diretamente com model string hardcoded | Quebra troca de provider; o nome do modelo fica espalhado pelo codebase | Sempre use `_modelRegistry.GetChatClient("alias")` — veja `ai-agents-providers-model-registry` |
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## Checklist (verifiable by morph-eval)
|
|
231
|
+
|
|
232
|
+
- [ ] Todo agente que alimenta outro sistema (front-end, banco, pipeline, outro agente) usa `RunAsync<T>` ou `ResponseFormat` — nenhum retorna `response.Text` para parsing downstream.
|
|
233
|
+
- [ ] O tipo de saída é um `sealed record` ou `sealed class` decorado com `[Description("...")]`.
|
|
234
|
+
- [ ] CADA propriedade do tipo de saída tem `[JsonPropertyName("...")]` explícito.
|
|
235
|
+
- [ ] Validação de regras de negócio existe após `RunAsync<T>` — o resultado é verificado além da shape do schema.
|
|
236
|
+
- [ ] O agente é construído a partir de `_modelRegistry.GetChatClient("alias")` — nenhum model name hardcoded.
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## References
|
|
241
|
+
|
|
242
|
+
- `ai-agents-setup` — packages, DI, e setup mínimo de agente
|
|
243
|
+
- `ai-agents-sweet-spot` — quando usar agente, quando não usar
|
|
244
|
+
- `ai-agents-providers-model-registry` — como registrar e resolver modelos por alias
|
|
245
|
+
- Microsoft Agent Framework docs: https://learn.microsoft.com/agent-framework/
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
*MORPH-SPEC by Polymorphism Tech — ai-agents/structured-output.md v1.0 (2026-05-19)*
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Sweet Spot — When to use what in MAF
|
|
2
|
+
|
|
3
|
+
> **Scope:** stacks=["dotnet"]
|
|
4
|
+
> **Layer:** 0 (always-load via persona maf-expert)
|
|
5
|
+
> **Keywords:** sweet spot, when to use agent, agent vs workflow, when not to use workflow, MAF decision, simple agent
|
|
6
|
+
> **Read by Claude in:** plan (decide arquitetura da feature antes de quebrar em tasks) + implement (validar que a arquitetura ainda é a mais simples possível)
|
|
7
|
+
|
|
8
|
+
**Verified against:** MAF Tier List research (2026-05-18) + Microsoft Learn docs. Last-verified: 2026-05-19.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## The 4-feature rule
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
95% of production AI agents need ONLY:
|
|
16
|
+
|
|
17
|
+
1. Chat (the LLM call)
|
|
18
|
+
2. Structured Output (typed records, not free text)
|
|
19
|
+
3. Tools (typed functions the agent can call)
|
|
20
|
+
4. RAG Custom (pgvector tool, not hosted RAG)
|
|
21
|
+
|
|
22
|
+
If your feature needs ONLY these 4 → use a single agent. Don't reach for workflows.
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Apply this rule before deciding multi-agent or workflow. Most of the time the answer is "single agent".
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Decision tree (Claude reads this in plan phase)
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
Step 1 — Does the task even need an LLM?
|
|
33
|
+
├─ "Can a deterministic function solve this?" → YES → write the function, no agent
|
|
34
|
+
└─ NO → continue
|
|
35
|
+
|
|
36
|
+
Step 2 — Single agent vs multi-agent?
|
|
37
|
+
├─ One topic + one decision → single agent (DEFAULT)
|
|
38
|
+
├─ Multiple specialized topics with clear handoff → multi-agent
|
|
39
|
+
│ └─ Prefer Agent-as-Tool pattern (one agent uses another as a tool)
|
|
40
|
+
│ └─ See ai-agents-multi-agent-patterns
|
|
41
|
+
└─ "I'm not sure" → start with single agent, escalate if needed
|
|
42
|
+
|
|
43
|
+
Step 3 — Need a Workflow?
|
|
44
|
+
├─ The feature has fan-in/out (many inputs aggregated) → maybe workflow
|
|
45
|
+
│ └─ Confirm: can you write it as a foreach + LINQ aggregate?
|
|
46
|
+
│ └─ YES → write the foreach, NO workflow
|
|
47
|
+
│ └─ NO → workflow may help
|
|
48
|
+
├─ Long-running with human-in-the-loop checkpoints → maybe workflow
|
|
49
|
+
│ └─ See ai-agents-workflows (Onda 2)
|
|
50
|
+
└─ Otherwise → NO workflow
|
|
51
|
+
|
|
52
|
+
Step 4 — Which provider?
|
|
53
|
+
├─ ALWAYS direct models — never a hosted agent service
|
|
54
|
+
├─ Provider choice (OpenAI / Google / Anthropic / Ollama) lives in the
|
|
55
|
+
│ project's Model Registry, not hardcoded → see ai-agents-providers-model-registry
|
|
56
|
+
└─ Hosted services (Foundry Agent Service, Vertex AI hosted) → NOT used
|
|
57
|
+
|
|
58
|
+
Step 5 — RAG approach?
|
|
59
|
+
├─ Need control over chunking/embedding/storage? → RAG custom (pgvector)
|
|
60
|
+
│ └─ See ai-agents-rag-custom-pgvector (Onda 2)
|
|
61
|
+
└─ Don't reach for hosted RAG — loses control
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## Anti-patterns (what Claude should NOT do)
|
|
67
|
+
|
|
68
|
+
| Anti-pattern | Why it's wrong | What to do instead |
|
|
69
|
+
|--------------|----------------|---------------------|
|
|
70
|
+
| Reach for Workflow when a function does the job | "Tudo que Workflows fazem, código C# normal faz com menos complexidade" — pesquisa | Write the function. Wrap in a tool if an agent needs to call it. |
|
|
71
|
+
| Use a hosted agent service | Hosted is "always 6-9 months behind" on models + removes control | Direct models always (OpenAI / Google / Anthropic / Ollama) |
|
|
72
|
+
| Upload PDFs to a hosted RAG | Loses control of chunking + embedding + storage | Custom RAG with pgvector. See ai-agents-rag-custom-pgvector |
|
|
73
|
+
| Add Memory/Session because "agents need state" | If not building a chatbot, don't add chat state | Skip. Add when a real chat UI exists. |
|
|
74
|
+
| Use Semantic Kernel for new features | SK is superseded by MAF | Use Microsoft.Agents.AI. See ai-agents-setup |
|
|
75
|
+
| Return free text and parse it downstream | LLM output is non-deterministic | Structured Output. See ai-agents-structured-output (Onda 2) |
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## When the 4-feature rule does NOT apply
|
|
80
|
+
|
|
81
|
+
You may need to step outside the sweet spot when:
|
|
82
|
+
- The feature genuinely fans-out (e.g., monthly report aggregating N items) → workflow with fan-in
|
|
83
|
+
- The feature needs vision/audio/image-gen → modality-specific standards (see ai-agents-modalities-* — Onda 3)
|
|
84
|
+
|
|
85
|
+
**Even in these cases:** the core of the agent still follows the 4-feature rule. Only the orchestration layer changes.
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Checklist (verifiable by morph-eval)
|
|
90
|
+
|
|
91
|
+
- [ ] Was each agent designed as single-agent BEFORE reaching for multi-agent? (Check `decisions.md`.)
|
|
92
|
+
- [ ] If a Workflow is used, is fan-in/out or HITL checkpointing genuinely present? Or could `foreach + LINQ` replace it?
|
|
93
|
+
- [ ] Are the 4 features (Chat, Structured Output, Tools, RAG Custom) all present where applicable?
|
|
94
|
+
- [ ] Are hosted agent services avoided?
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## References
|
|
99
|
+
|
|
100
|
+
- `ai-agents-setup` — packages and DI
|
|
101
|
+
- `ai-agents-providers-model-registry` — provider-agnostic config
|
|
102
|
+
- `ai-agents-structured-output` (Onda 2)
|
|
103
|
+
- `ai-agents-multi-agent-patterns` (Onda 2)
|
|
104
|
+
- `ai-agents-workflows` (Onda 2, reframed)
|
|
105
|
+
- `ai-agents-rag-custom-pgvector` (Onda 2)
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
*MORPH-SPEC by Polymorphism Tech — ai-agents/sweet-spot.md v1.0 (2026-05-19)*
|