Skip to content

API Reference parrot.voice.handler

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.voice.handler

View source

VoiceChatHandler - WebSocket Handler with Authentication

Enhanced WebSocket handler for voice chat with:

  • JWT authentication via Sec-WebSocket-Protocol (pre-connection)
  • JWT authentication via message type (post-connection)
  • Configurable route setup via setup_routes()
  • Heartbeat/ping mechanism

This handler ONLY handles WebSocket transport. It does NOT know about Google/Gemini - all voice logic is encapsulated in VoiceBot/GeminiLiveClient.

Alias AuthenticatedUser

Re-exported from parrot.core.ws_auth.AuthenticatedUser.

Attribute BROADCAST_ATTACH_TIMEOUT_S

Type: float

Attribute BROADCAST_MAX_AUDIO_B64_BYTES

Type: int

Attribute BROADCAST_MAX_MSGS_PER_SECOND

Type: int

Attribute BROADCAST_WS_ROUTE

Type: str

Class BotConfig

Configuration for VoiceBot creation.

Parameter Type Default Description
name str 'Voice Assistant'
voice_name str 'Puck'
language str 'en-US'
system_prompt Optional[str] None
tools Optional[List[Any]] None
voice_config Optional[VoiceConfig] None
api_key Optional[str] None
vertexai bool False
project Optional[str] None
location Optional[str] None
credentials_file Optional[str] None
aws_access_key Optional[str] None
aws_secret_key Optional[str] None
aws_id Optional[str] None
region Optional[str] None
region_prefix Optional[str] None

Fields:

Field Type Default Description
name str 'Voice Assistant'
voice_name str 'Puck'
language str 'en-US'
system_prompt Optional[str] None
tools Optional[List[Any]] None
voice_config Optional[VoiceConfig] None
api_key Optional[str] None
vertexai bool False
project Optional[str] None
location Optional[str] None
credentials_file Optional[str] None
aws_access_key Optional[str] None
aws_secret_key Optional[str] None
aws_id Optional[str] None
region Optional[str] None
region_prefix Optional[str] None

Method BotConfig.as_dict

Convert to dictionary, excluding None values.

as_dict() -> Dict[str, Any]

Returns: Dict[str, Any]

Method BotConfig.merge_with

Create new BotConfig with overrides applied.

merge_with(overrides: Dict[str, Any]) -> 'BotConfig'

Parameter Type Default Description
overrides Dict[str, Any]

Returns: 'BotConfig'

Method BotConfig.from_dict

Create BotConfig from dictionary.

from_dict(data: Dict[str, Any]) -> 'BotConfig'

Parameter Type Default Description
data Dict[str, Any]

Returns: 'BotConfig'

Alias TokenValidator

Re-exported from parrot.core.ws_auth.TokenValidator.

Class ToolCallDedupState

Per-turn tool_call de-duplication bookkeeping.

A streamed delta and the final completion snapshot carry the SAME :class:LiveToolCall objects (FEAT-536 TASK-2940/2941 arrival-order accumulation), so without this every already-relayed id would be emitted again on is_complete. Keyed by turn_no so ids may legitimately be reused in a LATER turn.

Extracted from _HandlerVoiceSession (FEAT-537 TASK-2959) so the broadcast relay shares one implementation with the single-user path instead of growing a near-copy that can drift.

Parameter Type Default Description
turn_no Optional[int] None
sent_ids set set()
assistant_text_sent str ''

Fields:

Field Type Default Description
turn_no Optional[int] None The turn the current sent_ids belong to.
sent_ids set field(default_factory=set) Tool-call ids already emitted this turn.
assistant_text_sent str '' Assistant transcript already relayed this turn, so a closing frame's full-turn recap is not appended on top of the deltas already streamed (see :func:_novel_assistant_text).

Method ToolCallDedupState.reset_if_new_turn

Clear the per-turn bookkeeping when the turn number changes.

reset_if_new_turn(turn_no: int) -> None

Parameter Type Default Description
turn_no int The turn being relayed.

Alias VoiceBot

Re-exported from parrot.bots.voice.VoiceBot.

Class VoiceChatHandler

WebSocket handler for voice chat with authentication support.

Features:

  • Pre-connection auth via Sec-WebSocket-Protocol header
  • Post-connection auth via 'auth' message type
  • Configurable route setup
  • Heartbeat/ping mechanism

Authentication Methods:

  1. Sec-WebSocket-Protocol (recommended for browsers):

    // Frontend
    const ws = new WebSocket(url, ["jwt", token]);
  2. Query parameter:

    const ws = new WebSocket(`${url}?token=${token}`);
  3. Post-connection message:

    ws.send(JSON.stringify({type: "auth", token: "..."}));
