Skip to content

Streaming Turn callbacks silently discard documented speaker confidence scores #322

Backlog

Description

@codebanditssss

Reproduced on 0ba094c.

Observed behavior

The streaming Word and TurnEvent models do not declare speaker_confidence. A complete valid Turn containing turn-level and word-level scores parses successfully, but the scores disappear from sync/async callbacks and serialized models.

The streaming diarization docs document both fields and permit omission. Expected: preserve supplied scores, including 0.0, while allowing absent fields. Existing speaker labels should remain unchanged. These experimental scores are not calibrated probabilities; no absolute-threshold behavior is requested.

Source: assemblyai/streaming/v3/models.py.

Reproduction evidence

Python 3.12; install the SDK's dependencies, save the script below in the repository root, then run python reproduce.py. It was run under Pydantic 1.10.26 and 2.12.5, with websockets 15.0.1 and httpx 0.28.1.

No credentials, real service connections, or billable API calls are used. These scripts assert baseline observations and controls, not fixed behavior.

Offline reproduction script
"""Public callbacks fed complete wire events at mocked WebSocket boundary."""
import asyncio
import copy
import json
import queue
import sys
import os
import threading
from unittest.mock import patch
sys.dont_write_bytecode = True
sys.path.insert(0, os.environ.get("AAI_SDK_ROOT", os.getcwd()))
import pydantic
import websockets
from assemblyai.streaming.v3 import (
    RealTimeTranscriber, AsyncRealTimeTranscriber, RealTimeTranscriberOptions,
    RealTimeEvents, RealTimeParameters,
)

BASE = {
    "type": "Turn", "turn_order": 0, "turn_is_formatted": True,
    "end_of_turn": True, "end_of_turn_confidence": 0.99,
    "transcript": "Good morning. Thanks for joining.",
    "speaker_label": "A", "speaker_confidence": 0.938865,
    "language_code": "en", "language_confidence": 0.99,
    "words": [
        {"text": text, "speaker": "A", "speaker_confidence": sc,
         "word_is_final": True, "start": start, "end": end, "confidence": confidence}
        for text, start, end, confidence, sc in [
            ("Good", 120, 280, 0.994210, 0.976504),
            ("morning.", 280, 530, 0.998112, 0.976504),
            ("Thanks", 690, 880, 0.991004, 0.913772),
            ("for", 880, 960, 0.987663, 0.913772),
            ("joining.", 960, 1320, 0.996518, 0.913772),
        ]
    ],
}
PAYLOADS = [copy.deepcopy(BASE) for _ in range(3)]
PAYLOADS[1]["turn_order"] = 1
PAYLOADS[1]["speaker_confidence"] = 0.0
for word in PAYLOADS[1]["words"]:
    word["speaker_confidence"] = 0.0
PAYLOADS[2]["turn_order"] = 2
del PAYLOADS[2]["speaker_confidence"]
for word in PAYLOADS[2]["words"]:
    del word["speaker_confidence"]
OPTIONS = RealTimeTranscriberOptions(api_key="unused-offline")
PARAMS = RealTimeParameters(sample_rate=16000, speech_model="assemblyai-stt-3-7-realtime", speaker_labels=True)
MESSAGES = [json.dumps({"type": "Begin", "id": "offline-session", "expires_at": "2030-01-01T00:00:00Z"})] + [json.dumps(p) for p in PAYLOADS]

class Socket:
    def __init__(self):
        self.incoming = queue.Queue()
        for message in MESSAGES:
            self.incoming.put(message)
        self.closed = False
    def recv(self, timeout=1):
        try:
            return self.incoming.get(timeout=min(timeout, 0.05))
        except queue.Empty:
            raise TimeoutError
    def send(self, data):
        pass
    def close(self):
        self.closed = True

class AsyncSocket(Socket):
    async def recv(self):
        if not self.incoming.empty():
            return self.incoming.get_nowait()
        await asyncio.Future()
    async def send(self, data):
        pass
    async def close(self):
        super().close()

def inspect_event(mode, event):
    source = PAYLOADS[event.turn_order]
    dumped = event.model_dump() if hasattr(event, "model_dump") else event.dict()
    expected_remaining = copy.deepcopy(source)
    expected_remaining.pop("speaker_confidence", None)
    for word in expected_remaining["words"]:
        word.pop("speaker_confidence", None)
    assert dumped == expected_remaining, "other fields changed"
    assert not hasattr(event, "speaker_confidence")
    assert all(not hasattr(word, "speaker_confidence") for word in event.words)
    print(json.dumps({"client": mode, "turn_order": event.turn_order,
                      "wire_turn_score": source.get("speaker_confidence", "OMITTED"),
                      "wire_word_scores": [w.get("speaker_confidence", "OMITTED") for w in source["words"]],
                      "callback_turn_score": getattr(event, "speaker_confidence", "MISSING"),
                      "callback_word_scores": [getattr(w, "speaker_confidence", "MISSING") for w in event.words],
                      "other_fields_exactly_preserved": True, "serialized_callback": dumped}))

