> ## 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 in workflows

> Run agents from your own code, as steps of a handler or as separate services: chains, parallel agents, worker services, routing, review loops, and races.

A handler can run agents as steps of a workflow, next to your own code and other durable operations, such as service calls, timers, and journaled calls to external APIs. Your code decides the control flow, and each run journals its model calls and the durable steps of its tools, so after a failure, the handler replays its journal and continues where it stopped.
To let the model decide when another agent takes part in a run, see [Sub-agents, handoffs, and forks](https://docs.restate.dev/harness/sub-agents.md).

If a handler starts more than one run, give each run a distinct `name`. See [Run names](https://docs.restate.dev/harness/agents.md#run-names).

## Chains

Run agents one after the other, with your own code and durable steps in between. Typed output passes structured data from one step to the next:

```typescript {"CODE_LOAD::harness/src/workflows.ts#chain"}  theme={null}
const extractor = agent({
  model,
  instructions: "Extract the refund claim from the customer's email.",
  output: z.object({orderId: z.string(), amountCents: z.number().int().positive()}),
});
const replyWriter = agent({model, instructions: "Write a short reply to the customer about their refund claim."});

export const refundClaims = restate.service({
  name: "RefundClaims",
  handlers: {
    *process(email: string) {
      // 1. An agent extracts the claim
      const claim = yield* extractor.run(email, {name: "extract"});
      if (claim.status !== "completed") throw new TerminalError(`Extractor ${claim.status}`);

      // 2. Your code applies the refund policy, and a journaled step calls the payment API
      const {orderId, amountCents} = claim.output;
      let decision = "escalated to a person";
      if (amountCents <= 10_000) {
        const refund = yield* restate.run(() => issueRefund(orderId, amountCents), {name: "Issue refund"});
        decision = `refunded with ID ${refund.refundId}`;
      }

      // 3. Another agent writes the reply
      const reply = yield* replyWriter.run(JSON.stringify({orderId, decision}), {name: "reply"});
      if (reply.status !== "completed") throw new TerminalError(`Reply writer ${reply.status}`);
      return reply.output;
    },
  },
});
```

* Your code, not the model, applies the refund policy to the extracted amount.
* `restate.run` journals the result of the refund, so a replay returns it instead of calling the payment API again. Make the call idempotent, because a crash before Restate journals the result runs it again.
* To wait for a person between steps, for example before a large refund, wait for a [signal or an awakeable](https://docs.restate.dev/develop/ts/external-events.md). To let a person approve a tool call, see [Human approval](https://docs.restate.dev/harness/human-approval.md).

## Parallel agents

Start each run with `restate.spawn`, and wait for all of them with `restate.all`:

```typescript {"CODE_LOAD::harness/src/workflows.ts#parallel"}  theme={null}
const securityReviewer = agent({model, instructions: "Review the change for security issues."});
const performanceReviewer = agent({model, instructions: "Review the change for performance issues."});
const testReviewer = agent({model, instructions: "Review the change for missing tests."});
const summarizer = agent({model, instructions: "Merge the reviews into one list of findings, most severe first."});

export const changeReview = restate.service({
  name: "ChangeReview",
  handlers: {
    *review(diff: string) {
      // The three reviews run at the same time
      const [security, performance, tests] = yield* restate.all([
        restate.spawn(securityReviewer.run(diff, {name: "security"})),
        restate.spawn(performanceReviewer.run(diff, {name: "performance"})),
        restate.spawn(testReviewer.run(diff, {name: "tests"})),
      ]);
      for (const review of [security, performance, tests]) {
        if (review.status !== "completed") throw new TerminalError(`Review ${review.status}`);
      }
      const reviews = {security: security.output, performance: performance.output, tests: tests.output};
      const summary = yield* summarizer.run(JSON.stringify(reviews), {name: "summary"});
      if (summary.status !== "completed") throw new TerminalError(`Summarizer ${summary.status}`);
      return summary.output;
    },
  },
});
```

The runs execute concurrently in the handler's invocation, and each journals its own model calls and tool steps.
To give each agent its own invocation, make it a [worker service](#worker-services).
Runs that save to a conversation need a conversation each. See [Parallel runs](#parallel-runs).

## Worker services

Make each worker a service, and fan out typed calls from an orchestrator:

```typescript {"CODE_LOAD::harness/src/multi_agent.ts#workers"}  theme={null}
export const researchWorker = restate.service({
  name: "ResearchWorker",
  handlers: {
    *research(question: string) {
      const result = yield* researcher.run(question);
      if (result.status !== "completed") throw new TerminalError(`Research ${result.status}`);
      return result.output;
    },
  },
});

export const researchReport = restate.service({
  name: "ResearchReport",
  handlers: {
    *generate(topic: string) {
      const plan = yield* planner.run(topic, {name: "planner"});
      if (plan.status !== "completed") throw new TerminalError(`Planner ${plan.status}`);
      const findings = yield* restate.all(
        plan.output.questions.map((question) => restate.client(researchWorker).research(question)),
      );
      const report = yield* reportWriter.run(JSON.stringify({topic, findings}), {name: "writer"});
      if (report.status !== "completed") throw new TerminalError(`Writer ${report.status}`);
      return report.output;
    },
  },
});
```

Each worker invocation has its own journal, retries, and entry in the Restate UI. Cancelling the orchestrator cancels the unfinished workers.
If the workers are Virtual Objects, call each one under its own key, because Restate runs one exclusive handler per key at a time. The [peer review example](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/15_peer_review_rpc.ts) calls each reviewer under the key `<review key>/<focus>`.

## Routing

A router agent with typed output picks the specialist, and your code runs it:

```typescript {"CODE_LOAD::harness/src/multi_agent.ts#routing"}  theme={null}
const router = agent({
  model,
  instructions: "Choose the one specialist best suited to the question. Classify only.",
  output: z.object({specialist: z.enum(["billing", "account", "product"])}),
});
const specialists = {billing, account, product};

export const supportRouter = restate.service({
  name: "SupportRouter",
  handlers: {
    *ask(question: string) {
      const routed = yield* router.run(question, {name: "router"});
      if (routed.status !== "completed") throw new TerminalError(`Router ${routed.status}`);
      const result = yield* specialists[routed.output.specialist].run(question, {name: "specialist"});
      if (result.status !== "completed") return result.output ?? result.reason;
      return result.output;
    },
  },
});
```

## Review loop

Run a writer and a reviewer in a bounded loop:

```typescript {"CODE_LOAD::harness/src/multi_agent.ts#loop"}  theme={null}
let code = "";
let feedback = "";
for (let i = 1; i <= 3; i++) {
  const draft = yield* writer.run(JSON.stringify({task, code, feedback}), {name: `write-${i}`});
  if (draft.status !== "completed") throw new TerminalError(`Writer ${draft.status}`);
  code = draft.output.code;
  const review = yield* reviewer.run(JSON.stringify({task, code}), {name: `review-${i}`});
  if (review.status !== "completed") throw new TerminalError(`Reviewer ${review.status}`);
  if (review.output.approved) return code;
  feedback = review.output.feedback;
}
return code;
```

Each input to the writer above repeats the earlier draft. Alternatively, run the loop in a Virtual Object and give each agent its own conversation, with its own `stateKey`, such as `new Conversation({stateKey: "writer"})`. The writer's input for a revision is then only the reviewer's feedback, and the writer's conversation history already contains its earlier drafts, as in the [evaluator-optimizer example](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/05_evaluator_optimizer.ts). The same works across handlers: in the [peer review example](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/15_peer_review_rpc.ts), `PeerAuthor.revise` passes only the reviews to the author agent.

## Racing

Run agents concurrently, keep the first successful answer, and cancel the other runs:

```typescript {"CODE_LOAD::harness/src/multi_agent.ts#race"}  theme={null}
function* answerWith(name: string, candidate: Agent<undefined>, question: string, messages: readonly Message[] = []) {
  const result = yield* candidate.run(question, {name, messages});
  if (result.status !== "completed") throw new TerminalError(`${name} ${result.status}`);
  return result;
}

function* firstSuccess<T>(tasks: restate.Task<T>[]) {
  try {
    return yield* restate.any(tasks); // the first success wins
  } catch (error) {
    // Every run failed terminally: stop retrying the handler
    const failures: unknown[] = error instanceof AggregateError ? error.errors : [];
    if (failures.length && failures.every((e) => e instanceof TerminalError)) {
      throw new TerminalError("No agent produced an answer");
    }
    throw error;
  } finally {
    for (const task of tasks) task.interrupt(); // cancel the other runs
    yield* restate.allSettled(tasks);
  }
}

export const racingAgents = restate.service({
  name: "RacingAgents",
  handlers: {
    *ask(question: string) {
      const winner = yield* firstSuccess([
        restate.spawn(answerWith("fast", fast, question)),
        restate.spawn(answerWith("thorough", thorough, question)),
      ]);
      return winner.output;
    },
  },
});
```

`restate.any` returns the first successful result and ignores failed runs. If every run fails, it throws an `AggregateError`, which Restate retries. When every run failed with a `TerminalError`, a retry would fail the same way, so `firstSuccess` throws a `TerminalError` instead.
Interrupting the losing task cancels its model call and tools, and `restate.allSettled` waits until the cleanup finishes.

## Conversations

A [`Conversation`](https://docs.restate.dev/harness/sessions#conversation-history) accepts the messages of one run at a time. Two runs that use one conversation at the same time in one handler, for example in `restate.all`, load the same version: the first one to [save](https://docs.restate.dev/harness/sessions.md#saving-progress) succeeds, and the other one throws `ConversationConflictError` at its next save, which fails the handler. The messages that the first run saved stay in the conversation.

### Parallel runs

Give each run its own conversation with `stateKey`:

```typescript {"CODE_LOAD::harness/src/multi_agent.ts#parallel_conversations"}  theme={null}
export const tripSession = restate.object({
  name: "TripSession",
  handlers: {
    *plan(request: string) {
      const [flights, hotels] = yield* restate.all([
        restate.spawn(flightAgent.run(request, {
          name: "flights",
          conversation: new Conversation({stateKey: "conversation/flights"}),
        })),
        restate.spawn(hotelAgent.run(request, {
          name: "hotels",
          conversation: new Conversation({stateKey: "conversation/hotels"}),
        })),
      ]);
      return {flights: flights.output, hotels: hotels.output};
    },
  },
  options: {
    state: {
      preload: [
        "conversation/flights/meta", "conversation/flights/summary",
        "conversation/hotels/meta", "conversation/hotels/summary",
      ],
    },
  },
});
```

Each run loads only its own conversation. The object preloads the metadata and summary keys of both conversations, so each run fetches only the chunks that it reads. See [Several conversations](https://docs.restate.dev/harness/sessions.md#several-conversations) for the keys that each conversation uses.

### Racing runs

Racing runs can't share a conversation either: the first run to save, for example at its first tool call or because it stopped early, makes the other runs fail at their next save, even if it doesn't produce the answer. To keep one history that contains the winning answer, load the conversation once, pass its messages to every run, and save only the winner's messages. The handler uses `answerWith` and `firstSuccess` from [Racing](#racing):

```typescript {"CODE_LOAD::harness/src/multi_agent.ts#race_conversation"}  theme={null}
export const racingSession = restate.object({
  name: "RacingSession",
  handlers: {
    *ask(question: string) {
      const conversation = new Conversation();
      const {messages, version} = yield* conversation.load();
      const winner = yield* firstSuccess([
        restate.spawn(answerWith("fast", fast, question, messages)),
        restate.spawn(answerWith("thorough", thorough, question, messages)),
      ]);
      // Save only the winner's turn: its messages after the loaded history
      yield* conversation.append(winner.messages.slice(messages.length), version);
      return winner.output;
    },
  },
  options: {state: {preload: ["conversation/meta", "conversation/summary"]}},
});
```

* `load` returns the messages and the version. `append` saves the new messages if the version is unchanged.
* The runs receive `messages` instead of the conversation, so the losing runs save nothing.
* A run that receives `messages` doesn't store its [summaries](https://docs.restate.dev/harness/compaction.md#compaction-in-conversations) in the conversation. If other runs store summaries in it, `load` returns only the messages after the last summary, and the summary itself in `summary`. The runs in this example receive only `messages`, so their model calls don't include that summary.


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