Building an AI Agent
with Tool-Calling & APIs
A complete walkthrough of how modern LLM agents perceive, reason, and act — from first prompt to production loop.
What is an AI Agent?
An AI agent is a system where a language model doesn’t just generate text — it takes actions. The model reasons about a goal, decides which tools to invoke, executes them, observes results, and loops until the task is done.
Tool-Calling Explained
You describe tools (functions) to the model as JSON schemas. The model outputs structured calls; your code executes them and returns results back into the conversation context.
// 1. Define a tool const tools = [{ name: "search_web", description: "Search the internet for up-to-date info", input_schema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] } }]; // 2. Pass tools to the model const response = await anthropic.messages.create({ model: "claude-sonnet-4-6", tools, messages: [{ role: "user", content: userGoal }] });
The Agentic Loop
- 1
Send the user message + tool definitions to the LLM.
- 2
If the model responds with
stop_reason: "tool_use", extract the tool call. - 3
Execute the tool in your environment (API call, DB query, code run…).
- 4
Append the tool result as a
tool_resultmessage. - 5
Repeat until
stop_reason: "end_turn"— the agent is done.
while (true) { const res = await anthropic.messages.create({ messages }); if (res.stop_reason === "end_turn") break; for (const block of res.content) { if (block.type === "tool_use") { const result = await executeTool(block.name, block.input); messages.push(assistantMsg, toolResultMsg(block.id, result)); } } }
Common Agent Tools
Web Search
Live internet lookups via Brave, Tavily, or SerpAPI.
Database
SQL queries against Postgres, SQLite, or vector stores.
Code Exec
Run Python/JS sandboxed for calculations & data tasks.
REST APIs
Call any HTTP endpoint — Stripe, GitHub, Slack, etc.
File System
Read, write, and parse local or cloud files.
Memory
Store & retrieve facts across sessions with embeddings.
Design Tips
- ✦
Keep tool descriptions concise and unambiguous.
- ✦
Validate & sanitize all tool inputs before execution.
- ✦
Set a max-iterations guard to prevent infinite loops.
- ✦
Stream responses for better perceived latency.
Choosing a Pattern
- →
Single-agent — one LLM drives all tools.
- →
Orchestrator — a planner spawns sub-agents.
- →
ReAct loop — Reason + Act interleaved in one prompt.
- →
Plan & Execute — upfront plan, then sequential steps.

