Skip to content

Move OpenAI Realtime inference client into agents core - #7318

Merged
russellmartin-livekit merged 4 commits into
mainfrom
cursor/core-realtime-inference
Sep 18, 2026
Merged

russellmartin-livekit merged 4 commits into
mainfrom
cursor/core-realtime-inference

Conversation

@russellmartin-livekit

@russellmartin-livekit russellmartin-livekit commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • move the OpenAI Realtime protocol engine into a private core module
  • add the hosted RealtimeModel under livekit.agents.inference
  • retain the direct-provider API and legacy hosted imports through compatibility wrappers
  • keep GPT-Live owned by livekit-plugins-openai until LiveKit Inference supports it
  • update dependency bounds, documentation, and realtime CI paths

Compatibility

  • preserve the existing direct OpenAI RealtimeModel metrics label
  • restore realtime.utils and realtime.gpt_live_types package attributes
  • realtime engine logs now use the livekit.agents logger because the implementation lives in core

Validation

  • 126 targeted unit tests passed
  • Ruff lint and format checks passed for affected files
  • mypy passed for livekit.agents and livekit.plugins.openai

@russellmartin-livekit
russellmartin-livekit requested a review from a team September 17, 2026 17:08
@russellmartin-livekit russellmartin-livekit self-assigned this Sep 17, 2026
@russellmartin-livekit
russellmartin-livekit force-pushed the cursor/core-realtime-inference branch from 145ef3f to ad7833b Compare September 17, 2026 17:11
@russellmartin-livekit
russellmartin-livekit marked this pull request as ready for review September 17, 2026 18:40
@russellmartin-livekit
russellmartin-livekit requested a review from a team as a code owner September 17, 2026 18:40

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

This report is out of date. Scroll down for Devin Review's latest report on this PR.

βœ… Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@russellmartin-livekit russellmartin-livekit changed the title Move realtime inference clients into agents core Move OpenAI Realtime inference client into agents core Sep 17, 2026

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

1 flag not posted on this PR by your GitHub settings β€” view it in Devin Review. (Configure)

Devin Review

Comment on lines +3 to +8
from livekit.agents.inference.realtime.openai import (
RealtimeModel as InferenceRealtimeModel,
RealtimeSession as InferenceRealtimeSession,
)


@dataclass
class _InferenceOptions:
provider: str | None
api_key: str
api_secret: str
inference_class: InferenceClass | None


class InferenceRealtimeModel(RealtimeModel):
"""OpenAI-compatible realtime model authenticated through LiveKit Inference."""

def __init__(
self,
model: str,
*,
provider: str | None = None,
base_url: str | None = None,
api_key: str | None = None,
api_secret: str | None = None,
inference_class: InferenceClass | None = None,
voice: NotGivenOr[str] = NOT_GIVEN,
modalities: NotGivenOr[list[Literal["text", "audio"]]] = NOT_GIVEN,
input_audio_transcription: NotGivenOr[AudioTranscription | None] = NOT_GIVEN,
input_audio_noise_reduction: NotGivenOr[
NoiseReductionType | NoiseReduction | None
] = NOT_GIVEN,
turn_detection: NotGivenOr[RealtimeAudioInputTurnDetection | None] = NOT_GIVEN,
tool_choice: NotGivenOr[llm.ToolChoice | None] = NOT_GIVEN,
speed: NotGivenOr[float] = NOT_GIVEN,
tracing: NotGivenOr[Tracing | None] = NOT_GIVEN,
truncation: NotGivenOr[RealtimeTruncation | None] = NOT_GIVEN,
reasoning: NotGivenOr[RealtimeReasoning | None] = NOT_GIVEN,
http_session: aiohttp.ClientSession | None = None,
max_session_duration: NotGivenOr[float | None] = NOT_GIVEN,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
) -> None:
if "/" not in model:
raise ValueError("model must be provider-prefixed, for example 'openai/gpt-realtime'")

resolved_api_key = api_key or os.getenv(
"LIVEKIT_INFERENCE_API_KEY", os.getenv("LIVEKIT_API_KEY", "")
)
if not resolved_api_key:
raise ValueError(
"api_key is required, either as argument or set LIVEKIT_API_KEY environmental variable"
)

