Streaming chat
Chat does not go through /v1/portal/*. It goes to the LLM proxy, the same
OpenAI-compatible surface agents use, authenticated with the user’s portal JWT. Every
governance step runs on it: model access for the workspace, limits, input and output
guardrails, knowledge-base grounding, the run ledger and evidence.
Send a turn
Section titled “Send a turn”The request the shipped portal sends (built in src/lib/aiSdkTransport.ts):
curl -sN http://localhost:8100/v1/proxy/llm/chat/completions \ -H "Content-Type: application/json" \ -H "X-Tenant-ID: default" \ -H "X-Gateway-Authorization: Bearer $JWT" \ -H "X-Resource-Group: group-01M61N376V2RR6J2TV7Q7EVRET" \ -H "X-Brutor-Run-Id: 01JZ8Q4W6V3G1R2T5Y7U9I0P1A" \ -H "X-Brutor-Session-Id: chat-01JZ8Q2N4K" \ -H "X-Brutor-Conversation-Handle: 01JZ8Q2N4KX6M3B7C9D1E5F0GH" \ -d '{ "model": "gpt-5.4-mini", "model_id": "llm-01KQGWDF0CQ1587ZH8K3T9721P", "messages": [ {"role": "user", "content": "Summarise our affordability rules in three bullets."} ], "stream": true }'import jsonimport requests
def stream_chat(model: dict, messages: list, run_id: str, handle: str): headers = portal.headers() | { "Content-Type": "application/json", "X-Brutor-Run-Id": run_id, "X-Brutor-Conversation-Handle": handle, } body = { "model": model["model_name"], "model_id": model["id"], "messages": messages, "stream": True, } with requests.post(f"{BASE}/v1/proxy/llm/chat/completions", headers=headers, json=body, stream=True, timeout=300) as r: r.raise_for_status() print("run:", r.headers.get("x-brutor-run-id")) if warning := r.headers.get("x-usage-warning"): print("usage warning:", warning) for line in r.iter_lines(decode_unicode=True): if not line or not line.startswith("data: "): continue payload = line[6:] if payload == "[DONE]": return chunk = json.loads(payload) for choice in chunk.get("choices", []): if text := choice.get("delta", {}).get("content"): yield text
for token in stream_chat(model, [{"role": "user", "content": "Hello"}], run_id="01JZ8Q4W6V3G1R2T5Y7U9I0P1A", handle="01JZ8Q2N4KX6M3B7C9D1E5F0GH"): print(token, end="", flush=True)export async function* streamChat(model, messages, { runId, handle, onRunId } = {}) { const res = await fetch(`${BASE}/v1/proxy/llm/chat/completions`, { method: "POST", headers: headers({ "Content-Type": "application/json", ...(runId && { "X-Brutor-Run-Id": runId }), ...(handle && { "X-Brutor-Conversation-Handle": handle }), }), body: JSON.stringify({ model: model.model_name, model_id: model.id, messages, stream: true, }), }); if (!res.ok) throw Object.assign(new Error(`HTTP ${res.status}`), { res }); onRunId?.(res.headers.get("x-brutor-run-id"));
const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = ""; for (;;) { const { done, value } = await reader.read(); if (done) return; buf += decoder.decode(value, { stream: true }); let cut; while ((cut = buf.indexOf("\n\n")) !== -1) { const frame = buf.slice(0, cut); buf = buf.slice(cut + 2); for (const line of frame.split("\n")) { if (!line.startsWith("data: ")) continue; const payload = line.slice(6); if (payload === "[DONE]") return; const delta = JSON.parse(payload).choices?.[0]?.delta?.content; if (delta) yield delta; } } }}The stream is text/event-stream, one OpenAI chunk per data: frame, ending with
data: [DONE]:
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant"},"index":0}]}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"delta":{"content":"- Disposable income"},"index":0}]}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"delta":{},"index":0,"finish_reason":"stop"}]}
data: [DONE]Split on blank lines, not on each network read: a frame can arrive across two reads. When
an output guardrail blocks mid-stream, the stream can end without a
finish_reason: "stop" chunk; your parser must tolerate that
(Streaming output guardrails).
What each part of the request does
Section titled “What each part of the request does”| Field or header | Example | Why |
|---|---|---|
model |
gpt-5.4-mini |
The model’s model_name from the catalog |
model_id |
llm-01KQGWDF0CQ1587ZH8K3T9721P |
The catalog id. Preferred when both are sent; keeps the call on the model this workspace was granted when names repeat. Never send it empty |
messages |
[{"role": "user", "content": "..."}] |
The full conversation so far: the gateway keeps no chat state (see Conversations) |
stream |
true |
SSE. false returns one OpenAI chat.completion object with usage |
temperature, max_tokens |
0.3, 1024 |
Optional. Leave them out unless the user set them: the gateway then injects the model’s configured defaults and clamps everything to the workspace’s caps |
tools, tool_choice |
[...], "auto" |
Only when the user connected MCP servers; see Tool calls. Omit tools entirely when empty |
X-Resource-Group |
group-01M61N376V2RR6J2TV7Q7EVRET |
The workspace. Send it on every call; without it the gateway falls back to the user’s primary_group_id, which can be unset or a different workspace |
X-Brutor-Run-Id |
01JZ8Q4W6V3G1R2T5Y7U9I0P1A |
Your id for this turn, the same on every call the turn makes |
X-Brutor-Session-Id |
chat-01JZ8Q2N4K |
Your id for the conversation |
X-Brutor-Conversation-Handle |
01JZ8Q2N4KX6M3B7C9D1E5F0GH |
Fresh ULID per conversation, links turns to the AI-interaction notice |
The three X-Brutor-* ids are explained on
Conversations, notice and feedback.
Response headers to read
Section titled “Response headers to read”| Header | Example | Use it to |
|---|---|---|
x-brutor-run-id |
06GSDAPWJY4T107B1PKHEY4HT1 |
Keep it with the rendered answer; it is the id for thumbs feedback. It is not the id you sent |
X-Brutor-AI-Generated |
true |
Label the answer as AI-generated, in the UI and in exports |
X-Usage-Warning |
Daily budget at 85%: $4.25 / $5.00 |
Tell the user before they hit the limit: a person mid-chat cannot retry into another budget |
x-correlation-id |
23edca88-b748-451e-ace4-abdf6f79d049 |
Quote it in support requests; it names this call’s audit row |
Read them from the response before consuming the body. In a browser, they are readable
because the proxy exposes all headers (Access-Control-Expose-Headers: *).
A non-streaming response is the standard OpenAI shape. When governance changed the request,
it carries an extra top-level brutor_governance field you can surface:
{ "id": "chatcmpl-abc123", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "- Disposable income ..."}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 412, "completion_tokens": 96, "total_tokens": 508}, "brutor_governance": { "max_tokens": {"requested": 50000, "applied": 2000, "reason": "capped"}, "system_prompt_fragment": {"applied": true, "source": "model_profile"} }}Errors on the chat path
Section titled “Errors on the chat path”Branch on the body before you blame the provider: a 403 or 429 from the gateway never
reached it.
| Status | Body | Your UI |
|---|---|---|
400 |
{"error": "Model 'gpt-5.5' only supports the Responses endpoint. POST to /v1/proxy/llm/responses with this model_name instead."} |
Switch endpoint for this model (below) |
401 |
{"error": "..."} with WWW-Authenticate |
Back to login |
403 |
{"error": {"code": "guardrail_blocked", "message": "PII detected in input: credit_card", ...}} |
Show the message; do not retry the same text |
403 |
model not granted to the workspace | Refresh the catalog with group_id |
429 |
rate limit or usage limit, with Retry-After |
Show a limit notice, back off |
Full shapes: LLM API error handling.
Models that need the Responses API
Section titled “Models that need the Responses API”When the catalog shows capabilities.requires_responses_api: true, send the turn to
POST /v1/proxy/llm/responses instead, reshaped to the Responses API: system messages
become instructions, the rest becomes input, and max_tokens becomes
max_output_tokens.
{ "model": "gpt-5.5", "model_id": "llm-01KQGWE3J8H5D2S9A7F4G6K1L0", "instructions": "You are a careful credit analyst.", "input": [{"role": "user", "content": "Summarise our affordability rules in three bullets."}], "stream": true}The same headers apply. The proxy does not translate between the two dialects; your client picks the endpoint per model, read at send time so a model switch takes effect on the next message. The streamed events are the provider’s Responses API events; see Responses API.
Attach documents
Section titled “Attach documents”The shipped portal reads attached files in the browser (text formats directly, PDFs
with PDF.js) and sends the extracted text, not the file. It places each document as a
leading system message, once, ahead of the conversation:
{ "model": "gpt-5.4-mini", "model_id": "llm-01KQGWDF0CQ1587ZH8K3T9721P", "messages": [ {"role": "system", "content": "--- Attached file: affordability-policy.pdf ---\nSection 3. Disposable income after the new instalment must ...\n--- End of affordability-policy.pdf ---"}, {"role": "user", "content": "Does a 36% post-loan DTI pass section 3?"} ], "stream": true}Putting the document in a stable position at the front, instead of inside each user message, means it is billed once per turn rather than once per message in the history, and provider prompt caches can reuse it. Input guardrails inspect it like any other content.
Images, speech and video
Section titled “Images, speech and video”The catalog lists media models by mode; each has its own proxy route, called with the same
headers:
| Mode | Route | Returns |
|---|---|---|
image_generation |
POST /v1/proxy/llm/images/generations |
data[].url or b64_json, plus brutor_file_id and brutor_cost_usd |
audio_speech |
POST /v1/proxy/llm/audio/speech |
Audio bytes; X-Brutor-Cost-USD, X-Brutor-File-Id headers |
audio_transcription |
POST /v1/proxy/llm/audio/transcriptions (multipart file, model) |
{text, language?, duration?, brutor_cost_usd} |
video_generation |
POST /v1/proxy/llm/video/generations, then poll GET /v1/proxy/llm/video/jobs/{job_id} |
A job; output_file_id once status is succeeded |
Generated media is stored by the gateway. A stored file’s signed URL expires; keep the
brutor_file_id with the message and mint a fresh URL with
GET /v1/proxy/files/{file_id}/url when you re-render an old chat. Use the model’s
supported_image_sizes, supported_voices, supported_video_durations and so on to fill
option pickers: a value outside the list answers 400. Bodies and fields:
Images, Audio,
Video, Files.
Related
Section titled “Related”- Conversations, notice and feedback: the run, session and conversation ids
- Tool calls and approvals in chat: when the model asks for a tool
- LLM API: the chat surface in depth
- Knowledge bases: how grounding is injected

