BYO voice agent over media streams
Goal: run your own speech-to-text → LLM → text-to-speech stack and plug it into phone calls. We handle telephony; you get raw audio over a WebSocket and send audio back.
1. Start a bidirectional stream on the call
Return a stream command from your call webhook (or put it in a flow, or send it with calls.actions):
import { VoiceResponse } from "@kolwire/sdk";
res.json(
new VoiceResponse().answer().stream(`wss://agent.example.com/media?token=${process.env.MEDIA_TOKEN}`, {
bidirectional: true,
codec: "pcm16", // or "mulaw"
sample_rate: 16000, // or 8000
track: "inbound", // what we send you: caller audio
}),
);from kolwire import VoiceResponse
return VoiceResponse().answer().stream(
f"wss://agent.example.com/media?token={MEDIA_TOKEN}",
bidirectional=True, codec="pcm16", sample_rate=16000, track="inbound",
).to_dict()Or skip the webhook: create an agent with mode: "byo_agent" and byo_agent_url: "wss://agent.example.com/media?token=…", and route numbers/calls to it with agent_id.
2. Run the media server
The SDKs include a small, dependency-free WebSocket server that speaks the protocol for you.
import { createMediaStreamServer } from "@kolwire/sdk/node";
await createMediaStreamServer({
port: 8080,
path: "/media",
token: process.env.MEDIA_TOKEN, // checked against ?token= on the stream URL
onSession(s) {
const stt = myStt.open();
s.on("start", (info) => console.log("call", info.call_id, info.codec, info.sample_rate));
s.on("audio", (frame) => stt.write(frame.pcm)); // Int16Array at the stream's sample rate
s.on("dtmf", (digit) => console.log("pressed", digit));
stt.on("utterance", async (text) => {
s.clear(); // barge-in: drop anything still queued
for await (const pcm of myTts.speak(await myLlm.reply(text))) {
s.sendAudio(pcm, { sampleRate: 24000 }); // resampled + encoded for you
}
s.mark("reply-done"); // tells you when playback reaches here
});
s.on("mark", (name) => console.log("played up to", name));
s.on("stop", () => stt.close());
},
});import asyncio, os
from kolwire.media import serve_media_stream
async def handler(session):
info = await session.started() # the start frame's metadata (dict)
print("call", info["call_id"], info["codec"], info["sample_rate"])
stt = my_stt.open()
async for frame in session.audio_frames(): # frame.pcm = PCM16 little-endian bytes
text = stt.feed(frame.pcm)
if text:
await session.clear() # barge-in
async for pcm in my_tts.speak(await my_llm.reply(text)):
await session.send_audio(pcm, sample_rate=24000)
await session.mark("reply-done")
async def main():
server = await serve_media_stream(handler, port=8080, path="/media", token=os.environ["MEDIA_TOKEN"])
await server.serve_forever()
asyncio.run(main())Need to hang up, transfer or send DTMF from your agent? Use the REST API with the call id from the start frame: vi.calls.actions(info.call_id, { commands: [{ command: "transfer", target: "+1…" }] }) (Python: await aclient.calls.actions(session.call_id, commands=[...])).
Protocol
JSON text frames. Audio payloads are base64.
| Direction | Frame | Meaning |
|---|---|---|
| we → you | { "event": "start", "stream_id", "sequence", "start": { call_id, from, to, direction, codec, sample_rate, track, bidirectional, variables } } | First frame of every stream. |
| we → you | { "event": "media", "stream_id", "sequence", "media": { "track": "inbound"|"outbound", "timestamp", "payload" } } | 20 ms of audio. |
| we → you | { "event": "dtmf", "stream_id", "dtmf": { "digit": "5" } } | Caller pressed a key. |
| we → you | { "event": "mark", "stream_id", "mark": { "name" } } | Playback reached a mark you sent. |
| we → you | { "event": "stop", "stream_id", "stop": { "reason" } } | Stream ended (hangup or stream action: "stop"). |
| you → we | { "event": "media", "stream_id", "media": { "payload" } } | Audio to play to the caller (bidirectional only), same codec/rate as start. |
| you → we | { "event": "mark", "stream_id", "mark": { "name" } } | Ask to be notified when playback gets here. |
| you → we | { "event": "clear", "stream_id" } | Drop all queued, unplayed audio (barge-in). |
Audio formats
codec | Bytes per sample | Notes |
|---|---|---|
pcm16 | 2 | Signed 16-bit little-endian, mono. Best quality; use sample_rate: 16000. |
mulaw | 1 | G.711 µ-law at 8 kHz, the native telephone format. Lowest bandwidth. |
The SDKs ship helpers: Node mulawEncode, mulawDecode, resample, pcm16ToBytes, bytesToPcm16; Python kolwire.audio with the same functions in snake_case.
Security
The stream URL is yours, so authenticate the connection: put a long random secret in the URL (?token=) and pass it to token in the server helper, which compares it in constant time and rejects other connections with 401. Use wss:// in production.