How to build an AI agent: a tested TypeScript example
AI Techbom · AI Agents · · 8 min read
An AI agent is a language model that can call tools, look at the results and decide what to do next, in a loop, until it can answer. This tutorial builds a small one from scratch: it answers questions about orders and can move a delivery date, but only when a person has approved the change. It runs on a local model through Ollama, so it needs no API key, and every output below is what it actually printed.
Tested on 21 November 2026 with Node.js 26, Ollama 0.40.16 and the qwen2.5:3b model on a laptop CPU with no dedicated GPU, run with tsx 4. The code type-checks with TypeScript 5 in strict mode. On that laptop the first answer took about 27 seconds; a GPU or a hosted model is much faster.
1. Set up
Install Ollama from ollama.com, then download the model and create the project. The agent uses Node's built-in fetch, so the only packages are for running TypeScript.
ollama pull qwen2.5:3b
mkdir order-agent && cd order-agent
npm init -y
npm pkg set type=module
npm install -D tsx@4 typescript@5 @types/node@242. The four parts of an agent
- A model that supports tool calling. qwen2.5:3b does, and is small enough to run on a laptop.
- Tools, described with a name, a description and a JSON schema for their arguments. The model only ever sees these descriptions; your code runs the tool.
- A loop: send the conversation, run any tool calls the model asks for, add the results, and repeat until the model answers without calling a tool. A step limit stops it running forever.
- Guardrails in code, not in the prompt: here, changing a delivery date returns a refusal unless a person has approved it.
3. The code
// A small AI agent: a model, two tools, a loop, and an approval step.
// Runs against a local model through Ollama's chat API.
const MODEL = "qwen2.5:3b";
const OLLAMA_URL = "http://localhost:11434/api/chat";
// In a real agent these would call your order system.
const orders: Record<string, { status: string; deliveryDate: string }> = {
"1042": { status: "packed", deliveryDate: "2026-11-24" },
};
const tools = [
{
type: "function",
function: {
name: "get_order",
description: "Get the status and delivery date of an order by its number.",
parameters: {
type: "object",
properties: { order_id: { type: "string", description: "Order number, for example 1042" } },
required: ["order_id"],
},
},
},
{
type: "function",
function: {
name: "reschedule_delivery",
description: "Move an order's delivery to a new date (YYYY-MM-DD). Needs staff approval.",
parameters: {
type: "object",
properties: {
order_id: { type: "string" },
new_date: { type: "string", description: "New delivery date, YYYY-MM-DD" },
},
required: ["order_id", "new_date"],
},
},
},
];
// Anything that changes data waits for a person. Here a flag stands in for that person.
const approved = process.env.APPROVE === "yes";
function runTool(name: string, args: Record<string, string>): string {
const order = orders[args.order_id];
if (!order) return `No order ${args.order_id}.`;
if (name === "get_order") return JSON.stringify({ order_id: args.order_id, ...order });
if (name === "reschedule_delivery") {
if (!approved) return "Not done: a staff member must approve changes to delivery dates.";
order.deliveryDate = args.new_date;
return `Delivery for order ${args.order_id} moved to ${args.new_date}.`;
}
return `Unknown tool ${name}.`;
}
type Message = { role: string; content: string; tool_calls?: ToolCall[]; tool_name?: string };
type ToolCall = { function: { name: string; arguments: Record<string, string> } };
async function chat(messages: Message[]): Promise<Message> {
const response = await fetch(OLLAMA_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: MODEL, messages, tools, stream: false, options: { temperature: 0 } }),
});
if (!response.ok) throw new Error(`Ollama returned ${response.status}`);
const data = (await response.json()) as { message: Message };
return data.message;
}
export async function runAgent(request: string, maxSteps = 5): Promise<string> {
const messages: Message[] = [
{
role: "system",
content:
"You help customers with their orders. Use the tools to look things up; never guess order details. " +
"If a tool says a change was not done, tell the customer it needs staff approval.",
},
{ role: "user", content: request },
];
for (let step = 1; step <= maxSteps; step++) {
const reply = await chat(messages);
messages.push(reply);
if (!reply.tool_calls?.length) return reply.content; // no tool needed: this is the answer
for (const call of reply.tool_calls) {
const result = runTool(call.function.name, call.function.arguments);
console.log(` step ${step}: ${call.function.name}(${JSON.stringify(call.function.arguments)}) -> ${result}`);
messages.push({ role: "tool", tool_name: call.function.name, content: result });
}
}
return "Stopped: too many steps without an answer.";
}
const request = process.argv.slice(2).join(" ") || "Where is order 1042?";
console.log(`> ${request}`);
console.log(await runAgent(request));4. Run it
Ask about an order:
npx tsx agent.ts "Where is order 1042 and when will it arrive?"> Where is order 1042 and when will it arrive?
step 1: get_order({"order_id":"1042"}) -> {"order_id":"1042","status":"packed","deliveryDate":"2026-11-24"}
Order 1042 is currently in the "packed" status and is scheduled to arrive on November 24, 2026.Ask for a change without approval:
npx tsx agent.ts "Please move the delivery of order 1042 to 2026-11-26."> Please move the delivery of order 1042 to 2026-11-26.
step 1: reschedule_delivery({"order_id":"1042","new_date":"2026-11-26"}) -> Not done: a staff member must approve changes to delivery dates.
The delivery date for order 1042 cannot be changed at this time. It needs staff approval. Please contact customer support for further assistance.The same request with approval given (in PowerShell, set $env:APPROVE = "yes" first instead):
APPROVE=yes npx tsx agent.ts "Please move the delivery of order 1042 to 2026-11-26."> Please move the delivery of order 1042 to 2026-11-26.
step 1: reschedule_delivery({"new_date":"2026-11-26","order_id":"1042"}) -> Delivery for order 1042 moved to 2026-11-26.
The delivery of order 1042 has been successfully rescheduled to 2026-11-26.And an order that does not exist:
npx tsx agent.ts "Where is order 9999?"> Where is order 9999?
step 1: get_order({"order_id":"9999"}) -> No order 9999.
I'm sorry, but there is no order with the number 9999. Could you please provide the correct order number?5. What the output shows
- The model chose the right tool each time and filled in the arguments from the customer's words, including the date format the schema asked for.
- When the change was refused, the model passed that on instead of claiming success. The refusal came from the code, so a persuasive customer cannot talk the agent past it.
- For the missing order, it reported what the tool said rather than inventing a status.
- Each run needed one tool call. The loop allows up to five, for requests that need a look-up before a change.
6. Using a hosted model instead
Hosted model APIs use the same ideas: a list of messages, tool definitions with JSON schemas, and tool calls in the reply. Field names and the shape of tool results differ between providers, so only the chat function needs to change; the tools, the loop and the approval check stay as they are.
7. Before it goes near real customers
- Replace the flag with a real approval step: a person sees the proposed change and accepts or rejects it.
- Give each tool only the access it needs, and log every call with its arguments and result.
- Write a set of test requests, including awkward ones, and re-run it whenever you change the prompt, the tools or the model.
- Make tools safe to retry, so a repeated call never changes something twice.
- Keep the step limit, and return a clear message when it is reached.
Want an agent built around your own systems and approval rules? AI agent development