Direct chat streaming

Clients can build their own interface without an iframe. Use two transports: text chat over server-sent events (SSE), and text plus voice over a metered WebSocket relay. The model and service instructions remain managed by the service. Text chat accepts an optional temperature from 0 to 1; omission defaults to 0.7. The same setting works with standard JSON and streaming replies. Invalid values return HTTP 422 before generation or billing. Temperature does not change pricing. Internal media-planning calls retain their service-controlled default. Realtime voice does not expose this parameter. Existing non-streaming requests continue to return JSON.

Mode Endpoint Billing
Text only POST /api/v2/chat with stream: true Same as normal chat: currently 1 credit per successful response
Text and voice POST /api/v2/voice/realtime/session, then its relay URL 15 credits per started minute of connected time

The legacy POST /api/v1/ollama/chat and /api/v1/ollama-chat routes also accept stream: true. This is a direct HTTP API feature; the MCP chat tool remains non-streaming.

Updated October 24, 2026. MCP tools | Companion in a Box.

Backend authentication and controls

Call these HTTP endpoints from your server with the existing API-Key and Client-ID headers. Keep both values on your server. Authenticate your members, apply your existing compliance screening and member spending controls, and choose the account and session configuration there. Do not forward arbitrary browser-supplied headers, system instructions, origin, or call limits.

The existing API authentication, account credits, shared service instructions, and voice minute billing remain in force. Direct sessions do not inherit a separate iframe widget session's character, history, budget reservations, media tools, or webhooks. Your backend must enforce any member-level budget across concurrent calls. The relay enforces the signed per-call time limit and the account's available credits.

Text only

Input Supported setting
messages Required nonempty array of system/user/assistant roles and nonempty string content; include prior turns for context
stream Optional boolean, default false; true selects SSE
temperature Optional number 0-1, default 0.7; supported on regular chat in either response mode
max_tokens Optional integer 1-4096, default 512; a maximum response length, not an exact word count
response_format Optional object with type json_object or json_schema; json_schema requires a json_schema object
idempotency_key Optional string of 1-128 characters for SSE requests; use a new value only for intentional new work

The separate /api/v2/chat/structured endpoint uses its own fixed response contract and does not expose stream, temperature, or a caller-selected response_format. Story and backstory endpoints return completed JSON rather than SSE.

Request to https://api.lightspeedcloud.ai/api/v2/chat:

{
  "messages": [{"role": "user", "content": "Hello"}],
  "stream": true,
  "temperature": 0.7,
  "idempotency_key": "a-unique-id-for-this-response"
}

Use a new idempotency_key for each intentional response. Reusing one returns HTTP 409 without generating or charging again, including when the original attempt failed. A retry that intentionally starts new work needs a new key. If omitted, the service generates a request ID.

Before streaming, normal authentication/validation/credit errors return JSON and a non-2xx status. Successful stream setup returns Content-Type: text/event-stream:

event: start
data: {"request_id":"a-unique-id-for-this-response"}

event: delta
data: {"text":"Hello"}

event: delta
data: {"text":" there!"}

event: done
data: {"request_id":"a-unique-id-for-this-response","charged_credits":1,"finish_reason":"stop"}

A credit is reserved atomically before generation, then finalized once after a complete, usable response. Empty, refused, and failed/incomplete transport responses are refunded. A completed response that reaches max_tokens (finish_reason: length) can still be charged; a token limit is not a transport failure. Streaming chunks are not separate requests or charges. Usage records remain type chat, request count 1, with the assembled response and elapsed time.

A terminal error event has code, message, charged_credits: 0, and discard: true. Treat deltas as provisional: clear the unfinished reply on this event. HTTP status cannot change after a stream begins. A dropped connection without a terminal event is an uncertain result; do not automatically retry. The server finishes the bounded generation and accounting even if the browser disconnects, charging a successfully completed response. Check usage using the request ID if necessary.

Proxy SSE from your backend without buffering, JSON decoding, caching, or response compression. Forward the event bytes as they arrive. A browser can consume the POST response with fetch and ReadableStream; native EventSource cannot POST this body. Structured JSON response_format is supported. Treat its deltas as incomplete JSON; validate the complete response before executing any tool calls. Backstory requests continue to use the ordinary JSON path.

Direct text and voice

Your backend POSTs to https://api.lightspeedcloud.ai/api/v2/voice/realtime/session with API-Key and Client-ID headers. At least 15 available credits are required. The following example explicitly selects hands-free mode; omission of turn_detection defaults to push-to-talk:

{
  "client_origin": "https://members.example.com",
  "instructions": "You are the character configured by our application. Keep replies concise.",
  "voice": "eve",
  "turn_detection": {"type": "server_vad", "silence_duration_ms": 1000},
  "call_limit_seconds": 120
}

client_origin must be an exact HTTPS origin with no path or trailing slash. It is bound to the signed token and checked before any upstream connection or debit. Include client_origin to select the direct protocol. Omission preserves the legacy iframe protocol and its existing origin restriction. Set call_limit_seconds to -1 for unlimited duration, still subject to credits; otherwise use a positive integer number of seconds. Omission retains the API's 300-second default. The /poc demo retains its five-minute cap.

