@@ -81,7 +81,6 @@ def __init__(
81
81
self ._model_config = model_config or {}
82
82
self ._event_queue : asyncio .Queue [RealtimeSessionEvent ] = asyncio .Queue ()
83
83
self ._closed = False
84
- self ._background_task : asyncio .Task [None ] | None = None
85
84
86
85
async def __aenter__ (self ) -> RealtimeSession :
87
86
"""Start the session by connecting to the model. After this, you will be able to stream
@@ -129,14 +128,6 @@ async def close(self) -> None:
129
128
self ._model .remove_listener (self )
130
129
await self ._model .close ()
131
130
132
- # Cancel any background tasks
133
- if self ._background_task and not self ._background_task .done ():
134
- self ._background_task .cancel ()
135
- try :
136
- await self ._background_task
137
- except asyncio .CancelledError :
138
- pass
139
-
140
131
async def send_message (self , message : RealtimeUserInput ) -> None :
141
132
"""Send a message to the model."""
142
133
await self ._model .send_message (message )
@@ -155,16 +146,15 @@ async def on_event(self, event: RealtimeModelEvent) -> None:
155
146
if event .type == "error" :
156
147
await self ._put_event (RealtimeError (info = self ._event_info , error = event .error ))
157
148
elif event .type == "function_call" :
158
- # Handle tool calls in the background to avoid blocking event stream
159
- self ._background_task = asyncio .create_task (self ._handle_tool_call (event ))
149
+ await self ._handle_tool_call (event )
160
150
elif event .type == "audio" :
161
151
await self ._put_event (RealtimeAudio (info = self ._event_info , audio = event ))
162
152
elif event .type == "audio_interrupted" :
163
153
await self ._put_event (RealtimeAudioInterrupted (info = self ._event_info ))
164
154
elif event .type == "audio_done" :
165
155
await self ._put_event (RealtimeAudioEnd (info = self ._event_info ))
166
156
elif event .type == "conversation.item.input_audio_transcription.completed" :
167
- self ._history = self ._get_new_history (self ._history , event )
157
+ self ._history = RealtimeSession ._get_new_history (self ._history , event )
168
158
await self ._put_event (
169
159
RealtimeHistoryUpdated (info = self ._event_info , history = self ._history )
170
160
)
@@ -250,8 +240,9 @@ async def _handle_tool_call(self, event: RealtimeModelToolCallEvent) -> None:
250
240
# TODO (rm) Add error handling
251
241
pass
252
242
243
+ @classmethod
253
244
def _get_new_history (
254
- self ,
245
+ cls ,
255
246
old_history : list [RealtimeItem ],
256
247
event : RealtimeModelInputAudioTranscriptionCompletedEvent | RealtimeItem ,
257
248
) -> list [RealtimeItem ]:
@@ -296,5 +287,6 @@ def _get_new_history(
296
287
new_history = old_history .copy ()
297
288
new_history .insert (previous_index + 1 , event )
298
289
return new_history
290
+
299
291
# Otherwise, add it to the end
300
292
return old_history + [event ]
0 commit comments