can you guide me on how to setup a websocket bridg...
# ask-ai
f
can you guide me on how to setup a websocket bridge with my livekit agents so i can point to that websocket from plivo / twilio audio stream as an alternative to SIP calls?
t
Thanks for reaching out, Manav. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you want to point Plivo/Twilio audio streams to a WebSocket bridge via LiveKit instead of using SIP. I can guide you two practical ways to do that and help you pick which fits your needs. Which approach do you want to explore first — Track Egress to WebSocket (LiveKit streams the track to your websocket server) or LiveKit Agent bridging (an agent joins the room, reads audio frames, and forwards them to your websocket)? If you’re unsure, tell me whether you prefer lower latency/control (Agent) or a simpler setup that offloads streaming (Egress). Sources: Create and configure a Plivo SIP trunk | LiveKit docs | Create and configure a Twilio SIP trunk | LiveKit docs | Track egress | LiveKit docs | Capturing the First Few Seconds of a Call for Processing | Processing raw media tracks | LiveKit docs
f
i want lowest latency possible, and would not want to change anything in my voice agents pipeline code, it would be better if there's a way i can create a bridge between twilio/plivo <> websocket bridge <> livekit agent. I would want the agent to speak / hear and respond bidirectionally with a websocket bridge too.
t
Thanks — you want the lowest latency and no changes to your existing voice-agent pipeline. You can do that by placing a lightweight WebSocket bridge between Twilio/Plivo and a LiveKit Agent: Twilio/Plivo <-> WebSocket bridge <-> LiveKit Agent (agent joins LiveKit room and forwards audio frames to/from your existing agent over the websocket). Below is a concise plan and next steps to implement this with minimal changes to your pipeline. High-level design (keeps your pipeline unchanged) • Twilio/Plivo -> WebSocket bridge: configure Twilio/Plivo to stream call audio to your WebSocket endpoint (use Twilio Media Streams or Plivo’s equivalent). • WebSocket bridge -> LiveKit Agent: the bridge forwards incoming PCM audio frames received from Twilio/Plivo into a LiveKit room by sending them to a LiveKit Agent over a websocket (or directly using the Agent SDK). • LiveKit Agent -> Bridge -> Twilio/Plivo: the LiveKit Agent subscribes to agent and remote tracks, outputs PCM frames to the bridge, which forwards them back to Twilio/Plivo over the media websocket so your agent can speak back into the call. • Your existing voice-agent pipeline stays connected to the same WebSocket bridge endpoint and receives/sends the same audio frames it already expects. Two low-latency implementation options 1) Agent-as-proxy (recommended for lowest latency) • The bridge only translates framing/protocols; the LiveKit Agent joins the room and exposes raw PCM in real time to the bridge via a local websocket or IPC. • Agent uses
rtc.AudioStream
(or equivalent) to read/write PCM frames and immediately forwards frames to your voice-agent socket. • Minimizes serialization and external hops. 2) Track Egress + bridge (simpler but higher latency) • Use Track Egress to stream audio to your websocket bridge and forward the websocket audio to your agent. • Reverse direction (agent -> call) is more complex with egress; not ideal for truly bidirectional, ultra-low-latency use. Concrete steps to implement Agent-as-proxy 1. Configure Twilio/Plivo to stream media to your bridge websocket. ◦ Use Twilio Media Streams or Plivo’s realtime media option. 1. Build a lightweight WebSocket bridge: ◦ Accept media websocket from Twilio/Plivo (binary PCM frames + control JSON). ◦ Maintain a websocket connection to your LiveKit Agent (or have the agent connect back). ◦ Forward PCM from Twilio -> Agent websocket; forward PCM from Agent -> Twilio. ◦ Propagate mute/unmute and connection events as needed. 1. Implement the LiveKit Agent behavior: ◦ Agent joins the LiveKit room as a participant. ◦ Subscribe to the SIP/call participant’s audio track or receive forwarded PCM from the bridge. ◦ Use
rtc.AudioStream
to read audio frames and immediately send them to the bridge websocket. ◦ To speak, Agent pushes frames into a local outgoing track (or uses the SDK to publish audio) which the bridge relays back to Twilio/Plivo. 1. Keep audio format consistent: ◦ Use PCM s16le (48 kHz preferred) end-to-end or add a minimal resampler at the bridge if your agent uses a different sample rate. ◦ Ensure framing/packetization matches what Twilio/Plivo expects. 1. Optimize for latency: ◦ Use UDP where possible for transports between components inside your network; keep message sizes small and avoid buffering. ◦ Process and forward frames immediately on receipt. ◦ Pin Agent and bridge to same region/network to reduce RTT. Example message flows (simplified) • Inbound (caller -> agent): a. Twilio streams PCM frames to Bridge WS. b. Bridge forwards frames to Agent WS. c. Agent reads frames via
AudioStream
and forwards into your voice pipeline (unchanged). • Outbound (agent -> caller): a. Your voice-agent sends PCM to Bridge WS. b. Bridge forwards PCM into Agent (or directly into LiveKit publish path). c. Agent publishes audio to LiveKit room or bridge sends directly to Twilio websocket. Questions so I can give exact code and config • Which realtime media product are you using on the PSTN side: Twilio Media Streams or Plivo realtime media? • Which language would you prefer example code for your LiveKit Agent and bridge (Node, Python, Go)? • What sample rate / audio format does your existing voice-agent pipeline expect (e.g., 16kHz s16le, 48kHz s16le)? If you confirm those, I’ll provide a minimal working example (agent + bridge) tailored to your choices.
f
Plivo audio stream, python is our language
t
Great — since you’re using Plivo and Python and want lowest latency with no changes to your agent pipeline, here’s a focused plan plus minimal Python examples to implement the WebSocket bridge + LiveKit Agent (Agent-as-proxy approach). Quick confirmations before code: • What PCM format and sample rate does your current voice-agent expect? (e.g.,
pcm_s16le
16 kHz or 48 kHz) • Do you want the Agent to publish audio into the LiveKit room (Agent publishes + subscribes) or have the bridge directly relay agent audio into Plivo? (Publishing keeps LiveKit semantics; direct relay can reduce hops.) If you confirm those two items I’ll provide: • A minimal Plivo media WebSocket bridge in Python that accepts Plivo frames (binary PCM + control JSON) and forwards to the Agent. • A minimal Python LiveKit Agent snippet that uses
rtc.AudioStream
to read/write PCM frames and exchange them with the bridge over a local websocket. • Notes on framing, resampling (if needed), and latency optimizations. Would you like the Agent to publish into LiveKit or have the bridge relay agent audio directly back to Plivo?
f
2025-12-02 055134,438 - main - INFO - Starting Plivo-LiveKit Bridge on 0.0.0.0:10000 ==> /////////////////////////////////////////////////////////// INFO: Started server process [1] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:10000 (Press CTRL+C to quit) INFO: 127.0.0.1:47282 - "HEAD / HTTP/1.1" 405 Method Not Allowed [GET]200websockets-jelu.onrender.com/clientIP="34.82.41.62" requestID="91cf4390-ae93-4d44" responseTimeMS=4 responseBytes=362 userAgent="Go-http-client/2.0" INFO: 10.16.128.130:51138 - "GET / HTTP/1.1" 200 OK ==> New primary port detected: 10000. Restarting deploy to update network configuration... ==> Docs on specifying a port: https://render.com/docs/web-services#port-binding INFO: ('10.17.245.229', 60310) - "WebSocket /plivo-media/socketroom-plivo-692e7e841e241" [accepted] 2025-12-02 055206,599 - main - INFO - Plivo connection established for call: socketroom-plivo-692e7e841e241 2025-12-02 055206,599 - main - INFO - Connecting to LiveKit room: socketroom-plivo-692e7e841e241 (this should match the room created by PHP) 2025-12-02 055206,600 - livekit - INFO - livekit_ffi:server125livekit ffi:server - initializing ffi server v0.5.0 2025-12-02 055206,600 - livekit - INFO - livekit_ffi:cabi27livekit ffi:cabi - initializing ffi server v0.5.0 INFO: connection open 2025-12-02 055206,604 - livekit - INFO - livekit_api:signal clientsignal stream88livekit apisignal client:signal_stream - connecting to wss://tabbly-m08l8mdk.livekit.cloud/rtc?sdk=rust&protocol=9&auto_subscribe=1&adaptive_stream=0&access_token=... 2025-12-02 055207,155 - main - INFO - Connected to LiveKit room 'socketroom-plivo-692e7e841e241' for call: socketroom-plivo-692e7e841e241 2025-12-02 055207,165 - main - INFO - Published audio track to LiveKit room: socketroom-plivo-692e7e841e241 2025-12-02 055207,213 - main - INFO - Successfully dispatched 'central' agent to room 'socketroom-plivo-692e7e841e241'. Dispatch ID: N/A 2025-12-02 055207,214 - main - INFO - Plivo stream started for socketroom-plivo-692e7e841e241 2025-12-02 055207,783 - main - INFO - Track subscribed: 1 from agent-AJ_ZAAPUngFVmWS in room socketroom-plivo-692e7e841e241 2025-12-02 055207,793 - main - INFO - First frame received - type: <class 'livekit.rtc.audio_stream.AudioFrameEvent'>, dir: ['frame'] 2025-12-02 055207,793 - main - INFO - Inner frame type: <class 'livekit.rtc.audio_frame.AudioFrame'>, dir: ['create', 'data', 'num_channels', 'remix_and_resample', 'sample_rate', 'samples_per_channel'] thread 'tokio-runtime-worker' panicked at livekit/src/rtc_engine/rtc_session.rs56643: called
Option::unwrap()
on a
None
value note: run with
RUST_BACKTRACE=1
environment variable to display a backtrace thread 'tokio-runtime-worker' panicked at /workspace/livekit-runtime/src/tokio.rs3846: Tasks should not panic: JoinError::Panic(Id(99), ...) 2025-12-02 055224,533 - main - INFO - Plivo WebSocket not connected for socketroom-plivo-692e7e841e241 2025-12-02 055224,533 - main - INFO - Stopping Plivo->LiveKit forwarding for socketroom-plivo-692e7e841e241 thread 'tokio-runtime-worker' panicked at /workspace/livekit-runtime/src/tokio.rs3846: Tasks should not panic: JoinError::Panic(Id(10), ...) 2025-12-02 055224,533 - main - ERROR - Error sending audio to Plivo for socketroom-plivo-692e7e841e241: received 1000 (OK); then sent 1000 (OK) INFO: connection closed 2025-12-02 055224,533 - livekit - CRITICAL - Panic: task 146 panicked thread 'tokio-runtime-worker' panicked at livekit-ffi/src/server/mod.rs21621: watch_panic: task panicked 2025-12-02 055224,534 - livekit - ERROR - livekit_ffi:server214livekit ffi:server - task panicked: JoinError::Panic(Id(146), ...) 2025-12-02 055224,542 - main - INFO - WebSocket disconnected for socketroom-plivo-692e7e841e241, stopping audio stream 2025-12-02 055224,542 - main - INFO - Audio streaming ended for socketroom-plivo-692e7e841e241 after 1675 frames INFO: Shutting down how to resolve this most probably.
t
Thanks — I’m responding to the runtime panic and stopped audio stream in your logs (the
Option::unwrap()
on None inside the LiveKit runtime). Below are focused causes and concrete next steps to find and fix it. Likely causes • Agent code or bridge sent an unexpected/empty audio frame event (missing fields LiveKit expects: sample rate, channels, samples_per_channel, or frame data). The runtime unwrap likely assumed a value present on an incoming AudioFrame event. • Mismatch in audio formatting (unexpected sample_rate or channel count) causing the agent to produce an empty/malformed frame. • Race where the track was unpublished or participant left while code still processed a frame (some fields nil). • Incompatible LiveKit ffi / runtime versions between your Python bindings and the livekit runtime binary. Immediate debugging steps (priority order) 1. Enable full backtrace to see exact panic location: ◦ Restart with RUST_BACKTRACE=1 in your environment and reproduce. Capture the backtrace to identify which Option was None. 1. Log every AudioFrameEvent before processing: ◦ Dump the event fields (
sample_rate
,
num_channels
,
samples_per_channel
,
data
length) and any nested objects so you can spot missing/None values before the unwrap occurs. 1. Add defensive checks around frames in your agent: ◦ Before any unwrap, verify fields exist and non-zero. If missing, skip frame and log a warning instead of letting runtime panic. ◦ Example checks:
if frame.sample_rate is None or frame.data is None or len(frame.data)==0: log and continue
1. Verify audio format end-to-end: ◦ Confirm Plivo sends PCM s16le at the sample rate you expect (check Plivo websocket message headers). ◦ Ensure your bridge does not drop or coalesce frames; keep frame sizes consistent. ◦ If your pipeline expects 16 kHz but LiveKit tracks are 48 kHz, add explicit resampling at the bridge. 1. Check publish/subscribe lifecycle ordering: ◦ Ensure you only process frames after the track subscription callback confirms a valid track and before unpublish/leave handlers run. ◦ Add try/catch around subscribe/unsubscribe handlers to avoid racing state. 1. Confirm versions and ABI compatibility: ◦ Make sure the Python LiveKit package, the livekit-ffi runtime, and any embedded native libs are aligned to the same release. Mismatched versions can change event shapes. 1. Reproduce locally with a minimal test: ◦ Create a small script that publishes synthetic audio frames with the same format your bridge uses; run the agent against it to see if it panics. This isolates Plivo/Render variables. Short-term mitigations to keep service stable • Catch panics at task boundaries by running the agent’s processing loop inside try/except and restarting only that loop on error (prevent whole runtime panic). • If needed, switch from automatic unwrap usage to safe-accessors in the agent code so malformed frames get logged and ignored. If you want, I can: • Review the specific Python agent frame-handling snippet that reads/publishes
AudioFrameEvent
and suggest exact defensive code changes. • Analyze the RUST_BACKTRACE output once you run with it to point to the exact unwrap site and a code fix. Which would you like me to do next — share the agent frame-processing code for a quick patch, or run with RUST_BACKTRACE=1 and paste the backtrace here?
f
can you tell me, how does plivo hear back the audio coming from the bridge?
t
You're asking how Plivo receives audio from your bridge (the return path: agent → bridge → Plivo). Here’s a concise explanation and the implementation details you need to wire it up. How Plivo receives audio (high level) • Plivo’s realtime media sends and receives audio over a media WebSocket. To play audio back to the caller, you must send PCM audio frames over that same WebSocket from your bridge to Plivo. • The bridge accepts audio from your voice agent, packages it in the format Plivo expects, and sends it on the Plivo media socket so Plivo injects it into the live call. Key protocol/format details • Audio payload: send raw PCM binary frames (commonly
pcm_s16le
). Confirm which sample rate Plivo session negotiated (often 16 kHz or 48 kHz) and use that end-to-end or resample at the bridge. • Frame vs message: Plivo typically expects small, timely binary frames (not large buffered chunks). Forward frames as you receive them with minimal buffering to keep latency low. • Control messages: Plivo uses text JSON frames for control (e.g., start/stop, mute). Preserve and forward relevant control states from your agent/bridge if needed. • RTP-like expectations: Although media goes over WebSocket, Plivo expects consistent timing/packetization. Keep frame sizes and inter-frame timing consistent with what Plivo sent to you. Practical implementation steps (bridge -> Plivo) 1. Open/maintain the Plivo media websocket connection for that call. 2. When your voice agent produces PCM frames: ◦ Ensure format/sample-rate/channels match Plivo’s expected format. ◦ Optionally convert/resample to Plivo’s rate/format at the bridge. ◦ Send the PCM as a binary WebSocket frame to Plivo immediately. 1. If Plivo requires a wrapper or envelope for binary frames (check the Plivo realtime docs you used for incoming frames), follow the same envelope for outbound frames (often no envelope, just raw PCM binary with occasional JSON control messages). 2. Send control JSON frames when needed (e.g., send mute/unmute or session-end events) so Plivo knows to stop playback or change state. 3. Monitor Plivo responses/close frames and handle errors/cleanup (close media socket when call ends). Latency & reliability tips • Send frames as soon as produced; avoid accumulating multiple audio frames. • Keep bridge and agent in same region/network as Plivo ingress to reduce RTT. • Use a small, fixed frame size (e.g., 20ms) to match telephony expectations. • If you must resample, do it in native code or an optimized library to avoid CPU lag. • Detect and drop malformed/empty frames to avoid plivo-side jitter or errors. If you want, I can: • Provide a minimal Python snippet that sends agent PCM frames as binary WebSocket frames to Plivo (matching the format you confirm), or • Show how to detect Plivo’s negotiated sample rate from the incoming messages and resample automatically before sending back. Which snippet would you like?
f
yes tell me minimal python snippet
t
Below is a minimal Python example that sends PCM frames back to Plivo over the Plivo media WebSocket. It assumes: • You already have a running WebSocket connection to Plivo for a call (ws). • Your voice agent or LiveKit Agent gives you PCM frames as bytes in
pcm_frame
. • Plivo expects raw PCM s16le frames at the negotiated sample rate (confirm your session; adjust resampling if needed). This example: • Receives PCM frames from an async queue
outgoing_queue
(producer: your agent/bridge). • Sends each frame immediately as a binary WebSocket message to Plivo. • Handles simple connection lifecycle and errors.
Copy code
import asyncio
import websockets
import logging

