# Stream Responses and Run Tools

These instructions apply to the legacy Admin Console.

This page shows how to stream text and run tools with the native Generate API: `POST /generate` and its WebSocket. If your code uses the OpenAI Chat Completions format, see [Use an OpenAI Chat Completions client](https://docs.contextual.io/legacy/tenants/tenant-apis/ai-gateway-api.md#use-an-openai-chat-completions-client).

The base URL is `https://ai-gateway.<tenant-id>.my.contextual.io/api/v1`. The hostname identifies your tenant, so you don't need the `x-org-id` header. If you send the header, its value must match the tenant ID in the hostname.

See [Get and use an access token](https://docs.contextual.io/legacy/tenants/tenant-apis/authentication-and-permissions.md#get-and-use-an-access-token) for authentication setup. The JSON examples below illustrate request and response data. Response examples omit unrelated fields; their values are illustrative.

## Choose HTTP or the WebSocket

Tools can run in two places:

* **Tools that your code runs**, or client tools. You describe them in `tools`, and the model asks your code to run them. For example, a tool can look up an order in your own system.
* **Tools that the provider runs**, or provider tools, such as web search. You turn them on in `providerTools`, and they run at the provider during the request.

For client tools, choose how your code exchanges tool calls and results with the API:

| | HTTP (`POST /generate`) | WebSocket (`/generate/ws`) |
| --- | --- | --- |
| Who runs the tool loop | Your code, with one request for each round of tool calls | The API, over one connection |
| Clients | Any HTTP client | A client that can set the `Authorization` header on the connection request. The browser's built-in `WebSocket` API cannot. |
| Time to run a tool | No limit. Send the next request when your tool finishes. | Each tool call must be answered within the tool timeout, 600 seconds by default. |
| Conversation state | None. Each request carries the full history. | Kept on the open connection, and lost if the connection drops |
| Retry a round | Send the same request again. | Start a new generation. |

Use HTTP for most backend integrations, and for tools that can take a long time. Use the WebSocket from a server process that wants the API to run several rounds of tool calls without resending the history.

## Stream text over HTTP

To receive text and reasoning while the model produces them, send `Accept: text/event-stream` with `POST /generate`. The request body is the same as for a JSON response. With `Accept: application/json` or `*/*`, you receive one JSON response when generation ends.

This example sends an inline prompt to `POST /generate`.

```json
{
  "route": "<ai-route-id>",
  "prompt": "Explain AI Route fallbacks in three sentences."
}
```

### Read the events

Each event is a `data:` line with a JSON object followed by a blank line. The object has `type` and `data` fields. Ignore `: keepalive` comments when reading events.

| `type` | When it arrives | `data` |
| --- | --- | --- |
| `generate.delta` | While the model writes | `id`, `type` (`text` or `reasoning`), `text`, and `model`, the provider model that writes it |
| `generate.fallback` | Before the first delta or the response, one for each provider attempt that failed | The failed attempt's provider, model, and error |
| `generate.response` | Last, when generation succeeds | The complete response, the same as the JSON response |
| `generate.error` | Last, if a request fails after the stream opens | `error`, optional HTTP `status` and `code`, and `providerErrors` when providers reported errors |

A delta with empty `text` starts a text or reasoning block. Later deltas with the same `id` add to that block. IDs are local to each provider step, so an empty start opens a new block even if an earlier step used the same ID.

Use `generate.response` as the result, not the text you collected from deltas. It holds the final `messages`, which you need to continue the conversation, and the token usage, warnings, sources, and provider details.

This stream format differs from the Chat Completions stream. It has no `event:` lines and no `[DONE]` marker, so a Chat Completions stream parser cannot read it.

For example, one text delta has this JSON envelope:

```json
{
  "type": "generate.delta",
  "data": {
    "id": "text-1",
    "type": "text",
    "text": "An AI Route chooses a provider and model.",
    "model": "<provider-model>"
  }
}
```

### Know what streaming changes

* **Keepalives.** 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.
* **Errors.** Before the stream opens, failures use the usual HTTP status and JSON body. After it opens, a failure ends the `200` response with `generate.error`. Always read the final event.
* **Provider retries and fallback.** The AI Route can retry or try another provider before the first `generate.delta`. Once the Gateway sends a delta, it stops retrying or switching providers.
* **Structured output:** A request with `schema` or `objectType` sends no deltas. The result arrives whole in `generate.response`. See [Generate Structured Output](https://docs.contextual.io/legacy/tenants/tenant-apis/ai-gateway-api/structured-output.md).
* **Cancellation:** If you close the connection, the API cancels the provider request. If your code stops reading, the API pauses reading from the provider until your code reads again.
* **Incomplete streams:** If the connection ends without `generate.response` or `generate.error`, treat the response as incomplete.

## Run client tools over HTTP

Over HTTP, the API never runs your tools. When the model calls a tool, the API stops and returns the calls to you. Your code runs them and sends the results in the next request. Repeat until the model answers without calling a tool.

### Run the tool loop

1. Send a request with `tools` and either `prompt` or `messages`. Describe each tool's input with a JSON Schema in `inputSchema`.
2. If the response's `finishReason` is `tool-calls`, its `messages` contain an `assistant` message with a `tool-call` part for each call. Each part has `toolCallId`, `toolName`, and `args`.
3. Run each call that has no matching `tool-result` part in the response.
4. Send the request again, with the same `tools`, and with `messages` set to:
   1. The messages you sent before. If you sent a `prompt`, send it as the first `user` message.
   2. The response's `messages`, unchanged.
   3. One `tool` message with a `tool-result` part for each call you ran.
5. Repeat until `finishReason` is not `tool-calls`, within a turn or time limit set by your application. The final response has the answer in `text`, or in `object` for structured output.

A `tool-result` part has these fields:

* `toolCallId` and `toolName`: The values from the call.
* `result`: Any JSON value that your tool returned, or a description of what went wrong.
* `isError`: Optional. Set it to `true` when the tool failed. Use a message that the model can act on, such as `No order with ID A-1001`.

### Keep the history complete and unchanged

The API keeps no conversation state between requests, so each request must carry the full history. Append the response's `messages` exactly as you received them. Their parts can carry `providerOptions` that the provider needs to continue, such as Anthropic thinking signatures, Gemini thought signatures, and OpenAI item IDs. If you remove or change them, the provider can reject the next request or lose the model's earlier reasoning.

Send the same `tools` in every request. The model can call only the tools in the current request, and some providers reject a history with tool calls when the request has no tools.

### Example Request and Continuation

This request describes an order lookup that your application implements:

```json
{
  "route": "<ai-route-id>",
  "prompt": "Where is order A-1001?",
  "tools": {
    "lookup_order": {
      "description": "Look up an order by ID",
      "inputSchema": {
        "type": "object",
        "properties": { "orderId": { "type": "string" } },
        "required": ["orderId"]
      }
    }
  }
}
```

If the model requests the tool, the response includes data like this:

```json
{
  "generationType": "text",
  "finishReason": "tool-calls",
  "messages": [
    {
      "role": "assistant",
      "content": [
        {
          "type": "tool-call",
          "toolCallId": "call_lookup_1",
          "toolName": "lookup_order",
          "args": { "orderId": "A-1001" }
        }
      ]
    }
  ]
}
```

Your application runs the lookup. Send the request again with the same `route`, `tools`, and other options, replacing `prompt` with the following `messages` field:

```json
{
  "messages": [
    { "role": "user", "content": "Where is order A-1001?" },
    {
      "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": { "orderId": "A-1001", "status": "shipped" }
        }
      ]
    }
  ]
}
```

Use the actual tool call and result from your exchange. Preserve any additional fields in the returned messages, as described above.

The model chooses when to call a tool and which arguments to send. Treat the arguments as untrusted input. In your tool code, check them and check that the caller may perform the action.

You can also stream each round. Send `Accept: text/event-stream`, and take the `messages` from the final `generate.response` event.

### Control and check tool calls

* **`toolChoice`:** Set how the model may use your tools: `auto`, the default, `none`, `required`, or one tool, as in `{ "type": "tool", "toolName": "lookup_order" }`.
* **`validation.toolInput`:** Set to `true` to check each call's `args` against the tool's `inputSchema`. The API does not return a call that fails the check. The model receives the validation error instead and can try again. If an `inputSchema` cannot be compiled, the API returns `400` before it calls a provider.
* **Structured output with tools:** When a request with `schema` or `objectType` stops for tool calls, the response has `generationType` set to `object` but no `object` yet. This is a successful response. Continue the loop, and the final response has the `object`.

## Use provider tools

Provider tools run at the provider during the request. You don't run or answer them. Web search, `webSearch`, is the provider tool that the API supports.

Turn it on in `providerTools`, under the provider family of each provider that your AI Route can select:

```json
{
  "route": "<ai-route-id>",
  "prompt": "Summarize this week's news about electric vehicle charging standards.",
  "providerTools": {
    "openai": { "webSearch": {} },
    "anthropic": { "webSearch": {} },
    "google": { "webSearch": {} }
  }
}
```

* **Provider families:** `openai` covers OpenAI and Azure OpenAI Connections. `anthropic` covers Anthropic and Vertex AI Anthropic Connections. `google` covers Google AI (Gemini) and Vertex AI Connections. The API applies only the entry for the provider that runs the request, so add an entry for each family that your AI Route's fallbacks can reach.
* **Settings:** Put tool settings in the provider's own format inside the tool's object. The API passes them to the provider unchanged. For Azure OpenAI, the API uses only `searchContextSize` and `userLocation` and ignores other settings.
* **Results:** The response lists the web sources in `sources`, and a summary of each search in `providerToolActivity`. Provider tools don't appear in `messages`.
* **With client tools:** You can use provider tools and client tools in one request. Gemini models before Gemini 3 cannot combine them, so the API skips provider tools for those models when the request has client tools.
* **Not available:** Provider tools don't run on OpenAI Compatible Connections, and the Chat Completions endpoint doesn't accept them.

## Run tools over the WebSocket

On the WebSocket, the API runs the tool loop. It sends each tool call to your code as an event and continues the generation with your result. Connect to `wss://ai-gateway.<tenant-id>.my.contextual.io/api/v1/generate/ws` with an `Authorization: Bearer <access-token>` header on the connection request. Use a client that can set the authorization header on the connection request.

Each message, in either direction, is a JSON text frame with a `type` and `data`. One generation runs on each connection:

1. The API sends `server.ready`.
2. Your code sends `generate.request`. Its `data` is the same body that `POST /generate` accepts.
3. For each tool call, the API sends `generate.tool-call` with `toolCallId`, `toolName`, and `args`. Your code runs the tool and sends `generate.tool-result` with the same `toolCallId` and a `result`.
4. The API sends `generate.response` with the complete response and closes the connection. If generation fails, it sends `generate.error` and closes the connection. Along with `data.error`, the error can include the corresponding HTTP `status` and error `code`.

Keep these rules in mind:

* **Set `maxSteps`.** It limits the number of model requests in the generation, and its default is `1`. The model sees your tool results only in a later step. Set `maxSteps` to the number of tool rounds you allow, plus one.
* **Answer each call in time.** A call not answered within the tool timeout, 600 seconds by default, gets a timeout message as its result, and the generation continues.
* **Report tool errors in `result`.** A tool result has no error flag. Put a description that the model can act on in `result`.
* **Prevent repeated side effects.** By default, if a provider fails after your code received a tool call, the API can retry or try the next provider. That restarts the generation, so the model can request the same tool actions again. If your tools change data, set `retryAfterClientTools` to `false` in the request.
* **Stream text if you need it.** Add `?stream=true` to the URL to also receive `generate.delta` events. After the API sends a delta or a tool call, it does not retry or try another provider.
* **Keep the connection alive.** The API sends a `heartbeat` event every 10 seconds and a WebSocket ping every 25 seconds. Most clients answer pings automatically. If the connection closes, the API cancels the generation, and you must start again on a new connection.

For each message schema, see `GET /generate/ws` and the `GenerateEvent` schemas in the [Swagger reference](https://docs.contextual.io/legacy/tenants/tenant-apis/ai-gateway-api.md#base-url-and-reference).
