Skip to content

Your first agent

You will build an agent that answers questions about orders. It looks an order up with a tool, streams its answer as the model writes it and tells you why it stopped. You need this to see the whole loop run once.

A tool is a name, a description the model reads, an input schema and a function. This tool looks an order up in your own order store and returns its status:

lookup-order-tool.ts
/** An order, as your order store returns it. */
export interface Order {
id: number;
status: "processing" | "shipped" | "delivered";
}
/** Finds an order by its number in your own store. */
export type FindOrder = (id: number) => Promise<Order | undefined>;
/** Builds the `lookup_order` tool over your order store. */
export function lookupOrderTool(findOrder: FindOrder) {
return defineTool({
name: "lookup_order",
description: "Look up an order by its number and return its status.",
inputSchema: z.object({ order: z.number().int().positive() }),
async execute({ order }) {
const found = await findOrder(order);
if (found === undefined) return { content: [{ type: "text", text: `No order ${order} exists.` }], isError: true };
return { content: [{ type: "text", text: `Order ${order} is ${found.status}.` }], structured: found };
},
});
}

The schema checks the model’s arguments before your function runs, so a bad order number never reaches your store.

The loop needs a model, which binds one adapter to one model id. You make the adapter with your own key, so the gateway never guesses a provider:

import { createModel } from "@buildanagent/gateway";
import { anthropic } from "@buildanagent/gateway/anthropic";
declare const apiKey: string; // from your secret store
const model = createModel({ adapter: anthropic({ apiKey }), id: "claude-opus-5-5" });

run() starts the loop. It sends your system prompt and the question, runs each tool the model calls and sends the results back. It goes on until the model answers without calling a tool. Iterate the run to read its events as they stream:

order-agent.ts
const started = run({
model,
system: SYSTEM_PROMPT,
input: question,
tools: [lookupOrderTool(findOrder)],
maxSteps: MAX_STEPS,
});
for await (const event of started) {
if (event.type === "text_delta") write(event.delta);
}
const result = await started.result;

A run ends with a result, not an exception. Its stop reason says whether the model finished, hit the step limit or failed, and the agent turns each case into a message:

order-agent.ts
switch (result.stopReason) {
case "done":
return answerOf(result.messages);
case "error":
return `the model call failed: ${result.error.message}`;
default:
return `the run stopped early: ${result.stopReason}`;
}

Next, learn what the stream carries.

These docs are licensedCC BY 4.0. Thelicence text is in the repository.