PLIVO_WS_URL = "wss://your-plivo-media-host/v1/..."  # Plivo media websocket URL for the call

async def plivo_send_loop(ws, outgoing_queue: asyncio.Queue):
    try:
        while True:
            pcm_frame = await outgoing_queue.get()  # bytes, e.g., PCM s16le
            if pcm_frame is None:
                # sentinel to end the stream
                await ws.close()
                return
            # Send raw PCM as binary frame to Plivo
            await ws.send(pcm_frame)
    except websockets.ConnectionClosed:
        logging.info("Plivo WS closed")
    except Exception:
        logging.exception("Error sending audio to Plivo")

async def run_bridge(outgoing_queue: asyncio.Queue):
    async with websockets.connect(PLIVO_WS_URL, max_size=None) as ws:
        # Optionally send any initial JSON control messages required by Plivo here
        # await ws.send(json.dumps({"event": "start"}))
        send_task = asyncio.create_task(plivo_send_loop(ws, outgoing_queue))

        # Example: read incoming from Plivo if you also need to receive caller audio
        async for message in ws:
            if isinstance(message, bytes):
                # incoming PCM from Plivo (forward to LiveKit/agent)
                handle_incoming_pcm(message)
            else:
                handle_plivo_control(message)

        await send_task

# Helpers (implement these to integrate with your agent)
def handle_incoming_pcm(pcm_bytes: bytes):
    # forward to LiveKit Agent or push into your agent pipeline
    pass

