> For the complete documentation index, see [llms.txt](/llms.txt).
> A full single-fetch corpus is available at [llms-full.txt](/llms-full.txt).
---
last_verified: 2026-10-09
title: Agents
description: Create agents with new Agent(), run or stream them, hand off between agents, and hook into the loop with callbacks
category: TypeScript SDK
hideRightSidebar: true
---

An agent is a model running in a loop with instructions and tools: it calls tools until it can answer. For a guided introduction, see [Agents](/docs/build/agents.md).

## `new Agent(options)`

```typescript
import { Agent, LM, tool, fn } from '@agnt5/sdk';
import type { Context } from '@agnt5/sdk';

const getWeather = tool(
  'get_weather',
  {
    description: 'Get the weather for a city',
    inputSchema: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] },
  },
  async (ctx: Context, input: { city: string }) => `Sunny, 22°C in ${input.city}`,
);

const weatherAgent = new Agent({
  name: 'weather_agent',
  model: LM.openai(),
  modelName: 'openai/gpt-6-luna',
  instructions: 'Answer weather questions. Call get_weather for the city.',
  tools: [getWeather],
});

export const askWeather = fn('ask_weather').run(async (ctx: Context, input: { message: string }) => {
  const result = await weatherAgent.run(input.message, ctx);
  return result.output;
});
```

### `AgentOptions`

| Option | Required | Description |
|---|---|---|
| `name` | Yes | The agent's name, shown in traces. |
| `model` | Yes | The model client, for example `LM.openai()` or `LM.anthropic()`. See [LM](/sdk/typescript/lm.md). |
| `modelName` | | The model to call, as `provider/model`, for example `'openai/gpt-6-luna'`. |
| `instructions` | Yes | The system instructions. |
| `tools` | | [Tools](/sdk/typescript/tools.md) the agent can call. An `Agent` in this list is called as a tool named after the agent. |
| `handoffs` | | Agents to hand the conversation to. See [Handoffs](#handoffs). |
| `maxIterations` | | Most model calls in one run. Default `10`. |
| `maxHandoffDepth` | | Most handoffs in a chain. |
| `builtInTools` | | Provider-hosted tools such as web search. |
| `cache` | | [Prompt caching](/docs/build/prompt-caching.md) policy, for example `{ ttl: '1h' }`. |
| `callbacks` | | Hooks around the agent, model calls, and tool calls. See [Callbacks](#callbacks). |
| `sandbox` | | A [sandbox](/docs/build/sandboxes.md) for file and code tools. |
| `skills`, `skillsDir` | | [Skills](/docs/build/skills.md) the agent can load. |
| `agentsMd` | | `AGENTS.md` guidance. See [Skills](/docs/build/skills.md). |

## Run an agent

### `agent.run(message, ctx?, history?, options?)`

Runs the loop and resolves to an `AgentResult`. Pass the handler's `ctx` so model and tool calls are traced inside the run.

| `AgentResult` field | Description |
|---|---|
| `output` | The agent's final answer. |
| `toolCalls` | Each tool call: `name`, `arguments` (a JSON string), `iteration`, and `id`. |
| `handoffTo` | The name of the agent that took over, or `null`. |
| `handoffMetadata` | Details of the handoff. |
| `context` | The context the run used. |

### `agent.stream(message, ctx?, history?, options?)`

An async generator that yields events while the agent runs, then the `AgentResult` last:

```typescript
for await (const event of weatherAgent.stream(input.message, ctx)) {
  if ('eventType' in event && event.eventType === 'lm.message.delta') {
    process.stdout.write(event.content ?? '');
  }
}
```

Event types include `agent.started`, `agent.iteration.started`, `tool_call.started`, `tool_call.completed`, `lm.message.start`, `lm.message.delta`, `lm.message.stop`, `agent.iteration.completed`, and `agent.completed`.

### `agent.chat(message, messages, ctx?)`

Sends one turn of a conversation and resolves to `[reply, messages]`, where `messages` is the history with the new user message and the reply appended. Pass it back on the next turn:

```typescript
const [reply, history] = await agent.chat('My order number is 4512.', [], ctx);
const [next] = await agent.chat('What was my order number?', history, ctx);
```

Use `run()` or `stream()` when the agent needs to call tools.

## Handoffs

`handoff(agent, description?)` lets an agent pass the conversation to another agent. The run's `handoffTo` names the agent that answered:

```typescript
import { handoff } from '@agnt5/sdk';

const billing = new Agent({
  name: 'billing',
  model: LM.openai(),
  modelName: 'openai/gpt-6-luna',
  instructions: 'You handle billing questions.',
});

const triage = new Agent({
  name: 'triage',
  model: LM.openai(),
  modelName: 'openai/gpt-6-luna',
  instructions: 'Route billing questions to the billing agent.',
  handoffs: [handoff(billing, 'Billing questions')],
});

const result = await triage.run('I was charged twice', ctx);
// result.handoffTo === 'billing'
```

To get another agent's answer back as a tool result instead of handing off, put the agent in `tools`.

## Callbacks

Callbacks run around the agent, each model call, and each tool call. Return nothing to continue, or return `callbackOverride(value)` to replace what would happen:

| Callback | Runs | Override |
|---|---|---|
| `beforeAgent(ctx)` | Before the loop starts | Returns this result without calling the model. |
| `afterAgent(ctx, result)` | After the loop ends | Replaces the result. |
| `beforeModel(ctx, request)` | Before each model call | Uses this response instead of calling the model. |
| `afterModel(ctx, request, response)` | After each model call | Replaces the response. |
| `beforeTool(ctx, call)` | Before each tool call | Uses this value as the tool result without running the tool. |
| `afterTool(ctx, call, result)` | After each tool call | Replaces the tool result. |

```typescript
import { callbackOverride } from '@agnt5/sdk';

const guarded = new Agent({
  name: 'guarded',
  model: LM.openai(),
  modelName: 'openai/gpt-6-luna',
  instructions: 'Answer weather questions.',
  tools: [getWeather],
  callbacks: {
    beforeTool: (_ctx, call) => {
      if (call.name === 'get_weather') return callbackOverride('Weather service is in maintenance.');
    },
  },
});
```

## Next steps

* [Tools](/sdk/typescript/tools.md): define the tools an agent calls.
* [LM](/sdk/typescript/lm.md): model clients and direct model calls.
* [Agents guide](/docs/build/agents.md): streaming, handoffs, and agents as tools in practice.
