🎉 Cyber Week: Pro for $6/month for your first 3 months, or a full year of Pro for $59. Ends Sunday, December 6. See the deal →
← Building with AI APIs
Building with AI APIs · ProLesson 5 of 6 · 12 min

Build a small agent with tool use

Let the model call your functions in a loop, with limits, confirmations and logs that keep it safe.

With tool use, you describe functions the model may call (look up an order, search a database, create a ticket). The model decides when to call them and with what arguments; your code runs them and sends back the results. Repeat until the model has an answer, and you have an agent.

agent.ts
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();
const tools: Anthropic.Tool[] = [{
  name: 'get_order_status',
  description: 'Look up a customer order by ID (like A1001). Read-only.',
  input_schema: {
    type: 'object',
    properties: { order_id: { type: 'string', description: 'Order ID like A1001' } },
    required: ['order_id'],
  },
}];

const messages: Anthropic.MessageParam[] = [{ role: 'user', content: 'Where is my order A1001?' }];

for (let step = 0; step < 5; step++) { // hard limit on steps
  const res = await client.messages.create({ model: 'claude-sonnet-5-5', max_tokens: 1000, tools, messages });
  messages.push({ role: 'assistant', content: res.content });

  if (res.stop_reason !== 'tool_use') {
    for (const b of res.content) if (b.type === 'text') console.log(b.text);
    break;
  }
  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const b of res.content) {
    if (b.type !== 'tool_use') continue;
    console.log('tool call', b.name, JSON.stringify(b.input)); // log every call
    results.push({ type: 'tool_result', tool_use_id: b.id, content: await runTool(b.name, b.input) });
  }
  messages.push({ role: 'user', content: results });
}

Make it safe before you make it clever

Unlock the rest of this lesson with Pro

In this lesson

  • Make it safe before you make it clever
  • Hands-on practice with personal feedback from Arvid
  • A quick quiz to check what you learned

Unlock this lesson and every lesson in the Foundations, Advanced and Expert levels and all courses, plus certificates and a monthly allowance of AI practice, for $12/month.

Start free, upgrade anytime

Already have an account? Log in

Build a small agent with tool use · ArvidAI