> ## 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.

# Models

> Connect agents to model providers, and configure retries, caching, and reasoning.

Restate Harness journals each model call as one durable step with its own retry policy.

| Model | Adapter |
| - | - |
| OpenAI, Anthropic, Amazon Bedrock, Google, and other [Vercel AI SDK](https://ai-sdk.dev) providers | `aiModel` from `@restatedev/harness/provider` |
| A model served by another Restate handler | `modelGateway` from `@restatedev/harness/provider` |
| Your own client, or a test fixture | `journaledModel` from `@restatedev/harness` |

## Providers

Restate Harness connects to providers through the Vercel AI SDK. The AI SDK implements each provider's API, and Restate Harness runs the agent loop, the tools, the retries, and the journaling.

1. Install the provider package, for example `@ai-sdk/openai`, `@ai-sdk/anthropic`, `@ai-sdk/amazon-bedrock`, `@ai-sdk/google`, `@ai-sdk/mistral`, or `@openrouter/ai-sdk-provider`.
2. Create the provider's model and wrap it with `aiModel`:

```typescript {"CODE_LOAD::harness/src/models.ts#openai"}  theme={null}
import {openai} from "@ai-sdk/openai";
import {aiModel} from "@restatedev/harness/provider";

const model = aiModel({model: openai("gpt-5.6-luna")});
```

The provider reads its credentials, such as `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`, when the agent makes a model call, not when you create the model.
To pass an API key, a base URL, or a custom `fetch` explicitly, create the provider with its factory function, such as `createOpenAI` or `createAmazonBedrock`.

The OpenAI provider uses the Responses API. For a server that implements only the Chat Completions API, use `createOpenAI({baseURL, apiKey}).chat(modelId)`.

## Retries

A model call makes three attempts by default. When the attempts run out, the agent run throws a `TerminalError`. Pass `retry` to change the policy:

```typescript {"CODE_LOAD::harness/src/models.ts#anthropic"}  theme={null}
import {anthropic} from "@ai-sdk/anthropic";

const claude = aiModel({
  model: anthropic("claude-sonnet-5-5"),
  retry: {maxAttempts: 5, initialInterval: {milliseconds: 500}, exponentiationFactor: 2},
});
```

`aiModel` turns off the AI SDK's own retries, so the `retry` policy controls all attempts.
When the provider throttles a call, the next attempt waits for the delay that the provider requests, for example in a `retry-after` header.

Some failures can't be fixed by retrying, such as a missing API key, a feature that the provider doesn't support, or a request that the provider rejects.
`aiModel` fails these calls immediately, and `run` throws a `TerminalError`. For a rejected request, the error code is the provider's HTTP status code.
A request that is longer than the model's context window is the exception: the run shrinks its context and sends the request once more. See [Context window](https://docs.restate.dev/harness/compaction.md#context-window).

A response that the model can fix, such as an empty reply or one stopped by a content filter, goes back to the model as a note instead of being retried. A reply cut off at the [reply limit](#reply-limit) fails the run instead. See [Model call failures](https://docs.restate.dev/harness/error-handling.md#model-call-failures).

## Reply limit

`maxOutputTokens` on the agent limits the tokens of each model reply, including compaction summaries that the agent's model writes, but not the summary of a stopped or interrupted run. When it's unset, Restate Harness leaves it out of the request, and the AI SDK provider chooses the limit:

| Provider | Limit when `maxOutputTokens` is unset |
| - | - |
| `@ai-sdk/anthropic` | The model's maximum from the provider's own table, such as 128,000 for recent Claude models, or 4,096 for a model that the table doesn't list. The provider also lowers a `maxOutputTokens` above a known maximum, with a warning. |
| `@ai-sdk/openai`, `@ai-sdk/google`, `@ai-sdk/openai-compatible` | The default of the model's API, because the request carries no limit |
| `@ai-sdk/amazon-bedrock` | The default of the model's API, because the request carries no limit. For Claude with a thinking budget (`reasoningConfig: {type: "enabled", budgetTokens}`), the provider sets the budget plus 4,096. |
| `@ai-sdk/gateway` | Vercel AI Gateway chooses the limit |

A reply cut off at the limit fails the run, so set `maxOutputTokens` when you expect long replies. See [Model call failures](https://docs.restate.dev/harness/error-handling.md#model-call-failures).

## Prompt caching

Prompt caching is on by default.
For Anthropic and Bedrock, `aiModel` marks the instructions, the newest message, and the end of the previous request as cache points, so each step reads the previous step's prefix from the cache.
Other providers ignore these markers.
Pass `caching: false` to send no cache points, for example for a Bedrock model without prompt caching.

## Reasoning models

Configure reasoning through the provider's options. For example, turn on adaptive thinking for Claude:

```typescript {"CODE_LOAD::harness/src/models.ts#reasoning"}  theme={null}
const thinkingModel = aiModel({
  model: anthropic("claude-sonnet-5-5"),
  providerOptions: {anthropic: {thinking: {type: "adaptive"}}},
});
```

For OpenAI, set `reasoningEffort`. For Gemini, set `thinkingConfig`.
Reasoning tokens count toward the [reply limit](#reply-limit): with `aiModel`, a reply whose output tokens, reasoning included, reach `maxOutputTokens` counts as cut off. If you set `maxOutputTokens`, leave room for the reasoning.

`aiModel` keeps the model's reasoning and sends it back on later requests, across the steps of a run and the runs of a conversation.
Don't edit the stored reasoning: providers reject reasoning that was changed.

> [!WARNING]
>
> For OpenAI, `aiModel` sets `store: false` by default.
> If you set `providerOptions: {openai: {store: true}}`, the conversation refers to reasoning that OpenAI stores, by default for 30 days.
> After OpenAI deletes it, later runs of the conversation refer to reasoning that no longer exists.
> Keep the default for long-lived conversations.

## OpenAI structured output

OpenAI structured output uses strict mode, which requires every property in the schema:

* Use `.nullable()` instead of `.optional()` in an `output` schema.
* For open-ended keys, such as `z.record()` or `.passthrough()`, pass `providerOptions: {openai: {strictJsonSchema: false}}`.

With `strictJsonSchema: false`, Restate Harness still validates the final answer against the `output` schema.

## Token usage

`result.usage` sums the tokens of every model call in the run, including the summary of a stopped or interrupted run, compaction summaries, sub-agents run with `agentTool`, and forks. It doesn't count model calls that tools or hooks make:

| Field | Description |
| - | - |
| `inputTokens` | Input tokens, including cache reads and writes |
| `outputTokens` | Output tokens |
| `totalTokens` | `inputTokens + outputTokens` |
| `cachedInputTokens` | Input tokens read from the cache |
| `cacheWriteInputTokens` | Input tokens written to the cache |

When `run` throws, `usageOf(error)` returns the totals up to the failure.
Record them only for a `TerminalError`: Restate retries other errors, and the replay counts the same calls again.

## Model gateway

`modelGateway` sends model requests to another Restate handler. Use it to keep provider keys, quotas, or routing in one service:

```typescript {"CODE_LOAD::harness/src/models.ts#gateway"}  theme={null}
import {modelGateway} from "@restatedev/harness/provider";

// A service that owns the provider keys, quotas, and routing.
export const modelService = restate.service({
  name: "ModelService",
  handlers: {
    *generate(request: ModelRequest) {
      return yield* model(request);
    },
  },
});

// Agents in other services send their model requests to it.
const viaGateway = modelGateway((request) => restate.client(modelService).generate(request));
```

## Custom models

A model is a generator function that takes a `ModelRequest` and returns a `ModelResponse`. Wrap any other client with `journaledModel`, which journals each call:

```typescript {"CODE_LOAD::harness/src/models.ts#custom"}  theme={null}
const customModel = journaledModel(async (request, {signal}) => {
  const response = await myLlmClient.complete(request, {signal});
  return {
    type: "final",
    text: response.text,
    usage: {inputTokens: response.inputTokens, outputTokens: response.outputTokens},
  };
});
```

A response is `{type: "final", text}`, `{type: "tool_calls", calls}`, or, for a reply cut off at the output token limit, `{type: "cut_off", text, calls}` with the tool calls whose arguments are complete. A cut-off reply fails the run, as it does with `aiModel`. Throw a `TerminalError` for a failure that a retry would repeat, such as an invalid API key. The run then fails instead of retrying.
When the provider rejects a request as longer than the model's context window, throw a `ContextOverflowError`, so that the run shrinks its context and asks again. See [Context window](https://docs.restate.dev/harness/compaction.md#context-window).
Include `usage` in the response, so that `result.usage` counts the call's tokens.

In the Restate UI, each step's model call appears as a journal entry named `Ask model`. With `modelGateway`, the agent's journal shows a call to the gateway handler, and the `Ask model` entry is in the gateway's invocation. Summary calls set the request's `name`: `Summarize stopped run`, and `Compact context` for [compaction](https://docs.restate.dev/harness/compaction.md). `journaledModel` names the entry after the request's `name`, then its own `name` option, then `Ask model`.


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