interactive explainer · prompting · llms

The words are the program.

A prompt is the only code an LLM runs. This guide climbs from the plainest question to ReAct agents, testing every technique on one stubborn little problem, and shows you exactly when a change of wording turns a wrong answer right. There is a live reasoning-vote you can drag, two agent loops you scroll through, and a lab at the end.

Part I · chapters 01 to 04

Asking

01 · the problem

Confident, fluent, and wrong

Solve this in your head first. A shelf holds 20 apples. In the morning the shop sells 40% of them. In the afternoon it sells 25% of what is left. How many apples remain? Hold your answer.

Here is the same question handed to a capable model as a bare instruction, the way most people prompt on their first day. Read what comes back.

prompt → completion · zero-shot, no scaffolding
you ▸ A shelf holds 20 apples. Morning sells 40%, afternoon sells 25% of what's left. How many remain?
model ▸ The shop sells 40% + 25% = 65%, so 35% remain. 35% of 20 is 7 apples.
Figure 1The confident wrong answer. It added the percentages instead of applying the second to the remainder.

The real answer is 9. Morning removes 8 and leaves 12; afternoon removes a quarter of twelve, which is 3; nine remain. The model did not reason toward 7. It produced the most probable-looking sentence, and adding two percentages looks probable. Nothing about the output signals doubt, which is the whole danger.

picture it Imagine a street musician who has heard every song ever recorded. Hand them the first half of a melody and they will finish it, fluently, with the notes that usually come next. That is the model. It is not looking up the answer to your question; it is playing the most likely continuation of your words. When enough sentences in its training ended a certain way, that ending feels right even when your particular question needed a different tune. The apples got a confident "7" because adding two percentages is a very common riff.

This is the ground everything else stands on. The model is a next-token predictor: it reads your text and guesses the next word, then the next, each guess shaped by the mountain of writing it learned from. It has no separate place where facts live and reasoning happens. The guessing is the thinking. The prompt is your only lever on what it guesses. Every technique in this guide is a different way to pull that lever, and we will test each one on these same 20 apples so you can see exactly what each is worth.

You are not asking a mind a question. You are steering a distribution toward the answer you want.
02 · the instruction

Say exactly what you want

The cheapest upgrade costs no new technique, only precision. A zero-shot prompt gives no examples; it leans entirely on the instruction, so the instruction has to carry the load. Vague asks get vague, average completions. Hover each part of the prompt below to see what job it does.

anatomy of a good instruction
instruction parts
hover a part of the prompt
Figure 2Hover each block. A prompt is not one string; it is several jobs stacked. Naming them is the first skill.

Precision alone will not fix the apples yet, because the failure is in the reasoning, not the phrasing. But clarity removes an entire class of failure: the model answering a question you did not mean to ask. Most bad outputs are bad inputs wearing a disguise.

03 · role and system

Tell it who is speaking

Chat models read two channels. The system prompt sets standing rules, persona, and boundaries for the whole conversation; the user prompt carries the turn-by-turn request. Assigning a role in the system channel shifts the whole distribution of the reply: vocabulary, caution, format, what it assumes you know.

same question, three system prompts
Figure 3Switch the system prompt. Notice the careful-checker role starts reaching for the right method on its own, before we teach any technique.
picture it Ask a doctor and a poet to describe rain and you get two different paragraphs, though the rain is the same. The system prompt is the hat the model puts on before it speaks. "You are a careful math checker who works step by step" adds no new knowledge; it selects the version of the model that already double-checks its work, the way the hat selects the doctor's voice over the poet's.

The role is not decoration. "You are a careful math checker who works step by step" quietly imports a behavior we are about to make explicit. A good persona is a compressed instruction. A costume with no instructions inside it ("you are a world-class genius") buys nothing.

04 · format

Constrain the shape and you constrain the content

Ask for prose and you get prose-shaped thinking. Ask for a table, a JSON object, or numbered steps, and the required shape drags the reasoning with it. Forcing a field called "steps" before a field called "answer" is a back-door way to make the model reason before it commits, which is the whole idea of the next part. Click through three output contracts for the apples task.

output contracts
Figure 4Click each contract. The steps-then-answer shape is doing real work: it forbids the model from blurting the number first.
picture it A teacher who makes you show your working is not being fussy. Writing the steps is where you catch the slip before you commit to a final number. Forcing a "steps" field before an "answer" field does the same thing to the model: the shape of the answer makes it think before it lands. The container you ask for changes what gets poured into it.
Structured output has teeth beyond neatness. A JSON schema your code can parse turns a chatty model into a reliable component, and the weeds cover the two ways to enforce it: prompt-only, and constrained decoding that makes invalid tokens impossible.
Part II · chapters 05 to 07

Showing and reasoning

05 · few-shot

Show, do not tell

Instead of describing the behavior you want, demonstrate it. Few-shot prompting puts a handful of worked examples in the context before the real question. The model reads the pattern and continues it. Each example teaches something specific: the format, the tone, the edge case, the method. Hover the examples below to see what each one is actually buying.

a few-shot prompt · hover each shot
hover an example, or the final question
Figure 5Hover each shot. Two well-chosen examples that both show the remainder method fix the apples where zero-shot could not.
picture it There are two ways to teach a task: describe the rule, or show two worked examples and say "like this." Beginners and models both learn faster from the examples. The model is an eager imitator; it reads the pattern in your examples and continues it. So few-shot is really you choosing, with care, the exact thing you want the model to copy, including the trap you want it to avoid.

Few-shot is powerful and quietly expensive. Every example rides in the context on every single call, costing tokens and latency forever. It also caps out: showing the method is not the same as making the model perform the method on a genuinely new shape. For that, you stop showing answers and start demanding the work.

06 · chain of thought

Make it show its work

Four words changed prompting more than any prompt library: let's think step by step. Chain-of-thought asks the model to write its reasoning before its answer. Because each token it writes becomes context for the next, the written steps literally give it more room to compute before it commits. Scroll, and watch the scratchpad fill.

picture it Multiply 47 by 28 in your head, then do it again on paper. Same brain, but the paper wins, because every digit you write down is one you can look back at instead of hold in mind. The model lives with that same limit, only sharper: between one word and the next it remembers almost nothing except the words already on the page. So chain-of-thought is not the model performing thoughtfulness for you. The written steps are its scratch paper, its working memory, built one line at a time, and the answer is just the last line of an argument it can finally see.
the model's scratchpad
step 0 · the trigger

We append one line to the prompt: Let's think step by step. That is the entire technique. No examples, no tools.

step 1 · the start count

The model now narrates. It writes down the starting amount before doing anything to it. A number on the page is a number it will not misremember.

step 2 · the morning

It computes the morning sale and the remainder as a separate written fact: 8 sold, 12 left. This is the exact step the blurted answer skipped.

step 3 · the afternoon

Now the move that decides everything. The afternoon percentage is applied to the 12 it just wrote, not to the original 20. Twenty-five percent of twelve is three.

step 4 · the answer falls out

Twelve minus three. The answer is not guessed; it is the last line of an argument the model can see. Nine.

Figure 6Scroll-driven. The same model that blurted 7 in Figure 1 reaches 9, only because it was made to write the intermediate remainder instead of leaping to a number.

Nothing was added to the model. The reasoning was always latent; the prompt gave it room to run before committing. That is the recurring lesson: the words do not describe the computation, they are the computation.

A blurted answer is one sample. A reasoned answer is many small samples, each conditioned on the last.
07 · the knob · self-consistency

Ask the same question many times and vote

Chain-of-thought helps, but a single reasoning path can still slip. Self-consistency runs the reasoning several times at nonzero temperature, so each run wanders a little, then takes the majority answer. Wrong paths tend to fail in scattered, different ways; the right path keeps landing on the same number. The vote finds it.

This is the one control that carries the whole guide, so it is real. Every time you move the slider the page samples that many independent reasoning attempts and tallies them live. Set the reasoning quality with the chips, then drag the number of samples and watch the majority sharpen.

picture it Ask one person a hard question and they might slip. Ask twelve and go with the answer most of them give, and the slips tend to cancel while the truth stacks up. That is the whole idea. Wrong reasoning fails in scattered, different ways, so wrong answers spread themselves thin across many values. The right answer keeps arriving at the same number, so as the votes pile up it rises to the top on its own.
self-consistency · live sampling
each bar is one candidate answer · height is its share of the vote
Figure 7Live majority vote over sampled reasoning paths. With blurt-quality reasoning the vote can settle on the wrong number; with chain-of-thought, more samples make 9 win more surely. Try one sample versus forty-one.

Two lessons hide in that slider. Reasoning quality sets where the vote tends to land, and sample count sets how reliably it lands there. Self-consistency buys reliability with compute: five to forty times the cost for one answer. You spend it only where being wrong is expensive.

Sampling once asks the model what it thinks. Sampling forty times and voting asks what it usually thinks.
Part III · chapters 08 to 11

Acting and searching

08 · react

Let it think, then act, then look

All of Part II reasons inside the model's own head, which fails the moment the answer lives in the world: today's price, a database row, a fact past the training cutoff. ReAct interleaves reasoning with actions. The model writes a Thought, chooses an Action (a tool call), reads the Observation that comes back, and loops until it can answer. Scroll the loop.

picture it Two students sit the same exam. One answers everything from memory and bluffs the parts they forgot. The other is allowed to open the textbook and use a calculator, so when they hit a fact they do not hold, they stop, look it up, and come back with it in hand. Everything in Part II was the first student, confident and sometimes making things up. ReAct is the second student: think, then look, then answer, so the numbers in the conclusion are fetched from the world, not invented in the head.
agent trace · new question: "is it cheaper to buy 20 apples here or at the market?"
the setup

A question the model cannot answer from memory: it needs two live prices. Pure reasoning would hallucinate them. ReAct refuses to guess.

thought

It reasons about what it is missing and what to do about it: it needs this shop's price, and there is a tool for that.

action → observation

It emits a structured tool call. The runtime executes it and feeds the real result back in as an Observation. This line is not the model's imagination; it is data.

loop again

One price is not enough. The model thinks again, calls the market tool, and reads the second real number. Grounding accumulates.

answer, grounded

Only now, holding two observed facts, does it compute and answer. Every number in the conclusion traces to a tool result, not a guess.

Figure 8Scroll-driven, and note the pinned trace sits on the right this time. Thought, Action, Observation, repeat. The loop is the entire agent.

Strip the jargon and an agent is this loop plus tools plus a stopping rule. Frameworks dress it up, but underneath, every one of them is prompting the model to produce a Thought and an Action, running the Action themselves, and pasting the Observation back into the prompt.

09 · tool use

The action is a contract, not a hope

ReAct only works because the Action is machine-readable. Modern models are trained for tool calling: you describe each tool as a name, a description, and a typed parameter schema, and the model replies with a structured call your code can execute. Click each layer of one tool round-trip.

one tool call, end to end · click a stage
Figure 9Click each stage. The model chooses and fills the call; your code, not the model, executes it. That boundary is the whole safety story.
picture it The model can think but it cannot touch. Tools are its hands. And you do not hand it the keys to your database; it fills out a request slip ("look up the market price of apples"), you read the slip, and your code decides whether to go and fetch what it asked for. The model proposes, your code disposes. That one rule is why a tool-using agent is powerful without being a loaded gun pointed at your systems.

Retrieval is just a tool. Point the search action at your own documents and you have the backbone of retrieval-augmented generation: the model asks for what it needs, your code fetches the real passage, and the answer is grounded in your data instead of the model's memory.

10 · searching and decomposing

When one chain is not enough

Chain-of-thought walks a single path. Some problems need search. Tree-of-thought lets the model branch: generate several candidate next steps, evaluate them, keep the promising branches, prune the rest. It trades a lot of compute for the ability to back out of a dead end that a single chain would ride to a wrong answer.

one chain vs a tree · hover a node
a thought / branch kept path pruned dead end
hover a node to read the thought at it
Figure 10Hover any node. The chain (top) commits to one line. The tree (below) explores, scores, and prunes, reaching the answer the chain missed.
picture it A single chain of thought is walking one corridor of a maze and hoping it ends at the exit. A tree is what a chess player does: look a few moves ahead down several branches, notice which ones lead to trouble, and quietly abandon them before committing. Decomposition is humbler still. You would never ask one worker to build a whole car alone; you build a line where each station does one job it can do reliably. Prompt chaining is that line, one dependable prompt per station.

The humbler cousin of search is decomposition: break a hard task into ordered sub-tasks and prompt each one separately, feeding results forward. This is prompt chaining, and it is how most real systems are built. One reliable prompt per step beats one heroic prompt attempting everything, because you can test, cache, and fix each link alone.

A rough ladder of cost and power: zero-shot, then few-shot, then chain-of-thought, then self-consistency, then tool-using ReAct, then tree search. Climb only as far as the problem forces you. Every rung up costs tokens, latency, and complexity, and the lab below lets you feel that trade.
11 · limitations

The prompt is powerful, not magic

Everything here bends the model's output without changing the model. That power has hard edges, and pretending otherwise is how prompt-engineered systems break in production.

picture it The reasoning the model writes is a story about how it might have reached the answer, not a security-camera recording of how it actually did. Often the story is faithful and useful. Sometimes the steps read perfectly and the answer is still wrong, or the steps wander and the answer is right anyway. So trust a technique because it scores better on your own tests, never because its explanation sounds convincing. A convincing story is exactly what a next-token predictor is best at producing.

It is sampling, not thinking. Chain-of-thought text is a useful artifact, but it is not a faithful log of a hidden reasoning process. A model can write correct steps and a wrong answer, or the reverse. Trust the method because it raises accuracy on your evals, not because the steps look convincing.

Prompts are brittle. Reordering examples, renaming a field, or a model version bump can move results more than you expect. A prompt is code with no type system. The only defense is an evaluation set you run on every change.

Prompt injection is unsolved. The moment your prompt includes untrusted text, a web page, a user document, an email, that text can try to hijack the instructions. Tool-using agents raise the stakes, because a hijacked instruction can now act. The weeds cover the partial defenses; none are complete.

More scaffolding costs more. Self-consistency multiplies calls, ReAct adds round-trips, tree search fans out. Reliability is bought with latency and money, and past a point a smaller, cheaper technique with a good eval beats an elaborate one you cannot afford to run.

Zero-shot asks.
Chain-of-thought reasons.
ReAct goes and finds out.
Pick the smallest one that gets you to nine.

the prompt lab

Stack the techniques, read the trade

The guide moved one variable at a time. Here they compose. Build a prompt stack for a task, and watch estimated reliability climb while cost and latency climb with it. The presets rebuild the setups this guide argued about. There is no single right answer; there is a right answer for your budget.

prompt stack · illustrative model
estimated reliability on hard tasks
relative cost per answer
relative latency
Figure 11Compose a stack. Turn everything on and watch cost explode for a last few points of reliability. The quick preset is the honest default for easy tasks.
into the weeds

For the readers who scrolled this far

Seven rabbit holes the main path stepped around. Each stands alone.

Temperature, top-p, and why sampling settings matter
Temperature scales how sharply the model favors its top guesses. At 0 it is nearly deterministic and picks the single most likely token, which is why self-consistency needs temperature above 0: identical samples cannot vote. Top-p (nucleus sampling) instead keeps the smallest set of tokens whose probability sums past p and samples among them. For reasoning you want enough randomness to explore different paths, not so much that arithmetic drifts. Around 0.7 is a common starting point.
Two ways to force valid JSON
Prompt-only: you ask for JSON and hope, then validate and retry on failure. Simple, and it fails a small fraction of the time. Constrained decoding: the serving layer masks any token that would break the schema, so the output is valid by construction. Most providers now expose this as a structured-output or JSON-schema mode. Prefer it when a downstream parser must never choke.
Zero-shot CoT vs few-shot CoT
Two flavors of chain-of-thought. Zero-shot is the bare trigger, "let's think step by step," which needs no examples. Few-shot CoT instead shows the model two or three fully worked examples that include their reasoning, then asks the new question. Few-shot CoT is usually stronger because it demonstrates the reasoning style you want, but it costs the example tokens on every call. Reach for zero-shot first; it is free.
ReAct is not the only agent loop
ReAct interleaves reasoning and acting in one stream. Alternatives split them: Plan-and-Execute writes a full plan first, then executes each step, which is cheaper and more predictable but less able to adapt mid-task. Reflexion adds a self-critique pass that feeds failures back as memory for the next attempt. All three are prompt patterns over the same tool-calling primitive.
Prompt injection, and the partial defenses
When untrusted text enters the prompt it can carry instructions that hijack yours. No defense is complete. The practical stack: keep system instructions above and separate from untrusted content, mark untrusted spans clearly, give tools the least privilege they need, require human confirmation before any irreversible action, and run adversarial evals. Treat an agent with powerful tools and untrusted input as a security boundary, not a feature.
RAG vs a very long context window
Two ways to get external knowledge into an answer. Retrieval fetches only the relevant passages and injects them, keeping prompts small and cheap and letting the corpus be huge. Long context pastes everything in and lets the model sort it out, which is simpler but costs tokens on every call and can bury the key fact in the middle, where models attend least. Most production systems retrieve; long context is the convenient default for small, static references.
Why the numbers in this page are illustrative
The self-consistency vote in Figure 7 is real: the page samples reasoning paths with genuine randomness and tallies them, so the majority genuinely sharpens as you add samples. The reasoning traces and the lab's reliability estimates are scripted from the documented behavior of these techniques, not run against a live model, because a single self-contained file cannot host one. They are honest about the mechanism and the direction of every trade; they are not a benchmark. Treat them as a teaching instrument, and trust your own evals for real numbers.