Skip to content

Extending Realtime Providers ​

A Realtime Provider adapts a realtime model service to the runtime; it is neither the client nor the Orchestration Runtime itself. A product host can inject a custom provider without changing shared session or backend-work logic. The example below assembles it through the Gateway application entry point.

For another model using an existing provider, maintain its support in that provider's data file under shared/realtime-models/ and add tests. Model definitions and adaptation parameters belong to framework code, not user configuration. Users select from the supported models.

js
import { createGatewayApplication } from 'qwen-audio-agent/gateway-application'
import {
  createRealtimeProviderRegistry,
} from 'qwen-audio-agent/realtime-provider'
import { privateRealtimeProvider } from './private-realtime-provider.mjs'

const realtimeProviderRegistry = createRealtimeProviderRegistry({
  providers: [privateRealtimeProvider],
  defaultProvider: privateRealtimeProvider.key,
})

createGatewayApplication({
  realtimeProviderRegistry,
  realtimeProvider: privateRealtimeProvider.key,
})

The extension boundary is:

  • Each Provider is an independent adapter that owns its URL, authentication, model, session, and error-classification semantics. Product differences should not be carried by reshaping another Provider.
  • url(), headers(), and model() can read the service URL, token, and model from host-owned configuration closures. The Gateway does not require product-specific environment variables.
  • createProtocol() runs once for each Realtime connection, so connection IDs and mutable state remain isolated.
  • createProtocol({ emit, send }) also receives two hooks: emit(event) injects a synthetic provider event through normalizeIncoming(), for example to close a spoken segment once output goes quiet; send(payload, options) sends a wire event of the protocol's own through encodeOutgoing(), and { correlate: false } keeps a response.create sent this way off the pending Gateway request.
  • concurrentVoicePlayback declares a full-duplex service: voice output runs alongside backend work, and the model decides whether a turn gets a reply, so an unanswered turn is released without an error. Mark playback-only synthetic responses __voicePlayback: true, and the model's own speech also __voiceAutomatic: true; they gate no Gateway request, and only a playback response answers a request to speak. A user interruption calls the optional interruptPlayback(), with { speech: true } when the user spoke, any other cancel calls it with { stop: true }, and it may return a frame to send. Later user turns supersede earlier tool calls only for respond_permission and update_agent_task, and an earlier turn's cancel_agent_task never reaches work a later turn started; a permission or backend question is answered only by a turn that began after the Gateway asked it. Announcements are confirmed when their response completes. Default off.
  • interruptionPlaysOut declares a model that finishes the speech it already generated when the user interrupts. A spoken barge-in, typed input, and interrupt clear no playback; voice.ready carries interruptionPlaysOut: true, so clients keep playing on listening and on their own interrupt. Default off.
  • pacedOutputAudio declares output audio that arrives at playback speed, with no lead. voice.ready carries pacedOutputAudio: true, and clients play it from a reserve even from a local Gateway, as they do from a remote one. Default off.
  • toolOutputsBeforeResponse declares a service that refuses response.create while a call has no output, and continues a response that made calls only on a later response.create. Outputs skip the response queue, Gateway requests wait until every open call has an output, and the runtime continues that response once, through the Gateway's follow-up or continueToolResults(). Outputs for calls the connection is not waiting on are not sent. Default off.
  • Optional synchronous validateSessionOptions({ sessionOptions }) runs before opening the upstream connection. Reject known-invalid service options; other service-specific values still need upstream validation. This does not bypass the catalog check for supported model IDs.
  • connectionMessages() emits raw handshake frames after the WebSocket opens and before session.update.
  • All later events pass through encodeOutgoing() and normalizeIncoming(), leaving Gateway tools, tasks, and client protocols unchanged.
  • Protocols without transient response instructions can implement responseInstructionsItem(response). Gateway creates and awaits that conversation item before calling responseCreate(response), which strips unsupported wire parameters. Set perResponseInstructions: false; these instructions remain in history.
  • conversationItemCreate(item, { contextOnly }) distinguishes context delivery from interactive user input. For message items, contextOnly: true must write context without triggering a reply; it must not merely cache the text for a later responseCreate. Gateway passes false for interactive text/file input. Tool receipts keep the provider's native continuation semantics.
  • Set automaticToolResponses: true only when tool results natively resume generation (Doubao Seeduplex and Google Live). Runtime sends these receipts without waiting for response completion, and the tool-batch follow-up uses ensureResponse(..., { afterToolResults: true }) without requesting a second reply. sendFunctionOutput acknowledges delivery with { delivered: true, automatic: true }; this is not speech completion. createResponse: false cannot disable the service's native continuation, nor can per-response instructions control it. Other providers keep explicit response creation and completion tracking.
  • Normalize events that only prove liveness to response.activity with a response_id, without forwarding thinking text.
  • An error that carries a response_id settles only that response. Leave the id off when the failure belongs to the request waiting on the frontend, so it falls back to the sole waiter.
  • Set conversationItemIdEcho: false when the service assigns new IDs to acknowledged conversation items. Gateway correlates the single pending item without delays or skipping acknowledgment.
  • Set imageRequiresAudioStart: true only if the service requires audio before the first video frame. Gateway primes that timeline with 20 ms of PCM16 silence so camera input does not require opening the microphone.
  • Set acknowledgesConversationItems: false when the service accepts input or tool-response messages without sending a conversation-item acknowledgment. Gateway resolves the send after writing the frame.
  • Set restoreConversationContext: false when injected history would be interpreted as live user input instead of passive context.
  • visibility: 'gateway-only' lets the host select a Provider without exposing it in desktop settings or the public Provider list.