resolved_api_secret = api_secret or os.getenv(
"LIVEKIT_INFERENCE_API_SECRET", os.getenv("LIVEKIT_API_SECRET", "")
)
if not resolved_api_secret:
raise ValueError(
"api_secret is required, either as argument or set LIVEKIT_API_SECRET environmental variable"
)

is_xai = model.startswith("xai/")
resolved_voice = voice if is_given(voice) else "eve" if is_xai else DEFAULT_VOICE
resolved_transcription = input_audio_transcription
resolved_turn_detection = turn_detection
# Preserve whether xAI's server VAD is a default the framework may disable.
can_disable_turn_detection = not is_given(turn_detection)
if is_xai:
if not is_given(resolved_transcription):
resolved_transcription = _XAI_DEFAULT_INPUT_AUDIO_TRANSCRIPTION
if not is_given(resolved_turn_detection):
resolved_turn_detection = _XAI_DEFAULT_TURN_DETECTION

super().__init__(
model=model,
voice=resolved_voice,
modalities=modalities,
input_audio_transcription=resolved_transcription,
input_audio_noise_reduction=input_audio_noise_reduction,
turn_detection=resolved_turn_detection,
tool_choice=tool_choice,
speed=speed,
tracing=tracing,
truncation=truncation,
reasoning=reasoning,
api_key="livekit-inference",
base_url=base_url or get_default_inference_url(),
http_session=http_session,
max_session_duration=max_session_duration,
conn_options=conn_options,
)
# LiveKit Inference always uses the OpenAI-compatible protocol; ambient Azure
# settings must not change its URL or session wire format.
self._opts.is_azure = False
self._opts.api_version = None
if is_xai:
self._capabilities.can_disable_turn_detection = can_disable_turn_detection
self._inference_opts = _InferenceOptions(
provider=provider,
api_key=resolved_api_key,
api_secret=resolved_api_secret,
inference_class=inference_class,
)
self._provider_label = "LiveKit Inference Realtime"

@property
def provider(self) -> str:
return "livekit"

def session(self, *, turn_detection_disabled: bool = False) -> InferenceRealtimeSession:
sess = InferenceRealtimeSession(self, turn_detection_disabled=turn_detection_disabled)
self._sessions.add(sess)
return sess


class InferenceRealtimeSession(RealtimeSession):
def __init__(
self,
realtime_model: InferenceRealtimeModel,
*,
turn_detection_disabled: bool = False,
) -> None:
self._inference_model = realtime_model
super().__init__(realtime_model, turn_detection_disabled=turn_detection_disabled)

def _create_ws_url_and_headers(self) -> tuple[str, dict[str, str]]:
opts = self._inference_model._inference_opts
url, _ = super()._create_ws_url_and_headers()
headers = get_inference_headers(inference_class=opts.inference_class)
headers["Authorization"] = f"Bearer {create_access_token(opts.api_key, opts.api_secret)}"
if opts.provider:
headers[HEADER_INFERENCE_PROVIDER] = opts.provider
return url, headers

def _wrap_session_update(self, event_id: str, session: Any) -> dict[str, Any]:
event = super()._wrap_session_update(event_id, session)
if hasattr(event, "model_dump"):
event = event.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=False)
else:
event = dict(event)

session_payload = event.get("session")
if isinstance(session_payload, dict):
session_payload.pop("model", None)
return event

