AI Watch · Prompt engineering
Show, don't tell: examples, prefill and output contracts
When the problem is "the answer is right but the format keeps changing," more adjectives won't help. Three tools do: an example, a started answer, and a written-down contract for the output. Here is how each works, where each breaks, and how to choose.
1. Why description fails and demonstration works
Try describing a tone in words: "concise but friendly, technical without jargon, slightly dry." Ten people would write ten different things from that. Now show one sample sentence and everyone converges. Models behave the same way. Anthropic's prompt engineering guide says it directly: examples "show rather than tell, clarifying subtle requirements that are difficult to express through description alone."
The guide lists four situations where examples earn their tokens: the desired format is easier to show than describe; you need a specific tone or style; the task involves subtle patterns or conventions; and simple instructions haven't produced consistent results. If none of these applies, you probably don't need an example — and the guide is explicit that examples are "not always necessary."
2. Examples: one-shot first, few-shot only if needed
One example is called one-shot; several are few-shot. Anthropic's advice is to start with one and add more only if the output still doesn't match. Every example costs tokens on every call, so more is not free.
A minimal pattern — an example, then the real input in the same shape:
Summarize each article in the style below.
Article: [EU passes AI Act ...]
Summary: EU passes comprehensive AI Act targeting high-risk systems.
Key provisions include transparency requirements and human oversight
mandates. Takes effect 2026.
Now summarize this article in the same style:
Article: [your new article]
Notice what the example fixes without a single rule: length (three short sentences), voice (neutral), content order (what happened, key provisions, when). Writing those as rules would take a paragraph and still leave gaps.
3. The trap: modern models copy your examples closely
The same guide adds an important warning: Claude 4.x-and-later models "pay very close attention to details in examples," so your examples should match the behavior you want and avoid patterns you don't. In practice, this means everything in the example is treated as signal:
- Accidental length. If your example summary is 28 words, expect 28-ish words.
- Accidental topic. If the example is about politics, outputs drift toward that framing; vary the subjects if you use several examples.
- Accidental quirks. A trailing "Hope this helps!" in the example will show up in every output.
- Over-fitting. If all your examples have three bullets, the model will force three bullets even when there are two real points.
Rule of thumb: read your example as if it were a spec. Anything you wouldn't be happy to see copied into every output doesn't belong in it.
4. Prefill: start the answer for the model
Prefilling means writing the first characters of the model's reply yourself, so it continues from there. It is the most direct way to enforce an output format or skip chatty preambles ("Sure! Here's the JSON you asked for:"). Anthropic's guide shows the API pattern: the last message has role assistant and content {, so the model can only continue a JSON object.
messages = [
{"role": "user",
"content": "Extract the name and price from this product description into JSON."},
{"role": "assistant", "content": "{"} # the prefill
]
Where it helps: structured output (JSON/XML), removing preambles, holding a persona or voice, and controlling how the answer begins. In a chat app you can't prefill, but the guide notes you can approximate it: "Output only valid JSON with no preamble. Begin your response with an opening brace."
Check your model: the guide I used is dated Nov 10, 2025. Support for prefilled assistant turns can differ between model generations and APIs, and I did not verify it for the current models — confirm in the docs for the model you actually call. If prefill isn't available, the explicit-instruction version and the output contract below are the fallback.
5. The output contract
A looser but very effective idea from the practitioner guides: write the output as a contract — format, length, tone and required sections — stated so it can be tested. "Be concise" can't be tested. "Max 80 words, no bullet points, end with one next step" can. A testable contract has two payoffs: the model has an unambiguous target, and you can write a tiny script that checks outputs automatically.
| Vague | Testable contract |
| "Keep it short" | "At most 80 words" |
| "Return structured data" | "Return only JSON with keys revenue, profit_margin, growth_rate" |
| "Don't make things up" | "If a value isn't stated in the report, use null" |
| "Professional tone" | "Second person, no exclamation marks, no emojis" |
Note the last-but-one row: it's the permission-to-abstain trick from the previous AI Watch lesson on hallucinations, expressed as part of the format. The guide itself recommends it ("use null rather than guessing").
Also, phrase the contract positively. The guide's example: instead of "Do not use markdown," say "Your response should be composed of smoothly flowing prose paragraphs." It also notes that your prompt's own style leaks into the output — a prompt full of bullets and bold tends to get bullets and bold back.
6. All three together (before/after)
Before:
Get the key numbers from this quarterly report as JSON.
Typical failure: a friendly sentence before the JSON, "$4.2M" in one run and "4200000" in another, and an invented growth rate when the report doesn't give one.
After: the structure below, adapted from the guide's own "putting it all together" example.
Extract key financial metrics from this quarterly report as JSON.
This feeds an automated pipeline, so respond with ONLY valid JSON,
no preamble or explanation.
Use this structure:
{
"revenue": "value with units",
"profit_margin": "percentage",
"growth_rate": "percentage"
}
If a metric is not clearly stated in the report, use null
rather than guessing.
Begin your response with an opening brace: {
It combines explicit instructions, the reason the format matters, an example structure, permission to be uncertain, and format control at the start of the reply. Each line removes one specific failure.
7. How to choose
| Symptom | Reach for | Cost |
| Format or tone keeps varying | One example, then few-shot | Tokens on every call; risk of copied quirks |
| Preamble before the data, or broken JSON | Prefill (if supported) or explicit "begin with {" | Model/API-dependent |
| Output "kind of right" but can't be checked | Testable output contract | Almost none |
| Task itself is too complex | None of these — split it (prompt chaining) | Extra calls and latency |
Takeaway: start with a clear contract, add one carefully chosen example if the format still drifts, and use prefill only for the specific problem it solves. Anthropic's own closing advice applies: the best prompt isn't the longest, it's the one that reliably gets the result with the minimum structure — and you only know that by testing each addition.
Sources
Note: no Anthropic/Claude announcement dated Oct 9, 2026 was found, so the category rotation (Prompt engineering) was applied. The Anthropic article was read in full; the two PromptBuilder pages were seen only through search-result summaries, and the claim about prefill support on current models is flagged above as unverified.
IA Watch · Prompt engineering
Mostre, não descreva: exemplos, prefill e contratos de saída
Quando o problema é "a resposta está certa, mas o formato muda toda hora", mais adjetivos não ajudam. Três ferramentas ajudam: um exemplo, uma resposta já iniciada e um contrato escrito para a saída. Veja como cada uma funciona, onde quebra e como escolher.
1. Por que descrever falha e demonstrar funciona
Tente descrever um tom em palavras: "conciso mas simpático, técnico sem jargão, levemente seco". Dez pessoas escreveriam dez coisas diferentes. Agora mostre uma frase de amostra e todo mundo converge. Os modelos se comportam do mesmo jeito. O guia de prompt engineering da Anthropic diz isso diretamente: exemplos "mostram em vez de contar, esclarecendo requisitos sutis difíceis de expressar só por descrição".
O guia lista quatro situações em que exemplos valem os tokens: o formato desejado é mais fácil de mostrar que de descrever; você precisa de um tom ou estilo específico; a tarefa envolve padrões ou convenções sutis; e instruções simples não geraram consistência. Se nada disso se aplica, provavelmente você não precisa de exemplo — e o guia deixa claro que exemplos "nem sempre são necessários".
2. Exemplos: um primeiro, vários só se precisar
Um exemplo é one-shot; vários são few-shot. A recomendação da Anthropic é começar com um e adicionar mais só se a saída ainda não bater. Cada exemplo custa tokens em toda chamada, então mais não é de graça.
Um padrão mínimo — um exemplo e depois a entrada real no mesmo formato:
Resuma cada artigo no estilo abaixo.
Artigo: [UE aprova AI Act ...]
Resumo: UE aprova AI Act abrangente voltado a sistemas de alto risco.
Principais pontos: requisitos de transparência e supervisão humana.
Entra em vigor em 2026.
Agora resuma este artigo no mesmo estilo:
Artigo: [seu novo artigo]
Note o que o exemplo fixa sem uma única regra: tamanho (três frases curtas), voz (neutra), ordem do conteúdo (o que aconteceu, pontos principais, quando). Escrever isso como regras levaria um parágrafo e ainda deixaria lacunas.
3. A armadilha: modelos modernos copiam seus exemplos de perto
O mesmo guia traz um aviso importante: modelos da geração Claude 4.x em diante "prestam muita atenção aos detalhes nos exemplos", então seus exemplos devem refletir o comportamento que você quer e evitar os padrões que não quer. Na prática, tudo no exemplo vira sinal:
- Tamanho acidental. Se o resumo do exemplo tem 28 palavras, espere algo perto de 28.
- Tema acidental. Se o exemplo é sobre política, as saídas tendem a esse enquadramento; varie os assuntos se usar vários exemplos.
- Cacoetes acidentais. Um "Espero ter ajudado!" no fim do exemplo vai aparecer em toda saída.
- Overfitting. Se todos os exemplos têm três tópicos, o modelo vai forçar três tópicos mesmo havendo só dois pontos reais.
Regra prática: leia seu exemplo como se fosse uma especificação. Tudo que você não gostaria de ver copiado em toda saída não deve estar nele.
4. Prefill: começar a resposta pelo modelo
Prefill é escrever você mesmo os primeiros caracteres da resposta, para o modelo continuar dali. É a forma mais direta de forçar um formato ou cortar preâmbulos ("Claro! Aqui está o JSON que você pediu:"). O guia da Anthropic mostra o padrão na API: a última mensagem tem role assistant e conteúdo {, então o modelo só consegue continuar um objeto JSON.
messages = [
{"role": "user",
"content": "Extraia nome e preço desta descrição de produto em JSON."},
{"role": "assistant", "content": "{"} # o prefill
]
Onde ajuda: saída estruturada (JSON/XML), remover preâmbulos, manter uma persona ou voz e controlar como a resposta começa. Em apps de chat você não consegue fazer prefill, mas o guia observa que dá para aproximar: "Responda apenas com JSON válido, sem preâmbulo. Comece a resposta com uma chave de abertura."
Confira seu modelo: o guia que usei é de 10/11/2025. O suporte a turnos do assistente pré-preenchidos pode variar entre gerações de modelo e APIs, e eu não verifiquei isso para os modelos atuais — confirme na documentação do modelo que você realmente chama. Se o prefill não estiver disponível, a versão com instrução explícita e o contrato de saída abaixo são o plano B.
5. O contrato de saída
Uma ideia mais solta, mas muito eficaz, dos guias de profissionais: escreva a saída como um contrato — formato, tamanho, tom e seções obrigatórias — enunciado de modo que possa ser testado. "Seja conciso" não é testável. "No máximo 80 palavras, sem bullets, terminando com um próximo passo" é. Um contrato testável tem dois ganhos: o modelo recebe um alvo sem ambiguidade e você pode escrever um script pequeno que confere as saídas automaticamente.
| Vago | Contrato testável |
| "Seja breve" | "No máximo 80 palavras" |
| "Devolva dados estruturados" | "Devolva apenas JSON com as chaves revenue, profit_margin, growth_rate" |
| "Não invente" | "Se um valor não estiver no relatório, use null" |
| "Tom profissional" | "Segunda pessoa, sem exclamações, sem emojis" |
Repare na penúltima linha: é o truque de permissão para se abster da lição anterior de IA Watch sobre alucinações, expresso como parte do formato. O próprio guia recomenda ("use null em vez de chutar").
Além disso, formule o contrato de forma positiva. O exemplo do guia: em vez de "Não use markdown", diga "Sua resposta deve ser composta de parágrafos de prosa fluida". Ele também observa que o estilo do seu prompt vaza para a saída — um prompt cheio de bullets e negrito tende a receber bullets e negrito de volta.
6. Os três juntos (antes/depois)
Antes:
Pegue os números principais deste relatório trimestral em JSON.
Falha típica: uma frase simpática antes do JSON, "US$ 4,2 mi" numa execução e "4200000" em outra, e uma taxa de crescimento inventada quando o relatório não traz.
Depois: a estrutura abaixo, adaptada do exemplo "putting it all together" do próprio guia.
Extraia as principais métricas financeiras deste relatório
trimestral em JSON. Isso alimenta um pipeline automático, então
responda SOMENTE com JSON válido, sem preâmbulo nem explicação.
Use esta estrutura:
{
"revenue": "valor com unidade",
"profit_margin": "percentual",
"growth_rate": "percentual"
}
Se uma métrica não estiver claramente no relatório, use null
em vez de chutar.
Comece a resposta com uma chave de abertura: {
Ele combina instruções explícitas, o motivo de o formato importar, uma estrutura de exemplo, permissão para a incerteza e controle de formato no começo da resposta. Cada linha elimina uma falha específica.
7. Como escolher
| Sintoma | Use | Custo |
| Formato ou tom variam sempre | Um exemplo e, depois, few-shot | Tokens em toda chamada; risco de copiar cacoetes |
| Preâmbulo antes dos dados, ou JSON quebrado | Prefill (se houver suporte) ou "comece com {" explícito | Depende do modelo/API |
| Saída "mais ou menos certa" e impossível de conferir | Contrato de saída testável | Quase nenhum |
| A própria tarefa é complexa demais | Nenhuma delas — divida a tarefa (prompt chaining) | Chamadas extras e latência |
Conclusão: comece com um contrato claro, adicione um exemplo bem escolhido se o formato ainda oscilar e use prefill só para o problema específico que ele resolve. O conselho final da própria Anthropic vale aqui: o melhor prompt não é o mais longo, é o que atinge o resultado de forma confiável com o mínimo de estrutura — e só se descobre isso testando cada acréscimo.
Fontes
Nota: não foi encontrado anúncio da Anthropic/Claude datado de 09/10/2026, então foi aplicada a rotação de categorias (Prompt engineering). O artigo da Anthropic foi lido por inteiro; as duas páginas da PromptBuilder foram vistas só pelos resumos da busca, e a afirmação sobre suporte a prefill nos modelos atuais está marcada acima como não verificada.