Merge pull request #3629 from pipecat-ai/fix/telephony-websocket-stopasynciteration

Fix StopAsyncIteration in parse_telephony_websocket
This commit is contained in:
Mark Backman
2026-02-03 12:10:07 -05:00
committed by GitHub
3 changed files with 179 additions and 13 deletions

View File

@@ -96,6 +96,9 @@ def _detect_transport_type_from_message(message_data: dict) -> str:
async def parse_telephony_websocket(websocket: WebSocket):
"""Parse telephony WebSocket messages and return transport type and call data.
Args:
websocket: FastAPI WebSocket connection from telephony provider.
Returns:
tuple: (transport_type: str, call_data: dict)
@@ -136,6 +139,9 @@ async def parse_telephony_websocket(websocket: WebSocket):
"to": str,
}
Raises:
ValueError: If WebSocket closes before sending any messages.
Example usage::
transport_type, call_data = await parse_telephony_websocket(websocket)
@@ -143,25 +149,31 @@ async def parse_telephony_websocket(websocket: WebSocket):
user_id = call_data["body"]["user_id"]
"""
# Read first two messages
start_data = websocket.iter_text()
message_stream = websocket.iter_text()
first_message = {}
second_message = {}
try:
# First message
first_message_raw = await start_data.__anext__()
# First message - required
first_message_raw = await message_stream.__anext__()
logger.trace(f"First message: {first_message_raw}")
try:
first_message = json.loads(first_message_raw)
except json.JSONDecodeError:
first_message = {}
first_message = json.loads(first_message_raw) if first_message_raw else {}
except json.JSONDecodeError:
pass
except StopAsyncIteration:
raise ValueError("WebSocket closed before receiving telephony handshake messages")
# Second message
second_message_raw = await start_data.__anext__()
try:
# Second message - optional, some providers may only send one
second_message_raw = await message_stream.__anext__()
logger.trace(f"Second message: {second_message_raw}")
try:
second_message = json.loads(second_message_raw)
except json.JSONDecodeError:
second_message = {}
second_message = json.loads(second_message_raw) if second_message_raw else {}
except json.JSONDecodeError:
pass
except StopAsyncIteration:
logger.warning("Only received one WebSocket message, expected two")
try:
# Try auto-detection on both messages
detected_type_first = _detect_transport_type_from_message(first_message)
detected_type_second = _detect_transport_type_from_message(second_message)