Parameter Type Default Description
bot_factory Optional[Callable[[], VoiceBot]] None Factory for creating VoiceBot instances
default_config Optional[Union[BotConfig, Dict[str, Any]]] None Default bot configuration
require_auth bool False Require authentication before session start
token_validator Optional[TokenValidator] None Custom token validator
secret_key Optional[str] None JWT secret key (if not using navigator_auth)
auth_timeout float 30.0 Timeout for post-connection auth (seconds)
ws_route str '/ws/voice' WebSocket route path
health_route str '/health' Health check route path
broadcast_service Optional[Any] None FEAT-537 broadcast facade (BroadcastService, TASK-2961). Typed loosely on purpose: the handler must not hard-import the broadcast package, which pulls in the optional LiveKit/Redis stack. None disables broadcast mode entirely and leaves every existing code path untouched.
nova_bot_factory Optional[Callable[[], 'VoiceBot']] None Factory used only for broadcasts. A broadcast fixes the provider to Nova for its lifetime (spec §2), so it must not reuse bot_factory, which the shared example rebinds when the user switches provider in the UI.

Attributes:

Attribute Type Description
connections Dict[str, WebSocketConnection]
broadcast_enabled bool Whether a broadcast service was injected (FEAT-537).
active_connections int Number of active connections.

Method VoiceChatHandler.resolve_provider_client

Resolve the AbstractClient subclass for provider (FEAT-302).

Thin wrapper around the module-level :func:resolve_voice_client_class — recognizes VoiceProvider.NOVA and returns :class:~parrot.clients.amazon.nova.NovaClient.

resolve_provider_client(provider: 'VoiceProvider')

Parameter Type Default Description
provider 'VoiceProvider'

Method VoiceChatHandler.setup_routes

Register routes on an aiohttp application.

setup_routes(app: web.Application, prefix: str = '', *, include_health: bool = True, include_static: bool = True, static_dir: Optional[str] = None) -> None

Parameter Type Default Description
app web.Application aiohttp Application
prefix str '' URL prefix for all routes (e.g., "/api/v1")
include_health bool True Include health check endpoint
include_static bool True Include static file serving
static_dir Optional[str] None Directory for static files

Method VoiceChatHandler.handle_websocket

Main WebSocket handler.

Protocol:

Client -> Server:

  • {"type": "auth", "token": ""}
  • {"type": "start_session", "config": {...}}
  • {"type": "audio_data", "data": ""}
  • {"type": "start_recording"}
  • {"type": "stop_recording"}
  • {"type": "send_text", "text": "..."}
  • {"type": "end_session"}
  • {"type": "ping"}

Server -> Client:

  • {"type": "connected", "session_id": "...", "authenticated": bool}
  • {"type": "auth_success", "user": {...}}
  • {"type": "auth_error", "message": "..."}
  • {"type": "session_started", "session_id": "..."}
  • {"type": "voice_response", ...}
  • {"type": "pong", "timestamp": "...", "ping_count": N}
  • {"type": "error", "message": "..."}

handle_websocket(request: web.Request) -> web.WebSocketResponse

Parameter Type Default Description
request web.Request

Returns: web.WebSocketResponse

Method VoiceChatHandler.handle_broadcast_websocket

Participant control and microphone socket for one broadcast.

Route: /ws/voice/broadcast/{agent_id}/{broadcast_id}.

Every admitted participant opens one of these to receive state. Only the participant currently holding the floor may also send microphone audio, and every such message is re-validated against the live floor state before it reaches a provider. Authentication alone, socket possession, being the moderator, or holding a LiveKit viewer token are each insufficient (spec §2).

Client → Server: - {"type": "attach", "lease_id": "..."} — required first message - {"type": "ping"} — control heartbeat, every 5 s - {"type": "start_session"} — attach to the existing broadcast voice session; never creates a bot - {"type": "start_recording", "floor_epoch": N} - {"type": "audio_data"|"audio_chunk", "data": "<b64>", "floor_epoch": N} - {"type": "stop_recording", "floor_epoch": N} - {"type": "finish_speaking"} — hand the floor back - {"type": "end_session"} — release only this speaking binding

Server → Client: - {"type": "attached", "lease_id": ..., "role": ...} - {"type": "broadcast_state", "state": {...}} - {"type": "floor_state", "granted": bool, "floor_epoch": N} - {"type": "floor_revoked", "floor_epoch": N} - {"type": "error", "code": "...", "message": "..."} - plus the shared voice frames fanned out by the relay

handle_broadcast_websocket(request: web.Request) -> web.WebSocketResponse

Parameter Type Default Description
request web.Request The aiohttp request.

Returns: web.WebSocketResponse — The prepared WebSocket response.

Method VoiceChatHandler.broadcast

Send message to all active connections.

broadcast(message: Dict[str, Any]) -> None

Parameter Type Default Description
message Dict[str, Any]

Alias VoiceConfig

Re-exported from parrot.models.voice.VoiceConfig.

Alias VoiceProvider

Re-exported from parrot.models.voice.VoiceProvider.

Alias VoiceSession

Re-exported from parrot.voice.session.VoiceSession.

Attribute WS_CLOSE_FORBIDDEN

Type: int

Attribute WS_CLOSE_UNAUTHENTICATED

Type: int

Class WebSocketConnection

Represents an active WebSocket connection with auth state.

