Repository navigation
Move OpenAI Realtime inference client into agents core - #2532
Conversation
🦋 Changeset detectedLatest commit: 457b84d The changes in this PR will be included in the next version bump. This PR includes changesets to release 41 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
There was a problem hiding this comment.
Note
Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.
Devin Review found 4 potential issues.
2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
| this.realtimeSession = this.llm.session({ | ||
| turnDetectionDisabled: !this.rtTurnDetectionEnabled, | ||
| }); |
There was a problem hiding this comment.
🔴 Reused sessions retain stale turn detection
During same-model handoffs, rtTurnDetectionEnabled can change while the old realtime session is reused. The stale server setting can produce duplicate replies or no reply.
Learn more
A realtime session stores its effective turn-detection setting when it is created. The new activity resolves that setting independently from its agent and session configuration. However, _detachReusableResources reuses a session based on model identity, context, instructions, and tools only. The reused session can therefore disagree with the new activity's rtTurnDetectionEnabled. If the session still uses server detection while the activity uses client detection, both sides can generate a reply. In the reverse direction, the activity waits for a server-generated reply that the reused session has disabled.
Example: Agent A uses realtime_llm, then hands off to Agent B using vad with the same model instance. Agent B treats server detection as disabled, but the reused session still has it enabled. The client commits and generates while the server also generates from VAD.
Recommended fix: Include the resolved turn-detection mode in realtime-session reuse eligibility. Close and recreate the session when this.rtTurnDetectionEnabled !== newActivity.rtTurnDetectionEnabled, or add a reliable mid-session update that changes the provider setting before reuse.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Fixed in 0b36cc3: a realtime session is only reused when both activities resolve the same turn-detection setting (agent_activity.ts:1138).
| async commitAudio(): Promise<void> { | ||
| if (this.pushedDurationMs > 100) { | ||
| // OpenAI requires at least 100ms of audio | ||
| this.sendEvent({ | ||
| type: 'input_audio_buffer.commit', | ||
| } as api_proto.InputAudioBufferCommitEvent); | ||
| this.pushedDurationMs = 0; | ||
| } |
There was a problem hiding this comment.
🔴 Turn boundaries leak buffered audio
When a client-managed turn ends between chunks, commitAudio leaves trailing audio in bstream. That audio is omitted, then prefixed to the next turn.
Learn more
bstream emits only complete 100 ms frames and retains any remainder. pushedDurationMs counts emitted frames, not retained audio. At a client-managed turn boundary, commitAudio commits the provider buffer without flushing or discarding that remainder. The remainder stays in bstream after pushedDurationMs resets, so later input completes a frame containing audio from two user turns. clearAudio has the same stale local remainder because it only clears the provider buffer and duration counter.
Example: A 250 ms turn emits 200 ms and retains 50 ms locally. commitAudio commits only 200 ms. The next user's first 50 ms combines with the retained 50 ms and is sent as that next turn's first chunk.
Recommended fix: Flush bstream at commit boundaries and send the remainder when the resulting provider buffer meets the minimum duration. Reset or replace bstream after every commit and clear. For sub-minimum turns, discard the local and remote buffers together rather than carrying bytes into another turn.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Valid: up to 90 ms of a client-committed turn's tail went out with the next turn. Fixed in 528a0ab: commitAudio sends the partial frame before committing, and clearAudio drops it. Python had the same bug, fixed in livekit/agents#7673.
| while (!this.#closed && !signal.aborted) { | ||
| this.#logger.debug('Creating WebSocket connection to OpenAI Realtime API'); | ||
| wsConn = await this.createWsConn(); |
There was a problem hiding this comment.
🟡 Initial connection failures bypass retries
When the first createWsConn fails, #mainTask exits before its retry handler. Transient handshake failures ignore maxRetry, and queued replies time out.
Learn more
The retry catch begins only after a WebSocket has been created. Hosted inference uses connectWs, which rejects with retryable APIConnectionError, APIStatusError, or APITimeoutError during the handshake. Because createWsConn() is awaited outside the inner try, those errors terminate the background task immediately. connOptions.maxRetry is never consulted, and pending generateReply() calls remain queued until their separate ten-second timeout.
Example: The gateway returns a transient 503 on the first handshake with maxRetry: 3. The session performs one attempt instead of four. A reply requested during startup fails later with generateReply timed out.
Recommended fix: Move connection creation inside the retry boundary and apply the same retryability and backoff logic to handshake failures. Ensure a failed attempt closes any partially created socket and settles pending work when retries are exhausted.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Valid, and worse on the direct path: the handshake had no 'error' listener, so a refused handshake threw out of the process. Fixed in 528a0ab: handshake failures map to retryable API errors and run inside the retry boundary. A failed first handshake retries as a fresh connection rather than a reconnection replay.
| private *resampleAudio(frame: AudioFrame): Generator<AudioFrame> { | ||
| yield frame; | ||
| } |
There was a problem hiding this comment.
🟡 Non-24kHz input audio is mislabeled
For non-24kHz input, resampleAudio forwards bytes unchanged. bstream labels them as 24kHz mono, distorting realtime speech.
Learn more
The realtime wire format is fixed at 24 kHz mono, and bstream is constructed for that format. Room input defaults to 24 kHz mono, but RoomInputOptions.audioSampleRate, audioNumChannels, and external audio streams can supply other formats. resampleAudio currently returns every frame unchanged, so the payload contains source-rate samples while the session advertises 24 kHz mono. The declared inputResampler is never initialized or closed.
Example: With room input configured for 48 kHz mono, one second supplies 48,000 samples. The provider interprets them as two seconds of 24 kHz audio, slowing speech and breaking turn timing.
Recommended fix: Track the current input sample rate and channel count. Create an AudioResampler targeting 24 kHz mono whenever either differs, recreate it if the source format changes, and close it during session teardown.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Valid when input isn't the 24 kHz mono default (e.g. audioSampleRate: 48000 or stereo). Fixed in 528a0ab: input is downmixed and resampled to 24 kHz mono, as the GPT-Live client already does.
384621c to
88df384
Compare
There was a problem hiding this comment.
Devin Review found 2 new potential issues.
2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
| } else if (!url.pathname || ['', '/v1', '/openai', '/openai/v1'].includes(pathStripped)) { | ||
| url.pathname = pathStripped + '/realtime'; |
There was a problem hiding this comment.
🔴 Custom API roots miss Realtime endpoint
For a custom API root such as /proxy/v1, processBaseURL connects to that root without appending /realtime. Prefixed OpenAI gateways reject the WebSocket handshake, preventing the agent from starting a Realtime session.
Learn more
A base URL can name an API root rather than the final WebSocket endpoint. The model passes its configured base URL directly to processBaseURL, which must turn an API root into a Realtime endpoint. The new path check recognizes only a few root names, so any prefixed API root stays unchanged and the connection goes to the wrong route. At the same time, fully qualified custom WebSocket paths must remain intact.
Example: Given baseURL: 'https://gateway.example.com/proxy/v1', the resulting URL is wss://gateway.example.com/proxy/v1?model=gpt-realtime. An API-root gateway expects /proxy/v1/realtime instead.
Recommended fix: Distinguish explicitly supplied complete WebSocket endpoints from API roots, or provide a documented option for that distinction. Append the Realtime segment for arbitrary API roots while retaining support for custom complete paths and query parameters.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Leaving this as is. A custom path is kept as given on purpose, same as Python's process_base_url. A full endpoint like https://gateway.example.com/proxy/v1/realtime already works, and appending /realtime to arbitrary paths would break it.
| if (isAzure) { | ||
| // remove from endpoint URL if present | ||
| url.searchParams.delete('api-version'); |
There was a problem hiding this comment.
🟡 Azure preview URL loses its version
When an Azure preview baseURL supplies api-version without a separate apiVersion option, processBaseURL removes the version. The preview endpoint then rejects the WebSocket request.
Learn more
An Azure preview endpoint can include api-version in the configured base URL. The Azure branch deletes that query parameter unconditionally, but only restores it when the separate apiVersion option is truthy. Therefore a caller who provides the version solely in the URL loses it before the WebSocket connects.
Example: With baseURL: 'https://resource.openai.azure.com/openai/realtime?api-version=2025-04-01-preview', azureDeployment: 'voice', and no apiVersion, the generated URL omits api-version, unlike the configured endpoint.
Recommended fix: Preserve an existing URL version when no replacement apiVersion was supplied. If a version in the URL selects preview behavior, use it consistently for the preview path and query construction.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Leaving this as is. It only affects the legacy Azure preview path, and apiVersion / OPENAI_API_VERSION is deprecated in both SDKs with a removal date of April 30, 2026. Pass apiVersion if you still need it.
f60cc91 to
40ba26d
Compare
| @@ -0,0 +1,6 @@ | |||
| --- | |||
| '@livekit/agents': minor | |||
| '@livekit/agents-plugin-openai': minor | |||
There was a problem hiding this comment.
could we collapse to one changeset and set them all as patch
There was a problem hiding this comment.
Done: one changeset, all four packages at patch.
|
Mirrored the API review from livekit/agents#7673: 528a0ab also fixes the valid Devin findings in |
…t choice Match Python: the eager default TurnDetector no longer counts as client-side turn taking, 'vad' needs a VAD, a realtime session is reused on handoff only when both activities resolve server turn detection the same way, and a runtime turnDetection change that would flip it warns.
…ider and inferenceClass
Move the GPT-Live client into agents core (llm/openai_realtime/gpt_live_model.ts). openai.realtime.GPTLiveModel becomes a thin subclass that converts the plugin's hosted tools, so direct-OpenAI behavior is unchanged. Add inference.GPTLiveModel, which connects to the gateway's /live/sessions?model= with a LiveKit token signed per connection, and resolve llm: 'openai/gpt-live-1' to it in Agent and AgentSession. It refuses what the gateway cannot meter before connecting: hosted tools and a non-default delegation service tier. Gateway refusals of session.start are fatal.
…and model strings
- DuplexModel/DuplexSession in inference/duplex.ts; model required, delegation and responsesOptions move into typed modelOptions - DuplexModels split out of RealtimeModels; isDuplexModel - retired realtime ids stay routed to RealtimeModel and warn - drop inferenceClass from the realtime and duplex paths (no effect) - one patch changeset
- createWsConn maps handshake failures to retryable APIErrors and handles the ws 'error' event, which was unhandled and threw out of the process - the handshake runs inside the retry boundary; a failed first handshake retries as a fresh connection instead of a reconnection replay - resample and downmix input to 24 kHz mono, as the GPT-Live client does - commitAudio sends the buffered partial frame; clearAudio drops it
528a0ab to
457b84d
Compare
Removes the write-only textModeRecoveryRetries field (declaration, two = 0 writes, and the stale TODO comment) from the OpenAI Realtime session, plus the matching field on the test-internal RealtimeSessionInternals type and its initialization. The inputResampler field was originally also targeted for removal but is now actively used after the move into agents core (#2532 added real usage in pushAudio/close), so it is kept. Rebased onto main: the implementation moved from plugins/openai/src/realtime/realtime_model.ts to agents/src/llm/openai_realtime/realtime_model.ts in #2532.
Summary
inference.RealtimeModelwith LiveKit Inference authentication, routing, hosted xAI defaults, and gateway error handlinginference.DuplexModelplusllm: 'openai/gpt-live-1'use it (see below)Port of livekit/agents#7318.
Alignment with livekit/agents#7673
Rebased onto
main, and brought in line with livekit/agents#7673:@livekit/agents-plugin-google): models without the placeholder-turn behavior (3.1, 3.8) now getgenerateReplyinstructions as auserturn wrapped in<instructions>…</instructions>; 2.5 keeps themodelturn plus"."user turn. Extracted asreplyTurns()with unit tests.@livekit/agents-plugin-xai,inference.RealtimeModel): replacedgrok-voice-think-fast-2.0withgrok-voice-3.0andgrok-voice-latestinGrokRealtimeModels, and setXAIRealtimeModelsto'xai/grok-voice' | 'xai/grok-voice-latest' | 'xai/grok-voice-3.0'.inference.RealtimeSession): the gateway forwards xAI'sconversation.item.input_audio_transcription.completedevents unchanged (https://github.com/livekit/agent-gateway/pull/1579), and xAI sends multiple.completedevents per user item (status: 'in_progress'partials plus revised commits across pauses). Whenmodelstarts withxai/,inference.RealtimeSessionnow holds committed transcripts inpendingTranscriptionand flushes one final transcript per turn when the agent answers, the next turn starts, or the session resets/closes, alongside xAI's held-turn chat-context preservation, tail anchoring for unanchoredconversation.item.addedevents, and abandoned-response cleanup (matching@livekit/agents-plugin-xai).inference.RealtimeModeldocumentsprovider(pins the host, e.g.azureoropenai; the session is refused if no host in the region matches). It takes noinferenceClass, since the gateway ignores the priority header on realtime. README clarifies hosted vs direct-provider usage.openai/gpt-realtime-2,openai/gpt-realtime-1.5andxai/grok-voice-think-fast-2.0still resolve toinference.RealtimeModeland log a warning naming the replacement (2.1 and Grok Voice 3.0), matching feat(inference, google): run GPT-Live as inference.DuplexModel, wrap Gemini 3.x reply instructions, update the realtime model list agents#7673._realtime_models.pylive inagents/src/inference/realtime.tsandagents/src/inference/duplex.ts.GPT-Live through LiveKit Inference
Ports change 5 of livekit/agents#7673:
gpt_live_model.tsandgpt_live_types.tsmove toagents/src/llm/openai_realtime/(git mv). The plugin re-exports the types andGPTLiveSession. The plugin'sGPTLiveModelis now a thin subclass of the core class that forwardsOpenAIToolhosted tools through a_providerToolConfig()hook, so core doesn't import the plugin.inference.DuplexModel(agents/src/inference/duplex.ts) is shaped like the otherinferenceclasses:modelis required, shared settings (voice,provider) are options, and GPT-Live'sdelegationandresponsesOptionsgo inmodelOptions, typed per model asOpenAIDuplexOptions. UnknownmodelOptionskeys throw.{inference url}/live/sessions?model=openai/gpt-live-1and signs a fresh LiveKit token for each connection.provider. There is noinferenceClass.RealtimeError.responsesOptions.serviceTiermust be unset or'default'.openai/gpt-live-1is in its ownDuplexModelstype withisDuplexModel(), not inRealtimeModels.inference.llmFromModelString()resolves duplex strings toinference.DuplexModel, realtime strings toinference.RealtimeModel, and every other string toinference.LLM.AgentSessionandAgentuse it and wrap duplex models inDuplexRealtimeAdapter.inference.RealtimeModelrejects duplex ids and points toinference.DuplexModel.GPTLiveVoicesreplaces'aster'(rejected by OpenAI withforbidden) with'cedar', and'forbidden'is treated as a fatal error code.RealtimeSession.handleConversationItemCreatedfalls back to appending at the tail whenprevious_item_idis not inremoteChatCtxfor all providers (such as Gemini sending'root'or server-side items after setup replay), matching Python.input_audio_transcription.completeduntil the agent speaks (93e3fd42), emitting one final user transcript per turn.patchfor@livekit/agents,@livekit/agents-plugin-openai,@livekit/agents-plugin-googleand@livekit/agents-plugin-xai. API reports regenerated.Validation for this part:
agents/src/inference/duplex.test.tsandagents/src/inference/realtime.test.ts, includingmodelOptionspassthrough, unknown-option rejection, the duplex-id guard and the retired-id warnings (493 tests acrossagents/src/inference,agents/src/llm/openai_realtimeandplugins/openai/src/realtime).wss://agent-gateway.livekit.cloud/v1) acrossopenai/gpt-live-1,openai/gpt-realtime-2.1,google/gemini-3.8-live,google/gemini-3.8-live-extended-thinking, andxai/grok-voice-think-fast-2.0.Provider pinning and fallback reporting depend on https://github.com/livekit/agent-gateway/pull/1572 and https://github.com/livekit/cloud-config/pull/20197 being deployed.
Realtime session fixes
Validated from review findings on the engine moved from
plugins/openai. These bugs predate this PR, and each has a test that fails without the fix:createWsConnhad no'error'listener, so a refused handshake (e.g. a 503) was an unhandled'error'event that threw out of the process. It also ran outside the retry boundary, soconnOptions.maxRetrynever applied to the first connect or to a reconnect. Handshake failures now map to retryableAPIConnectionError,APITimeoutError, orAPIStatusError(4xx stays fatal, as on the hosted path) and are retried. A failed first handshake retries as a fresh connection, not a reconnection replay, matching the same fix in feat(inference, google): run GPT-Live as inference.DuplexModel, wrap Gemini 3.x reply instructions, update the realtime model list agents#7673.resampleAudiopassed frames through unchanged, so input that wasn't 24 kHz mono (e.g.audioSampleRate: 48000or stereo room input) was sent as 24 kHz mono, at the wrong speed. It now downmixes and resamples like the GPT-Live client. The default 24 kHz mono input is unchanged.commitAudionow sends the buffered partial frame before committing, andclearAudiodrops it, so up to 90 ms of a client-committed turn no longer leaks into the next one. Same as feat(inference, google): run GPT-Live as inference.DuplexModel, wrap Gemini 3.x reply instructions, update the realtime model list agents#7673.Not changed: custom base URLs keep their path as given, matching Python (a full endpoint like
/proxy/v1/realtimealready works, and appending/realtimeto arbitrary paths would break it).api-versionin an Azure base URL is still replaced by theapiVersionoption, which both SDKs deprecated with a removal date of April 30, 2026.Validation
pnpm buildnpx --yes --package=node@24 -- node node_modules/vitest/vitest.mjs run agents --silent(2788passed,5skipped)env -u OPENAI_API_KEY pnpm test plugins/openai --silent(156passed,7skipped)pnpm test plugins/xai --silent(26passed,1skipped)pnpm typecheckpnpm format:checkpnpm throws:check@livekit/agents,@livekit/agents-plugin-openai, and@livekit/agents-plugin-xaiFull repository lint remains blocked by the pre-existing
@typescript-eslint/no-misused-promiseserror atplugins/openai/src/ws/llm.ts:127. Acue-clihosted realtime run was attempted with a temporary uncommitted agent, but room creation failed before dispatch with401 Unauthorized - invalid API key; the temporary harness was removed.Source diff coverage
Authoritative livekit/agents#7318 file-by-file coverage
.github/workflows/test-realtime.yml.github/workflows/test.yml: added OpenAI plugin triggers, OpenAI/xAI realtime suites, and hosted realtime inference coverage.AGENTS.mdCLAUDE.md: documented realtime as core inference infrastructure; target has noAGENTS.md.examples/README.mdREADME.md: documented hostedinference.RealtimeModeland direct-provider plugin usage; target has no examples README.livekit-agents/livekit/agents/inference/__init__.pyagents/src/inference/index.ts: exportsRealtimeModel,RealtimeSession, realtime namespace, andInferenceClass.livekit-agents/livekit/agents/inference/_utils.pyagents/src/inference/utils.ts: centralizedInferenceClass, credential resolution, priority metadata, and hosted WebSocket header precedence.livekit-agents/livekit/agents/inference/llm.pyagents/src/inference/llm.ts: consumes centralized inference credentials andInferenceClass.livekit-agents/livekit/agents/inference/realtime/__init__.pyagents/src/inference/realtime.ts: target inference modules use a flat file namespace.livekit-agents/livekit/agents/inference/realtime/openai.pyagents/src/inference/realtime.ts: hosted model/session, LiveKit auth refresh, provider routing, model omission, xAI defaults, nullable session duration, and fatal gateway errors.livekit-agents/livekit/agents/llm/_realtime/__init__.pyagents/package.json, matching the target module/export model.livekit-agents/livekit/agents/llm/_realtime/openai.pyagents/src/llm/openai_realtime/realtime_model.ts: moved the existing target protocol engine into core and added hosted extension points.livekit-agents/livekit/agents/llm/_realtime/openai_types.pyagents/src/llm/openai_realtime/api_proto.ts: moved protocol types into core and addedRealtimeModels.livekit-agents/livekit/agents/llm/_realtime/openai_utils.pyagents/src/llm/openai_realtime/realtime_model.ts, following the existing target architecture.livekit-agents/pyproject.toml@livekit/agentsalready directly depends on compatibleopenai,ws, and mutex versions.livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/models.pyplugins/openai/src/models.ts: re-exports the coreRealtimeModelstype.livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/__init__.pyplugins/openai/src/realtime/index.ts: preserves direct realtime and GPT Live exports and adds hosted compatibility aliases.livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/inference_realtime_model.pyInferenceRealtimeModelandInferenceRealtimeSessionaliases now resolve to canonical core inference classes.livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/realtime_model.pyplugins/openai/src/realtime/realtime_model.ts: thin compatibility re-export of the core engine.livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/utils.pylivekit-plugins/livekit-plugins-openai/pyproject.tomlplugins/openai/package.json: removed the now-redundant mutex dependency; retainedopenaiandwsbecause STT, GPT Live, Responses, and other plugin code still use them.tests/test_inference_utils.pyagents/src/inference/utils.test.ts: covers centralized credentials and inference-priority metadata.tests/test_realtime/test_openai_inference_realtime_model.pyagents/src/inference/realtime.test.ts: covers exports, credentials, URL/wire format, auth refresh, routing headers, model omission, fatal/recoverable errors, API shape, and xAI defaults.tests/test_realtime/test_openai_realtime_model.pyagents/src/llm/openai_realtime/realtime_model.test.ts; plugin compatibility assertions remain inplugins/openai/src/realtime/realtime_model.test.ts.uv.lockpnpm-lock.yaml: removed the OpenAI plugin mutex edge.Additional target infrastructure required for parity is included in
agents/src/llm/realtime.tsandagents/src/voice/agent_activity.ts: realtime models can advertise disableable server turn detection, and the voice pipeline resolves and passes the session-specific setting for client-side turn handling.Ported from livekit/agents#7318
Original PR description
Summary
Compatibility
Validation