Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ async with AsyncRealTimeTranscriber(RealTimeTranscriberOptions(token=token_from_
- Don't feed `AsyncRealTimeTranscriber.stream()` from a sync generator that blocks (e.g. `time.sleep` pacing) — it starves the read task. Use an `async def` generator with `await asyncio.sleep(...)` instead.
- `format_turns=True` enables punctuation/casing on end-of-turns. Set it at connect: the server ignores `format_turns` and `filter_profanity` in a mid-session `UpdateConfiguration`, and `set_params` logs a warning when either is set.
- `AsyncRealTimeTranscriber` used as `async with` calls `disconnect(terminate=True)` on normal block exit and `disconnect(terminate=False)` on exception — no explicit `disconnect()` needed inside the block.
- A server message the client cannot read (not JSON, not an object, or failing validation) is logged at warning level and skipped; the session goes on. The warning names the message type and the failing fields, never the contents. An `Error` or `Termination` message that fails validation still ends the session: it is delivered with the fields that could be read (`code` / durations `None` otherwise).

## Text-to-Speech

Expand Down
2 changes: 1 addition & 1 deletion assemblyai/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "1.10.12"
__version__ = "1.10.13"
114 changes: 112 additions & 2 deletions assemblyai/streaming/v3/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

- Wire-format helpers (``_dump_model``, ``_parse_model``, ``_build_uri``,
``_build_headers``, parameter normalization, user-agent construction).
- Inbound message parsing (``_parse_message`` + ``_parse_event_type``).
- Inbound message parsing (``_read_event``, ``_parse_message``,
``_parse_event_type``).
- Connection-closed error mapping (``_build_connection_closed_error``).
- The ``_BaseStreamingClient`` base class with shared init state and
the ``on(...)`` handler-registration entrypoint.
Expand All @@ -24,7 +25,7 @@
from urllib.parse import urlencode

import websockets
from pydantic import BaseModel
from pydantic import BaseModel, ValidationError

from assemblyai import __version__

Expand Down Expand Up @@ -71,6 +72,30 @@ def _parse_model(model_class: Type[_M], data: Dict[str, Any]) -> _M:
return model_class.parse_obj(data)


def _int_or_none(value: Any) -> Optional[int]:
"""Returns ``value`` when it is an integer, else ``None``."""
if isinstance(value, int) and not isinstance(value, bool):
return value
return None


def _describe_parse_failure(exc: Exception) -> str:
"""Names what failed to parse, for a log line.

Leaves out the exception's own text. pydantic v2 puts the rejected input
in it, and for a ``Turn`` that input is the transcript.
"""
if isinstance(exc, ValidationError):
try:
return "; ".join(
f"{'.'.join(str(part) for part in error['loc'])}: {error['type']}"
for error in exc.errors()
)
except Exception:
pass
return type(exc).__name__


def _normalize_min_turn_silence(params_dict: dict) -> dict:
"""Collapse `min_end_of_turn_silence_when_confident` into `min_turn_silence` so only
one wire key is ever sent. Emits deprecation warnings."""
Expand Down Expand Up @@ -319,6 +344,91 @@ def _parse_message(cls, data: Dict[str, Any]) -> Optional[EventMessage]:
return _parse_model(ErrorEvent, data)
return None

@classmethod
def _read_event(cls, message_data: Any) -> Optional[EventMessage]:
"""Decode and parse one inbound frame. No frame content makes it raise.

Both read loops call this. An exception that left a read loop would
end the read thread or task without an ``Error`` event, and the
session would deliver nothing more while audio was still being sent.

Returns ``None``, after logging a warning, for a frame to skip: one
that is not JSON, is not a JSON object, has an unsupported type, or
fails to parse. An ``Error`` or ``Termination`` message that fails to
parse is not skipped; see ``_terminal_event_from_unreadable``.
"""
try:
data = json.loads(message_data)
except Exception as exc:
# ``JSONDecodeError``; ``UnicodeDecodeError`` for a binary frame
# that is not UTF-8; ``RecursionError`` for JSON nested too deep.
logger.warning(f"Failed to decode message: {exc}")
return None

if not isinstance(data, dict):
logger.warning(
"Ignoring message that is not a JSON object: %s",
type(data).__name__,
)
return None

# Logged only when it is a string: any other value is message content.
message_type = data.get("type")
if not isinstance(message_type, str):
message_type = None

try:
message = cls._parse_message(data)
except Exception as exc:
# pydantic ``ValidationError``; pydantic v1 also lets some
# conversion errors through, such as ``OverflowError``.
logger.warning(
"Failed to parse %s message (%s)",
message_type,
_describe_parse_failure(exc),
)
return cls._terminal_event_from_unreadable(data)

if message is None:
logger.warning("Unsupported event type: %s", message_type)

return message

@classmethod
def _terminal_event_from_unreadable(
cls, data: Dict[str, Any]
) -> Optional[EventMessage]:
"""Rebuild an ``Error`` or ``Termination`` message that failed to parse.

Both end the session. Skipping one would hide the failure, or the
end, that the server reported, so each is rebuilt from the fields
that can be read. Returns ``None`` for any other message.
"""
event_type = cls._parse_event_type(data.get("type"))

if event_type == RealTimeEvents.Termination:
return TerminationEvent(
audio_duration_seconds=_int_or_none(data.get("audio_duration_seconds")),
session_duration_seconds=_int_or_none(
data.get("session_duration_seconds")
),
)

if event_type == RealTimeEvents.Error or (
"type" not in data and "error" in data
):
error = data.get("error")
return ErrorEvent(
error=(
error
if isinstance(error, str) and error
else "The server reported an error the client could not read"
),
error_code=_int_or_none(data.get("error_code")),
)

return None

@staticmethod
def _build_connection_closed_error(
error: Union[
Expand Down
11 changes: 1 addition & 10 deletions assemblyai/streaming/v3/async_client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import asyncio
import collections.abc
import inspect
import json
import logging
from typing import Any, AsyncIterable, Callable, Dict, Iterable, Optional, Union

Expand Down Expand Up @@ -408,22 +407,14 @@ async def _read_loop(self) -> None:
await self._report_connection_closed(exc)
return

try:
message_json = json.loads(message_data)
except json.JSONDecodeError as exc:
logger.warning(f"Failed to decode message: {exc}")
continue

message = self._parse_message(message_json)
message = self._read_event(message_data)

if isinstance(message, ErrorEvent):
await self._report_server_error(message)
elif isinstance(message, WarningEvent):
await self._handle_warning(message)
elif message:
await self._handle_message(message)
else:
logger.warning(f"Unsupported event type: {message_json.get('type')}")

async def _handle_message(self, message: EventMessage) -> None:
# ``_handle_message`` is only reached from ``_read_loop``, which only
Expand Down
11 changes: 1 addition & 10 deletions assemblyai/streaming/v3/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import inspect
import json
import logging
import queue
import threading
Expand Down Expand Up @@ -313,22 +312,14 @@ def _read_message(self) -> None:
self._report_connection_closed(exc)
return

try:
message_json = json.loads(message_data)
except json.JSONDecodeError as exc:
logger.warning(f"Failed to decode message: {exc}")
continue

message = self._parse_message(message_json)
message = self._read_event(message_data)

if isinstance(message, ErrorEvent):
self._report_server_error(message)
elif isinstance(message, WarningEvent):
self._handle_warning(message)
elif message:
self._handle_message(message)
else:
logger.warning(f"Unsupported event type: {message_json.get('type')}")

def _handle_message(self, message: EventMessage) -> None:
if isinstance(message, TerminationEvent):
Expand Down
Loading
Loading