← Back to Cooldecode
AI Watch · Prompt engineering in practice

Structure beats cleverness: prompting Claude in 2026

Two earlier AI Watch lessons covered prompt engineering basics and context engineering. This one zooms into the single most concrete, provable technique for getting better output from Claude specifically: structuring a prompt with XML tags — plus a second technique, self-consistency, for when one answer isn't enough to trust.

1. The core shift: style vs structure

Some models respond well to creative or conversational phrasing — clever framing, unusual analogies, persona tricks. Claude's own prompt engineering documentation makes a different point: what actually moves output quality is structure, not style. Being unambiguous about what's an instruction, what's context, and what's the actual task matters more than how cleverly any of it is worded.

That's a practical distinction, not a philosophical one. A prompt that mixes background information, examples, and the actual request into one paragraph forces the model to infer which sentence is which. A prompt that separates those pieces explicitly removes that inference step entirely.

2. Why XML tags specifically

XML tags — <role>, <context>, <instructions>, <examples>, <output_format> — give each part of a prompt an explicit, unambiguous label. Claude's documentation recommends this specifically for prompts that mix multiple types of content: background info, instructions, examples, and the variable input for the current request.

The tag names themselves aren't magic — there's no fixed vocabulary Claude requires. What matters is consistency: reuse the same tag name for the same kind of content across a prompt (and across a project, if you're building anything repeatable), and nest tags when the content has a natural hierarchy — multiple documents each inside their own <document index="n">, for example.

The mental model: XML tags do for a prompt what clear function signatures do for code. You could write a function that takes one big untyped blob and parses it internally — but naming and separating the arguments up front removes an entire category of misinterpretation before it can happen.

3. Before / after: an unstructured prompt vs a tagged one

Before — everything blended into one paragraph, forcing the model to guess which part is instruction and which is data:

Here's info about an athlete: height 6'2", weight 180 lbs,
goal is to build muscle, and they're vegetarian. Can you write
a meal plan for them, keep it realistic, and don't use meat obviously.

After — the same request, with content separated by what role it plays:

<athlete_information>
- Height: 6'2"
- Weight: 180 lbs
- Goal: Build muscle
- Dietary restrictions: Vegetarian
</athlete_information>

<task>
Generate a realistic one-week meal plan based on the athlete
information above.
</task>

Nothing about the underlying request changed. What changed is that the model no longer has to parse which words are data about the athlete versus which words are the instruction — that ambiguity is removed at the structure level, before generation even starts.

4. Where each tag goes, and why order matters

For longer, multi-part prompts, Claude's documentation suggests a rough ordering: <role> and <context> first, then <task>, then <instructions> and <output_format>. Claude reads the entire prompt before generating a response, so this isn't about "priming" the model the way position sometimes matters in older, more limited-context systems — it's about giving a human (or another agent debugging the prompt later) a predictable place to find each kind of content, and reducing the chance that a long block of context gets misread as part of the task itself.

5. A second technique: self-consistency for reasoning tasks

Structure fixes ambiguity in the prompt. It doesn't fix the model occasionally taking a wrong reasoning path on a genuinely hard multi-step problem. Self-consistency is the technique for that case: instead of asking once and taking the first answer, generate several independent reasoning attempts at the same problem (different sampling runs), then take the answer that shows up most often across them — a majority vote.

A simple illustration: if three independent attempts at a math problem produce 11, 11, and 10, the self-consistent answer is 11 — even though one of the three reasoning paths was internally flawed, the correct answer was still the majority outcome. This is specifically useful for arithmetic, logic, and multi-step reasoning tasks, where a single pass of chain-of-thought can occasionally follow a plausible-looking but wrong step.

Trade-off: self-consistency costs more — you're running the same prompt multiple times and comparing results, instead of once. It's worth reaching for on a genuinely important, hard reasoning task, not as a default for every request.

6. When structure is overkill

None of this is a rule to apply universally. For a short, simple, single-part question, plain text works fine — wrapping "what's the capital of Portugal" in <task> tags adds nothing. XML structuring earns its keep specifically when a prompt has multiple distinct sections (background context, several examples, formatting constraints) that could otherwise blur into each other. The test is simple: if you'd have trouble telling a colleague, out loud, which sentence in your prompt is an instruction versus which is data, that's the signal to add structure.

Newsletter

Learn what AI is creating for you. Don't get lost.

Get notified when a new deep dive or lesson goes up. No spam, just new posts.

IA Watch · Prompt engineering na prática

Estrutura vence criatividade: como fazer prompt pro Claude em 2026

Duas lições anteriores de IA Watch cobriram o básico de prompt engineering e context engineering. Esta foca na técnica mais concreta e comprovável pra melhorar a saída do Claude especificamente: estruturar um prompt com tags XML — mais uma segunda técnica, self-consistency, pra quando uma resposta só não é confiável o bastante.

1. A virada central: estilo vs estrutura

Alguns modelos respondem bem a frases criativas ou conversacionais — enquadramentos espertos, analogias incomuns, truques de persona. A própria documentação de prompt engineering do Claude aponta pra algo diferente: o que realmente move a qualidade da saída é estrutura, não estilo. Ser inequívoco sobre o que é instrução, o que é contexto e o que é a tarefa em si importa mais do que quão esperto qualquer trecho está redigido.

É uma distinção prática, não filosófica. Um prompt que mistura informação de fundo, exemplos e o pedido em si num parágrafo só força o modelo a inferir qual frase é qual coisa. Um prompt que separa essas partes explicitamente remove essa etapa de inferência por completo.

2. Por que tags XML especificamente

Tags XML — <role>, <context>, <instructions>, <examples>, <output_format> — dão a cada parte de um prompt um rótulo explícito e inequívoco. A documentação do Claude recomenda isso especificamente pra prompts que misturam vários tipos de conteúdo: informação de fundo, instruções, exemplos e a entrada variável do pedido atual.

Os nomes das tags em si não têm mágica — não existe um vocabulário fixo que o Claude exija. O que importa é consistência: reuse o mesmo nome de tag pro mesmo tipo de conteúdo dentro de um prompt (e entre projetos, se você está construindo algo repetível), e aninhe tags quando o conteúdo tiver uma hierarquia natural — vários documentos, cada um dentro do próprio <document index="n">, por exemplo.

O modelo mental: tags XML fazem pra um prompt o que assinaturas de função claras fazem pra código. Você poderia escrever uma função que recebe um blob gigante sem tipo e parseia tudo internamente — mas nomear e separar os argumentos de antemão remove uma categoria inteira de má interpretação antes mesmo que ela aconteça.

3. Antes / depois: um prompt sem estrutura vs um com tags

Antes — tudo misturado num parágrafo só, forçando o modelo a adivinhar qual parte é instrução e qual é dado:

Aqui vai informação sobre um atleta: 1,88m de altura, 82kg,
o objetivo é ganhar massa muscular, e é vegetariano. Você
consegue escrever um plano alimentar pra ele, mantendo realista,
e claro, sem usar carne?

Depois — o mesmo pedido, com o conteúdo separado pelo papel que ele exerce:

<informacoes_do_atleta>
- Altura: 1,88m
- Peso: 82kg
- Objetivo: Ganhar massa muscular
- Restrição alimentar: Vegetariano
</informacoes_do_atleta>

<tarefa>
Gere um plano alimentar realista de uma semana com base nas
informações do atleta acima.
</tarefa>

Nada no pedido em si mudou. O que mudou é que o modelo não precisa mais interpretar quais palavras são dados sobre o atleta e quais são a instrução — essa ambiguidade é removida no nível da estrutura, antes mesmo da geração começar.

4. Onde cada tag entra, e por que a ordem importa

Pra prompts mais longos e com várias partes, a documentação do Claude sugere uma ordem aproximada: <role> e <context> primeiro, depois <task>, depois <instructions> e <output_format>. O Claude lê o prompt inteiro antes de gerar uma resposta, então isso não é sobre "preparar" o modelo do jeito que a posição às vezes importava em sistemas mais antigos e com contexto mais limitado — é sobre dar a um humano (ou a outro agente depurando o prompt depois) um lugar previsível pra encontrar cada tipo de conteúdo, e reduzir a chance de um bloco longo de contexto ser lido erroneamente como parte da própria tarefa.

5. Uma segunda técnica: self-consistency pra raciocínio

Estrutura resolve a ambiguidade do prompt. Não resolve o modelo ocasionalmente seguir um caminho de raciocínio errado num problema genuinamente difícil de várias etapas. Self-consistency é a técnica pra esse caso: em vez de perguntar uma vez e aceitar a primeira resposta, gere várias tentativas de raciocínio independentes pro mesmo problema (execuções de amostragem diferentes), e aceite a resposta que aparece com mais frequência entre elas — um voto majoritário.

Uma ilustração simples: se três tentativas independentes num problema de matemática produzem 11, 11 e 10, a resposta self-consistent é 11 — mesmo que um dos três caminhos de raciocínio estivesse internamente falho, a resposta correta ainda foi o resultado majoritário. Isso é especificamente útil pra tarefas de aritmética, lógica e raciocínio de várias etapas, onde uma única passada de chain-of-thought pode ocasionalmente seguir um passo que parece plausível mas está errado.

Trade-off: self-consistency custa mais — você está rodando o mesmo prompt várias vezes e comparando resultados, em vez de uma vez só. Vale a pena usar numa tarefa de raciocínio genuinamente importante e difícil, não como padrão pra todo pedido.

6. Quando estrutura é exagero

Nada disso é uma regra pra aplicar universalmente. Pra uma pergunta curta, simples e de uma parte só, texto puro funciona bem — envolver "qual é a capital de Portugal" em tags <tarefa> não adiciona nada. A estruturação com XML se justifica especificamente quando um prompt tem várias seções distintas (contexto de fundo, vários exemplos, restrições de formatação) que de outra forma poderiam se misturar. O teste é simples: se você teria dificuldade de dizer a um colega, em voz alta, qual frase do seu prompt é instrução e qual é dado, esse é o sinal pra adicionar estrutura.

Newsletter

Saiba o que a IA está criando pra você. Não fique por fora.

Seja avisado quando eu postar uma imersão ou lição nova. Sem spam, só posts novos.