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 choices list. Do not read choices[0] without checking it exists. When stream_options.include_usage is true, a separate final chunk carries trace_id and call_id after a successful stream.
  • The gateway can refuse streaming before opening the stream with a 400 code ending in _streaming_unsupported. Retry only those refusals with stream=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.content

The 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 400 with a code ending in _streaming_unsupported means Forgebench cannot enforce a policy on a stream. Send the same request with stream=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: guardrail names the check (guardrails lists every one), direction is output and reason says what to change.
    • tool_registry_streaming_unsupported: an agent's key sent tools. See the tools recipe.
    • mcp_streaming_unsupported: the agent has MCP tools bound.
  • Image output (modalities containing image) is refused with a 400 when streaming. Set stream=false.
  • Strands Agents streams by default. For an agent with MCP or registry tools, build its OpenAIModel with stream=False in the model params; the model reads its stream config key on every call, so changing it with update_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.

Cookie settings

Our Cookie Policy lists every cookie and what it does.