99
1010logger = logging .getLogger ("elevenlabs.speech_engine" )
1111
12+
13+ def _make_log (
14+ debug : bool ,
15+ ) -> typing .Callable [..., None ]:
16+ """Return a per-instance log function, mirroring the JS SDK pattern."""
17+ if debug :
18+ def _log (msg : str , * args : typing .Any ) -> None :
19+ print ("[SpeechEngine]" , msg % args if args else msg )
20+ return _log
21+ return lambda * _args , ** _kw : None
22+
1223Callback = typing .Callable [..., typing .Any ]
1324
1425
@@ -170,15 +181,7 @@ def __init__(
170181 self ._closed = False
171182 self ._event_handlers = {} # type: typing.Dict[str, typing.List[Callback]]
172183 self ._once_handlers = {} # type: typing.Dict[str, typing.List[Callback]]
173-
174- if debug :
175- logger .setLevel (logging .DEBUG )
176- if not logger .handlers :
177- handler = logging .StreamHandler ()
178- handler .setFormatter (
179- logging .Formatter ("[SpeechEngine] %(message)s" )
180- )
181- logger .addHandler (handler )
184+ self ._log = _make_log (debug )
182185
183186 # ------------------------------------------------------------------
184187 # Event emitter interface
@@ -238,7 +241,7 @@ async def run(self) -> None:
238241 except asyncio .CancelledError :
239242 raise
240243 except Exception :
241- logger . debug ("WebSocket connection lost" )
244+ self . _log ("WebSocket connection lost" )
242245 break
243246
244247 try :
@@ -290,15 +293,15 @@ async def send_response(
290293 return
291294
292295 if isinstance (response , str ):
293- logger . debug (
296+ self . _log (
294297 'sending string response: "%s", event_id=%s' ,
295298 response ,
296299 self ._current_event_id ,
297300 )
298301 await self ._send_agent_response (response , False )
299302 await self ._send_agent_response ("" , True )
300303 else :
301- logger . debug (
304+ self . _log (
302305 "starting streamed response, event_id=%s" ,
303306 self ._current_event_id ,
304307 )
@@ -325,7 +328,7 @@ async def _handle_message(self, msg: typing.Dict[str, typing.Any]) -> None:
325328
326329 if msg_type == "init" :
327330 self ._conversation_id = msg .get ("conversation_id" )
328- logger . debug (
331+ self . _log (
329332 "session initialized, conversation_id=%s" ,
330333 self ._conversation_id ,
331334 )
@@ -339,7 +342,7 @@ async def _handle_message(self, msg: typing.Dict[str, typing.Any]) -> None:
339342 and self ._current_task is not None
340343 and not self ._current_task .done ()
341344 ):
342- logger . debug (
345+ self . _log (
343346 "skipping duplicate transcript, event_id=%s" ,
344347 incoming_event_id ,
345348 )
@@ -351,7 +354,7 @@ async def _handle_message(self, msg: typing.Dict[str, typing.Any]) -> None:
351354 )
352355 await self ._cancel_current_and_wait ()
353356 if was_active :
354- logger . debug (
357+ self . _log (
355358 "interrupted: cancelling previous response "
356359 "(event_id=%s) for new transcript (event_id=%s)" ,
357360 self ._current_event_id ,
@@ -360,16 +363,20 @@ async def _handle_message(self, msg: typing.Dict[str, typing.Any]) -> None:
360363
361364 self ._current_event_id = incoming_event_id
362365 transcript_data = msg .get ("user_transcript" , [])
363- logger . debug (
366+ self . _log (
364367 "received transcript, event_id=%s, messages=%d" ,
365368 self ._current_event_id ,
366369 len (transcript_data ),
367370 )
368371
369- transcript = [
370- ConversationMessage (role = m ["role" ], content = m ["content" ])
371- for m in transcript_data
372- ]
372+ try :
373+ transcript = [
374+ ConversationMessage (role = m ["role" ], content = m ["content" ])
375+ for m in transcript_data
376+ ]
377+ except (KeyError , TypeError ) as e :
378+ await self ._emit ("error" , e )
379+ return
373380
374381 handlers = list (
375382 self ._event_handlers .get ("user_transcript" , [])
@@ -419,7 +426,7 @@ async def _stream_response(self, stream: typing.Any) -> None:
419426 try :
420427 async for chunk in stream :
421428 if self ._closed :
422- logger . debug (
429+ self . _log (
423430 "stream stopped: session closed after %d chunks, "
424431 "event_id=%s" ,
425432 chunks ,
@@ -431,7 +438,7 @@ async def _stream_response(self, stream: typing.Any) -> None:
431438 chunks += 1
432439 await self ._send_agent_response (text , False , event_id )
433440 if not self ._closed :
434- logger . debug (
441+ self . _log (
435442 "stream complete: %d chunks sent, event_id=%s" ,
436443 chunks ,
437444 event_id ,
0 commit comments