Integrate: stream responses
Stream a model's answer to your user token by token, through the Forgebench gateway.
Detect
Find the calls that already stream, and the code that reads the chunks:
grep -rnoE "stream[[:space:]]*=[[:space:]]*True|stream:[[:space:]]*true|\.stream\(|streamText\(|text/event-stream|choices\[0\]\.delta|choices\?*\.\[0\]\?*\.delta" --include='*.py' --include='*.ts' --include='*.js' --include='*.tsx' --exclude-dir={node_modules,.git,.venv,dist,build} .Connect these calls first, as in the connect recipe. A streaming call needs no other change to reach the gateway.
Change
Keep stream=True and your chunk loop. Two things differ from a call that does not stream:
- A chunk can carry token usage and an empty
choiceslist. Do not readchoices[0]without checking it exists. Whenstream_options.include_usageistrue, a separate final chunk carriestrace_idandcall_idafter a successful stream. - The gateway can refuse streaming before opening the stream with a
400code ending in_streaming_unsupported. Retry only those refusals withstream=False.
Keep the model name the app already uses wherever a snippet shows YOUR_MODEL, and take model names from the Gateway model catalog. mock-gpt is only for the Verify step.
Python
import openai
def stream_answer(messages):
try:
stream = client.chat.completions.create(
model="YOUR_MODEL", messages=messages, stream=True,
)
for chunk in stream:
if not chunk.choices: # usage or correlation chunk
continue
delta = chunk.choices[0].delta.content
if delta:
yield delta
except openai.BadRequestError as e: # 400: streaming is refused for this request
if "streaming_unsupported" not in str(e):
raise
resp = client.chat.completions.create(model="YOUR_MODEL", messages=messages)
yield resp.choices[0].message.contentThe same pattern works with AsyncOpenAI: use async for and await.
TypeScript
import OpenAI from "openai";
async function* streamAnswer(messages: OpenAI.Chat.ChatCompletionMessageParam[]) {
try {
const stream = await client.chat.completions.create({
model: "YOUR_MODEL",
messages,
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content; // choices is empty on the usage chunk
if (delta) yield delta;
}
} catch (e) {
if (!(e instanceof OpenAI.BadRequestError) || !String(e.message).includes("streaming_unsupported")) throw e;
const res = await client.chat.completions.create({ model: "YOUR_MODEL", messages });
yield res.choices[0].message.content ?? "";
}
}curl
curl -N -X POST "$FORGEBENCH_BASE_URL/v1/chat/completions" \
-H "Authorization: Bearer $FORGEBENCH_API_KEY" -H "Content-Type: application/json" \
-d '{"model":"YOUR_MODEL","messages":[{"role":"user","content":"hello"}],"stream":true}'The stream ends with data: [DONE].
Env
FORGEBENCH_API_KEY and FORGEBENCH_BASE_URL, as in the connect recipe. Read them from the environment with no default value, add .env to .gitignore first, and name both in .env.example (no values).
Verify
Stream one call with mock-gpt and print the response headers. A streamed response carries its ids in the X-Trace-Id and X-Call-Id headers.
curl -sN -D - -o /dev/null -X POST "$FORGEBENCH_BASE_URL/v1/chat/completions" \
-H "Authorization: Bearer $FORGEBENCH_API_KEY" -H "Content-Type: application/json" \
-d '{"model":"mock-gpt","messages":[{"role":"user","content":"ping"}],"stream":true}' | grep -iE "x-trace-id|x-call-id"To read the ids from the body instead, set stream_options to {"include_usage": true}. After a successful stream, the last chunk before data: [DONE] has an empty choices list and carries trace_id and call_id. This correlation chunk is separate from the usage chunk.
Then run the app so that it streams one answer, and call forgebench_integrate verify with stream: true. It checks the newest call, so run the app just before and pass minutes: 2: an older call then cannot stand in for it. A streamed call stays pending until the stream ends: call it again after a few seconds.
What you get
The budget check runs before the first byte, so a call over budget fails immediately and costs nothing. The call is traced and audited like any other. Tokens are metered from the provider's usage report.
Pitfalls
- The budget check (
402) runs before the stream opens, so a refusal is an ordinary HTTP error, not a broken stream. Handle it as in the errors recipe. - A
400with a code ending in_streaming_unsupportedmeans Forgebench cannot enforce a policy on a stream. Send the same request withstream=false. The codes are:guardrail_streaming_unsupported: a guardrail is set to Block for responses, or a guard model that judges responses is set to fail closed. The body has the same fields as a blocked call:guardrailnames the check (guardrailslists every one),directionisoutputandreasonsays what to change.tool_registry_streaming_unsupported: an agent's key senttools. See the tools recipe.mcp_streaming_unsupported: the agent has MCP tools bound.
- Image output (
modalitiescontainingimage) is refused with a400when streaming. Setstream=false. - Strands Agents streams by default. For an agent with MCP or registry tools, build its
OpenAIModelwithstream=Falsein the model params; the model reads itsstreamconfig key on every call, so changing it withupdate_config(stream=False)also works on a live model. - Do not repeat a stream that has already started producing output: the tokens already produced are billed, and the repeat is billed again.
- If the client disconnects mid-stream, the tokens already produced are still metered and are not refunded.
- A streamed call's cost is computed from the provider's token usage, so it can differ slightly from the same call without streaming.

