Build Your First AI Agent · Lesson 3 of 8
Lesson 3 — The tool-use loop
60 minutes. The core code pattern that turns Claude into an agent.
---
```js import Anthropic from '@anthropic-ai/sdk' const client = new Anthropic()
const tools = [/* the tool defs from Lesson 2 */] const messages = [{ role: 'user', content: 'Process this morning\'s inbox.' }]
while (true) { const res = await client.messages.create({ model: 'claude-sonnet-4-6', max_tokens: 2048, tools, messages, })
// Add the assistant turn to history messages.push({ role: 'assistant', content: res.content })
if (res.stop_reason === 'end_turn') { console.log('Final response:', extractText(res.content)) break }
if (res.stop_reason === 'tool_use') { const toolResults = [] for (const block of res.content) { if (block.type !== 'tool_use') continue const result = await runTool(block.name, block.input) toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: JSON.stringify(result), }) } messages.push({ role: 'user', content: toolResults }) // loop continues — model now has the tool results } } ```
That's it. That's an agent.
```js async function runTool(name, input) { switch (name) { case 'read_inbox': return await readInbox(input) case 'lookup_customer': return await lookupCustomer(input) case 'draft_reply': return await draftReply(input) case 'log_action': return await logAction(input) case 'request_approval': return await requestApproval(input) default: throw new Error(`Unknown tool: ${name}`) } } ```
Each branch calls a real function. `readInbox` might hit the Gmail API. `lookupCustomer` might query SQLite. We'll wire those up in Lesson 5.
The model is the brain. Your tools are the hands. The loop is the bloodstream carrying messages between them.
You'll spend most of your debugging time in three places:
- The tool descriptions — when the model picks the wrong tool, the description was unclear.
- The tool implementations — when the agent crashes, the tool threw an error you didn't catch.
- The system prompt — when the agent does weird things, the role and constraints weren't tight enough.
→ Lesson 4 — State, memory, and context
Previous: Lesson 2 — Tools and tool definitions · Next: Lesson 4 — State, memory, and context