Repository navigation
Move OpenAI Realtime inference client into agents core - #7318
Conversation
145ef3f to
ad7833b
Compare
There was a problem hiding this comment.
Devin Review found 1 new potential issue.
1 flag not posted on this PR by your GitHub settings β view it in Devin Review. (Configure)
| 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"] |
There was a problem hiding this comment.
π‘ Legacy inference class import removed
Importing InferenceClass from the legacy hosted module now raises ImportError. Applications retaining this compatibility import fail during startup.
| 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"] |
Was this helpful? React with π or π to provide feedback.
shawnfeldman
left a comment
There was a problem hiding this comment.
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:
-
Metrics label asymmetry.
_labelisf"{type(self).__module__}.{type(self).__name__}". You pinned the direct class's pre-move label, but the hosted one moves fromlivekit.plugins.openai.realtime.inference_realtime_model.InferenceRealtimeModeltolivekit.agents.inference.realtime.openai.RealtimeModel. Presumably intended given the class is being renamed and re-namespaced on purpose β but it will shiftRealtimeModelMetricslabels for hosted sessions, so anyone grouping dashboards on that string sees a break. Worth a line in the PR body if deliberate. -
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.
Summary
Compatibility
Validation