-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathrealtime_model.py
More file actions
1954 lines (1700 loc) ยท 82 KB
/
realtime_model.py
File metadata and controls
1954 lines (1700 loc) ยท 82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import base64
import contextlib
import copy
import json
import os
import time
import weakref
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any, Literal, overload
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
import aiohttp
from pydantic import BaseModel, ValidationError
from livekit import rtc
from livekit.agents import APIConnectionError, APIError, io, llm, utils
from livekit.agents.metrics import RealtimeModelMetrics
from livekit.agents.metrics.base import Metadata
from livekit.agents.types import (
DEFAULT_API_CONNECT_OPTIONS,
NOT_GIVEN,
APIConnectOptions,
NotGivenOr,
)
from livekit.agents.utils import is_given
from livekit.agents.voice.generation import remove_instructions
from openai.types import realtime
from openai.types.beta.realtime.session import (
InputAudioNoiseReduction,
InputAudioTranscription,
TurnDetection,
)
from openai.types.beta.realtime.session_update_event import (
Session as AzureSession,
SessionInputAudioNoiseReduction as AzureNoiseReduction,
SessionInputAudioTranscription as AzureInputAudioTranscription,
SessionTurnDetection as AzureTurnDetection,
SessionUpdateEvent as AzureSessionUpdateEvent,
)
from openai.types.realtime import (
AudioTranscription,
ConversationItemAdded,
ConversationItemCreateEvent,
ConversationItemDeletedEvent,
ConversationItemDeleteEvent,
ConversationItemInputAudioTranscriptionCompletedEvent,
ConversationItemInputAudioTranscriptionFailedEvent,
ConversationItemTruncateEvent,
InputAudioBufferAppendEvent,
InputAudioBufferClearEvent,
InputAudioBufferCommitEvent,
InputAudioBufferSpeechStartedEvent,
InputAudioBufferSpeechStoppedEvent,
NoiseReductionType,
RealtimeAudioConfig,
RealtimeAudioConfigInput,
RealtimeAudioConfigOutput,
RealtimeAudioInputTurnDetection,
RealtimeClientEvent,
RealtimeConversationItemFunctionCall,
RealtimeErrorEvent,
RealtimeFunctionTool,
RealtimeResponseCreateParams,
RealtimeSessionCreateRequest,
ResponseAudioDeltaEvent,
ResponseAudioDoneEvent,
ResponseCancelEvent,
ResponseContentPartAddedEvent,
ResponseCreatedEvent,
ResponseCreateEvent,
ResponseDoneEvent,
ResponseOutputItemAddedEvent,
ResponseOutputItemDoneEvent,
ResponseTextDeltaEvent,
ResponseTextDoneEvent,
SessionUpdateEvent,
)
from openai.types.realtime.realtime_audio_config_input import NoiseReduction
from openai.types.realtime.realtime_session_create_response import (
Tracing,
)
from openai.types.realtime.realtime_truncation import RealtimeTruncation
from ..log import logger
from ..models import RealtimeModels
from .utils import (
AZURE_DEFAULT_INPUT_AUDIO_TRANSCRIPTION,
AZURE_DEFAULT_TURN_DETECTION,
DEFAULT_MAX_RESPONSE_OUTPUT_TOKENS,
DEFAULT_MAX_SESSION_DURATION,
calculate_confidence_from_logprobs,
livekit_item_to_openai_item,
openai_item_to_livekit_item,
to_audio_transcription,
to_noise_reduction,
to_oai_tool_choice,
to_turn_detection,
)
# When a response is created with the OpenAI Realtime API, those events are sent in this order:
# 1. response.created (contains resp_id)
# 2. response.output_item.added (contains item_id)
# 3. conversation.item.added
# 4. response.content_part.added (type audio/text)
# 5. response.output_audio_transcript.delta (x2, x3, x4, etc)
# 6. response.output_audio.delta (x2, x3, x4, etc)
# 7. response.content_part.done
# 8. response.output_item.done (contains item_status: "completed/incomplete")
# 9. response.done (contains status_details for cancelled/failed/turn_detected/content_filter)
#
# Ourcode assumes a response will generate only one item with type "message"
SAMPLE_RATE = 24000
NUM_CHANNELS = 1
OPENAI_BASE_URL = "https://api.openai.com/v1"
DEFAULT_VOICE = "marin"
lk_oai_debug = int(os.getenv("LK_OPENAI_DEBUG", 0))
# Azure OpenAI Realtime API uses old-style (beta) event names.
# This mapping normalizes them to the current OpenAI GA event names
# so the handler code only deals with one set of names.
_AZURE_EVENT_MAPPING: dict[str, str] = {
"response.text.delta": "response.output_text.delta",
"response.text.done": "response.output_text.done",
"response.audio_transcript.delta": "response.output_audio_transcript.delta",
"response.audio_transcript.done": "response.output_audio_transcript.done",
"response.audio.delta": "response.output_audio.delta",
"response.audio.done": "response.output_audio.done",
"conversation.item.created": "conversation.item.added",
}
def _convert_model(obj: BaseModel, target_cls: type[BaseModel]) -> BaseModel:
"""Convert a Pydantic model to a different type with the same field structure."""
return target_cls.model_validate(
obj.model_dump(by_alias=True, exclude_unset=True, exclude_defaults=True)
)
def _oai_session_to_azure(session: RealtimeSessionCreateRequest) -> AzureSession:
"""Convert a new-style OpenAI RealtimeSessionCreateRequest to Azure's old-style flat format.
Azure OpenAI Realtime API doesn't support the newer nested `audio` config or
`output_modalities` / `type` fields. Instead it uses flat top-level fields like
`modalities`, `voice`, `input_audio_format`, `turn_detection`, etc.
"""
mapped: dict[str, Any] = {}
# Flatten output_modalities โ modalities (Azure uses the old field name)
# Azure requires ["audio", "text"] when audio is enabled โ ["audio"] alone is not allowed
if session.output_modalities is not None:
if "audio" in session.output_modalities:
mapped["modalities"] = ["audio", "text"]
else:
mapped["modalities"] = list(session.output_modalities)
mapped["input_audio_format"] = "pcm16"
mapped["output_audio_format"] = "pcm16"
# Flatten nested audio config to top-level fields, converting types
if session.audio is not None:
inp = session.audio.input
out = session.audio.output
if inp is not None:
if inp.noise_reduction is not None:
mapped["input_audio_noise_reduction"] = _convert_model(
inp.noise_reduction, AzureNoiseReduction
)
if inp.transcription is not None:
mapped["input_audio_transcription"] = _convert_model(
inp.transcription, AzureInputAudioTranscription
)
if inp.turn_detection is not None:
mapped["turn_detection"] = _convert_model(inp.turn_detection, AzureTurnDetection)
if out is not None:
if out.voice is not None:
mapped["voice"] = out.voice
if out.speed is not None:
mapped["speed"] = out.speed
# Fields that map 1:1
if session.model is not None:
mapped["model"] = session.model
if session.instructions is not None:
mapped["instructions"] = session.instructions
if session.tools is not None:
mapped["tools"] = session.tools
if session.tool_choice is not None:
mapped["tool_choice"] = session.tool_choice
if session.max_output_tokens is not None:
mapped["max_response_output_tokens"] = session.max_output_tokens
if session.tracing is not None:
mapped["tracing"] = session.tracing
return AzureSession.model_construct(**mapped)
def _normalize_azure_client_event(event: dict[str, Any]) -> None:
"""In-place normalization of client event dicts for Azure compatibility.
Azure uses "input_text" for all text content parts (including assistant messages),
while the new OpenAI API uses "output_text" for assistant content.
"""
item = event.get("item")
if item is None:
return
for content_part in item.get("content", ()):
if content_part.get("type") == "output_text":
content_part["type"] = "input_text"
@dataclass
class _RealtimeOptions:
model: str
voice: str
tool_choice: llm.ToolChoice | None
input_audio_transcription: AudioTranscription | None
input_audio_noise_reduction: NoiseReduction | None
turn_detection: RealtimeAudioInputTurnDetection | None
max_response_output_tokens: int | Literal["inf"] | None
tracing: Tracing | None
truncation: RealtimeTruncation | None
api_key: str | None
base_url: str
is_azure: bool
azure_deployment: str | None
entra_token: str | None
api_version: str | None
modalities: list[Literal["text", "audio"]]
max_session_duration: float | None
"""reset the connection after this many seconds if provided"""
conn_options: APIConnectOptions
speed: float = 1.0
@dataclass
class _MessageGeneration:
message_id: str
text_ch: utils.aio.Chan[str]
audio_ch: utils.aio.Chan[rtc.AudioFrame]
modalities: asyncio.Future[list[Literal["text", "audio"]]]
audio_transcript: str = ""
@dataclass
class _ResponseGeneration:
message_ch: utils.aio.Chan[llm.MessageGeneration]
function_ch: utils.aio.Chan[llm.FunctionCall]
messages: dict[str, _MessageGeneration]
_done_fut: asyncio.Future[None]
_created_timestamp: float
"""timestamp when the response was created"""
_first_token_timestamp: float | None = None
"""timestamp when the first token was received"""
class RealtimeModel(llm.RealtimeModel):
@overload
def __init__(
self,
*,
model: RealtimeModels | str = "gpt-realtime",
voice: str = DEFAULT_VOICE,
modalities: NotGivenOr[list[Literal["text", "audio"]]] = NOT_GIVEN,
input_audio_transcription: NotGivenOr[
AudioTranscription | InputAudioTranscription | None
] = NOT_GIVEN,
input_audio_noise_reduction: NotGivenOr[
NoiseReductionType | NoiseReduction | InputAudioNoiseReduction | None
] = NOT_GIVEN,
turn_detection: NotGivenOr[
RealtimeAudioInputTurnDetection | TurnDetection | 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,
api_key: str | None = None,
base_url: NotGivenOr[str] = NOT_GIVEN,
http_session: aiohttp.ClientSession | None = None,
max_session_duration: NotGivenOr[float | None] = NOT_GIVEN,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
temperature: NotGivenOr[float] = NOT_GIVEN, # deprecated, unused in v1
) -> None: ...
@overload
def __init__(
self,
*,
azure_deployment: str | None = None,
entra_token: str | None = None,
api_key: str | None = None,
api_version: str | None = None,
base_url: NotGivenOr[str] = NOT_GIVEN,
voice: str = DEFAULT_VOICE,
modalities: NotGivenOr[list[Literal["text", "audio"]]] = NOT_GIVEN,
input_audio_transcription: NotGivenOr[
AudioTranscription | InputAudioTranscription | None
] = NOT_GIVEN,
input_audio_noise_reduction: NotGivenOr[
NoiseReductionType | NoiseReduction | InputAudioNoiseReduction | None
] = NOT_GIVEN,
turn_detection: NotGivenOr[
RealtimeAudioInputTurnDetection | TurnDetection | 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,
http_session: aiohttp.ClientSession | None = None,
max_session_duration: NotGivenOr[float | None] = NOT_GIVEN,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
temperature: NotGivenOr[float] = NOT_GIVEN, # deprecated, unused in v1
) -> None: ...
def __init__(
self,
*,
model: str = "gpt-realtime",
voice: str = DEFAULT_VOICE,
modalities: NotGivenOr[list[Literal["text", "audio"]]] = NOT_GIVEN,
tool_choice: NotGivenOr[llm.ToolChoice | None] = NOT_GIVEN,
base_url: NotGivenOr[str] = NOT_GIVEN,
input_audio_transcription: NotGivenOr[
AudioTranscription | InputAudioTranscription | None
] = NOT_GIVEN,
input_audio_noise_reduction: NotGivenOr[
NoiseReductionType | NoiseReduction | InputAudioNoiseReduction | None
] = NOT_GIVEN,
turn_detection: NotGivenOr[
RealtimeAudioInputTurnDetection | TurnDetection | None
] = NOT_GIVEN,
speed: NotGivenOr[float] = NOT_GIVEN,
tracing: NotGivenOr[Tracing | None] = NOT_GIVEN,
truncation: NotGivenOr[RealtimeTruncation | None] = NOT_GIVEN,
api_key: str | None = None,
http_session: aiohttp.ClientSession | None = None,
azure_deployment: str | None = None,
entra_token: str | None = None,
api_version: str | None = None,
max_session_duration: NotGivenOr[float | None] = NOT_GIVEN,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
temperature: NotGivenOr[float] = NOT_GIVEN, # deprecated, unused in v1
) -> None:
"""
Initialize a Realtime model client for OpenAI or Azure OpenAI.
Args:
model (str): Realtime model name, e.g., "gpt-realtime".
voice (str): Voice used for audio responses. Defaults to "marin".
modalities (list[Literal["text", "audio"]] | NotGiven): Modalities to enable. Defaults to ["text", "audio"] if not provided.
tool_choice (llm.ToolChoice | None | NotGiven): Tool selection policy for responses.
base_url (str | NotGiven): HTTP base URL of the OpenAI/Azure API. If not provided, uses OPENAI_BASE_URL for OpenAI; for Azure, constructed from AZURE_OPENAI_ENDPOINT.
input_audio_transcription (AudioTranscription | None | NotGiven): Options for transcribing input audio.
input_audio_noise_reduction (NoiseReductionType | NoiseReduction | InputAudioNoiseReduction | None | NotGiven): Input audio noise reduction settings.
turn_detection (RealtimeAudioInputTurnDetection | None | NotGiven): Server-side turn-detection options.
speed (float | NotGiven): Audio playback speed multiplier.
tracing (Tracing | None | NotGiven): Tracing configuration for OpenAI Realtime.
truncation (RealtimeTruncation | None | NotGiven): Truncation configuration for OpenAI Realtime.
api_key (str | None): OpenAI API key. If None and not using Azure, read from OPENAI_API_KEY.
http_session (aiohttp.ClientSession | None): Optional shared HTTP session.
azure_deployment (str | None): Azure deployment name. Presence of any Azure-specific option enables Azure mode.
entra_token (str | None): Azure Entra token auth (alternative to api_key).
api_version (str | None): Azure OpenAI API version appended as query parameter.
max_session_duration (float | None | NotGiven): Seconds before recycling the connection.
conn_options (APIConnectOptions): Retry/backoff and connection settings.
temperature (float | NotGiven): Deprecated; ignored by Realtime v1.
Raises:
ValueError: If OPENAI_API_KEY is missing in non-Azure mode, or if Azure endpoint cannot be determined when in Azure mode.
Examples:
Basic OpenAI usage:
```python
from livekit.plugins.openai.realtime import RealtimeModel
from openai.types import realtime
model = RealtimeModel(
voice="marin",
modalities=["audio"],
input_audio_transcription=realtime.AudioTranscription(
model="gpt-4o-transcribe",
),
input_audio_noise_reduction="near_field",
turn_detection=realtime.realtime_audio_input_turn_detection.SemanticVad(
type="semantic_vad",
create_response=True,
eagerness="auto",
interrupt_response=True,
),
)
session = AgentSession(llm=model)
```
"""
modalities = modalities if is_given(modalities) else ["text", "audio"]
super().__init__(
capabilities=llm.RealtimeCapabilities(
message_truncation=True,
turn_detection=turn_detection is not None,
user_transcription=input_audio_transcription is not None,
auto_tool_reply_generation=False,
audio_output="audio" in modalities,
manual_function_calls=True,
per_response_tool_choice=True,
)
)
is_azure = (
api_version is not None or entra_token is not None or azure_deployment is not None
)
api_key = api_key or os.environ.get("OPENAI_API_KEY")
if api_key is None and not is_azure:
raise ValueError(
"The api_key client option must be set either by passing api_key "
"to the client or by setting the OPENAI_API_KEY environment variable"
)
if is_given(base_url):
base_url_val = base_url
else:
if is_azure:
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
if azure_endpoint is None:
raise ValueError(
"Missing Azure endpoint. Please pass base_url "
"or set AZURE_OPENAI_ENDPOINT environment variable."
)
base_url_val = f"{azure_endpoint.rstrip('/')}/openai"
else:
base_url_val = OPENAI_BASE_URL
self._opts = _RealtimeOptions(
model=model,
voice=voice,
tool_choice=tool_choice or None,
modalities=modalities,
input_audio_transcription=to_audio_transcription(input_audio_transcription),
input_audio_noise_reduction=to_noise_reduction(input_audio_noise_reduction),
turn_detection=to_turn_detection(turn_detection),
api_key=api_key,
base_url=base_url_val,
is_azure=is_azure,
azure_deployment=azure_deployment,
entra_token=entra_token,
api_version=api_version,
max_response_output_tokens=DEFAULT_MAX_RESPONSE_OUTPUT_TOKENS, # type: ignore
speed=speed if is_given(speed) else 1.0,
tracing=tracing if is_given(tracing) else None,
truncation=truncation if is_given(truncation) else None,
max_session_duration=max_session_duration
if is_given(max_session_duration)
else DEFAULT_MAX_SESSION_DURATION,
conn_options=conn_options,
)
self._http_session = http_session
self._http_session_owned = False
self._sessions = weakref.WeakSet[RealtimeSession]()
@property
def model(self) -> str:
return self._opts.model
@property
def provider(self) -> str:
from urllib.parse import urlparse
return urlparse(self._opts.base_url).netloc
@classmethod
def with_azure(
cls,
*,
azure_deployment: str,
azure_endpoint: str | None = None,
api_version: str | None = None,
api_key: str | None = None,
entra_token: str | None = None,
base_url: str | None = None,
voice: str = DEFAULT_VOICE,
modalities: NotGivenOr[list[Literal["text", "audio"]]] = NOT_GIVEN,
input_audio_transcription: NotGivenOr[
AudioTranscription | InputAudioTranscription | None
] = NOT_GIVEN,
input_audio_noise_reduction: NoiseReductionType | InputAudioNoiseReduction | None = None,
turn_detection: NotGivenOr[
RealtimeAudioInputTurnDetection | TurnDetection | None
] = NOT_GIVEN,
speed: NotGivenOr[float] = NOT_GIVEN,
tracing: NotGivenOr[Tracing | None] = NOT_GIVEN,
http_session: aiohttp.ClientSession | None = None,
temperature: NotGivenOr[float] = NOT_GIVEN, # deprecated, unused in v1
) -> RealtimeModel:
"""
Create a RealtimeModel configured for Azure OpenAI.
Args:
azure_deployment (str): Azure OpenAI deployment name.
azure_endpoint (str | None): Azure endpoint URL; if None, taken from AZURE_OPENAI_ENDPOINT.
api_version (str | None): Azure API version; if None, taken from OPENAI_API_VERSION.
api_key (str | None): Azure API key; if None, taken from AZURE_OPENAI_API_KEY. Omit if using `entra_token`.
entra_token (str | None): Azure Entra token for AAD auth. Provide instead of `api_key`.
base_url (str | None): Explicit base URL. Mutually exclusive with `azure_endpoint`. If provided, used as-is.
voice (str): Voice used for audio responses.
modalities (list[Literal["text", "audio"]] | NotGiven): Modalities to enable. Defaults to ["text", "audio"] if not provided.
input_audio_transcription (AudioTranscription | InputAudioTranscription | None | NotGiven): Transcription options; defaults to Azure-optimized values when not provided.
input_audio_noise_reduction (NoiseReductionType | InputAudioNoiseReduction | None): Input noise reduction settings. Defaults to None.
turn_detection (RealtimeAudioInputTurnDetection | TurnDetection | None | NotGiven): Server-side VAD; defaults to Azure-optimized values when not provided.
speed (float | NotGiven): Audio playback speed multiplier.
tracing (Tracing | None | NotGiven): Tracing configuration for OpenAI Realtime.
http_session (aiohttp.ClientSession | None): Optional shared HTTP session.
temperature (float | NotGiven): Deprecated; ignored by Realtime v1.
Returns:
RealtimeModel: Configured client for Azure OpenAI Realtime.
Raises:
ValueError: If credentials are missing, `api_version` is not provided, Azure endpoint cannot be determined, or both `base_url` and `azure_endpoint` are provided.
Examples:
Azure usage with api-version 2024-10-01-preview:
```python
from livekit.plugins.openai.realtime import RealtimeModel
from openai.types.beta import realtime
model = openai.realtime.RealtimeModel.with_azure(
azure_deployment="gpt-realtime",
azure_endpoint="https://yourendpoint.azure.com",
api_version="2024-10-01-preview",
api_key="your-api-key",
modalities=["text", "audio"],
input_audio_transcription=realtime.session.InputAudioTranscription(
model="gpt-4o-transcribe",
),
input_audio_noise_reduction=realtime.session.InputAudioNoiseReduction(
type="near_field",
),
turn_detection=realtime.session.TurnDetection(
type="semantic_vad",
create_response=True,
eagerness="auto",
interrupt_response=True,
),
)
```
Azure usage with api-version 2025-08-28:
```python
from livekit.plugins.openai.realtime import RealtimeModel
from openai.types import realtime
model = RealtimeModel(
azure_deployment="gpt-realtime",
azure_endpoint="https://yourendpoint.azure.com",
api_version="2024-10-01-preview",
api_key="your-api-key",
input_audio_transcription=realtime.AudioTranscription(
model="gpt-4o-transcribe",
),
input_audio_noise_reduction="near_field",
turn_detection=realtime.realtime_audio_input_turn_detection.SemanticVad(
type="semantic_vad",
create_response=True,
eagerness="auto",
interrupt_response=True,
),
)
```
"""
api_key = api_key or os.getenv("AZURE_OPENAI_API_KEY")
if api_key is None and entra_token is None:
raise ValueError(
"Missing credentials. Please pass one of `api_key`, `entra_token`, "
"or the `AZURE_OPENAI_API_KEY` environment variable."
)
api_version = api_version or os.getenv("OPENAI_API_VERSION")
if api_version is None:
raise ValueError(
"Must provide either the `api_version` argument or the "
"`OPENAI_API_VERSION` environment variable"
)
if base_url is None:
azure_endpoint = azure_endpoint or os.getenv("AZURE_OPENAI_ENDPOINT")
if azure_endpoint is None:
raise ValueError(
"Missing Azure endpoint. Please pass the `azure_endpoint` "
"parameter or set the `AZURE_OPENAI_ENDPOINT` environment variable."
)
base_url = f"{azure_endpoint.rstrip('/')}/openai"
elif azure_endpoint is not None:
raise ValueError("base_url and azure_endpoint are mutually exclusive")
if not is_given(input_audio_transcription):
input_audio_transcription = AZURE_DEFAULT_INPUT_AUDIO_TRANSCRIPTION
if not is_given(turn_detection):
turn_detection = AZURE_DEFAULT_TURN_DETECTION
return RealtimeModel(
voice=voice,
modalities=modalities,
input_audio_transcription=input_audio_transcription,
input_audio_noise_reduction=input_audio_noise_reduction,
turn_detection=turn_detection,
speed=speed,
tracing=tracing,
api_key=api_key,
http_session=http_session,
azure_deployment=azure_deployment,
api_version=api_version,
entra_token=entra_token,
base_url=base_url,
)
def update_options(
self,
*,
voice: NotGivenOr[str] = NOT_GIVEN,
turn_detection: NotGivenOr[
RealtimeAudioInputTurnDetection | TurnDetection | None
] = NOT_GIVEN,
tool_choice: NotGivenOr[llm.ToolChoice | None] = NOT_GIVEN,
input_audio_transcription: NotGivenOr[
InputAudioTranscription | AudioTranscription | None
] = NOT_GIVEN,
input_audio_noise_reduction: NotGivenOr[
NoiseReduction | NoiseReductionType | InputAudioNoiseReduction | None
] = NOT_GIVEN,
max_response_output_tokens: NotGivenOr[int | Literal["inf"] | None] = NOT_GIVEN,
speed: NotGivenOr[float] = NOT_GIVEN,
tracing: NotGivenOr[Tracing | None] = NOT_GIVEN,
truncation: NotGivenOr[RealtimeTruncation | None] = NOT_GIVEN,
temperature: NotGivenOr[float] = NOT_GIVEN, # deprecated, unused in v1
) -> None:
if is_given(voice):
self._opts.voice = voice
if is_given(turn_detection):
self._opts.turn_detection = to_turn_detection(turn_detection)
if is_given(tool_choice):
self._opts.tool_choice = tool_choice
if is_given(input_audio_transcription):
self._opts.input_audio_transcription = to_audio_transcription(input_audio_transcription)
if is_given(input_audio_noise_reduction):
self._opts.input_audio_noise_reduction = to_noise_reduction(input_audio_noise_reduction)
if is_given(max_response_output_tokens):
self._opts.max_response_output_tokens = max_response_output_tokens
if is_given(speed):
self._opts.speed = speed
if is_given(tracing):
self._opts.tracing = tracing
if is_given(truncation):
self._opts.truncation = truncation
for sess in self._sessions:
sess.update_options(
voice=voice,
turn_detection=self._opts.turn_detection,
tool_choice=tool_choice,
input_audio_transcription=self._opts.input_audio_transcription,
input_audio_noise_reduction=self._opts.input_audio_noise_reduction,
max_response_output_tokens=max_response_output_tokens,
speed=speed,
tracing=tracing,
truncation=truncation,
)
def _ensure_http_session(self) -> aiohttp.ClientSession:
if not self._http_session:
try:
self._http_session = utils.http_context.http_session()
except RuntimeError:
self._http_session = aiohttp.ClientSession()
self._http_session_owned = True
return self._http_session
def session(self) -> RealtimeSession:
sess = RealtimeSession(self)
self._sessions.add(sess)
return sess
async def aclose(self) -> None:
if self._http_session_owned and self._http_session:
await self._http_session.close()
def process_base_url(
url: str,
model: str,
is_azure: bool = False,
azure_deployment: str | None = None,
api_version: str | None = None,
) -> str:
if url.startswith("http"):
url = url.replace("http", "ws", 1)
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
# ensure "/realtime" is added if the path is empty OR "/v1"
if not parsed_url.path or parsed_url.path.rstrip("/") in ["", "/v1", "/openai", "/openai/v1"]:
path = parsed_url.path.rstrip("/") + "/realtime"
else:
path = parsed_url.path
if is_azure:
if api_version:
query_params["api-version"] = [api_version]
if azure_deployment:
query_params["deployment"] = [azure_deployment]
else:
if "model" not in query_params:
query_params["model"] = [model]
new_query = urlencode(query_params, doseq=True)
new_url = urlunparse((parsed_url.scheme, parsed_url.netloc, path, "", new_query, ""))
return new_url
class RealtimeSession(
llm.RealtimeSession[Literal["openai_server_event_received", "openai_client_event_queued"]]
):
"""
A session for the OpenAI Realtime API.
This class is used to interact with the OpenAI Realtime API.
It is responsible for sending events to the OpenAI Realtime API and receiving events from it.
It exposes two more events:
- openai_server_event_received: expose the raw server events from the OpenAI Realtime API
- openai_client_event_queued: expose the raw client events sent to the OpenAI Realtime API
"""
def __init__(self, realtime_model: RealtimeModel) -> None:
super().__init__(realtime_model)
self._realtime_model: RealtimeModel = realtime_model
self._tools = llm.ToolContext.empty()
self._msg_ch = utils.aio.Chan[RealtimeClientEvent | dict[str, Any]]()
self._input_resampler: rtc.AudioResampler | None = None
self._instructions: str | None = None
self._main_atask = asyncio.create_task(self._main_task(), name="RealtimeSession._main_task")
self.send_event(self._create_session_update_event())
self._response_created_futures: dict[str, asyncio.Future[llm.GenerationCreatedEvent]] = {}
self._item_delete_future: dict[str, asyncio.Future] = {}
self._item_create_future: dict[str, asyncio.Future] = {}
self._current_generation: _ResponseGeneration | None = None
self._remote_chat_ctx = llm.remote_chat_context.RemoteChatContext()
self._update_chat_ctx_lock = asyncio.Lock()
self._update_fnc_ctx_lock = asyncio.Lock()
# 100ms chunks
self._bstream = utils.audio.AudioByteStream(
SAMPLE_RATE, NUM_CHANNELS, samples_per_channel=SAMPLE_RATE // 10
)
self._pushed_duration_s: float = 0 # duration of audio pushed to the OpenAI Realtime API
def send_event(self, event: RealtimeClientEvent | dict[str, Any]) -> None:
with contextlib.suppress(utils.aio.channel.ChanClosed):
self._msg_ch.send_nowait(event)
@utils.log_exceptions(logger=logger)
async def _main_task(self) -> None:
num_retries: int = 0
max_retries = self._realtime_model._opts.conn_options.max_retry
async def _reconnect() -> None:
logger.debug(
"reconnecting to OpenAI Realtime API",
extra={"max_session_duration": self._realtime_model._opts.max_session_duration},
)
events: list[RealtimeClientEvent | dict[str, Any]] = []
# options and instructions
events.append(self._create_session_update_event())
# tools
tools = self._tools.flatten()
if tools:
events.append(self._create_tools_update_event(tools))
# chat context
chat_ctx = self.chat_ctx.copy(
exclude_function_call=True,
exclude_instructions=True,
exclude_empty_message=True,
exclude_handoff=True,
exclude_config_update=True,
)
old_chat_ctx = self._remote_chat_ctx
self._remote_chat_ctx = llm.remote_chat_context.RemoteChatContext()
events.extend(self._create_update_chat_ctx_events(chat_ctx))
try:
for ev in events:
# certain events could already be in dict format
if isinstance(ev, BaseModel):
ev = ev.model_dump(
by_alias=True, exclude_unset=True, exclude_defaults=False
)
if self._realtime_model._opts.is_azure:
_normalize_azure_client_event(ev)
self.emit("openai_client_event_queued", ev)
await ws_conn.send_str(json.dumps(ev))
except Exception as e:
self._remote_chat_ctx = old_chat_ctx # restore the old chat context
raise APIConnectionError(
message=(
"Failed to send message to OpenAI Realtime API during session re-connection"
),
) from e
for fut in self._response_created_futures.values():
if not fut.done():
fut.set_exception(
llm.RealtimeError("pending response discarded due to session reconnection")
)
self._response_created_futures.clear()
self._close_current_generation("session reconnection")
logger.debug("reconnected to OpenAI Realtime API")
self.emit("session_reconnected", llm.RealtimeSessionReconnectedEvent())
reconnecting = False
while not self._msg_ch.closed:
try:
ws_conn = await self._create_ws_conn()
if reconnecting:
await _reconnect()
num_retries = 0 # reset the retry counter
await self._run_ws(ws_conn)
except APIError as e:
if max_retries == 0 or not e.retryable:
self._emit_error(e, recoverable=False)
raise
elif num_retries == max_retries:
self._emit_error(e, recoverable=False)
raise APIConnectionError(
f"OpenAI Realtime API connection failed after {num_retries} attempts",
) from e
else:
self._emit_error(e, recoverable=True)
retry_interval = self._realtime_model._opts.conn_options._interval_for_retry(
num_retries
)
logger.warning(
f"OpenAI Realtime API connection failed, retrying in {retry_interval}s",
exc_info=e,
extra={"attempt": num_retries, "max_retries": max_retries},
)
await asyncio.sleep(retry_interval)
num_retries += 1
except Exception as e:
self._emit_error(e, recoverable=False)
raise
reconnecting = True
async def _create_ws_conn(self) -> aiohttp.ClientWebSocketResponse:
headers = {"User-Agent": "LiveKit Agents"}
if self._realtime_model._opts.is_azure:
if self._realtime_model._opts.entra_token:
headers["Authorization"] = f"Bearer {self._realtime_model._opts.entra_token}"
if self._realtime_model._opts.api_key:
headers["api-key"] = self._realtime_model._opts.api_key
else:
headers["Authorization"] = f"Bearer {self._realtime_model._opts.api_key}"
url = process_base_url(
self._realtime_model._opts.base_url,
self._realtime_model._opts.model,
is_azure=self._realtime_model._opts.is_azure,
api_version=self._realtime_model._opts.api_version,
azure_deployment=self._realtime_model._opts.azure_deployment,
)
if lk_oai_debug:
logger.debug(f"connecting to Realtime API: {url}")
t0 = time.perf_counter()
try:
ws = await asyncio.wait_for(
self._realtime_model._ensure_http_session().ws_connect(url=url, headers=headers),
self._realtime_model._opts.conn_options.timeout,
)
self._report_connection_acquired(time.perf_counter() - t0)
return ws
except aiohttp.ClientError as e:
raise APIConnectionError("OpenAI Realtime API client connection error") from e
except asyncio.TimeoutError as e:
raise APIConnectionError(
message="OpenAI Realtime API connection timed out",
) from e
async def _run_ws(self, ws_conn: aiohttp.ClientWebSocketResponse) -> None:
closing = False
@utils.log_exceptions(logger=logger)
async def _send_task() -> None:
nonlocal closing
async for msg in self._msg_ch:
try:
if isinstance(msg, BaseModel):
msg = msg.model_dump(
by_alias=True, exclude_unset=True, exclude_defaults=False
)
# Azure uses "input_text" for all content parts, while
# the new API uses "output_text" for assistant content.
if self._realtime_model._opts.is_azure:
_normalize_azure_client_event(msg)
self.emit("openai_client_event_queued", msg)
await ws_conn.send_str(json.dumps(msg))
if lk_oai_debug:
msg_copy = msg.copy()
if msg_copy["type"] == "input_audio_buffer.append":
msg_copy = {**msg_copy, "audio": "..."}
logger.debug(f">>> {msg_copy}")
except Exception:
logger.exception("failed to send event")
closing = True
await ws_conn.close()
@utils.log_exceptions(logger=logger)
async def _recv_task() -> None:
while True:
msg = await ws_conn.receive()
if msg.type in (
aiohttp.WSMsgType.CLOSED,
aiohttp.WSMsgType.CLOSE,
aiohttp.WSMsgType.CLOSING,
):
if closing: # closing is expected, see _send_task
return
# this will trigger a reconnection
raise APIConnectionError(message="OpenAI S2S connection closed unexpectedly")
if msg.type != aiohttp.WSMsgType.TEXT:
continue
event = json.loads(msg.data)
# Azure OpenAI uses old-style event names from the beta API.
# Normalize them to the current OpenAI event names so the rest
# of the handler code only needs to deal with one set of names.
if self._realtime_model._opts.is_azure:
event_type = event.get("type", "")
normalized = _AZURE_EVENT_MAPPING.get(event_type)
if normalized is not None:
event["type"] = normalized
# emit the raw json dictionary instead of the BaseModel because different
# providers can have different event types that are not part of the OpenAI Realtime API # noqa: E501
self.emit("openai_server_event_received", event)
try:
if lk_oai_debug:
event_copy = event.copy()
if event_copy["type"] == "response.output_audio.delta":
event_copy = {**event_copy, "delta": "..."}
logger.debug(f"<<< {event_copy}")