Unify db api

This commit is contained in:
Xin Wang
2026-02-26 01:58:39 +08:00
parent 56f8aa2191
commit 72ed7d0512
40 changed files with 3926 additions and 593 deletions

View File

@@ -36,8 +36,18 @@ def generate_sine_wave(duration_ms=1000):
return audio_data
async def receive_loop(ws, ready_event: asyncio.Event):
async def receive_loop(ws, ready_event: asyncio.Event, track_debug: bool = False):
"""Listen for incoming messages from the server."""
def event_ids_suffix(data):
payload = data.get("data") if isinstance(data.get("data"), dict) else {}
keys = ("turn_id", "utterance_id", "response_id", "tool_call_id", "tts_id")
parts = []
for key in keys:
value = payload.get(key, data.get(key))
if value:
parts.append(f"{key}={value}")
return f" [{' '.join(parts)}]" if parts else ""
print("👂 Listening for server responses...")
async for msg in ws:
timestamp = datetime.now().strftime("%H:%M:%S")
@@ -46,7 +56,10 @@ async def receive_loop(ws, ready_event: asyncio.Event):
try:
data = json.loads(msg.data)
event_type = data.get('type', 'Unknown')
print(f"[{timestamp}] 📨 Event: {event_type} | {msg.data[:150]}...")
ids = event_ids_suffix(data)
print(f"[{timestamp}] 📨 Event: {event_type}{ids} | {msg.data[:150]}...")
if track_debug:
print(f"[{timestamp}] [track-debug] event={event_type} trackId={data.get('trackId')}{ids}")
if event_type == "session.started":
ready_event.set()
except json.JSONDecodeError:
@@ -113,7 +126,7 @@ async def send_sine_loop(ws):
print("\n✅ Finished streaming test audio.")
async def run_client(url, file_path=None, use_sine=False):
async def run_client(url, file_path=None, use_sine=False, track_debug: bool = False):
"""Run the WebSocket test client."""
session = aiohttp.ClientSession()
try:
@@ -121,7 +134,7 @@ async def run_client(url, file_path=None, use_sine=False):
async with session.ws_connect(url) as ws:
print("✅ Connected!")
session_ready = asyncio.Event()
recv_task = asyncio.create_task(receive_loop(ws, session_ready))
recv_task = asyncio.create_task(receive_loop(ws, session_ready, track_debug=track_debug))
# Send v1 hello + session.start handshake
await ws.send_json({"type": "hello", "version": "v1"})
@@ -131,7 +144,12 @@ async def run_client(url, file_path=None, use_sine=False):
"encoding": "pcm_s16le",
"sample_rate_hz": SAMPLE_RATE,
"channels": 1
}
},
"metadata": {
"appId": "assistant_demo",
"channel": "test_websocket",
"configVersionId": "local-dev",
},
})
print("📤 Sent v1 hello/session.start")
await asyncio.wait_for(session_ready.wait(), timeout=8)
@@ -168,9 +186,10 @@ if __name__ == "__main__":
parser.add_argument("--url", default=SERVER_URL, help="WebSocket endpoint URL")
parser.add_argument("--file", help="Path to PCM/WAV file to stream")
parser.add_argument("--sine", action="store_true", help="Use sine wave generation (default)")
parser.add_argument("--track-debug", action="store_true", help="Print event trackId for protocol debugging")
args = parser.parse_args()
try:
asyncio.run(run_client(args.url, args.file, args.sine))
asyncio.run(run_client(args.url, args.file, args.sine, args.track_debug))
except KeyboardInterrupt:
print("\n👋 Client stopped.")