Loading learning content…
Loading learning content…
Build and configure a production-ready single agent with tools, memory, and error handling.
Read through the lesson, mark it complete when the concept is clear, then move to the next lesson in the sequence or jump back to the module map.
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
const tools = [
{
name: "web_search",
description: "Search the web for current information",
input_schema: {
type: "object",
properties: {
query: { type: "string", description: "Search query" }
},
required: ["query"]
}
}
];
async function runAgent(userMessage: string) {
const messages = [{ role: "user", content: userMessage }];
while (true) {
const response = await client.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 4096,
tools,
messages,
system: "You are a research assistant. Use tools to gather information."
});
if (response.stop_reason === "end_turn") {
return response.content;
}
if (response.stop_reason === "tool_use") {
const toolUse = response.content.find(c => c.type === "tool_use");
const toolResult = await executeTool(toolUse);
messages.push({ role: "assistant", content: response.content });
messages.push({ role: "user", content: [toolResult] });
}
}
}
System prompt — Define the agent's role, capabilities, and constraints clearly. This is the most important configuration.
Tool selection — Give the agent only the tools it needs. Fewer tools = less confusion and fewer edge cases.
Max iterations — Always cap the loop. An agent stuck in a bad state can loop forever. Set a max turns limit (10–20 for most tasks).
Error handling — Tool calls fail. Handle errors gracefully: retry with backoff, provide fallback behavior, or surface the failure cleanly.
For agents that maintain state across conversations, persist the message history to a database. On each new conversation, retrieve relevant history and inject it into context.
Don't try to maintain everything in memory — it doesn't scale and won't survive process restarts.