Stream Responses and Run Tools
Stream generated text, run your own tools, and use provider tools such as web search with the native Generate API.
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.
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 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.
To run a saved AI Call on the socket, send generate.call instead of generate.request. It sends heartbeats while generation runs and returns the same result as POST /generate/call, including Call provenance and application data. Stored Calls do not use the interactive tool loop described below. See Run a Call Over the WebSocket.
Stream text over HTTP
To receive text and reasoning while the model produces them, send Accept: text/event-stream with POST /generate or POST /generate/call. 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.
{
"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 |
For a saved Call, the event may also include data.effectMayHaveOccurred: false and template details in data.issues. See Handle Saved Call Failures.
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:
{
"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
: keepalivecomment opens the HTTP200response. 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
200response withgenerate.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
schemaorobjectTypesends no deltas. The result arrives whole ingenerate.response. See Generate Structured Output. - 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.responseorgenerate.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
- Send a request with
toolsand eitherpromptormessages. Describe each tool's input with a JSON Schema ininputSchema. - If the response's
finishReasonistool-calls, itsmessagescontain anassistantmessage with atool-callpart for each call. Each part hastoolCallId,toolName, andargs. - Run each call that has no matching
tool-resultpart in the response. - Send the request again, with the same
tools, and withmessagesset to:- The messages you sent before. If you sent a
prompt, send it as the firstusermessage. - The response's
messages, unchanged. - One
toolmessage with atool-resultpart for each call you ran.
- The messages you sent before. If you sent a
- Repeat until
finishReasonis nottool-calls, within a turn or time limit set by your application. The final response has the answer intext, or inobjectfor structured output.
A tool-result part has these fields:
toolCallIdandtoolName: The values from the call.result: Any JSON value that your tool returned, or a description of what went wrong.isError: Optional. Set it totruewhen the tool failed. Use a message that the model can act on, such asNo 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:
{
"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:
{
"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:
{
"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 totrueto check each call'sargsagainst the tool'sinputSchema. The API does not return a call that fails the check. The model receives the validation error instead and can try again. If aninputSchemacannot be compiled, the API returns400before it calls a provider.- Structured output with tools: When a request with
schemaorobjectTypestops for tool calls, the response hasgenerationTypeset toobjectbut noobjectyet. This is a successful response. Continue the loop, and the final response has theobject.
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:
{
"route": "<ai-route-id>",
"prompt": "Summarize this week's news about electric vehicle charging standards.",
"providerTools": {
"openai": { "webSearch": {} },
"anthropic": { "webSearch": {} },
"google": { "webSearch": {} }
}
}
- Provider families:
openaicovers OpenAI and Azure OpenAI Connections.anthropiccovers Anthropic and Vertex AI Anthropic Connections.googlecovers 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
searchContextSizeanduserLocationand ignores other settings. - Results: The response lists the web sources in
sources, and a summary of each search inproviderToolActivity. Provider tools don't appear inmessages. - 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:
- The API sends
server.ready. - Your code sends
generate.request. Itsdatais the same body thatPOST /generateaccepts. - For each tool call, the API sends
generate.tool-callwithtoolCallId,toolName, andargs. Your code runs the tool and sendsgenerate.tool-resultwith the sametoolCallIdand aresult. - The API sends
generate.responsewith the complete response and closes the connection. If generation fails, it sendsgenerate.errorand closes the connection. Along withdata.error, the error can include the corresponding HTTPstatusand errorcode.
Keep these rules in mind:
- Set
maxSteps. It limits the number of model requests in the generation, and its default is1. The model sees your tool results only in a later step. SetmaxStepsto 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 inresult. - 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
retryAfterClientToolstofalsein the request. - Stream text if you need it. Add
?stream=trueto the URL to also receivegenerate.deltaevents. 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
heartbeatevent 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.