A Provider must implement the full contract — model(), voice(), isConfigured(), url(), headers(), classifyError(), buildSession(), buildSpeakResponse(), buildResultInjection(), buildPermissionInjection() — plus numeric inputSampleRate and outputSampleRate fields; registration throws on any missing member.

Provider and Protocol contracts are validated during registration and connection setup, so missing methods or invalid values fail immediately.

Behavior verification ​

Run node --test server/test/realtime-provider-behavior.test.mjs from the repository root. The same suite exercises every built-in Provider through the real session runtime and a local WebSocket service: context-only updates, tool continuation, permissions, cancellation, queued asynchronous replies, and reconnect/context restoration. Unsupported features must return an explicit unsupported result or error; the suite does not treat them as successful delivery.

The fixtures implement native wire behavior rather than calling the adapters to construct mock replies. When adding a dialect, add its fixture and run the shared suite. This is deterministic contract coverage, not a substitute for live service validation or audio/device testing.

server/test/native-tool-continuation.test.mjs additionally covers MCP result normalization through ToolCallHandler to a local native-protocol service, including failures, transport errors, and mixed results. In Doubao Seeduplex, function calls can precede response.done; the service waits for the matching tool results before completing the interaction. Tests must preserve that ordering rather than inventing an earlier terminal event.

For Google Live, context-only history uses clientContent with turnComplete: false; committing the turn starts a reply. Unlike passive history insertion in some protocols, Google documents that clientContent also interrupts active generation. Queued context waits for idle, while an immediate permission/context delivery can interrupt. Tool responses resume generation natively, and generationComplete does not release the response slot until turnComplete arrives.

Desktop settings ​

Built-in frontend settings live in shared/realtime-provider-definitions.mjs, a browser-safe catalog without credentials or connection implementations. Declare a provider's name, configurable fields, and defaults there. All providers share the active connection's QWEN_AUDIO_REALTIME_* environment fields; adding a provider does not require another set of credential, model, URL, and voice variables. Provider-specific model and API data live in shared/realtime-models/dashscope.mjs, stepfun.mjs, gpt-live.mjs, gpt-live-1.mjs, google-live.mjs, and doubao-seeduplex.mjs; shared/realtime-model-catalog.mjs is their public facade. These code-owned records define model IDs, API bindings, capabilities, session defaults, and constraints. Aggregation and resolution contain no provider-specific configuration. The desktop model dropdown uses the resulting static supported-model list; it does not accept user-defined model records or infer support from a free-form model name.

The form displays Service URL, API Key, Model, and Voice, mapped to the endpoint, credential, model, and voice slots. Providers expose only configurable slots; upstream-owned model and voice controls remain disabled. Bearer tokens use the API Key field. Switching provider must clear or replace the previous connection's values rather than send its credential to another service. Legacy variable names are handled at the configuration-read boundary, not in adapters. A remote Gateway continues to own its frontend configuration.

Settings metadata is separate from runtime adapters. Host-injected custom Providers are not automatically registered in the desktop chooser.