def sync_run():
    socket = Socket()
    client = RealTimeTranscriber(OPTIONS)
    done = threading.Event()
    events = []
    errors = []
    def on_turn(c, event):
        assert c is client
        events.append(event)
        if len(events) == 3:
            done.set()
    client.on(RealTimeEvents.Turn, on_turn)
    client.on(RealTimeEvents.Error, lambda c, e: errors.append(str(e)))
    with patch("assemblyai.streaming.v3.client.websocket_connect", lambda *a, **k: socket):
        try:
            client.connect(PARAMS)
            assert done.wait(2), "missing Turn callback"
            assert not errors
            for event in events:
                inspect_event("sync", event)
        finally:
            client.disconnect()
            client._client._http_client.close()
    assert socket.closed and not client._read_thread.is_alive() and not client._write_thread.is_alive()

async def async_run():
    socket = AsyncSocket()
    client = AsyncRealTimeTranscriber(OPTIONS)
    done = asyncio.Event()
    events = []
    async def on_turn(c, event):
        assert c is client
        events.append(event)
        if len(events) == 3:
            done.set()
    async def connect(*a, **k):
        return socket
    client.on(RealTimeEvents.Turn, on_turn)
    with patch("assemblyai.streaming.v3.async_client.websocket_connect_async", connect):
        try:
            await client.connect(PARAMS)
            await asyncio.wait_for(done.wait(), 2)
            for event in events:
                inspect_event("async", event)
        finally:
            await client.disconnect()
    assert socket.closed

if __name__ == "__main__":
    print(f"Python {sys.version.split()[0]}, pydantic {pydantic.__version__}, websockets {websockets.__version__}")
    sync_run()
    asyncio.run(asyncio.wait_for(async_run(), 5))
    print("All six Turn callbacks observed; all sockets and SDK workers cleaned up.")
Observed output
Python 3.12.13, pydantic 2.12.5, websockets 15.0.1
{"client":"sync","turn_order":0,"wire_turn_score":0.938865,"wire_word_scores":[0.976504,0.976504,0.913772,0.913772,0.913772],"callback_turn_score":"MISSING","callback_word_scores":["MISSING","MISSING","MISSING","MISSING","MISSING"],"other_fields_exactly_preserved":true}
{"client":"sync","turn_order":1,"wire_turn_score":0,"wire_word_scores":[0,0,0,0,0],"callback_turn_score":"MISSING","callback_word_scores":["MISSING","MISSING","MISSING","MISSING","MISSING"],"other_fields_exactly_preserved":true}
{"client":"sync","turn_order":2,"wire_turn_score":"OMITTED","wire_word_scores":["OMITTED","OMITTED","OMITTED","OMITTED","OMITTED"],"callback_turn_score":"MISSING","callback_word_scores":["MISSING","MISSING","MISSING","MISSING","MISSING"],"other_fields_exactly_preserved":true}
{"client":"async","turn_order":0,"wire_turn_score":0.938865,"wire_word_scores":[0.976504,0.976504,0.913772,0.913772,0.913772],"callback_turn_score":"MISSING","callback_word_scores":["MISSING","MISSING","MISSING","MISSING","MISSING"],"other_fields_exactly_preserved":true}
{"client":"async","turn_order":1,"wire_turn_score":0,"wire_word_scores":[0,0,0,0,0],"callback_turn_score":"MISSING","callback_word_scores":["MISSING","MISSING","MISSING","MISSING","MISSING"],"other_fields_exactly_preserved":true}
{"client":"async","turn_order":2,"wire_turn_score":"OMITTED","wire_word_scores":["OMITTED","OMITTED","OMITTED","OMITTED","OMITTED"],"callback_turn_score":"MISSING","callback_word_scores":["MISSING","MISSING","MISSING","MISSING","MISSING"],"other_fields_exactly_preserved":true}
All six Turn callbacks observed; all sockets and SDK workers cleaned up.

Controls and scope

Six public Turn callbacks per environment were checked: populated, zero, and omitted scores through sync and async clients. All other serialized event fields were exactly preserved. This concerns streaming models, not the separate prerecorded confidence addition in #314.

All six Python executions (three reproductions under both Pydantic versions) exited 0.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions