> ## Documentation Index
> Fetch the complete documentation index at: https://docs.restate.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Agents

> Define an agent, run it in a handler, and handle its result.

An agent definition combines a model, instructions, tools, and limits. You define it once and run it from any handler.

## Define an agent

Create the agent at module scope with `agent()`:

```typescript {"CODE_LOAD::harness/src/agents.ts#define"}  theme={null}
const assistant = agent({
  model,
  instructions: "Answer support questions briefly.",
  maxSteps: 6,
});
```

The main options are:

| Option | Description |
| - | - |
| `model` | The model adapter. See [Models](https://docs.restate.dev/harness/models.md). |
| `instructions` | The system prompt, as a string or a generator function that reads the [run context](#run-context). |
| `tools` | A map of tool name to tool. See [Tools](https://docs.restate.dev/harness/tools.md). |
| `output` | A Zod schema for [typed output](#typed-output). |
| `maxSteps`, `maxToolCalls` | Maximum number of steps and tool calls per run. See [Limits](#limits). |

## Run an agent

Run the agent with `yield* agent.run(input)`:

```typescript {"CODE_LOAD::harness/src/agents.ts#run"}  theme={null}
export const support = restate.service({
  name: "Support",
  handlers: {
    *ask(question: string) {
      const result = yield* assistant.run(question);
      if (result.status !== "completed") return result.output ?? result.reason;
      return result.output;
    },
  },
});
```

Without the `conversation` or `messages` option, each call to `run` starts a run without history. To keep history between requests, see [Choose a service or a Virtual Object](#choose-a-service-or-a-virtual-object).

## Choose a service or a Virtual Object

Run the agent in a service when each request is a self-contained task. Run it in a [Virtual Object](https://docs.restate.dev/foundations/services.md#virtual-object) with a conversation when a request continues an earlier one, such as the next turn of a chat.

* **Service: each request is a self-contained task.** The handler calls `agent.run(input)` without a conversation, so each request starts a new conversation, and the caller doesn't need a key. Examples: [classify a ticket](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/04_structured_output.ts), [write a research report](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/08_research_report.ts), and [run a coding task in a sandbox](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/11_coding_agent.ts).
* **Virtual Object: requests to the same key are follow-ups.** The handler passes `conversation: new Conversation()` to `run`. The object key identifies the session, customer, or thread. Restate runs one exclusive handler per key at a time, so each conversation has one writer. Examples: [chat](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/03_conversation.ts), [support session](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/09_support_session.ts), and the [quickstart](https://docs.restate.dev/ai-quickstart.md). See [Sessions](https://docs.restate.dev/harness/sessions.md).

A conversation can outlive the resources that its runs used. If the agent creates a resource per request, such as the sandbox in the coding task example, the history of a later request refers to a resource that no longer exists. Run such an agent in a service, or keep the resource per key. See [Sandboxes](https://docs.restate.dev/harness/sandboxes.md).

A Virtual Object handler that runs the same agent several times in one request can also use a conversation, so that each run has the earlier runs in its history. See [Review loop](https://docs.restate.dev/harness/workflows.md#review-loop).

## Run results

`run` returns a `RunResult` with one of three statuses:

| Status | Meaning |
| - | - |
| `completed` | The model returned a final answer. `output` holds the answer. |
| `stopped` | The run reached `maxSteps` or `maxToolCalls`. `reason` is `max_steps` or `max_tool_calls`. |
| `interrupted` | The application [interrupted](https://docs.restate.dev/harness/steering.md) the run. `reason` holds the interrupt reason. |

If the run fails, for example because a model call fails after its retries or a reply is cut off at the output token limit, `run` throws instead of returning a result. See [Error handling](https://docs.restate.dev/harness/error-handling.md).

Read `output` as the answer only when the status is `completed`.
For a stopped or interrupted run, Restate Harness makes one more model call, without tools, that summarizes the run, and puts the summary in `output`. If that call fails, `output` holds a note that no summary could be generated.
Set `finalize` to the model for that call, or to `false` to skip it. It defaults to the agent's model.

Every result also includes the number of `steps`, the run's `messages`, and its token `usage`. `messages` holds the earlier messages, from `messages` or the loaded `conversation`, followed by the messages of this run. A conversation with a stored [summary](https://docs.restate.dev/harness/compaction.md#compaction-in-conversations) loads only the messages after the summary, so `messages` starts there.

## Typed output

Give the agent a Zod `output` schema. Restate Harness asks the model for output that matches the schema, validates the response, and asks again if the response doesn't match. Each new attempt counts toward `maxSteps`:

```typescript {"CODE_LOAD::harness/src/agents.ts#output"}  theme={null}
const triage = agent({
  model,
  instructions: "Classify the support request and summarize it in one sentence.",
  output: z.object({
    category: z.enum(["billing", "technical", "other"]),
    summary: z.string(),
  }),
});

export const ticketTriage = restate.service({
  name: "TicketTriage",
  handlers: {
    *classify(message: string) {
      const result = yield* triage.run(message);
      if (result.status !== "completed") {
        throw new TerminalError(`Triage ${result.status}: ${result.reason}`);
      }
      return result.output; // {category, summary}
    },
  },
});
```

`result.output` has the type that the schema defines. The schema must convert to JSON Schema, so Zod transforms aren't supported.
For OpenAI models, see [structured output with OpenAI](https://docs.restate.dev/harness/models.md#openai-structured-output).

When the output feeds the next step of your code, throw a `TerminalError` for a stopped or interrupted run, as in the example.

## Run context

Declare a context type on the agent and pass the context to `run`.
Restate Harness passes the context to the `instructions` function, to every tool, and to every guardrail. It doesn't add the context to model requests: only what your instructions and tools put into the prompt reaches the model:

```typescript {"CODE_LOAD::harness/src/agents.ts#context"}  theme={null}
type Customer = {customerId: string; plan: "free" | "pro"};

const accountAgent = agent<Customer>({
  model,
  *instructions({context}) {
    return `You help customer ${context.customerId}, who is on the ${context.plan} plan.`;
  },
});

export const accounts = restate.object({
  name: "Accounts",
  handlers: {
    *ask(question: string) {
      const customerId = restate.handlerRequest().key!;
      const plan = (yield* restate.state().get<"free" | "pro">("plan")) ?? "free";
      const result = yield* accountAgent.run(question, {context: {customerId, plan}});
      return result.status === "completed" ? result.output : (result.output ?? result.reason);
    },
  },
});
```

When the agent declares a context type, `run` requires the `context` option.
Use the context for trusted data, such as user IDs, prices, and limits, instead of letting the model supply these values as tool arguments.

## Run names

If a handler starts more than one run of the same agent, or of agents without a `name`, for example in a loop or a race, give each run a distinct `name`. Without one, a run uses the agent's `name`, or `agent` if the agent has none:

```typescript theme={null}
const draft = yield* writer.run(task, {name: `write-${i}`});
```

Restate Harness includes the name in the run's approval signal names, so an approval for one run can't resolve a tool call in another. See [Agents in workflows](https://docs.restate.dev/harness/workflows.md#review-loop) for a complete example.

## Limits

| Option | Default | Effect |
| - | - | - |
| `maxSteps` | 10 | Steps per run, including the final answer. A step whose model call a [guardrail](https://docs.restate.dev/harness/guardrails.md) rejects also counts. The run stops with `max_steps` when it reaches the limit. |
| `maxToolCalls` | 128 | Tool calls per run, including nested calls, such as the calls made from [code mode](https://docs.restate.dev/harness/code-mode.md). If a step requests more calls than remain, none of them run, and the run stops with `max_tool_calls`. A nested call over the limit also stops the run. |
| `maxToolDepth` | 16 | Depth of nested tool calls. A deeper call fails with the code `depth_limit`. |
| `maxOutputTokens` | Unset | Tokens per model reply. When it's unset, the model's provider chooses the limit. A reply cut off at the limit fails the run. See [Reply limit](https://docs.restate.dev/harness/models.md#reply-limit). |
| `maxOutputChars` | 128000 | Characters of model text, tool output, and final output. A tool output over the limit fails the tool call with the code `output_limit`. |

Reaching `maxSteps` or `maxToolCalls` stops the run with a result, not an error.
Retries are configured separately on the [model](https://docs.restate.dev/harness/models.md#retries) and on each [tool](https://docs.restate.dev/harness/tools.md#async-tools).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.