def handle_plivo_control(msg_text: str):
    # handle JSON control messages from Plivo (start/stop/mute)
    pass

# Example producer that puts agent audio into outgoing_queue
async def agent_producer(outgoing_queue: asyncio.Queue):
    while True:
        pcm = await get_next_agent_frame()  # implement to pull from your agent
        await outgoing_queue.put(pcm)

async def main():
    outgoing_queue = asyncio.Queue(maxsize=50)
    producer = asyncio.create_task(agent_producer(outgoing_queue))
    bridge = asyncio.create_task(run_bridge(outgoing_queue))
    await asyncio.gather(producer, bridge)

# Placeholder - replace with your agent integration
async def get_next_agent_frame() -> bytes:
    await asyncio.sleep(0.02)  # simulate 20ms frames
    return b"\x00" * 320  # example 16kHz 20ms mono s16le (replace with real frames)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())
Notes: • Confirm the exact PCM format and frame size Plivo negotiated (sample rate, channels). Adjust `get_next_agent_frame`/resampling accordingly. • Keep frames small (e.g., 20ms) and send immediately to minimize latency. • If Plivo requires a specific envelope for outgoing frames, wrap the bytes per that envelope; otherwise raw PCM binary is typically accepted. • Monitor WebSocket close codes and log any Plivo control messages for session state. Would you like the snippet adapted to include resampling (e.g., to convert 48 kHz -> 16 kHz) or an example that integrates directly with LiveKit’s
rtc.AudioStream
in Python?
f
kindly share exact details that i need to send plivo as frames to make sure its audible over the plivo call
t
Below are the exact, actionable details you need to send audio frames to Plivo so the audio is audible on the live call. I’ll cover payload format, frame sizing & timing, control messages, and a concise checklist for integration. Audio payload format • Send raw PCM samples as binary WebSocket frames. • Encoding: signed 16-bit little-endian PCM (
pcm_s16le
). • Channels: mono (1) unless your Plivo session negotiated stereo. • Sample rate: match the negotiated session rate (commonly 16 kHz or 48 kHz). If unsure, inspect the incoming Plivo messages for a sample_rate field and use that value. Frame size & timing • Use small, consistent frames (recommended 20 ms per frame). ◦ Example sizes: ▪︎ 16 kHz mono, 20 ms → 16,000 samples/sec * 0.02 s = 320 samples → 320 samples * 2 bytes = 640 bytes/frame ▪︎ 48 kHz mono, 20 ms → 48,000 * 0.02 = 960 samples → 1,920 bytes/frame • Send each frame immediately as a binary WebSocket message as soon as it’s available. Do not batch multiple frames into one message. • Maintain steady inter-frame timing (~20 ms apart) to match telephony jitter expectations. Control messages & session lifecycle • Plivo sends text/JSON control frames for events (start/stop/mute). Respect those events. • When call ends, close the media WS or send any required end control frame per Plivo’s realtime docs. • If you must signal mute/unmute from your side, send the equivalent JSON control messages (mirror Plivo’s control schema). Forward Plivo control messages to your agent if it relies on them. Envelope / framing specifics • For outbound audio you generally send raw binary (no wrapper) unless your Plivo realtime integration used a custom envelope for incoming frames. If your incoming Plivo frames included any metadata wrapper, mirror that same envelope for outbound frames. • If Plivo provided an `event`/`header` describing sample_rate or channels at connection start, follow that for outbound frames. Resampling & channel mapping • If your agent uses a different sample rate or channels: ◦ Resample to Plivo’s negotiated sample_rate (do this at the bridge). ◦ Mixdown to mono if Plivo expects mono (simple average or choose a channel). • Use a low-latency resampler (native/compiled library) to avoid CPU stalls. Error handling & robustness • Drop malformed or empty frames—don’t send zero-length frames to Plivo. • On WebSocket send errors, log the close code and attempt a controlled close or reconnect per your call lifecycle. • Keep frames small and the WS max_size setting large enough to accept your incoming binary frames. Minimal checklist before sending frames 1. Confirm negotiated sample_rate & channels from Plivo connection start. 2. Convert agent PCM to
pcm_s16le
if not already. 3. Resample to the negotiated sample_rate and convert to mono if required. 4. Slice audio into fixed 20 ms frames (or whatever frame size Plivo used for incoming). 5. Send each 20 ms chunk as a binary WS message immediately. 6. Observe Plivo control messages and close the media socket when call ends. If you want, I can generate a tiny Python snippet that: • Detects Plivo’s negotiated sample rate from the incoming JSON handshake, • Resamples from 48k→16k (or vice versa) with a low-latency library call, • Sends correctly framed 20 ms
pcm_s16le
binary frames to Plivo. Which sample rates do you need supported?