@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,173 @@
|
|
|
1
|
+
# Modalities — Image Generation (Text to Image)
|
|
2
|
+
|
|
3
|
+
> **Scope:** stacks=["dotnet"]
|
|
4
|
+
> **Layer:** 2 (on-keyword)
|
|
5
|
+
> **Keywords:** image generation, text to image, dall-e, gpt-image, mockup generation, image synthesis
|
|
6
|
+
> **Read by Claude in:** implement (quando o projeto precisa gerar imagens a partir de texto)
|
|
7
|
+
|
|
8
|
+
**Verified against:** MAF 1.0 GA + OpenAI .NET SDK 2.x. Last-verified: 2026-05-19.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Quando usar geração de imagem
|
|
13
|
+
|
|
14
|
+
Use quando o produto precisa criar imagens em runtime a partir de um prompt textual:
|
|
15
|
+
|
|
16
|
+
- **Mockups e protótipos visuais:** gerar capa de produto, banner de campanha, layout de tela
|
|
17
|
+
- **Conteúdo para social media:** imagens para posts geradas a partir de briefing do usuário
|
|
18
|
+
- **Visualizações:** diagramas, ilustrações ou thumbnails dinâmicos
|
|
19
|
+
|
|
20
|
+
**Nota importante:** geração de imagem é uma **chamada de serviço ao provider**, não um agente conversacional. Não crie um `AIAgent` para isso — use `ImageClient` diretamente via DI.
|
|
21
|
+
|
|
22
|
+
**Não use** quando um asset estático resolve o problema. Geração de imagem tem custo por chamada e latência de vários segundos. Se a imagem não muda por usuário/contexto, sirva de CDN.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## A API
|
|
27
|
+
|
|
28
|
+
O projeto resolve o `ImageClient` para o provider configurado. No OpenAI SDK (.NET 2.x), o caminho é:
|
|
29
|
+
|
|
30
|
+
```csharp
|
|
31
|
+
using OpenAI.Images;
|
|
32
|
+
|
|
33
|
+
ImageClient client = new("dall-e-3", apiKey);
|
|
34
|
+
GeneratedImage image = await client.GenerateImageAsync(prompt, options);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
O projeto injeta `ImageClient` via DI (ver §Exemplo). A resolução pode ser feita via factory ou diretamente por configuração — não há um `GetImageClient("alias")` no `ModelRegistry` padrão; registre o `ImageClient` como serviço nomeado ou use uma factory simples que lê `model-registry.json`.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Exemplo C# completo
|
|
42
|
+
|
|
43
|
+
```csharp
|
|
44
|
+
using OpenAI.Images;
|
|
45
|
+
using Microsoft.Extensions.Configuration;
|
|
46
|
+
|
|
47
|
+
public sealed class ImageGenerationService
|
|
48
|
+
{
|
|
49
|
+
private readonly ImageClient _client;
|
|
50
|
+
|
|
51
|
+
public ImageGenerationService(IConfiguration config)
|
|
52
|
+
{
|
|
53
|
+
// O projeto configura o modelo e a chave via config/model-registry.json ou appsettings
|
|
54
|
+
var model = config["ImageGen:Model"] ?? "dall-e-3";
|
|
55
|
+
var apiKey = config["OpenAI:ApiKey"]!;
|
|
56
|
+
_client = new ImageClient(model, apiKey);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// <summary>
|
|
60
|
+
/// Gera uma imagem a partir de um prompt e retorna os bytes PNG.
|
|
61
|
+
/// Prefira armazenar os bytes; URLs retornadas pelo provider são efêmeras (expiram em ~1h).
|
|
62
|
+
/// </summary>
|
|
63
|
+
public async Task<BinaryData> GenerateImageBytesAsync(
|
|
64
|
+
string prompt,
|
|
65
|
+
GeneratedImageSize? size = null,
|
|
66
|
+
GeneratedImageQuality? quality = null,
|
|
67
|
+
CancellationToken ct = default)
|
|
68
|
+
{
|
|
69
|
+
var resolvedSize = size ?? GeneratedImageSize.W1024xH1024;
|
|
70
|
+
var resolvedQuality = quality ?? GeneratedImageQuality.Standard;
|
|
71
|
+
|
|
72
|
+
var options = new ImageGenerationOptions
|
|
73
|
+
{
|
|
74
|
+
Size = resolvedSize,
|
|
75
|
+
Quality = resolvedQuality,
|
|
76
|
+
ResponseFormat = GeneratedImageFormat.Bytes
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
GeneratedImage image = await _client.GenerateImageAsync(prompt, options, ct);
|
|
80
|
+
return image.ImageBytes;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// <summary>
|
|
84
|
+
/// Gera uma imagem e retorna a URI. Use apenas quando precisar da URL diretamente
|
|
85
|
+
/// e souber que o downstream vai consumir a URL antes de ela expirar (~1h no OpenAI).
|
|
86
|
+
/// </summary>
|
|
87
|
+
public async Task<Uri> GenerateImageUriAsync(string prompt, CancellationToken ct = default)
|
|
88
|
+
{
|
|
89
|
+
var options = new ImageGenerationOptions
|
|
90
|
+
{
|
|
91
|
+
Size = GeneratedImageSize.W1024xH1024,
|
|
92
|
+
Quality = GeneratedImageQuality.Standard,
|
|
93
|
+
ResponseFormat = GeneratedImageFormat.Uri
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
GeneratedImage image = await _client.GenerateImageAsync(prompt, options, ct);
|
|
97
|
+
return image.ImageUri!;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
**Registro DI:**
|
|
103
|
+
|
|
104
|
+
```csharp
|
|
105
|
+
// Program.cs
|
|
106
|
+
builder.Services.AddSingleton<ImageGenerationService>();
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
**Consumo:**
|
|
110
|
+
|
|
111
|
+
```csharp
|
|
112
|
+
public class CampaignController(ImageGenerationService imageGen, IBlobStorage storage) : ControllerBase
|
|
113
|
+
{
|
|
114
|
+
[HttpPost("generate-banner")]
|
|
115
|
+
public async Task<IActionResult> GenerateBanner([FromBody] BannerRequest req)
|
|
116
|
+
{
|
|
117
|
+
BinaryData bytes = await imageGen.GenerateImageBytesAsync(
|
|
118
|
+
prompt: req.Briefing,
|
|
119
|
+
size: GeneratedImageSize.W1792xH1024,
|
|
120
|
+
quality: GeneratedImageQuality.High);
|
|
121
|
+
|
|
122
|
+
// Persista no storage do projeto antes de retornar
|
|
123
|
+
string storedUrl = await storage.UploadAsync(bytes, "image/png");
|
|
124
|
+
return Ok(new { url = storedUrl });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## Parâmetros
|
|
132
|
+
|
|
133
|
+
> Valores verificados contra OpenAI .NET SDK 2.x / DALL-E 3 (2026-05-19). Outros providers podem variar.
|
|
134
|
+
|
|
135
|
+
| Parâmetro | Tipo | Opções | Nota |
|
|
136
|
+
|-----------|------|--------|------|
|
|
137
|
+
| `Size` | `GeneratedImageSize` | `W1024xH1024`, `W1792xH1024`, `W1024xH1792` | DALL-E 3 suporta os três; DALL-E 2 tem conjunto diferente |
|
|
138
|
+
| `Quality` | `GeneratedImageQuality` | `Standard`, `High` | `High` = mais detalhe, mais custo e latência |
|
|
139
|
+
| `Style` | `GeneratedImageStyle` | `Natural`, `Vivid` | `Vivid` = mais saturado/dramático; `Natural` = realista |
|
|
140
|
+
| `ResponseFormat` | `GeneratedImageFormat` | `Bytes`, `Uri` | Prefira `Bytes` — URLs expiram em ~1h |
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Anti-patterns
|
|
145
|
+
|
|
146
|
+
| Anti-pattern | Por quê é errado | Jeito certo |
|
|
147
|
+
|--------------|-----------------|-------------|
|
|
148
|
+
| Gerar imagem quando asset estático resolve | Custo por chamada + latência sem ganho | Sirva de CDN; só gere quando o conteúdo é dinâmico por usuário/contexto |
|
|
149
|
+
| Não moderar o prompt antes de enviar | Prompts maliciosos podem gerar conteúdo impróprio; o provider rejeitará e você terá erro 400 sem log útil | Aplique validação/moderação de prompt antes de chamar `GenerateImageAsync`; veja `ai-agents-middleware-patterns` |
|
|
150
|
+
| Armazenar a URI retornada sem baixar | URLs do provider são efêmeras (~1h no OpenAI); links quebram depois | Use `ResponseFormat = Bytes`, persista no storage do projeto e sirva sua própria URL |
|
|
151
|
+
| Criar `AIAgent` para geração de imagem | `ImageClient` não é `IChatClient`; não há sentido em wrappear como agente | Injete `ImageGenerationService` diretamente — é um serviço, não um agente |
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Checklist (verifiable by morph-eval)
|
|
156
|
+
|
|
157
|
+
- [ ] `ImageClient` injetado via DI — não instanciado inline nos controllers
|
|
158
|
+
- [ ] `ResponseFormat = GeneratedImageFormat.Bytes` na maioria dos casos; URLs armazenadas no storage do projeto
|
|
159
|
+
- [ ] Prompt passa por validação/moderação antes de ir ao provider
|
|
160
|
+
- [ ] Não usa `AIAgent`/`AsAIAgent` para geração de imagem — é um `ImageGenerationService`
|
|
161
|
+
- [ ] Model e API key vêm de config, não hardcoded
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## References
|
|
166
|
+
|
|
167
|
+
- `ai-agents-setup` — packages, DI, e providers disponíveis
|
|
168
|
+
- `ai-agents-providers-model-registry` — padrão de alias; adapte para resolver `ImageClient` por provider
|
|
169
|
+
- OpenAI .NET SDK — `ImageClient`: https://github.com/openai/openai-dotnet
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
*MORPH-SPEC by Polymorphism Tech — ai-agents/modalities-image-gen.md v1.0 (2026-05-19)*
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# Modalities — Speech to Text (Audio to Text)
|
|
2
|
+
|
|
3
|
+
> **Scope:** stacks=["dotnet"]
|
|
4
|
+
> **Layer:** 2 (on-keyword)
|
|
5
|
+
> **Keywords:** speech to text, transcription, whisper, audio to text, voice transcription
|
|
6
|
+
> **Read by Claude in:** implement (quando o projeto precisa transcrever áudio para texto)
|
|
7
|
+
|
|
8
|
+
**Verified against:** MAF 1.0 GA + OpenAI .NET SDK 2.x. Last-verified: 2026-05-19.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Quando usar STT
|
|
13
|
+
|
|
14
|
+
Use quando o input real do usuário é áudio e você precisa de texto para processamento downstream:
|
|
15
|
+
|
|
16
|
+
- **Transcrição de reuniões:** gravar áudio da reunião → transcrever → alimentar um Status Agent que extrai ações, decisões e responsáveis
|
|
17
|
+
- **Notas de voz:** usuário fala → transcreve → salva como nota textual ou input para outro agente
|
|
18
|
+
- **Suporte por voz:** áudio do cliente → transcreve → agente de roteamento classifica e responde
|
|
19
|
+
|
|
20
|
+
**Fluxo típico:** `áudio (bytes/arquivo)` → `TranscriptionService` → `texto` → `AIAgent` downstream
|
|
21
|
+
|
|
22
|
+
Transcrição é uma **chamada de serviço**, não um agente conversacional. Use `AudioClient` diretamente via DI — não crie `AIAgent` para isso.
|
|
23
|
+
|
|
24
|
+
**Não se aplica** quando o input já é texto. Se o áudio foi transcrito por outra ferramenta, use o texto diretamente.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## A API
|
|
29
|
+
|
|
30
|
+
No OpenAI SDK (.NET 2.x), o caminho é `AudioClient.TranscribeAudio`:
|
|
31
|
+
|
|
32
|
+
```csharp
|
|
33
|
+
using OpenAI.Audio;
|
|
34
|
+
|
|
35
|
+
AudioClient client = new("whisper-1", apiKey);
|
|
36
|
+
AudioTranscription transcription = await client.TranscribeAudioAsync(audioFilePath);
|
|
37
|
+
string text = transcription.Text;
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
O projeto injeta `AudioClient` via DI. Para transcrição com timestamps (ex: sincronização de legenda), use `AudioTranscriptionOptions` com `ResponseFormat = AudioTranscriptionFormat.Verbose`.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Exemplo C# completo
|
|
45
|
+
|
|
46
|
+
```csharp
|
|
47
|
+
using OpenAI.Audio;
|
|
48
|
+
using Microsoft.Extensions.Configuration;
|
|
49
|
+
|
|
50
|
+
public sealed class TranscriptionService
|
|
51
|
+
{
|
|
52
|
+
private readonly AudioClient _client;
|
|
53
|
+
|
|
54
|
+
public TranscriptionService(IConfiguration config)
|
|
55
|
+
{
|
|
56
|
+
var model = config["Transcription:Model"] ?? "whisper-1";
|
|
57
|
+
var apiKey = config["OpenAI:ApiKey"]!;
|
|
58
|
+
_client = new AudioClient(model, apiKey);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// <summary>
|
|
62
|
+
/// Transcreve áudio a partir de um arquivo e retorna texto simples.
|
|
63
|
+
/// O transcript retornado pode ser passado diretamente como input para um AIAgent downstream.
|
|
64
|
+
/// </summary>
|
|
65
|
+
public async Task<string> TranscribeAsync(string audioFilePath, CancellationToken ct = default)
|
|
66
|
+
{
|
|
67
|
+
AudioTranscription transcription = await _client.TranscribeAudioAsync(audioFilePath, cancellationToken: ct);
|
|
68
|
+
return transcription.Text;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// <summary>
|
|
72
|
+
/// Transcreve áudio a partir de bytes (ex: upload do usuário) e retorna texto simples.
|
|
73
|
+
/// </summary>
|
|
74
|
+
public async Task<string> TranscribeBytesAsync(
|
|
75
|
+
Stream audioStream,
|
|
76
|
+
string fileName,
|
|
77
|
+
string mediaType = "audio/mpeg",
|
|
78
|
+
CancellationToken ct = default)
|
|
79
|
+
{
|
|
80
|
+
var options = new AudioTranscriptionOptions
|
|
81
|
+
{
|
|
82
|
+
ResponseFormat = AudioTranscriptionFormat.Simple
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
AudioTranscription transcription = await _client.TranscribeAudioAsync(
|
|
86
|
+
audioStream, fileName, options, cancellationToken: ct);
|
|
87
|
+
return transcription.Text;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// <summary>
|
|
91
|
+
/// Transcreve com timestamps por palavra e segmento (útil para legendas ou busca por trecho).
|
|
92
|
+
/// </summary>
|
|
93
|
+
public async Task<AudioTranscription> TranscribeVerboseAsync(string audioFilePath, CancellationToken ct = default)
|
|
94
|
+
{
|
|
95
|
+
var options = new AudioTranscriptionOptions
|
|
96
|
+
{
|
|
97
|
+
ResponseFormat = AudioTranscriptionFormat.Verbose,
|
|
98
|
+
TimestampGranularities = { AudioTimestampGranularity.Word, AudioTimestampGranularity.Segment }
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
return await _client.TranscribeAudioAsync(audioFilePath, options, cancellationToken: ct);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**Alimentando um agente downstream com o transcript:**
|
|
107
|
+
|
|
108
|
+
```csharp
|
|
109
|
+
// O transcript é texto puro — basta passar como input para qualquer AIAgent
|
|
110
|
+
string transcript = await _transcription.TranscribeAsync("meeting-2024-05-19.mp3");
|
|
111
|
+
|
|
112
|
+
// Ex: Status Agent que extrai ações da reunião
|
|
113
|
+
AgentResponse<MeetingActions> actions = await _statusAgent.RunAsync<MeetingActions>(
|
|
114
|
+
$"Extraia ações, decisões e responsáveis desta transcrição:\n\n{transcript}");
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
**Registro DI:**
|
|
118
|
+
|
|
119
|
+
```csharp
|
|
120
|
+
// Program.cs
|
|
121
|
+
builder.Services.AddSingleton<TranscriptionService>();
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Formatos e limites
|
|
127
|
+
|
|
128
|
+
> Valores verificados contra OpenAI Whisper API (2026-05-19). Confirme limites atuais na documentação do provider ao fazer deploy.
|
|
129
|
+
|
|
130
|
+
| Aspecto | Detalhe |
|
|
131
|
+
|---------|---------|
|
|
132
|
+
| Formatos suportados | `mp3`, `mp4`, `mpeg`, `mpga`, `m4a`, `wav`, `webm` |
|
|
133
|
+
| Limite por request | **25 MB** por arquivo (OpenAI Whisper) |
|
|
134
|
+
| Duração aproximada | ~1h de áudio ≈ 25MB em MP3 128kbps |
|
|
135
|
+
| Áudio longo | Pré-processe client-side: divida em chunks antes de enviar (ffmpeg, NAudio, etc.) — não há API de chunking automático no SDK |
|
|
136
|
+
| Idiomas | Whisper suporta 99 idiomas; especifique `Language = "pt"` em `AudioTranscriptionOptions` para melhor acurácia em português |
|
|
137
|
+
|
|
138
|
+
**Chunking de áudio longo:** para arquivos acima de 25MB, divida o arquivo em segmentos de ~20MB antes de enviar. Concatene os textos retornados. Não há sobreposição automática — adicione alguns segundos de overlap entre chunks se a precisão nos cortes for crítica.
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## Anti-patterns
|
|
143
|
+
|
|
144
|
+
| Anti-pattern | Por quê é errado | Jeito certo |
|
|
145
|
+
|--------------|-----------------|-------------|
|
|
146
|
+
| Transcrever quando o input já é texto | Custo e latência desnecessários | Use o texto diretamente como input do agente downstream |
|
|
147
|
+
| Enviar áudio longo (>25MB) sem chunking | O provider rejeita a request com erro 413 | Divida client-side em chunks ≤20MB antes de enviar |
|
|
148
|
+
| Criar `AIAgent` para transcrição | `AudioClient` não é `IChatClient`; o pipeline é simples (bytes → texto) | Injete `TranscriptionService` via DI — é um serviço, não um agente |
|
|
149
|
+
| Ignorar o idioma do áudio | Whisper infere o idioma, mas pode errar em áudios com muita sigla ou sotaque | Especifique `Language` em `AudioTranscriptionOptions` quando o idioma for conhecido |
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## Checklist (verifiable by morph-eval)
|
|
154
|
+
|
|
155
|
+
- [ ] `AudioClient` injetado via DI — não instanciado inline
|
|
156
|
+
- [ ] Áudio longo (>25MB) tratado com chunking antes de enviar ao provider
|
|
157
|
+
- [ ] Transcript retornado como `string` e passado como input ao agente downstream — sem re-formatação manual
|
|
158
|
+
- [ ] `Language` especificado em `AudioTranscriptionOptions` quando o idioma do áudio é conhecido
|
|
159
|
+
- [ ] Model e API key vêm de config, não hardcoded
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## References
|
|
164
|
+
|
|
165
|
+
- `ai-agents-setup` — packages, DI, e providers disponíveis
|
|
166
|
+
- `ai-agents-providers-model-registry` — padrão de alias; adapte para resolver `AudioClient` por provider
|
|
167
|
+
- OpenAI .NET SDK — `AudioClient`: https://github.com/openai/openai-dotnet
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
*MORPH-SPEC by Polymorphism Tech — ai-agents/modalities-speech-to-text.md v1.0 (2026-05-19)*
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# Modalities — Text to Speech (Text to Audio)
|
|
2
|
+
|
|
3
|
+
> **Scope:** stacks=["dotnet"]
|
|
4
|
+
> **Layer:** 2 (on-keyword)
|
|
5
|
+
> **Keywords:** text to speech, TTS, voice synthesis, audio generation, speech synthesis
|
|
6
|
+
> **Read by Claude in:** implement (quando o projeto precisa gerar áudio a partir de texto)
|
|
7
|
+
|
|
8
|
+
**Verified against:** MAF 1.0 GA + OpenAI .NET SDK 2.x. Last-verified: 2026-05-19.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Quando usar TTS
|
|
13
|
+
|
|
14
|
+
TTS converte texto em áudio narrado. É um caso de uso **raro** — só adicione quando há demanda real e comprovada:
|
|
15
|
+
|
|
16
|
+
- **Acessibilidade:** leitura em voz alta para usuários com deficiência visual ou dificuldade de leitura
|
|
17
|
+
- **Notificações em áudio:** resumos falados de alertas ou relatórios em contextos hands-free (painel industrial, carro)
|
|
18
|
+
- **Resumos falados:** o usuário quer ouvir um digest em vez de ler (ex: podcast personalizado gerado on-demand)
|
|
19
|
+
|
|
20
|
+
**Nota honesta:** TTS tem custo por caractere e latência perceptível. Se o caso de uso não é explicitamente solicitado pelo usuário final ou pelo cliente, não adicione — um botão "copiar texto" ou um leitor de tela nativo do SO resolve a maioria dos casos de acessibilidade sem custo de API.
|
|
21
|
+
|
|
22
|
+
TTS é uma **chamada de serviço**, não um agente conversacional. Use `AudioClient` diretamente via DI — não crie `AIAgent` para isso.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## A API
|
|
27
|
+
|
|
28
|
+
No OpenAI SDK (.NET 2.x), o caminho é `AudioClient.GenerateSpeech`:
|
|
29
|
+
|
|
30
|
+
```csharp
|
|
31
|
+
using OpenAI.Audio;
|
|
32
|
+
|
|
33
|
+
AudioClient client = new("tts-1", apiKey);
|
|
34
|
+
BinaryData speech = await client.GenerateSpeechAsync(text, GeneratedSpeechVoice.Alloy);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Retorna `BinaryData` (bytes de áudio) que você persiste ou serve via stream. Para controlar formato e velocidade, use `SpeechGenerationOptions`.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Exemplo C# completo
|
|
42
|
+
|
|
43
|
+
```csharp
|
|
44
|
+
using OpenAI.Audio;
|
|
45
|
+
using Microsoft.Extensions.Configuration;
|
|
46
|
+
|
|
47
|
+
public sealed class TextToSpeechService
|
|
48
|
+
{
|
|
49
|
+
private readonly AudioClient _client;
|
|
50
|
+
|
|
51
|
+
public TextToSpeechService(IConfiguration config)
|
|
52
|
+
{
|
|
53
|
+
// tts-1: mais rápido, menor qualidade. tts-1-hd: mais lento, maior qualidade.
|
|
54
|
+
var model = config["TTS:Model"] ?? "tts-1";
|
|
55
|
+
var apiKey = config["OpenAI:ApiKey"]!;
|
|
56
|
+
_client = new AudioClient(model, apiKey);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// <summary>
|
|
60
|
+
/// Converte texto em áudio e retorna bytes MP3.
|
|
61
|
+
/// Cachear o resultado é altamente recomendado para textos repetitivos — gerar o mesmo texto
|
|
62
|
+
/// duas vezes é desperdício de custo e latência.
|
|
63
|
+
/// </summary>
|
|
64
|
+
public async Task<BinaryData> SynthesizeAsync(
|
|
65
|
+
string text,
|
|
66
|
+
GeneratedSpeechVoice? voice = null,
|
|
67
|
+
GeneratedSpeechFormat? format = null,
|
|
68
|
+
float speedRatio = 1.0f,
|
|
69
|
+
CancellationToken ct = default)
|
|
70
|
+
{
|
|
71
|
+
var resolvedVoice = voice ?? GeneratedSpeechVoice.Alloy;
|
|
72
|
+
var resolvedFormat = format ?? GeneratedSpeechFormat.Mp3;
|
|
73
|
+
|
|
74
|
+
var options = new SpeechGenerationOptions
|
|
75
|
+
{
|
|
76
|
+
ResponseFormat = resolvedFormat,
|
|
77
|
+
SpeedRatio = speedRatio
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
BinaryData speech = await _client.GenerateSpeechAsync(text, resolvedVoice, options, ct);
|
|
81
|
+
return speech;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**Registro DI:**
|
|
87
|
+
|
|
88
|
+
```csharp
|
|
89
|
+
// Program.cs
|
|
90
|
+
builder.Services.AddSingleton<TextToSpeechService>();
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**Servindo como download ou stream:**
|
|
94
|
+
|
|
95
|
+
```csharp
|
|
96
|
+
public class AudioController(TextToSpeechService tts) : ControllerBase
|
|
97
|
+
{
|
|
98
|
+
[HttpPost("synthesize")]
|
|
99
|
+
public async Task<IActionResult> Synthesize([FromBody] SynthesizeRequest req)
|
|
100
|
+
{
|
|
101
|
+
// Verificar cache antes de gerar (ver Anti-patterns)
|
|
102
|
+
BinaryData audio = await tts.SynthesizeAsync(
|
|
103
|
+
text: req.Text,
|
|
104
|
+
voice: GeneratedSpeechVoice.Nova,
|
|
105
|
+
format: GeneratedSpeechFormat.Mp3,
|
|
106
|
+
speedRatio: 1.1f);
|
|
107
|
+
|
|
108
|
+
// the storage layer may assign the final name; use a timestamp-based name here
|
|
109
|
+
var fileName = $"tts-{DateTime.UtcNow:yyyyMMddHHmmss}.mp3";
|
|
110
|
+
return File(audio.ToStream(), "audio/mpeg", fileName);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## Parâmetros
|
|
118
|
+
|
|
119
|
+
> Valores verificados contra OpenAI TTS API + OpenAI .NET SDK 2.x (2026-05-19).
|
|
120
|
+
|
|
121
|
+
**Vozes disponíveis (`GeneratedSpeechVoice`):**
|
|
122
|
+
|
|
123
|
+
| Voz | Característica |
|
|
124
|
+
|-----|---------------|
|
|
125
|
+
| `Alloy` | Neutra, versátil — boa escolha padrão |
|
|
126
|
+
| `Echo` | Masculina, suave |
|
|
127
|
+
| `Fable` | Britânica, expressiva |
|
|
128
|
+
| `Onyx` | Masculina, grave |
|
|
129
|
+
| `Nova` | Feminina, amigável |
|
|
130
|
+
| `Shimmer` | Feminina, suave |
|
|
131
|
+
|
|
132
|
+
**Formatos de saída (`GeneratedSpeechFormat`):**
|
|
133
|
+
|
|
134
|
+
| Formato | Caso de uso |
|
|
135
|
+
|---------|-------------|
|
|
136
|
+
| `Mp3` | Default — compatibilidade universal |
|
|
137
|
+
| `Opus` | Streaming de baixa latência |
|
|
138
|
+
| `Aac` | Dispositivos Apple / YouTube |
|
|
139
|
+
| `Flac` | Arquivo sem perda |
|
|
140
|
+
| `Wav` | Processamento de áudio downstream |
|
|
141
|
+
| `Pcm` | Raw bytes sem container |
|
|
142
|
+
|
|
143
|
+
**`SpeedRatio`:** `0.25` (muito lento) a `4.0` (muito rápido). Padrão `1.0`.
|
|
144
|
+
|
|
145
|
+
**Modelos:**
|
|
146
|
+
- `tts-1` — rápido, custo menor, qualidade suficiente para a maioria dos casos
|
|
147
|
+
- `tts-1-hd` — maior qualidade, mais lento e mais caro — use apenas quando a clareza de voz é crítica
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## Anti-patterns
|
|
152
|
+
|
|
153
|
+
| Anti-pattern | Por quê é errado | Jeito certo |
|
|
154
|
+
|--------------|-----------------|-------------|
|
|
155
|
+
| Adicionar TTS sem caso de uso real | Custo por caractere + latência sem benefício ao usuário | Só adicione com demanda explícita; leitores de tela nativos cobrem acessibilidade básica |
|
|
156
|
+
| Gerar o mesmo texto repetidamente sem cache | Textos fixos (intro, disclaimers, respostas FAQ) custam o mesmo toda vez | Cachear bytes de áudio para textos invariantes — CDN ou Redis com key baseada em hash do texto + voz + formato |
|
|
157
|
+
| Criar `AIAgent` para TTS | `AudioClient.GenerateSpeech` não é conversacional; não há raciocínio LLM envolvido | Injete `TextToSpeechService` via DI — é um serviço de síntese, não um agente |
|
|
158
|
+
| Gerar texto longo de uma vez sem segmentar | Providers têm limite de caracteres por request (OpenAI: ~4096 tokens / ~4000 chars); textos muito longos falham | Divida em parágrafos, gere áudio por segmento, concatene os bytes |
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
## Checklist (verifiable by morph-eval)
|
|
163
|
+
|
|
164
|
+
- [ ] `AudioClient` injetado via DI — não instanciado inline
|
|
165
|
+
- [ ] Cache implementado para textos invariantes (não gera o mesmo áudio duas vezes)
|
|
166
|
+
- [ ] Textos longos segmentados antes de enviar ao provider
|
|
167
|
+
- [ ] `GeneratedSpeechVoice` e `GeneratedSpeechFormat` escolhidos adequados ao contexto (não só defaults)
|
|
168
|
+
- [ ] Model e API key vêm de config, não hardcoded
|
|
169
|
+
- [ ] Não usa `AIAgent`/`AsAIAgent` para TTS — é um `TextToSpeechService`
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## References
|
|
174
|
+
|
|
175
|
+
- `ai-agents-setup` — packages, DI, e providers disponíveis
|
|
176
|
+
- `ai-agents-providers-model-registry` — padrão de alias; adapte para resolver `AudioClient` por provider
|
|
177
|
+
- OpenAI .NET SDK — `AudioClient`: https://github.com/openai/openai-dotnet
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
*MORPH-SPEC by Polymorphism Tech — ai-agents/modalities-text-to-speech.md v1.0 (2026-05-19)*
|