The session response contains relay.url, relay.token, relay.call_limit_seconds, expires_at (Unix seconds), and billing (credits_per_minute: 15, block_seconds: 60, rounding: up, minimum_credits: 15). Return this session response to your browser. Its token expires after 60 seconds for connection establishment and is single-use. It contains encrypted account identity and instructions. It is not an account credential. Do not cache or log it. The browser opens relay.url and sends:

{"type":"auth","token":"the-issued-relay-token"}

Wait for relay.ready before sending content. The relay configures the upstream session and waits for acknowledgement before the first charge. Failed connection or configuration attempts are not charged. Once ready, connected time is billed, including silence and idle time. Always stop unused calls.

Supported browser events:

Event Fields Action
client.text text, nonempty, up to 12000 characters Send a user message and request text plus audio
client.audio audio, base64 PCM16 little-endian mono at 24000 Hz Append microphone audio; up to 96000 base64 characters per event
client.commit none Commit buffered microphone audio and request a reply
client.cancel none Cancel the current reply and clear uncommitted microphone audio
client.stop none End the call and finalize duration accounting

Omit turn_detection, or send {"type":"push_to_talk"}, to retain manual microphone commit. Set {"type":"server_vad"} on your backend session request for hands-free conversation. Settings are encrypted and signed with the trusted session policy; they cannot be changed through the browser WebSocket. Start a new call to change mode. The backend must validate the member's requested mode/timing and construct these fields explicitly, while retaining its fixed origin, instructions and limits.

Automatic setting Default Accepted range
silence_duration_ms 1000 Integer 500-2000
prefix_padding_ms 300 Integer 0-1000
threshold 0.5 Number 0.1-0.9

Continue sending microphone PCM, including silence, throughout automatic calls. The service detects speech end, commits audio and creates one reply automatically. Do not send client.commit in automatic mode; it is ignored to prevent duplicates. The one-second pause default protects brief thinking pauses; increase it to 1500 or 2000 ms for slower speech. This is silence detection, not a guarantee that a speaker has finished their thought. Lower thresholds detect quieter speech but can admit more noise. Prefix padding protects the beginning of the first word.

On input.speech_started, immediately stop and discard queued assistant playback. The service interrupts generation without clearing the new microphone input. Cancelled response deltas are suppressed by response ID. A response.started event begins a new assistant reply; reset the transcript there. Keep capture running for consecutive turns. client.cancel discards buffered input and cancels a reply without ending the call; continuous capture then continues listening. Stop capture as well if you intend to stop listening. client.stop ends billing and the call. A manual text/commit request while a response is active returns a recoverable relay.error; wait for response.done or cancellation completion before submitting another turn. Use echo cancellation or a headset to prevent speaker output triggering detection.

Send ordinary content only: raw session.update, system messages, tools, and per-response instruction overrides are rejected.

Server events:

Event Important fields
relay.ready session_id, charged_credits, billed_minutes, remaining_credits, turn_detection (null for push-to-talk)
input.speech_started / input.speech_stopped Speech activity boundaries in automatic mode
response.started Begin a new assistant reply
response.cancelled Manual cancellation acknowledged; discard queued playback
text.delta text, append to the current assistant reply
audio.delta audio, format: pcm_s16le, sample_rate: 24000
input.transcript text, completed microphone transcription
response.done status
relay.billing current cumulative charged_credits and remaining_credits
relay.error message
relay.metrics session_id, connected_seconds, charged_credits, billed_minutes, reason

No upstream session configuration or provider credentials are forwarded. Do not automatically reconnect; a new session starts a new billable call. Muting playback does not turn a voice session into per-request text billing. For text-only pricing, use the text SSE route.

Browser example

Copy examples/direct-chat-client.mjs, examples/pcm-capture.js, and examples/direct-chat.html into your own HTTPS application. Implement the two same-origin backend routes named in the HTML: /member/chat-stream and /member/voice-session. They must authenticate the member and call the service with server-held credentials. The voice backend sets the member site's fixed origin, trusted character instructions, and an affordable call limit. Return only the session response to the browser; never return account credentials.

The example uses native page controls, incremental text display, streamed PCM playback, a hands-free/push-to-talk selector, pause timing and cancellation. Click Start voice call, then Start speaking to grant microphone access. In automatic mode the microphone remains open across turns; in manual mode Finish speaking flushes the final PCM and sends client.commit. The example sends the selected turn_detection to /member/voice-session; that backend must validate and forward only those allowed settings when requesting the session. It requires a user gesture for audio and browser microphone permission. It does not automatically retry billable work.

Verification scope

Regression tests cover signed turn settings, manual compatibility, duplicate commit prevention, interruption/cancellation and subsequent turns, browser playback and existing billing/security behavior. Mocked tests establish source-level behavior; they do not establish acoustic detection accuracy or a production deployment. Before release verification, run an actual microphone call with short pauses, long pauses, two consecutive turns, speech during playback, manual cancellation, and push-to-talk. Record deployment and live-test results separately.

2026-10-24 candidate verification: live upstream testing with synthetic PCM confirmed two consecutive turns in each mode, streamed audio/transcripts, and no manual reply before client.commit. A 400 ms internal pause remained one automatic turn. Billing in this probe was isolated, so no production account was debited. Physical microphone/acoustic echo behavior and production billing were not verified by this probe; interruption races were regression-tested.