Skip to navigation

Conversations via WebSockets

WebSocket conversations support the same features as webhook conversations but are much more flexible. Because you will run your own server that manually forwards audio chunks between Phonic and your own audio interface, you can implement offline tools and use your own audio interface, via telephony, web, or otherwise.

In this guide we’ll demonstrate the basic mechanics of WebSocket conversations. The example code for this guide is available here.

Open a WebSocket connection to Phonic

The first step is to open a WebSocket connection to Phonic, which sends and receives various types of messages, detailed here.

On the receiving side, the most important message is the audio_chunk_response, which contains the Phonic-generated audio that your server will forward to your audio interface, along with its transcript.

Similarly, on the sending side, the most important message is the audio_chunk, which contains the user audio that your server will forward to Phonic.

Here is an example implementation of this WebSocket connection:

import { createNodeWebSocket } from "@hono/node-ws";
import { Hono } from "hono";
import type { WSContext } from "hono/ws";
import { PhonicClient } from "phonic";
import { phonicApiKey } from "./env-vars";
const app = new Hono();
const phonicClient = new PhonicClient({
apiKey: phonicApiKey,
});
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
app.get(
"/ws",
upgradeWebSocket(() => {
let phonicSocket: Awaited<
ReturnType<typeof phonicClient.conversations.connect>
> | null = null;
let streamSid: string | null = null;
const sendToTwilio = (ws: WSContext, data: unknown) => {
ws.send(JSON.stringify(data));
};
return {
async onOpen(_, ws) {
phonicSocket = await phonicClient.conversations.connect();
phonicSocket.on("message", (message) => {
if (streamSid && message.type === "audio_chunk") {
sendToTwilio(ws, {
event: "media",
streamSid: streamSid,
media: {
payload: message.audio,
},
});
}
})
await phonicSocket.sendConfig({
type: "config",
agent: "agent-websocket",
};
},
async onMessage(event, ws) {
const message = event.data;
if (typeof message !== "string") return;
const data = JSON.parse(message);
switch (data.event) {
case "start":
streamSid = data.streamSid;
break;
case "media":
if (phonicSocket && data.media.track === "inbound") {
await phonicSocket.sendAudioChunk({
type: "audio_chunk",
audio: data.media.payload,
});
}
break;
case "stop":
ws.close();
break;
}
},
onClose() {
console.log("Twilio WebSocket closed");
if (phonicSocket) {
phonicSocket.close();
}
},
};
}),
);

Open a connection with your audio interface

Now that your server is open and receiving messages from Phonic, you can use any audio interface for the user. Here is a simple example using Twilio:

import VoiceResponse from "twilio/lib/twiml/VoiceResponse";
app.post("/inbound", (c) => {
const url = new URL(c.req.url);
const response = new VoiceResponse();
response.connect().stream({
url: `wss://${url.host}/ws`,
});
return c.text(response.toString(), 200, { "Content-Type": "text/xml" });
});
See here for a complete code example.

Automatic reconnection on abnormal disconnect

A live WebSocket connection can drop unexpectedly — most often when the socket is severed with no close handshake (surfaced to the client as close code 1006), or when the edge proxy in front of Phonic redeploys and drains connections (the client is closed with 1012 “service restart”, or sometimes 1001 “going away” with reason "restarting"). By default a dropped conversation is lost and a new one must be started. Both the TypeScript and Python SDKs support automatic reconnection, which resumes the existing conversation seamlessly after a recoverable disconnect.

To enable it, pass reconnectConversationOnAbnormalDisconnect: true (TypeScript) or reconnect_conversation_on_abnormal_disconnect=True (Python) when creating the client:

const phonicClient = new PhonicClient({
apiKey: phonicApiKey,
reconnectConversationOnAbnormalDisconnect: true,
});
// connect() now returns a ReconnectableConversationsSocket
const socket = await phonicClient.conversations.connect();
socket.on("message", (message) => {
// Your message handler works the same as before. On a recoverable close
// (1006, 1012, or 1001/"restarting"), the SDK automatically reconnects
// using the conversation ID from the original session.
});

When enabled:

  • On a recoverable close — 1006, 1012, or 1001 with reason "restarting" — the SDK opens a new WebSocket with the reconnect_conv_id query parameter set to the original conversation ID. A deliberate close (a bare 1001, or a normal 1000) ends the conversation as usual and does not trigger a reconnect.
  • The server resumes the existing conversation and sends a conversation_reconnected message; audio streaming restarts automatically.
  • Reconnection retries with exponential backoff, starting at 500 ms and doubling up to a 5 s cap. The server holds the conversation for approximately 30 seconds after the disconnect, so retries are sent up to 10 times or until the server expires the conversation, whichever occurs first. If the conversation is expired, the reconnect attempt receives a close code of 4800.

Close codes

When Phonic ends a conversation, it closes the WebSocket with one of the codes below. The close reason carries the text in the Reason column. Use the code, not the reason text, to decide how to handle the close.

Conversation ended by a setting or a request.

CodeReasonWhen
4001Conversation cancelledThe conversation was canceled through the Cancel endpoint.
4500Conversation became inactiveNo input was received for no_input_end_conversation_sec (default 180). The timer pauses while the user speaks and restarts when the assistant finishes speaking.
4505Conversation time limit reachedThe conversation reached max_conversation_duration_sec.

When the assistant ends the conversation, Phonic sends an assistant_ended_conversation message instead of closing the socket. Close it from your side with code 1000 once any remaining audio has played.

Connection problems.

CodeReasonWhen
1006Connection lostThe socket was severed without a close handshake. Recoverable: see automatic reconnection.
4506WebSocket input/output timed outPhonic received nothing from your side for websocket_timeout_sec (default 60), for example because audio stopped streaming. Send silence rather than pausing the audio stream.
4800Session not found or expiredA reconnect attempt arrived after the server stopped holding the conversation.

Limits and setup. 4004 (insufficient capacity), 4010 (concurrency limit reached) and 4429 (rate limit exceeded) mean the conversation could not start; retry later. Codes 4100–4108 and 4300–4323 mean the connection parameters or agent configuration were rejected; the close reason says which.

Unexpected errors. 4501–4504 and 4206 mean something failed on Phonic’s side. Start a new conversation and contact Phonic support if it keeps happening.