Welcome, Developer đź‘‹
You probably heard the word “agent” a lot this year. It sounds complicated, but the idea is simple. An agent is a loop. The model decides what to do, your code does it, and you send the result back to the model. You repeat this until the model has the answer.
Today we build one from scratch in TypeScript. No framework, around 50 lines of code.
Setup
Create a new folder and install the packages:
mkdir typescript-ai-agent && cd typescript-ai-agent
npm init -y
npm install @anthropic-ai/sdk
npm install -D typescript tsx @types/nodeTo get an API key, go to platform.claude.com, sign in (or create an account), then go to Settings → API keys and click Create key. Copy it right away, the Console only shows it once. Also good to know that the API is paid separately from a Claude Pro subscription, so you need some credits in your Console account before your first call.
Then set your API key in the terminal:
export ANTHROPIC_API_KEY=your-key-hereStep 1: Give the agent a tool
A tool is just a function the model can ask you to run. The model never runs it by itself. It only says “please call get_weather with Christchurch”, and your code does the real work.
Create a file called agent.ts:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
// this is how the model knows the tool exists and when to use it
const tools: Anthropic.Tool[] = [
{
name: "get_weather",
description: "Get the current temperature for a city",
input_schema: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"],
},
},
];
// here we run the real code for the tool (fake data for now)
function runTool(name: string, input: any): string {
console.log(`Calling ${name}`, input);
if (name === "get_weather") return `It is 23°C in ${input.city}`;
return "Unknown tool";
}Pay attention to the description. A good description is how the model decides if it should use the tool or not.
Step 2: The loop
This is the agent. In the same file:
async function runAgent(question: string) {
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: question },
];
// we keep looping until the model don't need any tool anymore
for (let step = 0; step < 5; step++) {
const response = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 1024,
tools,
messages,
});
messages.push({ role: "assistant", content: response.content });
// no tool asked, so the model has the final answer
if (response.stop_reason !== "tool_use") {
const text = response.content.find((b) => b.type === "text");
return text?.type === "text" ? text.text : "";
}
// the model asked for tools, so we run them and send back the results
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === "tool_use") {
results.push({
type: "tool_result",
tool_use_id: block.id,
content: runTool(block.name, block.input),
});
}
}
messages.push({ role: "user", content: results });
}
return "Stopped: too many steps";
}
runAgent("What's the weather in Christchurch?").then(console.log);Let’s look at what we send in client.messages.create. model is the Claude model that answers, max_tokens is the max size of the answer, tools is the list of tools the model can ask for, and messages is the whole conversation so far.
One important thing here: the model has no memory between calls. That’s why we keep adding everything to the messages array (the question, the model reply, the tool results) and send it all again every time. This array is the memory of your agent.
Every time we call the model, we check the stop_reason. If it is tool_use, the model wants a tool, so we run it and send the result back. If not, the model is done and we return the answer.
The step < 5 is a safety limit. Without it, a confused agent could loop forever and burn your tokens.
Step 3: Run it
npx tsx agent.tsYou should see something like this:
Calling get_weather { city: 'Christchurch' }
It's currently 23°C in Christchurch.That’s your first agent. The model read the question, decided it needed the weather, asked for the tool, got the result and wrote the answer.
Try it yourself
Now it’s your turn. First, replace the fake weather with real data from Open-Meteo. It’s free and doesn’t need an API key. Then add a second tool called get_time that returns the local time of a city, ask “What’s the weather and the time in Tokyo?” and watch the agent call both tools by itself.
A few hints if you get stuck. Open-Meteo needs latitude and longitude, so look up the city first with their geocoding API. It gives you the city timezone, which is all you need for the time. Since fetch is async, runTool becomes async too, so remember to await it in the loop.
If you want to see the full conversation the model receives, add console.log(JSON.stringify(messages, null, 2)) right before the final return. It’s the best way to understand the logic done by the model.
This is my code on GitHub.
What’s next
This agent is very basic on purpose. It has two simple tools and forgets everything when the script ends. In a real project you would call your own APIs or database inside runTool, handle errors, and save the conversation somewhere.
An agent is not magic, Developer. If you start from the basics, you’ll see it can be as simple as a loop with a model. Once you understand this, every agent framework out there will make much more sense, trust me!
Stay focused, Developer! 🚀