Inteligência Artificial

Prompt Engineering para Código — Templates e Padrões

Como escrever prompts que geram código de alta qualidade. Técnicas avançadas de prompt engineering específicas para desenvolvimento de software com LLMs.

1 min

Prompt engineering para código tem regras diferentes de prompt engineering para texto. O contexto importa mais, os exemplos precisam ser mais concretos e a estrutura define se o código funciona ou não.


Os 7 princípios

1. Especifique o stack explicitamente

❌ "Crie uma API de usuários"
✅ "Crie uma API REST de usuários com Express.js, TypeScript strict,
   Prisma ORM, PostgreSQL. Endpoints: GET /users, POST /users,
   GET /users/:id, PUT /users/:id, DELETE /users/:id."

2. Liste as validações como regras

❌ "Valide os dados de entrada"
✅ "Validações obrigatórias:
   - email: formato válido, único no banco
   - password: mínimo 8 chars, 1 maiúscula, 1 número
   - name: não vazio, máximo 100 caracteres
   - age: inteiro entre 0 e 150"

3. Defina o formato de saída

❌ "Retorne os dados do usuário"
✅ "Retorne JSON no formato:
   { id: string, email: string, name: string, createdAt: ISO8601 }
   Nunca exponha passwordHash, __v ou _id no response."

4. Inclua exemplos de input/output

❌ "Processe o arquivo CSV"
✅ "Processe arquivos CSV com este formato:
   Input: name,email,age
   João,[email protected],30

   Output esperado:
   { name: "João", email: "[email protected]", age: 30 }

   Trate: campos vazios (null), emails inválidos (skip),
   age não-numérico (0)."

5. Especifique o que NÃO fazer

❌ (nada)
✅ "NÃO use any tipo 'any'.
   NÃO use console.log em produção.
   NÃO ignore erros de async/await.
   NÃO crie funções com mais de 30 linhas.
   NÃO use var — apenas const/let."

6. Peça testes antes da implementação

❌ "Implemente e teste"
✅ "PRIMEIRO: escreva testes Vitest para todos os cenários.
   DEPOIS: implemente até todos os testes passarem.
   NÃO modifique os testes após escritos."

7. Use referências a arquivos existentes

❌ "Siga o padrão do projeto"
✅ "Siga o padrão de src/api/users.ts para criar o endpoint.
   Use o mesmo middleware de auth de src/middleware/auth.ts.
   Use o mesmo schema pattern de src/models/user.ts."

Templates de prompt por tipo de tarefa

Implementar novo endpoint

Implement [ENDPOINT] as described in specs/[SPEC].md.

Context:
- Stack: [TECH STACK]
- Database: [DB + ORM]
- Auth: [AUTH METHOD]

Requirements:
- [VALIDATION RULE 1]
- [VALIDATION RULE 2]
- [ERROR HANDLING]

Process:
1. Read the spec file
2. Write Vitest tests covering: happy path, validation errors, auth errors, edge cases
3. Implement the endpoint
4. Run tests: pnpm vitest run [test-file]
5. If any test fails, fix until all pass
6. Run pnpm lint:fix
7. Commit with conventional message

Output: the implemented file + test file.

Refatorar código existente

Refactor [FILE/FUNCTION] to [GOAL].

Current code: @file src/path/to/file.ts

Constraints:
- Behavior must NOT change (existing tests must pass)
- Do not change function signatures
- Do not remove or weaken existing tests
- Add new tests for any new code paths

Process:
1. Read the current code and all tests
2. Write additional tests for edge cases you find
3. Refactor incrementally, running tests after each change
4. Run: pnpm vitest run && pnpm lint:fix
5. Commit with message: refactor([scope]): [description]

Debug de erro

Debug this error:

[PASTE ERROR + STACK TRACE]

Context:
- Stack: [TECH STACK]
- The error happens when [TRIGGER]

Process:
1. Read the file(s) mentioned in the stack trace
2. Identify the root cause
3. Explain the root cause before fixing
4. Fix the bug
5. Write a test that reproduces the bug
6. Run tests to verify the fix
7. Commit with message: fix([scope]): [description]

Gerar testes

Generate comprehensive Vitest tests for @file src/path/to/module.ts.

Requirements:
- Cover all exported functions
- Cover happy path, error cases, edge cases
- Use descriptive test names in Portuguese
- Use vi.fn() for mocking dependencies
- Do NOT test implementation details — test behavior

Output: src/__tests__/module.test.ts

Anti-patterns de prompt

Anti-promptProblemaCorreção
"Faça isso funcionar"Sem contextoInclua erro + stack trace + arquivo
"Melhore este código"SubjetivoEspecifique: performance? legibilidade? segurança?
"Adicione feature X"VagoListe endpoints, validações, testes esperados
"Corrija todos os bugs"Impossível em um promptUm bug por prompt, com reprodução
"Reescreva tudo"DestrutivoRefatore incrementalmente, um módulo por vez
"Use a melhor prática"SubjetivoListe as práticas específicas que você quer

Padronização de prompts no projeto

Crie um prompts/ directory com templates reutilizáveis:

prompts/
├── implement-endpoint.md    # Template para novo endpoint
├── refactor.md              # Template para refatoração
├── debug.md                 # Template para debug
├── generate-tests.md        # Template para gerar testes
├── review-pr.md             # Template para review de PR
└── migrate.md               # Template para migração

CLAUDE.md referenciando prompts

## Prompts
For new endpoints, use: @prompts/implement-endpoint.md
For refactoring, use: @prompts/refactor.md
For debugging, use: @prompts/debug.md
For test generation, use: @prompts/generate-tests.md

On this page