Phase 1: Foundations (Weeks 1–3)
Week 1 — The agent loop, conceptually
Agentic workflow vs. autonomous agent — the distinction that actually matters
This is the single most important conceptual distinction in the whole plan, and it's easy to nod along with when reading "Building Effective Agents" and then lose in practice. Get it concrete now:
Agentic workflow — a fixed set of steps a human lays out ahead of time. The LLM fills in what each step says, but not the order of steps. Example: a summarizer that always does extract → summarize → format, same order every time. The LLM writes the summary; it doesn't decide to skip a step or reorder things.
Autonomous agent — the LLM decides what to do next, at every step, based on what it's seen so far. No human wrote the sequence in advance; the model figures out the plan as it goes. A research agent deciding "I need one more search" vs. "I have enough, time to answer" is making that call itself, turn by turn.
Why it matters: Workflows are cheaper, more predictable, and easier to debug — you can point at the step that failed. Agents are more flexible but harder to control — they can loop pointlessly (calling the same tool over and over without progress), cost more, or take actions a person wouldn't have chosen.
Why this matters for the plan: Most things you build in Phases 1–3 fall somewhere between these two extremes. Real skill is choosing where on that spectrum a system belongs — not just defaulting to "fully autonomous" because it sounds impressive. The Week 3 bare ReAct agent is intentionally close to the autonomous end (the model picks tools and decides when to stop) so you personally experience its failure modes early — infinite tool-call loops, the model giving up too soon, wasted tool calls — things a rigid workflow would never expose you to. You need to get burned by an ungoverned loop once before Phase 3's guardrails (Week 11) feel motivated instead of like busywork.
The ReAct loop: perceive → plan → act → observe
The ReAct paper (Yao et al., 2022) is the origin of the pattern basically every tool-calling agent uses today, even ones that never cite it. Skim the paper for the mental model, not the benchmark numbers — here's the mental model distilled:
- Perceive — the model reads the conversation so far: the user's request, plus every past tool call and result. In the Messages API, this is just the
messagesarray — there's no separate "perceive" step, it's just the context you send. - Plan — the model reasons about what to do next, often in plain language ("I should check the weather before answering"). This can show up as visible text before a tool call, or, with extended thinking on, in a dedicated
thinkingblock. Either way, it's the same "plan" step. - Act — the model outputs a
tool_useblock: a request to call a specific tool with specific arguments. This is the only step that leaves the model — a real function runs, with real side effects if the tool has any. - Observe — your code (not the model) runs the tool, gets the result, and sends it back as a
tool_resultin the next request. The model reads this new info and the loop repeats.
The key thing this diagram hides: the model doesn't run the loop. Each API call, the model does one perceive→plan→act step and stops — it has no hands, it can't call a function itself. Your code closes the loop: you see the tool_use block, actually run the tool, and send the result back. This is what people miss when reading about agents: the "agent" is really your harness code plus repeated model calls, not some special mode the model switches into.
The tool-use wire format, conceptually
Before touching curl in Week 2, get the shape of this fixed in your head, because Week 3's Go code is entirely about producing and parsing exactly this:
Four things worth internalizing before you write a single line of code:
tool_use_idis the correlation key. Nothing else ties a result back to its request. If you're running tool calls concurrently (goroutines, in Go's case) and the model requests multiple tools in one turn, you must return onetool_resultpertool_use_id, and the model doesn't care what order they arrive in — but you must include all of them before the nextassistantturn makes sense.- The tool result is sent as a
user-role message, not some specialtoolrole — this trips people up coming from other providers' APIs that use a distincttoolrole. Anthropic's Messages API represents it as ausermessage whose content is atool_resultblock. - The full transcript is resent every single call. There's no server-side session state — every API call is stateless and includes the entire
messagesarray so far. This is why prompt caching (Prompt caching — mental model and cache_control) isn't an optimization you bolt on later; it's structural to how expensive a naive multi-turn tool loop gets, and Week 3's exit criteria specifically checks you've internalized this. - The model can request multiple tools in a single turn. A
contentarray on one assistant turn can contain severaltool_useblocks side by side — this is what lets a well-designed agent parallelize independent lookups (e.g., checking weather in two cities at once) instead of round-tripping serially. You won't need this for Week 3's simple project, but recognizing it now means Week 5 (streaming) and Phase 3 (parallel workers) won't be a surprise.
Week 2 — Raw API fluency
The plan is explicit: no Go yet, no SDK. Work through this entirely in curl so the wire format becomes second nature rather than something hidden behind a client library's abstractions. Everything below assumes $ANTHROPIC_API_KEY is set (see Prerequisites and Setup).
Your first Messages API call
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 512,
"messages": [
{"role": "user", "content": "What is 12 times 7?"}
]
}' | jq
(Piping through jq is worth doing for every call in this section — the raw response is dense JSON and you want to actually read the shape, not squint at a one-liner.)
Response shape to internalize:
{
"id": "msg_01XYZ...",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-5",
"content": [
{"type": "text", "text": "12 times 7 is 84."}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 14,
"output_tokens": 10
}
}
Note content is always an array of blocks, even for a plain text reply with nothing else going on — this uniformity is exactly what makes tool use fit into the same shape without a special-cased response format.
Defining a tool
Add a tools array to the request. Each tool definition is a JSON Schema describing its inputs — this is the contract the model uses to decide whether to call the tool and how to structure input when it does.
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 512,
"tools": [
{
"name": "calculator",
"description": "Evaluates a basic arithmetic expression and returns the numeric result. Use this whenever the user asks for a calculation rather than doing arithmetic yourself.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "A basic arithmetic expression, e.g. \"12 * 7\" or \"(3 + 4) / 2\""
}
},
"required": ["expression"]
}
}
],
"messages": [
{"role": "user", "content": "What is 12 times 7?"}
]
}' | jq
The description field is doing real work, not documentation for humans. The model uses it, verbatim, to decide when to reach for this tool over just answering directly, and how to fill input. A vague description ("does math") produces worse tool-selection behavior than a specific one ("evaluates a basic arithmetic expression... use this whenever the user asks for a calculation rather than doing arithmetic yourself") — this is a real, load-bearing form of prompting, and it's worth treating tool descriptions with the same care you'd put into a system prompt.
Expect the response this time to have stop_reason: "tool_use" and a content array containing a tool_use block:
{
"content": [
{
"type": "tool_use",
"id": "toolu_01AbCdEfGhIjKlMnOpQrSt",
"name": "calculator",
"input": {"expression": "12 * 7"}
}
],
"stop_reason": "tool_use",
"usage": {"input_tokens": 312, "output_tokens": 42}
}
The full loop, worked end-to-end with curl
This is the exercise the plan means by "loop until end_turn." Do it by hand once, literally copy-pasting IDs between curl calls, before writing any Go — feeling the tedium of doing this manually is exactly what makes you appreciate why Week 3 automates it.
Turn 1 — send the request, get a tool_use back (as above). Note the id field on the tool_use block — copy it.
Turn 2 — you execute the tool yourself (mentally: 12 * 7 = 84), then send the result back, replaying the entire prior turn plus your new tool_result.
Critical: replay the assistant content exactly as received. The response from Turn 1 may contain a thinking block alongside the tool_use block. You must include it verbatim — the API verifies its signature and will reject the request if you drop it or alter it. Treat the thinking block as opaque bytes: copy it through, don't read it as application logic.
A real Turn 1 response with thinking looks like:
{
"role": "assistant",
"content": [
{
"type": "thinking",
"thinking": "...",
"signature": "EokCCokBCA8YAip..."
},
{
"type": "tool_use",
"id": "toolu_01WaaRTmryJK8KmM8bJnPwM5",
"name": "calculator",
"input": {"expression": "12 * 7"}
}
]
}
Both blocks go back in the assistant message in Turn 2:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 512,
"tools": [
{
"name": "calculator",
"description": "Evaluates a basic arithmetic expression and returns the numeric result. Use this whenever the user asks for a calculation rather than doing arithmetic yourself.",
"input_schema": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "A basic arithmetic expression, e.g. \"12 * 7\""}
},
"required": ["expression"]
}
}
],
"messages": [
{"role": "user", "content": "What is 12 times 7?"},
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "...", "signature": "EokCCokBCA8YAip..."},
{"type": "tool_use", "id": "toolu_01WaaRTmryJK8KmM8bJnPwM5", "name": "calculator", "input": {"expression": "12 * 7"}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "toolu_01WaaRTmryJK8KmM8bJnPwM5", "content": "84"}
]}
]
}' | jq
Replace the placeholder id and signature with the actual values from your Turn 1 response. If thinking was absent in Turn 1, the assistant content array will only contain the tool_use block — that is fine, just replay whatever you received.
Expect stop_reason: "end_turn" and a final text block, e.g. "12 times 7 is 84.". You just ran a complete agent loop by hand. Everything Week 3 does in Go is mechanizing exactly these three things: (1) notice stop_reason == "tool_use", (2) actually execute the named tool with the given input, (3) append a tool_result and call again — repeat until stop_reason == "end_turn".
A few things worth deliberately breaking, to see the error shape before you're debugging it blind in Go:
- Send a
tool_resultwith the wrongtool_use_id(typo one character) — see what error comes back. - Drop the
thinkingblock from the assistant content when one was returned — the API will reject it with a signature validation error. - Omit the
toolsarray entirely on turn 2 (leave it in the prior assistant turn but drop it from the request) — see whether the API still accepts a danglingtool_use/tool_resultpair without the tool defined. (It generally will, since it's not re-validating history against a live schema — but confirm this yourself rather than trusting this doc, since exact validation behavior is the kind of thing that can tighten between API versions.) - Send
max_tokenstoo low to fit a full response — see thestop_reason: "max_tokens"case, the third value you'll need to handle alongsideend_turnandtool_use.
stop_reason — the field that drives your loop
This is the single field your Week 3 loop branches on. Know all the values, not just the two you'll hit most often:
stop_reason |
What it means | What your loop should do |
|---|---|---|
end_turn |
Model produced a complete response and has nothing more to say | Exit the loop, show the final text to the user |
tool_use |
Model wants to call one or more tools | Execute each requested tool, append tool_result blocks, call again |
max_tokens |
Response was cut off because it hit your max_tokens limit |
Either treat as an error, or (more robustly) raise max_tokens and retry — a tool_use block cut off mid-JSON is unparseable, and this is a real production failure mode worth handling deliberately rather than ignoring |
stop_sequence |
Model hit a custom stop sequence you configured | Only relevant if you set stop_sequences in the request — not used in this phase |
pause_turn |
Model paused a long-running turn (e.g. involving server-side tools) and expects you to continue it | Not relevant to Week 3's client-side-only tools; you'll meet this if you ever use Anthropic's server-side tools (web search, code execution) |
For Week 3, your loop's exit condition is simply: keep looping while stop_reason == "tool_use"; stop on anything else. Treating max_tokens as "keep looping" by accident is a classic bug — it looks like the model is being unresponsive when actually your limit is too low.
Prompt caching — mental model and cache_control
Read the prompt caching docs in full, but the mental model that matters is this one, and it's worth having memorized before Week 3:
Prompt caching is a prefix match, not a semantic cache. The API doesn't understand "this is roughly the same question as before" — it checks whether the exact token sequence up to a marked breakpoint matches something cached from a recent prior call (cache entries currently last a few minutes by default, extendable). This has a direct structural consequence for how you build the messages array:
Anything after a change invalidates the cache for everything after that point in the prefix — so if your tool definitions are listed in a different order on two calls, or your system prompt has a timestamp interpolated into it, you silently pay full price every time because the prefix never matches. This is the single most common way people accidentally defeat their own caching without noticing (see Common pitfalls in Phase 1).
How you actually mark a breakpoint: add a cache_control field to the content block you want the cache to extend through:
{
"system": [
{
"type": "text",
"text": "You are a helpful assistant with access to tools...",
"cache_control": {"type": "ephemeral"}
}
],
"tools": [ ... ],
"messages": [ ... ]
}
This tells the API "everything up through this block is a stable prefix — cache it."
Which parts does one breakpoint cover?
The API always builds the prompt in a fixed order: tools first, then system, then messages. The field order in your JSON doesn't matter.
A cache_control mark does not mean "cache this one block". It means "cache the whole prefix that ends here". Tools come before system. So a mark on the last system block caches the tool definitions too. You never need to put cache_control on the tools themselves.
"But I still send the tools on every request — so what does caching save?"
You do still send them, every time. Caching does not shrink the request. The API needs the exact bytes to check them against the cache. What caching saves is the work of processing those tokens again — and that is what you pay for.
Here is what happens across the turns of one agent loop:
| Turn | What you send | What the API does with tools + system | What you pay for tools + system |
|---|---|---|---|
| 1 | tools + system + user message | No match yet. It processes the prefix and saves it. | A cache write: a small premium over the normal input price. Shows up as cache_creation_input_tokens. |
| 2 | the same tools + system + the longer history | It finds a byte-for-byte match and reuses the saved work. Only the new messages are processed fresh. | A cache read: roughly a tenth of the normal price. Shows up as cache_read_input_tokens. |
| 3…N | the same again | It reuses the saved work again. Each read also resets the cache timer. | A cache read again. |
So the bytes go over the wire every turn, but you pay full price for them only once. Responses also start faster, because the model skips work it has already done.
What this breakpoint does not cache
This mark caches only the fixed part: tools + system. The conversation history after it is still processed at full price every turn. Phase 2 adds more breakpoints for the growing history (see the 20-block lookback note in Phase 2: Usage and cache accounting under streaming).
The two catches
- The prefix must be identical, byte for byte, on every turn. A changed tool order, a new tool, or a timestamp in the system prompt breaks the match. See the checklist in Proving your cache is actually hitting.
- The prefix must be big enough. Each model has a minimum cacheable size. Below it, nothing is cached, and you get no error. See Proving your cache is actually hitting.
Why this is structural, not an afterthought
Recall from The tool-use wire format, conceptually that the entire transcript is resent on every single loop iteration. A 5-tool-call agent loop with a 2,000-token system prompt and tool definitions means you're paying full price for those same 2,000 tokens five times if caching isn't wired up — versus once, with every subsequent call reading from cache. This is exactly why the plan has you logging cache_read_input_tokens from Week 3 onward and makes it a Phase 1 exit criterion rather than something deferred to Phase 5's cost-optimization pass.
Context windows — what actually fills them up
The context window is everything the model can see in one request, including the reply it is writing. Think of it as the model's working memory for that call. It has nothing to do with the data the model was trained on.
What counts toward the window
- Everything you send: the system prompt, your tool definitions, and every message in
messages, including tool results, images and documents. - Everything the model writes for this turn, including its thinking.
- Cached tokens too. With prompt caching,
usagesplits input intoinput_tokens,cache_read_input_tokensandcache_creation_input_tokens. All three count. Caching changes what you pay for those tokens, not whether they take up space.
Now connect this to the loop: the whole transcript is resent every turn, so the whole transcript fills the window every turn. That's the system prompt + tool definitions + every earlier user message + every earlier assistant text and tool_use block + every earlier tool_result. An agent with verbose tool results (say, a tool that dumps a full API response) can use up a large part of the window in a handful of turns, long before the conversation feels long to a human reading it.
How big is it
- Current models: 1M tokens. This covers Opus 4.6 and later, Sonnet 4.6 and later, Haiku 5.5, and the Fable and Mythos models. It is the default: no beta header, standard pricing. The one exception is Haiku 5.5, where prompts over 100,000 tokens cost more.
- Older models: 200k tokens, including Sonnet 4.5 (deprecated).
- Output per request: up to 128k tokens (
max_tokens) on the 1M-token models. - Images and PDFs: up to 600 images or PDF pages per request (100 on 200k-token models). With large files you may hit the request size limit before the token limit.
Bigger is not automatically better. As the token count grows, the model gets worse at finding and using what's in there. Anthropic calls this context rot; it's the same effect as "lost in the middle" from the foundations chapter. So choosing what goes into the window matters as much as how much fits.
Thinking and the window
- Thinking tokens come out of your
max_tokens, are billed as output tokens, and count toward the window for that turn. - Thinking from earlier turns: newer models (Opus 4.5 and later, Sonnet 4.6 and later, Haiku 5.5, Fable, Mythos) keep it by default, so it counts as input on every later turn. Older models drop it automatically when you send it back. Either way, you don't strip it yourself.
- Thinking with tools, the one rule you must follow: when you send a
tool_result, send back the thinking block that came with thattool_use, complete and unmodified. It carries a cryptographic signature, and the API returns an error if it was changed. This is the only case where you must return thinking blocks.
Does the model know how full it is?
Some models do. Sonnet 5, Sonnet 4.6, Sonnet 4.5 and Haiku 4.5 have context awareness: the API tells the model its total budget at the start (<budget:token_budget>) and adds a short note after each tool call, like Token usage: 35000/200000; 165000 remaining. You don't enable or send anything; the API does it. Newer models (Opus 4.7 and later, Sonnet 5.5, Haiku 5.5, Fable, Mythos) don't get these notes. For those, you can set an explicit budget with task budgets (in beta).
What happens when it overflows
| Situation | What the API does |
|---|---|
| Your input alone is bigger than the window | Rejects the request: 400 invalid_request_error, "prompt is too long". Same on every model. |
Input fits, but input + max_tokens is bigger than the window (Claude 4.5 models and newer) | Accepts the request. If the reply then runs into the limit, it stops with stop_reason: "model_context_window_exceeded". Your loop must handle this stop reason. |
| Same, on older models | Returns a validation error, unless you opt in with the model-context-window-exceeded-2025-08-26 beta header. |
How to stay inside it
- Measure before you send: the token counting API estimates a request's size without running it.
- Compaction (beta, Claude 4.6 and later): the server summarizes the older part of the conversation so it can keep going past the limit. This is the main tool for long-running agents.
- Context editing: automatically clear old tool results, or old thinking blocks, from earlier turns.
- Shrink tool definitions: load tool definitions only when needed (the tool search tool) instead of sending every tool on every call.
Source: Claude docs, Context windows, checked 2026-10-25. Model names and limits change often; recheck before relying on a specific number.
Two concrete implications for later phases, worth having in your head now even though you won't act on them until then:
- Tool results should be trimmed/summarized before being sent back, not passed through raw — a search tool returning 50KB of HTML is a context-window and cost problem waiting to happen, and this becomes directly relevant in Phase 2 Week 7 (memory: rolling buffer + summarization).
- This is also why "just make max_tokens huge" isn't free — every token of context (input) still counts toward the window regardless of how much of it is "just" replayed history versus new content.
MCP architecture, distilled
Read the architecture page. Just that page for now; hands-on MCP work is Phase 2 Week 6. This section is the plain-language version.
The problem MCP solves: every AI app (Claude Code, VS Code, your own agent) wants to use outside services: GitHub, Slack, a database, your files. Without a standard, each app writes its own connector for each service, so N apps × M services = N×M integrations. MCP is one standard plug: a service exposes it once, and any app that speaks MCP can use it. That turns N×M into N+M.
Analogy: USB-C. Your laptop doesn't need a special port for every device. Each device speaks USB-C, and anything that speaks USB-C plugs in.
The three players
| Player | What it is | Example |
|---|---|---|
| Host | The AI app you're using | Claude Code, VS Code |
| Client | A connector inside the host. There is one client per server. | VS Code creates one client for Sentry and another for your filesystem |
| Server | A small program that offers capabilities to the host | Sentry server, filesystem server |
If the host connects to 3 servers, it runs 3 clients, and each one has its own private line to its server. "Server" doesn't mean remote: a local server runs on your machine (the filesystem server), and a remote one runs on someone else's platform (Sentry's).
Two layers: what is said vs. how it travels
- Data layer (the language): what the messages say. It uses JSON-RPC 2.0, which is just "call this method with these arguments and get a result back."
- Transport layer (the delivery): how the messages get from one side to the other. There are two options:
- stdio: the host launches the server as a local process, and they talk through stdin/stdout. Fast, with no network involved.
- Streamable HTTP: for remote servers. It uses HTTP POST, with optional streaming, and normal auth such as OAuth, API keys or bearer tokens.
The messages look the same on either transport. Only the delivery changes.
What servers can offer (the important part)
| Primitive | Plain meaning | Example |
|---|---|---|
| Tools | Things the AI can do | Run a query, create a GitHub issue |
| Resources | Things the AI can read | A file, a database schema |
| Prompts | Ready-made templates | "Here's how to use this DB," with examples |
The pattern is always list it, then use it: tools/list asks "what tools do you have?", and tools/call says "run this one with these arguments." Resources and prompts follow the same pattern.
An MCP tool is the same tool_use/tool_result pattern you just learned. Once your harness has fetched the tool's schema from the server, the model can't tell it apart from any other tool.
What a client can offer back: elicitation, which lets a server ask the user a question through the host ("Are you sure you want to delete this?"). Sampling, where a server borrows the host's LLM, is deprecated as of protocol version 2026-07-28.
How a conversation actually goes
- Discover: the client asks
server/discover: "Which protocol version do you speak, and what can you do?" The server replies with something like "I have tools, and I'll tell you when they change." This step is optional, and the answer can be cached. - List: the client calls
tools/list. The server returns each tool'sname,descriptionandinputSchema, which says what arguments the tool takes. - Combine: the host merges the tool lists from all its servers into one list and hands it to the LLM.
- Call: the LLM decides to use
weather_current. The host sends that call to the right server withtools/calland gets the result back ("68°F, partly cloudy"). The result goes back into the conversation. - Stay updated: the client can subscribe with
subscriptions/listento hear when tools change. When it getsnotifications/tools/list_changed, it callstools/listagain. Notifications are best effort, so don't rely on them alone.
Two details worth knowing
- It's stateless now. Every request carries the protocol version and the client's capabilities in its
_metafield, so the server doesn't need to remember anything about earlier requests. That makes remote servers easier to scale. Older material describes aninitializehandshake; the current spec (2026-07-28) uses per-request metadata plusserver/discoverinstead. - MCP only moves context around. It doesn't decide how the host uses the LLM or what goes into the prompt. That's still your agent's job.
In one line: an AI app (host) runs one connector (client) per service (server). The two sides speak JSON-RPC over stdio (local) or HTTP (remote), and the server offers tools to do, resources to read and prompts to reuse, always listed first and then used.
Source: MCP docs, Architecture overview (protocol version 2026-07-28), checked 2026-10-25. You'll build one of these servers yourself in Week 6; this section is just so the shape isn't new to you then.
Week 3 — Project: a bare ReAct agent in Go
Scope: what "no SDK, no framework" buys you
The plan says to build this project without an SDK. Here is why, before you are tempted to use anthropic-sdk-go.
In Phase 2 you will use frameworks like Eino and LangChainGo. They will make much more sense once you have written, by hand, the parts they hide. An SDK hides three things:
- turning Go structs into JSON and back,
- matching each
tool_resultto itstool_use, - looping until
stop_reasonisend_turn.
Once you trust an SDK, hiding these things helps. While you are still learning, it gets in the way. So build this one by hand.
What to build:
- Plain
net/httpcalls tohttps://api.anthropic.com/v1/messages. No client library. - Exactly 2 tools: a calculator and a fake ("stub") web search. The stub can return made-up results. The goal is to practice how tool calls work, not to build real search.
- Your own code to turn requests into JSON and to parse the JSON responses.
- Your own loop, controlled by
stop_reason. - A log of token usage for every turn.
Code architecture
Keep the layout small and simple. You may feel the urge to build your own mini "framework". Notice that urge and skip it. The goal is to see how the parts work, not to hide them:
bare-react-agent/
├── go.mod
├── main.go # entry point: sets up the loop, runs it
├── client.go # HTTP client for the Messages API — request/response types, Send()
├── tools.go # Tool interface + calculator + web-search-stub implementations
├── eval.go # Tiny arithmetic evaluator the calculator tool calls
└── loop.go # The actual agent loop: perceive/plan/act/observe
mkdir bare-react-agent && cd bare-react-agent
go mod init bare-react-agent
The two tools
Give both tools the same small interface. Then, when you add a third tool later (you will, in Phase 2), you won't need to change the loop:
// tools.go
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Tool is anything the agent loop can invoke by name.
type Tool interface {
Name() string
Description() string
InputSchema() map[string]any
Execute(input json.RawMessage) (string, error)
}
// --- Calculator ---
type Calculator struct{}
func (c *Calculator) Name() string { return "calculator" }
func (c *Calculator) Description() string {
return "Evaluates a basic arithmetic expression (e.g. \"12 * 7\", \"(3 + 4) / 2\") and returns the numeric result. Use this whenever the user asks for a calculation rather than doing arithmetic yourself."
}
func (c *Calculator) InputSchema() map[string]any {
return map[string]any{
"type": "object",
"properties": map[string]any{
"expression": map[string]any{
"type": "string",
"description": "A basic arithmetic expression using +, -, *, /, and parentheses.",
},
},
"required": []string{"expression"},
}
}
type calculatorInput struct {
Expression string `json:"expression"`
}
func (c *Calculator) Execute(input json.RawMessage) (string, error) {
var in calculatorInput
if err := json.Unmarshal(input, &in); err != nil {
return "", fmt.Errorf("bad calculator input: %w", err)
}
result, err := evalArithmetic(in.Expression) // your own tiny evaluator, or shell out to a real one
if err != nil {
// IMPORTANT: return the error AS the tool result, don't just error out of
// the whole loop — the model needs to see "this expression was invalid"
// and can often recover (retry with corrected input, or apologize to the user).
return fmt.Sprintf("error evaluating expression: %v", err), nil
}
return strconv.FormatFloat(result, 'f', -1, 64), nil
}
// --- Web search stub ---
type WebSearchStub struct{}
func (w *WebSearchStub) Name() string { return "web_search" }
func (w *WebSearchStub) Description() string {
return "Searches the web for a query and returns a short summary of top results. Use this for questions about current events or facts you're not confident about."
}
func (w *WebSearchStub) InputSchema() map[string]any {
return map[string]any{
"type": "object",
"properties": map[string]any{
"query": map[string]any{"type": "string", "description": "The search query."},
},
"required": []string{"query"},
}
}
type webSearchInput struct {
Query string `json:"query"`
}
func (w *WebSearchStub) Execute(input json.RawMessage) (string, error) {
var in webSearchInput
if err := json.Unmarshal(input, &in); err != nil {
return "", fmt.Errorf("bad web_search input: %w", err)
}
// Canned response — the point of Week 3 is the tool-calling mechanism,
// not a real search integration. Make the fakeness obvious in the result
// itself so you never mistake this for a real answer while testing.
return fmt.Sprintf("[STUB RESULT] Simulated top result for %q: no real web access in this stub.", in.Query), nil
}
Look again at the error comment inside Execute. A tool failing is not the same as your program failing.
Say the calculator gets bad input. The model should find out, as a tool_result. Then it can react: retry, apologize, or ask the user a question. Your Go program should not crash, and the loop should not stop.
Keep the two kinds of failure apart:
- Tool failure (bad input, tool error) — send it back to the model as a result.
- Harness failure (for example, the API call itself fails) — return an error from your code.
This is cheap to get right now. It is costly to fix later, because Phase 3's guardrails expect tool failures to be visible and recoverable.
The calculator calls evalArithmetic. Its body is implementation detail (parsing math is not the point of this project), so the guide leaves it out. All the agent cares about is the contract:
// eval.go
func evalArithmetic(expr string) (float64, error)It should handle + - * /, parentheses, decimals and negative numbers, and return an error, not a panic, on bad input like "2 +", so the failure flows back to the model as a tool_result. Write a small recursive-descent parser, or pull in a library such as expr-lang/expr.
The client and the request/response types
// client.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const apiURL = "https://api.anthropic.com/v1/messages"
const apiVersion = "2023-06-01"
type Client struct {
apiKey string
httpClient *http.Client
}
func NewClient() *Client {
key := os.Getenv("ANTHROPIC_API_KEY")
if key == "" {
panic("ANTHROPIC_API_KEY not set")
}
return &Client{apiKey: key, httpClient: &http.Client{}}
}
// --- Content blocks: a message's content is a union type on the wire.
// Go has no native sum type, so model it with a struct that has every
// possible field and omits the ones that don't apply — this mirrors
// what you saw in the curl responses in §2.
type ContentBlock struct {
Type string `json:"type"` // "text" | "tool_use" | "tool_result"
// type == "text"
Text string `json:"text,omitempty"`
// type == "tool_use"
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
// type == "tool_result"
ToolUseID string `json:"tool_use_id,omitempty"`
Content string `json:"content,omitempty"`
IsError bool `json:"is_error,omitempty"` // Phase 2 §2.4: never drop a failed tool call, flag it instead
}
type Message struct {
Role string `json:"role"` // "user" | "assistant"
Content []ContentBlock `json:"content"`
}
type ToolDef struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]any `json:"input_schema"`
}
type SystemBlock struct {
Type string `json:"type"`
Text string `json:"text"`
CacheControl *CacheControl `json:"cache_control,omitempty"`
}
type CacheControl struct {
Type string `json:"type"` // "ephemeral"
}
type MessagesRequest struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
System []SystemBlock `json:"system,omitempty"`
Tools []ToolDef `json:"tools,omitempty"`
Messages []Message `json:"messages"`
Stream bool `json:"stream,omitempty"` // set by consumeStream, Phase 2 §2.2
}
type Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
CacheReadInputTokens int `json:"cache_read_input_tokens"`
}
type MessagesResponse struct {
ID string `json:"id"`
Role string `json:"role"`
Content []ContentBlock `json:"content"`
StopReason string `json:"stop_reason"`
Usage Usage `json:"usage"`
}
func (c *Client) Send(req MessagesRequest) (*MessagesResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
httpReq, err := http.NewRequest("POST", apiURL, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
httpReq.Header.Set("x-api-key", c.apiKey)
httpReq.Header.Set("anthropic-version", apiVersion)
httpReq.Header.Set("content-type", "application/json")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("do request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("api error (status %d): %s", resp.StatusCode, string(respBody))
}
var msgResp MessagesResponse
if err := json.Unmarshal(respBody, &msgResp); err != nil {
return nil, fmt.Errorf("unmarshal response: %w", err)
}
return &msgResp, nil
}
Two design choices to notice:
- One
ContentBlockstruct holds every possible field. On the wire, a content block can be one of several types (text,tool_use,tool_result). Go has no built-in way to say "one of these types". So we put every field in one struct and mark themomitempty, which leaves unused fields out of the JSON. It is a bit messy: a"text"block carries emptyIDandNamefields it never uses. For a learning project, that is fine. The cleaner production approach is customMarshalJSON/UnmarshalJSONcode for each block type. Frameworks like Eino already do this for you — a concrete example of what Phase 2 gives you. - Every error is wrapped with
%wand a short label (like"marshal request: %w"). When the HTTP call fails in the middle of a 5-tool-call run, the message tells you right away which step broke. You don't have to add print statements afterwards to find out.
The main loop
// loop.go
package main
import "fmt"
type Agent struct {
client *Client
tools []Tool
model string
}
func NewAgent(client *Client, tools []Tool) *Agent {
return &Agent{client: client, tools: tools, model: "claude-sonnet-5"}
}
func (a *Agent) toolDefs() []ToolDef {
defs := make([]ToolDef, len(a.tools))
for i, t := range a.tools {
defs[i] = ToolDef{Name: t.Name(), Description: t.Description(), InputSchema: t.InputSchema()}
}
return defs
}
func (a *Agent) findTool(name string) Tool {
for _, t := range a.tools {
if t.Name() == name {
return t
}
}
return nil
}
// Run executes the perceive/plan/act/observe loop until the model reaches
// end_turn (or another terminal stop_reason), returning the final text reply.
func (a *Agent) Run(userMessage string) (string, error) {
messages := []Message{
{Role: "user", Content: []ContentBlock{{Type: "text", Text: userMessage}}},
}
system := []SystemBlock{
{
Type: "text",
Text: "You are a careful assistant with access to a calculator and a web search tool. Use tools when they'd give a more reliable answer than reasoning alone.",
// Mark the system prompt as the cache breakpoint — see §2.5/§3.7.
// The API always builds the prompt in the order tools → system →
// messages, whatever the JSON field order. The cache covers
// everything up to this mark, so it holds the tool definitions
// AND this system prompt. The messages after it are not cached.
CacheControl: &CacheControl{Type: "ephemeral"},
},
}
turn := 0
for {
turn++
req := MessagesRequest{
Model: a.model,
MaxTokens: 1024,
System: system,
Tools: a.toolDefs(),
Messages: messages,
}
resp, err := a.client.Send(req)
if err != nil {
return "", fmt.Errorf("turn %d: %w", turn, err)
}
logTurnUsage(turn, resp.Usage) // see §3.6
// Append the assistant's turn to the transcript before deciding what to do next —
// whatever happens, this turn is now part of history for the next request.
messages = append(messages, Message{Role: "assistant", Content: resp.Content})
switch resp.StopReason {
case "end_turn":
return extractText(resp.Content), nil
case "tool_use":
var toolResults []ContentBlock
for _, block := range resp.Content {
if block.Type != "tool_use" {
continue
}
tool := a.findTool(block.Name)
var resultText string
if tool == nil {
resultText = fmt.Sprintf("error: no such tool %q", block.Name)
} else {
result, execErr := tool.Execute(block.Input)
if execErr != nil {
resultText = fmt.Sprintf("error: %v", execErr)
} else {
resultText = result
}
}
toolResults = append(toolResults, ContentBlock{
Type: "tool_result",
ToolUseID: block.ID,
Content: resultText,
})
}
// All tool_result blocks for this turn go in a SINGLE user message —
// not one message per result. This matches what you did by hand in §2.3.
messages = append(messages, Message{Role: "user", Content: toolResults})
case "max_tokens":
return "", fmt.Errorf("turn %d: hit max_tokens before completing — response may be truncated mid tool_use", turn)
default:
return "", fmt.Errorf("turn %d: unhandled stop_reason %q", turn, resp.StopReason)
}
}
}
func extractText(content []ContentBlock) string {
var out string
for _, block := range content {
if block.Type == "text" {
out += block.Text
}
}
return out
}
This switch statement is the loop from The ReAct loop: perceive → plan → act → observe and stop_reason — the field that drives your loop, written as code. Here is why each branch exists:
end_turn→ The model is done. Return its answer.tool_use→ These are the "act" and "observe" steps. Run every tool the model asked for (resp.Contentmay hold more than onetool_useblock). Put all the results into oneusermessage and add it to the history. Then loop again — the next request is the next "perceive" step.max_tokens→ The reply was cut off. Here we treat it as an error to keep things simple. A better version would raiseMaxTokensand resend the same request. Try this as a stretch goal once the basic loop works — it happens for real once tool results get long.default→ Any other value (likestop_sequenceorpause_turn) returns an error on purpose. A loop that quietly ignores an unknownstop_reasonhas a bug that hides itself.
Wiring it together. Nothing above creates the agent yet. That is the job of main.go. It builds the client, hands the agent its two tools, and runs one question taken from the command line:
// main.go
package main
import (
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, `usage: go run . "your question"`)
os.Exit(1)
}
// The order of this slice is the order of the tools array on the wire.
// Keep it fixed — see §3.7 on why tool order matters for caching.
agent := NewAgent(NewClient(), []Tool{&Calculator{}, &WebSearchStub{}})
answer, err := agent.Run(strings.Join(os.Args[1:], " "))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(answer)
}
Here is how the pieces connect:
main.gomakes aClientand anAgent, and gives the agent the list ofTools.- On every turn,
Run()callsa.toolDefs(). This turns eachToolinto aToolDef— the JSON shape the API expects — and sends them astoolsin the request. - When the model asks for a tool,
findTool()looks it up by name and calls itsExecute().
Put logTurnUsage from Token usage logging — what to log and why in loop.go, then run it:
go run . "What is (12 * 7) / 4 + 3?"
Token usage logging — what to log and why
This is not optional polish. It is one of the Phase 1 exit criteria. Log all four usage fields on every turn, not just at the end:
func logTurnUsage(turn int, u Usage) {
fmt.Printf(
"[turn %d] input=%d output=%d cache_write=%d cache_read=%d\n",
turn, u.InputTokens, u.OutputTokens, u.CacheCreationInputTokens, u.CacheReadInputTokens,
)
}
What to look for when you run the agent on a task that needs several tool calls:
input_tokensgoes up every turn. This is expected. The full history is resent on every call, and it keeps growing (The tool-use wire format, conceptually, point 3). This is the price of the API having no memory between calls.cache_creation_input_tokenson turn 1, thencache_read_input_tokensfrom turn 2 on. This pattern means caching works. Ifcache_read_input_tokensstays at 0 on every turn, the cache is not hitting — see Proving your cache is actually hitting.output_tokenson each turn. Tool-call turns are usually small (just thetool_useblock). The finalend_turnturn is bigger because it holds the full answer. A largeoutput_tokenson a middle turn can mean the model wrote a lot of text before calling a tool. That is not wrong, but you pay for it. If no user ever sees that text, it is wasted cost.
Adding it up. Each API call returns its own usage. A conversation's total is the sum over every call. That includes the tool-loop calls, not just one per user message. Keep in mind:
- Input is the whole transcript, not just the new message. Every call resends everything so far, so each reply is paid for once as output and then again as input on every later call. Over many turns, total input grows roughly with the square of the turn count. That is why input usually dominates the bill.
- The input is split across three fields, and each has its own price.
input_tokensis only the uncached part. Cached tokens show up incache_creation_input_tokens(charged a bit above the normal price) andcache_read_input_tokens(charged a small fraction of it). If you add up onlyinput_tokens, you undercount.
A small example, with no caching (a 500-token system prompt, ~50-token user messages, ~200-token replies):
| Call | Sent as input | Input | Output |
|---|---|---|---|
| 1 | system + U1 | 550 | 200 |
| 2 | system + U1 + A1 + U2 | 800 | 200 |
| 3 | system + U1 + A1 + U2 + A2 + U3 | 1,050 | 200 |
| Total | 2,400 | 600 |
At the end of Run(), print a per-field total over all turns, and a cost:
cost = Σ over calls ( input_tokens × input_price
+ cache_creation_tokens × cache_write_price
+ cache_read_tokens × cache_read_price
+ output_tokens × output_price )
This gives you one number: "this conversation cost $X". Phase 2 Week 9 builds on it — its exit criterion is to "state your agent's cost per conversation to within ~2x".
Proving your cache is actually hitting
Don't assume cache_control works just because it is in your request. Check it, the same way you checked pgvector in the prerequisites doc.
- Run your agent on a task that needs at least 2 tool calls. For example: "search for the population of France, then calculate 10% of it".
- Watch the per-turn log. You should see:
- Turn 1:
cache_creation_input_tokens > 0andcache_read_input_tokens == 0. There is nothing to read yet — this call creates the cache entry. - Turn 2 onward:
cache_read_input_tokens > 0, roughly the size of your fixed prefix (system prompt + tool definitions).cache_creation_input_tokens == 0, unless the prefix changed. A changed prefix starts a new cache entry (see below).
- Turn 1:
- If
cache_read_input_tokensis 0 on every turn, check these in order:-
Is
cache_creation_input_tokensalso 0 on turn 1? If both are 0, nothing was ever cached. Fix this first, before the other checks. There are two likely causes:- (a) No cache breakpoint is being sent (see the next check).
- (b) Your prefix is too short. Each model has a minimum cacheable prefix: 1024 tokens on Sonnet 5, 4096 on Haiku 4.5, 512 on Opus 5. Below that size, the API simply doesn't cache. There is no error and no warning — you just get 0. A short system prompt plus two small tools can easily be under 1024 tokens, so you may well hit this early.
Also note that the minimum does not simply go up or down with newer models. A 3K-token prefix caches fine on Opus 5 but not on Haiku 4.5. That can surprise you if you switch to a cheaper model for a test run. Count your prefix tokens before you assume your
cache_controlis in the wrong place. -
Is
cache_controlin the JSON on turn 2 and later, not just turn 1? Caching is not "set once". You mark the breakpoint on every request. The API then checks whether a matching earlier entry exists. -
Is your
systemblock exactly the same, byte for byte, on every turn? Any change, even whitespace, breaks the match. -
Is your
toolsarray in the same order on every turn? Go deliberately shuffles the order when you loop over a map. So if you ever buildtoolDefs()from a map instead of a slice, the order will change and caching will break. Thea.tools []Toolslice in The main loop avoids this by design — that is why a slice was used. -
Has more time passed than the cache TTL (how long a cache entry lives) since your last call? Unlikely in one test run, but it can happen if you pause in a debugger.
-
You are done when you can point at your own log and say: "Cache reads started on turn 2, and here is the exact, unchanged prefix that made it happen." A number that was non-zero once is not enough.
Exit criteria — how to self-verify each one
The plan lists three criteria. Here is how to really check each one, instead of eyeballing it.
"Your agent completes a task requiring a 3+ tool-call chain without you editing the prompt mid-run."
Pick a task that truly needs 3 tool calls in a row. For example: "search for the USD to EUR exchange rate, then search for the price of an item in USD, then calculate the price in EUR." Run it once without helping — no re-prompting, no nudging. Count the tool_use turns in your log.
- If the model makes 3 real tool calls, you pass.
- If it makes only 1 call and guesses the rest (instead of calling
web_searchtwice), that tells you something too: your task did not really need 3 calls. Redesign the test. Don't count it as a pass.
"You can explain, without notes, what happens on the wire between 'Claude wants a tool' and 'Claude sees the result.'" Really test yourself. Say it out loud, or better, explain it to someone else — even someone non-technical. Focus on the steps, not the jargon. Without help, you should cover:
- The response comes back with
stop_reason: "tool_use". - Your code reads the
tool_useblock(s). - It runs the real tool with the given
input. - It wraps the output in a
tool_resultwith the matchingtool_use_id. - It sends that as a new
usermessage, together with the full earlier history. - The model reads the result and carries on.
If you have to check this doc, re-read The tool-use wire format, conceptually and The full loop, worked end-to-end with curl before moving on.
"Your per-turn token log shows non-zero cache_read_input_tokens after turn 1."
Copy the console output from a real run and save it where you track progress — a personal note, a commit message, anywhere. Don't just remember that it worked once. Proving your cache is actually hitting has the full check.
Common pitfalls in Phase 1
Read these before you run into them, not after:
- Putting
tool_resultblocks in a specialtoolrole. They go in auser-role message. Some other providers' APIs (and some frameworks) use atoolrole, so this is the most common first mistake. The API will reject or misread a message with the wrong role. - Sending tool definitions in a different order between calls. This quietly breaks caching (Proving your cache is actually hitting). Build your
toolslist from something with a fixed order — a slice, not a map — from the start. - Reading
max_tokensas "the model is done". It actually means "the reply was cut off". If atool_useblock is cut off in the middle of its JSON, it will fail to parse. The error looks like a bug in your JSON code, but the real cause is the token limit. - Building your own mini-framework instead of a plain loop. In Week 3, if you catch yourself adding a plugin system, a generic "step" type, or tools loaded from config — stop. That urge is a preview of the real frameworks in Phase 2. Building your own now defeats the point of doing this by hand.
- Skipping the "break it on purpose" experiments in The full loop, worked end-to-end with curl. Reading what a bad
tool_use_iddoes is not the same as seeing the real error. It takes five minutes. Later, when that exact error shows up in your Week 3 Go code, you will know at once what it means. - Leaving token logging until "the agent works". It is tempting to get the happy path working first and add logging later. But as Prompt caching — mental model and cache_control and Context windows — what actually fills them up explain, cost and context problems often don't show up in the happy-path output. Add
logTurnUsageto your very first working loop, not later.