# Run AI Calls From Code

These instructions apply to the current Admin Console.

{% hint style="info" %}
AI Calls are in early access and may not be available in your account. [Contact Contextual support](mailto:help@contextual.io) to request that AI Calls be enabled for your tenant.
{% endhint %}

An application runs a saved AI Call through AI Gateway's Call endpoints. It names the Call and a version, and sends variable values. The response holds the model's result and records which Call version and Route produced it. This page shows the HTTP contract with cURL and the WebSocket message format for long-running Calls.

Response bodies on this page are shortened examples that follow the response schema. They are not captured output.

For command-line inspection, previews, and generation, see the [AI Calls CLI Reference](https://docs.contextual.io/connect/ai-calls/contextual-cli.md).

## Before You Start

You need:

* A tenant with [AI Calls enabled](https://docs.contextual.io/connect/ai-calls.md#availability).
* A saved Call. See [Create and Manage AI Calls](https://docs.contextual.io/connect/ai-calls/create-and-manage.md).
* The AI Gateway API base URL for the environment, such as `https://ai-gateway.<tenant-id>.my.contextual.io/api/v1` for a production tenant.
* A bearer token with `native-object:ai-call:read`. To use a named label such as `stable`, the caller also needs `native-object:ai-call-label:read`. Generation requires read access to the Route and read plus reveal or update access to its AI Connections. To run or describe a Call with Object Type output, the caller also needs read access to that Object Type.
* The tenant ID. Send it in the `x-org-id` header. On a tenant host such as `https://ai-gateway.<tenant>.<domain>`, the header is optional. If you send it there, it must match.

See [Authentication and Permissions](https://docs.contextual.io/tenants/tenant-apis/authentication-and-permissions.md) to obtain a tenant access token. Keep the token on the server. The examples use these shell variables:

```sh
export AI_GATEWAY_URL="https://<gateway-host>/api/v1"
export TOKEN="<bearer token>"
export TENANT="<tenant ID>"
```

## Endpoints

Every Call endpoint is a `POST` with a JSON body.

| Endpoint | Body | What It Does | Calls a Model |
| --- | --- | --- | --- |
| `/generate/call` | `{ call, variables?, overrides?, messages?, data? }` | Renders the Call and runs it through its Route | Yes |
| `/generate/call/render` | Same as `/generate/call` | Returns the request the Call would send | No |
| `/generate/call/inspect` | `{ call }` | Lists the variables the Call needs and any content problems | No |
| `/generate/call/openapi` | `{ call }` | Returns an OpenAPI 3.1 document for running the Call with the requested version reference | No |
| `/generate/call/labels` | `{ id }` | Lists the current version and the Call's valid labels | No |
| `/generate/call/labels/update` | See [Change Labels From Code](#change-labels-from-code) | Assigns or removes labels | No |

Use `POST /generate/call` when the request names a saved Call. For direct generation with an inline prompt and a Route, see the [AI Gateway API](https://docs.contextual.io/tenants/tenant-apis/ai-gateway-api.md).

## Choose a Version Reference

The `call` object names the Call and which saved version to use. The choice controls when the application sees a newly saved version:

| `call` | Runs | Sees a Newly Saved Version |
| --- | --- | --- |
| `{ "id": "order-summary" }` | The current version | On the next request |
| `{ "id": "order-summary", "label": "latest" }` | The current version. It does not read labels. | On the next request |
| `{ "id": "order-summary", "label": "stable" }` | The version `stable` points at. AI Gateway resolves the label on each request. | When someone moves `stable` to it |
| `{ "id": "order-summary", "version": 3 }` | Version 3 | Never. Change the reference to change versions. |

* `version` is a positive integer. Send `version` or `label`, not both.
* A label that does not point at a version of this Call returns `404`. AI Gateway does not fall back to the current version.
* No reference pins the Route or the output Object Type. AI Gateway reads both when the request runs.

Use a label when an application should follow reviewed versions without a code change. Use an exact version to keep the saved Call content fixed. The Route, Object Type, and provider can still change, so this does not guarantee the same generated result. Use the current version for development.

## Run a Call

This example uses a Call with the ID `order-summary`. Its user text is `Summarize this order note for a support agent: {{note}}`, and its output is **Text**. [Create the Call](https://docs.contextual.io/connect/ai-calls/create-and-manage.md#create-a-call) with an AI Route you can use. Assign the [version label](https://docs.contextual.io/connect/ai-calls/create-and-manage.md#label-a-version) `stable` to the saved version. The examples show version 4. Your version number can differ.

{% stepper %}
{% step %}
### Check the Inputs

`/generate/call/inspect` lists the variables the selected version needs. It does not render the Call or call a model.

```sh
curl -sS "$AI_GATEWAY_URL/generate/call/inspect" \
  -H "Authorization: Bearer $TOKEN" \
  -H "x-org-id: $TENANT" \
  -H "Content-Type: application/json" \
  -d '{ "call": { "id": "order-summary", "label": "stable" } }'
```

```json
{
  "call": { "id": "order-summary", "version": 4, "hash": "<content hash>", "label": "stable" },
  "inputs": [{ "name": "note", "kind": "text", "locations": ["content.user"] }],
  "issues": []
}
```

`kind` is `text` or `messages`. A non-empty `issues` list means the version has a content problem that blocks rendering.
{% endstep %}

{% step %}
### Preview the Request

`/generate/call/render` returns the request the Call would send with your values. It does not call a model.

```sh
curl -sS "$AI_GATEWAY_URL/generate/call/render" \
  -H "Authorization: Bearer $TOKEN" \
  -H "x-org-id: $TENANT" \
  -H "Content-Type: application/json" \
  -d '{
    "call": { "id": "order-summary", "label": "stable" },
    "variables": { "note": "Customer reports the package arrived damaged." }
  }'
```

```json
{
  "call": { "id": "order-summary", "version": 4, "hash": "<content hash>", "label": "stable" },
  "route": { "id": "support-text", "overridden": false },
  "request": {
    "prompt": "Summarize this order note for a support agent: Customer reports the package arrived damaged."
  },
  "variables": ["note"],
  "data": {}
}
```

`request` is the rendered AI Gateway request, not the provider's wire format. Route defaults are applied only when the Call runs.
{% endstep %}

{% step %}
### Run the Call

`/generate/call` runs the Call through its Route. This calls the provider and uses tokens.

```sh
curl -sS "$AI_GATEWAY_URL/generate/call" \
  -H "Authorization: Bearer $TOKEN" \
  -H "x-org-id: $TENANT" \
  -H "Content-Type: application/json" \
  -d '{
    "call": { "id": "order-summary", "label": "stable" },
    "variables": { "note": "Customer reports the package arrived damaged." },
    "data": { "ticketId": "T-1001" }
  }'
```

```json
{
  "generationType": "text",
  "text": "<generated summary>",
  "finishReason": "stop",
  "providerType": "<provider>",
  "model": "<provider model>",
  "messages": [{ "role": "assistant", "content": [{ "type": "text", "text": "<generated summary>" }] }],
  "usage": { "inputTokens": 42, "outputTokens": 25, "totalTokens": 67 },
  "call": {
    "id": "order-summary",
    "version": 4,
    "hash": "<content hash>",
    "label": "stable",
    "route": { "id": "support-text", "version": 2, "hash": "<route hash>" }
  },
  "data": { "invocation": { "ticketId": "T-1001" } }
}
```

The full response also includes `steps`, `providerErrors`, and other diagnostic fields.
{% endstep %}
{% endstepper %}

## Request Fields

| Field | Use |
| --- | --- |
| `call` | The Call and version reference. See [Choose a Version Reference](#choose-a-version-reference). |
| `variables` | A value for each variable. Send a string for a text variable, or a list of messages for a message list variable. Values are inserted as written and never read as templates. Names the content does not use are ignored. |
| `overrides` | Changes for this request only: `route` (another Route the caller can read), `settings` (replaced field by field), and `providerOptions` (merged one option key deep). You cannot override the content. |
| `messages` | Messages appended after the rendered content. Use them to [continue after tool calls](#continue-after-tool-calls). They are sent as written and never read as templates. |
| `data` | Your own JSON. It is returned as `data.invocation` and never sent to the model. |

`variables` and `messages` cannot contain the hidden-secret placeholders `<ENCRYPTED>` or `<REMOVED>`.

## Read the Response

A Call response is a normal AI Gateway generation response with two added fields:

* **`call`** records what produced the result: the Call `id`, `version`, and content `hash`, the `label` the request named, and the Route `id`, `version`, and `hash`. Log these fields to trace a result to its exact prompt and Route.
* **`data`** holds the Call's saved application data in `data.call`, and your request's `data` in `data.invocation`.

`generationType` is `text` or `object`. A text result is in `text`. An object result is in `object`. For Object Type output, `objectType` reports the type ID, version, hash, and a digest of the schema the output was checked against.

### Stream the Response

For the general streaming and client tool workflow, see [Stream Responses and Run Tools](https://docs.contextual.io/tenants/tenant-apis/ai-gateway-api/streaming-and-tool-calling.md).

To receive text as the model produces it, send `Accept: text/event-stream` to `/generate/call`. Each event is a `data:` line with JSON:

* `generate.fallback` reports a provider that failed before any output.
* `generate.delta` carries new text or reasoning.
* `generate.response` carries the full JSON response, including `call` and `data`. The stream then ends.
* `generate.error` reports a failure after the stream opens. Read `data.error` for the message and `data.status` and `data.code` for the corresponding HTTP status and error code when present. See [Handle Saved Call Failures](#handle-saved-call-failures) to decide whether to retry.

There are no `event:` lines and no `[DONE]` marker. Object and array output arrives only in `generate.response`.

The first event or a `: keepalive` comment opens the HTTP `200` response. After 15 seconds of silence, the Gateway sends a keepalive every 15 seconds while the stream stays quiet. Ignore these comments when reading events.

Before the stream opens, failures use the usual HTTP status and JSON body. After it opens, read the terminal `generate.error` event to detect a failure even when the HTTP status is `200`. After a delta is sent, AI Gateway stops retrying or switching providers. Closing the connection cancels the provider request. If the stream ends without `generate.response` or `generate.error`, treat the result as incomplete.

## Run a Call Over the WebSocket

Connect to `wss://ai-gateway.<tenant-id>.my.contextual.io/api/v1/generate/ws` with an `Authorization: Bearer <access-token>` header. Use a server-side client that can set this header; the browser's built-in `WebSocket` API cannot. Tenant identification and permissions are the same as for HTTP, including the AI Calls feature flag and read access to the Call, Route, Connections, and any output Object Type.

After `server.ready`, send one `generate.call` message. Its `data` is the same request body that `POST /generate/call` accepts:

```json
{
  "type": "generate.call",
  "data": {
    "call": { "id": "order-summary", "label": "stable" },
    "variables": { "note": "Customer reports the package arrived damaged." },
    "data": { "ticketId": "T-1001" }
  }
}
```

The API answers `generate.received` and sends a `heartbeat` every 10 seconds while it works. On success, `generate.response.data` contains the full Call response, including `call` provenance and `data.call` / `data.invocation`, and the socket closes with code `1000`. Add `?stream=true` to receive text and reasoning deltas as well.

Heartbeats keep an otherwise idle connection active. The client or proxy's absolute deadline still applies. If the connection closes without a final response or error event, treat the outcome as unknown.

A refused or failed Call sends `generate.error` and closes with code `1011`. Read `data.error` for the message and `data.status` and `data.code` for the corresponding HTTP failure when present. For example, a tenant without AI Calls enabled receives `status: 403` and `code: "AI_CALLS_DISABLED"`. Other protocol errors can use different close codes. Check the [failure details](#handle-saved-call-failures) in the event to decide whether to retry.

Stored Calls run no client tool loop on the socket. When the model requests a client tool, the Call returns those requests in its response, just as over HTTP. Run the tools in your application and start another Call with the returned history as described below. The interactive `generate.tool-call` / `generate.tool-result` exchange applies to `generate.request`, not `generate.call`.

## Continue After Tool Calls

When the model requests a client tool, the response stops with `finishReason: "tool-calls"`. Its `messages` hold an `assistant` message with one `tool-call` part for each request. For **Object** or **Array** output, `object` is absent. This is a successful, pending response, not a failure.

AI Gateway keeps no conversation state between requests. Your application runs the tools and sends the history back:

1. Run each requested tool in your application.
2. Send `/generate/call` again with:
   * the same `variables` and `overrides`,
   * `call` set to the exact `version` from the first response's `call`. A label resolves again on every request, so a label moved during the exchange would change the version.
   * `messages` set to the response's `messages`, unchanged, followed by one `tool` message with a `tool-result` part for each call.
3. Repeat until `finishReason` is no longer `"tool-calls"`. On each turn, append the new response's `messages` and your next `tool` message after the earlier ones. Set an application turn or time limit so that repeated tool requests cannot continue indefinitely.

```json
{
  "call": { "id": "order-status", "version": 3 },
  "variables": { "orderId": "A-1001" },
  "messages": [
    {
      "role": "assistant",
      "content": [
        { "type": "tool-call", "toolCallId": "call_lookup_1", "toolName": "lookup_order", "args": { "orderId": "A-1001" } }
      ]
    },
    {
      "role": "tool",
      "content": [
        { "type": "tool-result", "toolCallId": "call_lookup_1", "toolName": "lookup_order", "result": { "status": "shipped" } }
      ]
    }
  ]
}
```

Do not repeat the rendered prompt in `messages`. AI Gateway renders the Call again and puts its content first. Keep every part exactly as returned, including `providerOptions` and `reasoning` parts. Providers need them to continue.

Use the real `toolCallId` and `toolName` from the response. Provider tools, such as web search, run at the provider and need no reply.

## Get an OpenAPI Document

`/generate/call/openapi` returns a standalone OpenAPI 3.1 document for `POST /generate/call`. It lists the selected version's variables, their kinds, and the output schema. It contains no saved prompt text, defaults, or connection details.

```sh
curl -sS "$AI_GATEWAY_URL/generate/call/openapi" \
  -H "Authorization: Bearer $TOKEN" \
  -H "x-org-id: $TENANT" \
  -H "Content-Type: application/json" \
  -d '{ "call": { "id": "order-summary", "label": "stable" } }'
```

A document requested by ID alone uses `call.label: "latest"`. If you request the document with `latest` or a named label such as `stable`, it keeps that label. AI Gateway resolves the label on each request. A document requested with an explicit `version` pins that version.

The input and output schemas describe the version resolved when you generated the document. When the version your client uses changes its required inputs or output shape, regenerate the document and update your client.

## Change Labels From Code

You can change labels in the [Admin Console](https://docs.contextual.io/connect/ai-calls/create-and-manage.md#label-versions). To change them from code, read the current labels before sending an update. The caller needs Call and label read access, plus `native-object:ai-call-label:create` for the first label record or `native-object:ai-call-label:update` for an existing record.

{% hint style="warning" %}
A label update changes which version every label-based request runs. Requests that use the label switch on their next request.
{% endhint %}

1. List the Call's labels:

   ```sh
   curl -sS "$AI_GATEWAY_URL/generate/call/labels" \
     -H "Authorization: Bearer $TOKEN" \
     -H "x-org-id: $TENANT" \
     -H "Content-Type: application/json" \
     -d '{ "id": "order-summary" }'
   ```

   ```json
   {
     "id": "order-summary",
     "current": { "version": 5, "hash": "<hash of version 5>" },
     "labels": [{ "label": "stable", "version": 4, "hash": "<hash of version 4>" }],
     "labelRecordHash": "<label record hash>"
   }
   ```

2. Send the update. This example points `stable` at version 5:

   ```sh
   curl -sS "$AI_GATEWAY_URL/generate/call/labels/update" \
     -H "Authorization: Bearer $TOKEN" \
     -H "x-org-id: $TENANT" \
     -H "Content-Type: application/json" \
     -d '{
       "call": { "id": "order-summary", "version": 5, "hash": "<hash of version 5>" },
       "labels": ["stable"],
       "remove": [],
       "expectedLabelRecordHash": "<label record hash>"
     }'
   ```

   A confirmed update returns `{ "call": { ... }, "labelRecordHash": "<new hash>", "changed": true }`.

Rules for the update:

* `expectedLabelRecordHash` is required. Copy `labelRecordHash` from the list response. Send `null` when it was `null`, which means the Call has no labels yet.
* Change at least one and at most 100 label names. A name cannot be in both `labels` and `remove`. `latest` is not allowed.
* AI Gateway checks that the target version still has the given `hash`. Labels you do not name are kept.

Never retry a label update automatically. Only a `4xx` response with `error.effectMayHaveOccurred: false` proves that nothing changed. Treat any other failure, or a lost response, as an unknown outcome. List the labels again and check the result before you plan another change. A failed label update never changes or removes a saved Call version.

## Call From a Managed Worker

* [Wait for One Result](#wait-for-one-result) when your handler needs the complete text or structured output before it continues.
* [Stream Text as It Arrives](#stream-text-as-it-arrives) when you want to relay text to a client during generation.

Use managed Event, HTTP, or Scheduled template 0.11.1 with Rust host 0.18.0, or a later compatible template. You can write the handler in TypeScript, Rust, Go, or Python. Find your adapter version and methods in [Saved AI Call Operations](https://docs.contextual.io/build/contextual-workers/managed-workers/raw-platform-calls.md#saved-ai-call-operations).

Enable AI Calls in the tenant and use a saved Call. The host authenticates with the Worker's platform OAuth client. That client needs the Call, label, Route, AI Connection, and output Object Type permissions listed in [Before You Start](#before-you-start). See [Managed Worker Access Errors](#managed-worker-access-errors) if the Call returns `401` or `403`.

### Wait for One Result

1. Use your adapter's [typed method for `ai.generateCall`](https://docs.contextual.io/build/contextual-workers/managed-workers/raw-platform-calls.md#saved-ai-call-operations).
2. Pass the saved Call reference and its variables. For the [`order-summary` Call](#run-a-call), send the Call ID, the `stable` label, and a value for `note`. Set `timeoutMs` in the same request if you need a deadline.
3. Wait for the completed result. The host handles keepalives while generation runs.

### Stream Text as It Arrives

Use your adapter’s [raw platform call method](https://docs.contextual.io/build/contextual-workers/managed-workers/raw-platform-calls.md#saved-ai-call-operations).

1. Start the same saved Call with `ai.session.streamCall`. Pass the Call reference, variables, and optional `timeoutMs`.
2. Call `ai.session.next` with an empty object to read each event. When a `generate.delta` event has `data.type` set to `text`, forward `data.text` to the client. Use `heartbeat` events to keep the client connection open.
3. When you receive `generate.response`, read the completed result from `data`. If the handler stops reading before then, call `ai.session.cancel` with an empty object before returning.

For an HTTP Worker, see [Stream HTTP Requests and Responses](https://docs.contextual.io/build/contextual-workers/managed-workers/capabilities.md#stream-http-requests-and-responses).

Heartbeats arrive about every 10 seconds. The host answers Gateway pings and checks the Call deadline while it waits in `ai.session.next`. The Gateway can close the connection after more than 60 seconds without an answer.

Keep each relay write well below 60 seconds. Set a shorter write timeout when less time remains in the Call or the Worker invocation. Have the write reject on timeout so the handler has time to cancel the session. If the Gateway returns an error, the connection drops, or the Call deadline expires while the host is waiting for the next event, the host closes the session.

### Read the Result

Read generated text from `text` or completed structured output from `object`. The `call` field identifies the Call version and Route. When `finishReason` is `"tool-calls"`, look in `messages` for assistant messages with `tool-call` parts in `content`. Run the tools in your application, then start another Call with the returned history and your tool results. See [Continue After Tool Calls](#continue-after-tool-calls).

### Set a Deadline and Handle Interruptions

Both methods accept `timeoutMs` from 1,000 to 1,800,000 ms and default to 300,000 ms. Leave enough time in the Worker invocation to handle the result. For an HTTP Worker, account for [`HTTP_TIMEOUT_MS`](https://docs.contextual.io/build/contextual-workers/managed-workers/templates-and-options.md#http-template). Heartbeats keep idle connections open. The Call and invocation deadlines still apply.

After a deadline or disconnect without a final result, generation may already have used tokens. Before sending the Call again, check [whether the failure proves that generation did not run](https://docs.contextual.io/build/contextual-workers/managed-workers/raw-platform-calls.md#saved-ai-call-operations).

On an older template, the [generic `services.request` method](https://docs.contextual.io/build/contextual-workers/managed-workers/platform-services.md) can still send a buffered HTTP Call when `PLATFORM_SERVICES` includes `aiGatewayApi` and the request finishes within 20 seconds.

## Troubleshooting

AI Gateway JSON errors use the body `{ "code": ..., "message": ..., "errors": [...] }`. `code` is a named code when one exists, otherwise the HTTP status.

| Status and Code | Cause | What to Do |
| --- | --- | --- |
| `403` `AI_CALLS_DISABLED` | AI Calls are unavailable in this tenant. | Check the tenant ID and [contact Contextual support](mailto:help@contextual.io) about availability. |
| `403` without `AI_CALLS_DISABLED`, or `401` | The token is missing, expired, or lacks `native-object:ai-call:read`, or Native Objects denied a read. | Check the token, tenant, and required read permissions. |
| `404` | The Call, version, label, Route, or output Object Type does not exist, or the label no longer points at a version. | Check the ID and reference. A missing label never falls back to the current version. |
| `400` "AI call template could not be rendered" | A variable has no value or the wrong kind, or the content has a template problem. `errors` lists each issue with a `code`, such as `missing_variable` or `wrong_kind`, and its location. | Fix the request's `variables`, or fix the content and save a new version. Do not retry unchanged. |
| `400` "AI call variables and messages cannot carry hidden secret placeholders" | `variables` or `messages` contain `<ENCRYPTED>` or `<REMOVED>`. | Send real values. Keep secrets in AI Connections. |
| `400` "Inline generation requests cannot reference a stored AI call; use POST /generate/call" | The request went to `POST /generate` with a `call` field. | Use `/generate/call`. |
| `422` | The saved Call is not valid, holds hidden secret values, or its Object Type schema or selected fields cannot be used for structured output. | Fix the Call or the Object Type, then save a new version. |
| `502` | AI Gateway could not read the Call or its Object Type, or the read returned a different record. | Keep the error details for troubleshooting. Treat the generation outcome as unknown. |
| `400` "All model providers failed to generate a response" | Every provider in the Route failed. `errors` lists each provider's error. | Check the Route and its AI Connections. |
| `200` with `finishReason: "tool-calls"` and no `object` | The model is waiting for client tool results. | [Continue after tool calls](#continue-after-tool-calls). |

For label updates, `409` `AI_CALL_LABEL_STATE_CONFLICT` means the labels changed since you listed them, and `409` `AI_CALL_TARGET_CONFLICT` means the target version's content hash changed. Both happen before any write: list the labels again and plan a new update. `AI_CALL_LABEL_WRITE_CONFLICT`, `AI_CALL_LABEL_WRITE_REJECTED`, and `502` `AI_CALL_LABEL_WRITE_UNKNOWN` mean the write may have happened. List the labels and check before you act.

### Handle Saved Call Failures

`effectMayHaveOccurred: false` confirms that AI Gateway refused the Call before generation or billing. In a JSON HTTP error, read `error.effectMayHaveOccurred`. In an HTTP stream or WebSocket `generate.error` event, read `data.effectMayHaveOccurred`. Fix the cause before retrying.

For template refusals, `errors` in the JSON error body or `data.issues` in the event lists the template issues. Each issue has `code`, `location`, and `message`. When it names a variable, it also includes `variable`. For example, `missing_variable` identifies an input your request needs to supply.

If an error omits the flag or the connection closes without a final response or error event, the outcome is unknown. Avoid replaying the Call automatically.

### Managed Worker Access Errors

If AI Gateway returns `401` or `403`, check the target tenant, the Call reference, and whether AI Calls are enabled. In TypeScript, find the Gateway status in `PlatformError.responseStatus` or in `responseStatus` on the [raw failure envelope](https://docs.contextual.io/build/contextual-workers/managed-workers/raw-platform-calls.md#the-envelope). If the managed identity still gets an access error, [contact Contextual support](mailto:help@contextual.io) to investigate its credentials or permissions. See [Worker Identity](https://docs.contextual.io/build/contextual-workers/managed-workers/platform-services.md#worker-identity).