Parameter Type Default Description
ws web.WebSocketResponse
session_id str
created_at datetime datetime.now()
authenticated bool False
user Optional[AuthenticatedUser] None
_user_id Optional[str] None
bot Optional[VoiceBot] None
streaming_mode str 'streaming'
is_recording bool False
recording_start_time Optional[datetime] None
session_active bool False
stop_audio_sending bool False
gemini_responding bool False
audio_buffer bytes b''
audio_queue asyncio.Queue asyncio.Queue()
voice_task Optional[asyncio.Task] None
voice_session Optional['VoiceSession'] None
shutdown_event asyncio.Event asyncio.Event()
config Optional[BotConfig] None
stt_only bool False
last_ping Optional[datetime] None
ping_count int 0
avatar_session Optional[Any] None
_tool_dedup_turn_id Optional[str] None
_sent_tool_call_ids set set()
_assistant_text_sent str ''

Fields:

Field Type Default Description
ws web.WebSocketResponse
session_id str
created_at datetime field(default_factory=datetime.now)
authenticated bool False
user Optional[AuthenticatedUser] None
bot Optional[VoiceBot] None
streaming_mode str 'streaming'
is_recording bool False
recording_start_time Optional[datetime] None
session_active bool False
stop_audio_sending bool False
gemini_responding bool False
audio_buffer bytes b''
audio_queue asyncio.Queue field(default_factory=asyncio.Queue)
voice_task Optional[asyncio.Task] None
voice_session Optional['VoiceSession'] None
shutdown_event asyncio.Event field(default_factory=asyncio.Event)
config Optional[BotConfig] None
stt_only bool False
last_ping Optional[datetime] None
ping_count int 0
avatar_session Optional[Any] None

Attributes:

Attribute Type Description
user_id Optional[str] Get user ID from authenticated user or legacy field.

Attribute app

Attribute args

Function build_voice_frames

Translate one LiveVoiceResponse into VoiceChatHandler wire frames.

This is the single, pure implementation of the handler's rich frame protocol (FEAT-418 TASK-2174): response_chunk / transcription / display_data / tool_call / response_complete / ready_to_speak, plus the go_away → session_warning mapping, with STT-only gating and "thought" text filtering.

Both :class:_HandlerVoiceSession (single user) and the broadcast relay call it, so the two paths cannot drift apart in what a browser receives. The broadcast relay strips audio_base64 from the result afterwards — its PCM goes to the shared room, not down each participant's socket.

Must stay sync: the base VoiceSession._relay() calls build_frames() without awaiting.

build_voice_frames(resp: Any, turn_no: int, *, stt_only: bool, dedup_state: ToolCallDedupState) -> list

Parameter Type Default Description
resp Any The provider response to translate.
turn_no int Current turn number.
stt_only bool Whether the session is transcription-only.
dedup_state ToolCallDedupState Mutable per-turn tool-call dedup bookkeeping.

Returns: list — JSON-serializable frame dicts, in send order.

Function configure_voice_memory

Best-effort conversation memory for a voice session: Redis, falling back to in-memory.

memory_type defaults to "auto" (FEAT-886), which may resolve to in-memory; voice wants cross-turn persistence, so None / "memory" / "auto" become "redis". A Redis failure now raises from configure_conversation_memory (no silent fallback), so the in-memory fallback is made here, explicitly.

configure_voice_memory(bot, logger, session_id) -> None

Parameter Type Default Description
bot
logger
session_id

Alias create_voice_bot

Re-exported from parrot.bots.voice.create_voice_bot.

Function create_voice_server

Create complete voice server application.

create_voice_server(bot_factory: Optional[Callable[[], VoiceBot]] = None, bot_config: Optional[Union[BotConfig, Dict[str, Any]]] = None, *, require_auth: bool = False, secret_key: Optional[str] = None, static_dir: Optional[str] = None, **kwargs) -> web.Application

Parameter Type Default Description
bot_factory Optional[Callable[[], VoiceBot]] None Custom bot factory
bot_config Optional[Union[BotConfig, Dict[str, Any]]] None Default bot configuration
require_auth bool False Require JWT authentication
secret_key Optional[str] None JWT secret key
static_dir Optional[str] None Static files directory
**kwargs {} Additional handler arguments

Returns: web.Application — Configured aiohttp Application

Attribute parser

Function resolve_voice_client_class

Resolve the AbstractClient subclass for a given VoiceProvider.

Recognizes VoiceProvider.NOVA and returns :class:~parrot.clients.amazon.nova.NovaClient (lazily imported — the Pre-Alpha aws_sdk_bedrock_runtime extra is optional and is only required at first stream_voice() call, not at import time). Every other currently-declared provider resolves to :class:~parrot.clients.google.live.GeminiLiveClient, the only fully-wired voice client at this time (OPENAI_REALTIME / WHISPER_TTS are declared in the enum but not yet backed by dedicated client classes).

resolve_voice_client_class(provider: 'VoiceProvider')

Parameter Type Default Description
provider 'VoiceProvider' The VoiceProvider enum member to resolve.

Raises:

  • ImportError — When NOVA is requested and aws_sdk_bedrock_runtime (Pre-Alpha, Python >= 3.12 only) is not installed and stream_voice() is called — importing :class:NovaClient itself never requires it.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally