Skip to content

Planning and Reasoning in Agents

9 min read
constructed example · reasoning before an answer
prompt
a farmer has 17 sheep, all but 9 run away. how many are left?
no thinking budget
think: 0 words · answer: 4 words
answer8 sheep are left.← wrong
this answer subtracts 9 from 17
with thinking budget
think: 31 words · answer: 4 words
think"all but 9 run away" means 9 do NOT run.
thinkso 9 stay, not 17 − 9 = 8.
check8 is the number that leave; the question asks how many remain.
answer9 sheep are left.← correct
thinking may be hidden or summarized

These are two written examples. The second checks which sheep the phrase “all but 9” refers to before returning an answer.

Before an agent commits to a tool call, it can spend output tokens checking assumptions or comparing possible actions. That takes additional inference-time compute. The useful question is whether the extra work improves the next decision enough to justify its cost.

We will compare generating intermediate work, allocating a reasoning-token budget, and explicitly searching multiple candidate paths.


Reasoning before committing

Language models generate text one token at a time, left to right. Once a token is committed, it's in the context, and every later token is conditioned on it. An early mistake can therefore influence the rest of the response.

The sheep problem in the hero is a miniature version of this. The phrase “all but 9” specifies how many remain; subtracting 9 from 17 answers a different question. An answer beginning with “8” needs a later correction to give the right result.

One approach is to generate intermediate work before the final answer or action. These tokens extend the context, so later generation can build on or correct them. A single reasoning trace is still sequential decoding; it is not proof that the model searches a literal tree internally.


The minimal math: a compute-accuracy curve

Fix a model and an evaluation set, then vary the reasoning budget. Accuracy may improve, plateau, or fall as the budget changes. Record the stopping policy and token usage alongside each score.

Constructed accuracy curves · assumed reasoning budgets

0%25%50%75%100%0641k16kBudget (log₄(1 + tokens))

Curve A: 96.0%

Curve B: 64.0%

Curve C: 21.5%

Invented sigmoid curves, not measured task categories. They saturate by construction. A real budget decision requires a task evaluation and measured latency or cost.

Three assumed budget-response curves, shown to illustrate diminishing returns. Their levels and thresholds do not describe measured models or task categories.

Additional reasoning can also introduce errors. A model may revise a correct intermediate answer into a wrong one. Measure that behavior on your workload instead of treating the maximum budget as the best setting.


What extended thinking actually is at runtime

Zero-shot chain-of-thought prompting, studied in 2022, used an instruction such as “let’s think step by step” to encourage intermediate work before the answer. That differs from the few-shot worked examples in the original Chain-of-Thought paper.

Reasoning models add training aimed at using inference-time compute effectively. DeepSeek-R1 documents one such training approach. Provider APIs expose different controls: Claude Sonnet 4.5 manual thinking uses budget_tokens, while OpenAI Responses uses qualitative reasoning.effort. Gemini thought signatures carry reasoning state across requests; they are not a training method or a budget setting.

Reasoning support also affects the transcript and token budget:

  • The thinking block is separate from the final response in the transcript format. Users typically don't see it. Providers sometimes redact, summarize, or compress it on the way back to the client.
  • Thinking tokens are real tokens that go through the normal decoding loop, cost money, and fill the KV cache. Cost accumulates across the turns that generate them.
  • When the agent calls a tool, the thinking block frequently appears between the prompt and the tool_use output. The model is thinking about which tool to call, not just about what to say.
  • Thought signatures preserve the thinking across turns in some providers, so the model can refer back to its own reasoning on a later call without re-deriving it.

Worked example

Consider a puzzle with an explicitly checkable state after each action:

You have a 3-liter jug and a 5-liter jug. Measure exactly 4 liters.

A candidate answer can sound plausible while skipping a necessary pour. Check each state explicitly: fill the 5-liter jug, pour into the 3-liter jug, empty the 3-liter jug, transfer the remaining 2 liters into it, refill the 5-liter jug, then pour 1 liter to fill the 3-liter jug. Four liters remain in the 5-liter jug.

tree of thoughts · game of 24 · target = 24
nums: 4 6 8 94 + 6 → 10score 0.359 − 8 → 1score 0.808 × 9 → 72score 0.251 × 4 → 4score 0.306 / 1 → 6score 0.404 × 6 × 1 = 24score 0.98
step 6/7pick the winning leaf

Tree of Thoughts expands a handful of candidates at each step, asks the same model to score each one, and keeps only the best. Scores here are invented. The winning branch uses every input: 4 × 6 × (9 − 8) = 24. Greedy decoding is not guaranteed to choose the discarded branch. The cost is that you run the model many more times per task.

A separate Game of 24 example shows explicit branch expansion and pruning with illustrative scores. This is an orchestration algorithm, not a diagram of a reasoning model’s hidden computation.

Tree of Thoughts makes candidate generation, evaluation, and pruning explicit. The paper evaluates this extra search on tasks including Game of 24. Compare its task accuracy alongside the cost of that additional model work. A single long reasoning trace may contain revisions without using this external search procedure.


The plan-execution gap

A plausible plan can fail when its assumptions do not match the environment.

Constructed trace: update a plan from observations

Step 1

Plannedsearch repo for 'auth middleware'

Executedsearch repo for 'auth middleware'

Step 2

Plannedopen src/auth/middleware.py

Executedopen src/auth/middleware.ts

Changed: file is ts, not py — repo changed layout

Step 3

Plannedpatch the session validator at line 42

Executedpatch the session validator at line 61

Changed: line numbers shifted after refactor

Step 4

Plannedrun pytest tests/auth/

Executedrun npm test -- auth

Changed: wrong test runner for this codebase

Inspect the repository before choosing paths, line numbers, or a test runner.

An authored plan encounters mismatched paths and commands. Tool results expose those mismatches so the next step can be revised.

A repository may have moved a file, replaced its test runner, or changed the code around a remembered line number. Inspecting the current files and command results gives the agent a basis for revising the plan.

Recovery means detecting the mismatch and replanning from the tool results. Reflexion adds a separate reflection-and-retry procedure.

Feedback changes the next attempt

AttemptEvaluateReflectRetry
Constructed trace. The reflection becomes context for a new attempt; the cycle can continue if evaluation finds another problem.

Reflexion's outer loop. After a failed attempt, the agent writes a natural-language reflection and prepends it to the next attempt's context. The weights stay fixed; the later attempt receives additional context.

An ordinary tool loop can react to errors within its current attempt. Reflexion adds evaluation and stored feedback between attempts.


Implementation sketch

This example uses the manual extended-thinking mode supported by Claude Sonnet 4.5. Other model generations may use adaptive thinking and effort controls instead; check the selected model’s documentation. The output cap must leave room for both thinking and the answer.

import anthropic
 
client = anthropic.Anthropic()
 
resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=12000,
    thinking={
        "type": "enabled",
        "budget_tokens": 8000,   # spend up to 8k on interior reasoning
    },
    messages=[
        {
            "role": "user",
            "content": (
                "A farmer has 17 sheep. All but 9 run away. "
                "How many sheep are left? Think carefully."
            ),
        }
    ],
)
 
# The response is a list of blocks. Thinking blocks come before the text.
for block in resp.content:
    if block.type == "thinking":
        print("--- returned thinking (may be summarized) ---")
        print(block.thinking[:400], "...")
    elif block.type == "text":
        print("--- final answer ---")
        print(block.text)
 
# Output usage includes thinking; returned thinking may be a shorter summary.
print(f"output tokens (including thinking): {resp.usage.output_tokens}")

Thinking appears in a separate returned block, which may be summarized. Usage accounting includes the generated thinking, so visible text length is not a reliable token-cost measure. A budget is a cap rather than a charge for unused tokens. In a tool loop, preserve the provider-required thinking blocks and signatures instead of discarding them.


Misconceptions

"More reasoning tokens always help." Additional computation can help, plateau, or introduce errors. Evaluate the budget against task quality and cost; the maximum available setting is not automatically the best choice.

"Chain-of-thought prompting is the same as a reasoning model." A prompt asks for an output pattern; reasoning-oriented training changes the model. Follow the selected model’s prompting and budget guidance rather than assuming an extra “think step by step” instruction improves it.

"A long reasoning trace establishes that the model ran Tree of Thoughts." Explicit ToT evaluates multiple candidate continuations through an external search procedure. A single trace may revise an answer without using that procedure. Compare the cost and result of explicit search on the actual task.

"Returned thinking is the complete internal computation." Providers may return summaries, signed blocks, or opaque state. These are API representations with specific replay requirements, not a complete account of everything that produced the answer.

What's next

Some tasks require an agent to observe and interact with a graphical interface. The next post covers Computer Use and Browser Agents: how screenshot-driven loops choose actions and check their results.


Additional reading (and watching)