def _is_fatal_error(self, error: object | None) -> bool:
code = getattr(error, "code", None) or getattr(error, "type", None)
return (
isinstance(code, str)
and code
in {
"unsupported_transcription_model",
"unsupported_audio_transport",
"unsupported_audio_format",
}
) or super()._is_fatal_error(error)
__all__ = ["InferenceRealtimeModel", "InferenceRealtimeSession"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 Legacy inference class import removed

Importing InferenceClass from the legacy hosted module now raises ImportError. Applications retaining this compatibility import fail during startup.

Suggested change
from livekit.agents.inference.realtime.openai import (
RealtimeModel as InferenceRealtimeModel,
RealtimeSession as InferenceRealtimeSession,
)
@dataclass
class _InferenceOptions:
provider: str | None
api_key: str
api_secret: str
inference_class: InferenceClass | None
class InferenceRealtimeModel(RealtimeModel):
"""OpenAI-compatible realtime model authenticated through LiveKit Inference."""
def __init__(
self,
model: str,
*,
provider: str | None = None,
base_url: str | None = None,
api_key: str | None = None,
api_secret: str | None = None,
inference_class: InferenceClass | None = None,
voice: NotGivenOr[str] = NOT_GIVEN,
modalities: NotGivenOr[list[Literal["text", "audio"]]] = NOT_GIVEN,
input_audio_transcription: NotGivenOr[AudioTranscription | None] = NOT_GIVEN,
input_audio_noise_reduction: NotGivenOr[
NoiseReductionType | NoiseReduction | None
] = NOT_GIVEN,
turn_detection: NotGivenOr[RealtimeAudioInputTurnDetection | None] = NOT_GIVEN,
tool_choice: NotGivenOr[llm.ToolChoice | None] = NOT_GIVEN,
speed: NotGivenOr[float] = NOT_GIVEN,
tracing: NotGivenOr[Tracing | None] = NOT_GIVEN,
truncation: NotGivenOr[RealtimeTruncation | None] = NOT_GIVEN,
reasoning: NotGivenOr[RealtimeReasoning | None] = NOT_GIVEN,
http_session: aiohttp.ClientSession | None = None,
max_session_duration: NotGivenOr[float | None] = NOT_GIVEN,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
) -> None:
if "/" not in model:
raise ValueError("model must be provider-prefixed, for example 'openai/gpt-realtime'")
resolved_api_key = api_key or os.getenv(
"LIVEKIT_INFERENCE_API_KEY", os.getenv("LIVEKIT_API_KEY", "")
)
if not resolved_api_key:
raise ValueError(
"api_key is required, either as argument or set LIVEKIT_API_KEY environmental variable"
)
resolved_api_secret = api_secret or os.getenv(
"LIVEKIT_INFERENCE_API_SECRET", os.getenv("LIVEKIT_API_SECRET", "")
)
if not resolved_api_secret:
raise ValueError(
"api_secret is required, either as argument or set LIVEKIT_API_SECRET environmental variable"
)
is_xai = model.startswith("xai/")
resolved_voice = voice if is_given(voice) else "eve" if is_xai else DEFAULT_VOICE
resolved_transcription = input_audio_transcription
resolved_turn_detection = turn_detection
# Preserve whether xAI's server VAD is a default the framework may disable.
can_disable_turn_detection = not is_given(turn_detection)
if is_xai:
if not is_given(resolved_transcription):
resolved_transcription = _XAI_DEFAULT_INPUT_AUDIO_TRANSCRIPTION
if not is_given(resolved_turn_detection):
resolved_turn_detection = _XAI_DEFAULT_TURN_DETECTION
super().__init__(
model=model,
voice=resolved_voice,
modalities=modalities,
input_audio_transcription=resolved_transcription,
input_audio_noise_reduction=input_audio_noise_reduction,
turn_detection=resolved_turn_detection,
tool_choice=tool_choice,
speed=speed,
tracing=tracing,
truncation=truncation,
reasoning=reasoning,
api_key="livekit-inference",
base_url=base_url or get_default_inference_url(),
http_session=http_session,
max_session_duration=max_session_duration,
conn_options=conn_options,
)
# LiveKit Inference always uses the OpenAI-compatible protocol; ambient Azure
# settings must not change its URL or session wire format.
self._opts.is_azure = False
self._opts.api_version = None
if is_xai:
self._capabilities.can_disable_turn_detection = can_disable_turn_detection
self._inference_opts = _InferenceOptions(
provider=provider,
api_key=resolved_api_key,
api_secret=resolved_api_secret,
inference_class=inference_class,
)
self._provider_label = "LiveKit Inference Realtime"
@property
def provider(self) -> str:
return "livekit"
def session(self, *, turn_detection_disabled: bool = False) -> InferenceRealtimeSession:
sess = InferenceRealtimeSession(self, turn_detection_disabled=turn_detection_disabled)
self._sessions.add(sess)
return sess
class InferenceRealtimeSession(RealtimeSession):
def __init__(
self,
realtime_model: InferenceRealtimeModel,
*,
turn_detection_disabled: bool = False,
) -> None:
self._inference_model = realtime_model
super().__init__(realtime_model, turn_detection_disabled=turn_detection_disabled)
def _create_ws_url_and_headers(self) -> tuple[str, dict[str, str]]:
opts = self._inference_model._inference_opts
url, _ = super()._create_ws_url_and_headers()
headers = get_inference_headers(inference_class=opts.inference_class)
headers["Authorization"] = f"Bearer {create_access_token(opts.api_key, opts.api_secret)}"
if opts.provider:
headers[HEADER_INFERENCE_PROVIDER] = opts.provider
return url, headers
def _wrap_session_update(self, event_id: str, session: Any) -> dict[str, Any]:
event = super()._wrap_session_update(event_id, session)
if hasattr(event, "model_dump"):
event = event.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=False)
else:
event = dict(event)
session_payload = event.get("session")
if isinstance(session_payload, dict):
session_payload.pop("model", None)
return event
def _is_fatal_error(self, error: object | None) -> bool:
code = getattr(error, "code", None) or getattr(error, "type", None)
return (
isinstance(code, str)
and code
in {
"unsupported_transcription_model",
"unsupported_audio_transport",
"unsupported_audio_format",
}
) or super()._is_fatal_error(error)
__all__ = ["InferenceRealtimeModel", "InferenceRealtimeSession"]
from livekit.agents.inference import InferenceClass
from livekit.agents.inference.realtime.openai import (
RealtimeModel as InferenceRealtimeModel,
RealtimeSession as InferenceRealtimeSession,
)
__all__ = ["InferenceClass", "InferenceRealtimeModel", "InferenceRealtimeSession"]

Devin Review


Was this helpful? React with πŸ‘ or πŸ‘Ž to provide feedback.

@shawnfeldman shawnfeldman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving, with the scope of my review stated explicitly: I reviewed this as inference-gateway β€” the move fidelity and the hosted (LiveKit Inference) realtime client. I did not audit the 2.4k-line realtime protocol engine line by line, because it moves essentially unchanged.

Move fidelity. plugins/openai/realtime/realtime_model.py β†’ agents/llm/_realtime/openai.py differs by 37 lines out of 2449, and all but three are import re-homing (..log/..models/.utils β†’ absolute livekit.agents.* + .openai_types/.openai_utils). utils.py β†’ openai_utils.py likewise. Both old paths keep import * + __getattr__ shims, and test_plugin_import_is_canonical_class pins that the plugin import resolves to the canonical class.

The three non-move lines are the deliberate if type(self) is RealtimeModel: self._label = "livekit.plugins.openai.realtime.realtime_model.RealtimeModel" pin.

Hosted client (inference/realtime/openai.py) is a faithful port of inference_realtime_model.py β€” same three overrides (_create_ws_url_and_headers swapping in the inference token + X-LiveKit-Inference-Provider, _wrap_session_update stripping model from the session payload since the gateway takes it from ?model=, _is_fatal_error adding the three unsupported_* codes). Model is still required provider-prefixed, and self._opts.is_azure = False / api_version = None correctly keeps ambient Azure env off the gateway URL and wire format.

Rest of the delta is mechanical: resolve_credentials extracted from inference/llm.py (same env precedence, same messages), InferenceClass and RealtimeModels relocated to _utils/openai_types and re-exported. All 25 checks green including ruff, type-check 3.10/3.13, test-realtime, unit-tests and livekit-plugins-openai.

Two things worth a reply, neither blocking:

  1. Metrics label asymmetry. _label is f"{type(self).__module__}.{type(self).__name__}". You pinned the direct class's pre-move label, but the hosted one moves from livekit.plugins.openai.realtime.inference_realtime_model.InferenceRealtimeModel to livekit.agents.inference.realtime.openai.RealtimeModel. Presumably intended given the class is being renamed and re-namespaced on purpose β€” but it will shift RealtimeModelMetrics labels for hosted sessions, so anyone grouping dashboards on that string sees a break. Worth a line in the PR body if deliberate.

  2. Devin's second report says "1 new potential issue … not posted on this PR by your GitHub settings." It's only visible in the Devin UI, so it is outside what I can see from the PR. Please check it before merging.

No Critical or Important issues from my pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants