Skip to main content
skill CX Codex GP ChatGPT official · OpenAI

twilio-voice-conversation-relay — Codex skill: voice AI agents

Build voice-powered AI agents on Twilio with real-time speech handling. Wraps speech recognition (ASR) and text-to-speech (TTS) over WebSocket, so you work with text, not raw audio streams.

Install into Codex · Skills CLI (Vercel) All methods and platforms ↓
npx skills add openai/plugins --skill twilio-voice-conversation-relay -a codex
Open on GitHub

What twilio-voice-conversation-relay does

ConversationRelay connects Twilio's telephony to your app via a persistent WebSocket. Twilio manages ASR and TTS; your code receives call transcripts as text, passes them to an LLM, and returns text responses that Twilio plays back as speech.

The skill covers TwiML setup (Python and Node.js examples), WebSocket message types (connected, prompt, interrupt, dtmf, error), sending text for playback with the last flag, streaming LLM tokens for lower latency, and voice and provider configuration (ASR: Deepgram, Google Cloud STT; TTS: Deepgram, Amazon Polly, Google Cloud TTS, ElevenLabs).

Limitations: no raw audio access (use Media Streams instead), no built-in conversation memory, no WebSocket auto-reconnect (call hangs up on disconnect), incompatible with Media Streams on the same call. Requires a Twilio account with ConversationRelay access (granted via Console onboarding), TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN, a TLS-secured WebSocket server, and your own LLM integration.

What it helps with

  • Build a voice bot that answers caller questions in real time
  • Replace IVR menus with an AI agent using natural speech
  • Handle keypad input (DTMF) and speech recognition on the same call
  • Stream LLM responses to speech as they are generated, without waiting for completion
  • Configure voice, language, and TTS provider per call

Example prompts for the agent

  • Set up a voice agent that listens to the caller and responds via OpenAI — use the skill to handle WebSocket connection and Twilio events
  • Configure TwiML so incoming calls route to your WebSocket server by adding conversation_relay() with your chosen voice
  • Stream LLM response tokens so Twilio begins speaking while the model is still generating

How to install twilio-voice-conversation-relay

1Skills CLI (Vercel)

npx skills add openai/plugins --skill twilio-voice-conversation-relay -a codex

2Manually: put the files in place

.agents/skills/twilio-voice-conversation-relay/SKILL.md

For all projects use ~/.agents/skills/

Step by step, with commands for each platform: Codex skills: how to install, where they live, how to call them

Questions about twilio-voice-conversation-relay

How do I install twilio-voice-conversation-relay in Codex?

Run npx skills add openai/plugins --skill twilio-voice-conversation-relay -a codex, then open the skill docs at ~/.claude/skills/twilio-voice-conversation-relay/SKILL.md.

What does twilio-voice-conversation-relay do?

The skill helps you build a voice AI agent on Twilio ConversationRelay. Your code receives text from the caller's speech, sends it to an LLM, and returns a text response that Twilio speaks back. The skill covers TwiML setup, WebSocket event handling, token streaming, and voice configuration.

What do I need to use this skill?

You need a Twilio account with ConversationRelay access enabled (via Console > Voice > ConversationRelay > Onboarding), TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN, a TLS-secured WebSocket server (wss://), a Twilio voice number, and your own LLM integration (OpenAI, Anthropic, etc.).

Source text

SKILL.md · MIT
---
name: twilio-voice-conversation-relay
description: >
  Build AI-powered voice agents using Twilio ConversationRelay. Handles
  real-time speech recognition (ASR), text-to-speech (TTS), and bidirectional
  audio streaming via WebSocket. Covers TwiML setup, WebSocket message types,
  LLM integration, streaming responses, and voice provider configuration. Use
  this skill to build voice bots, IVR replacements, or real-time AI voice
  assistants on Twilio calls.
---

## Overview

ConversationRelay connects Twilio's telephony layer to your app via a persistent WebSocket. Twilio handles ASR (speech-to-text) and TTS (text-to-speech); your app receives transcripts, calls an LLM, and sends text back for playback.

```
Caller ←→ Twilio (ASR/TTS) ←→ WebSocket ←→ Your App ←→ LLM
```

---

## Prerequisites

- Upgraded Twilio account with ConversationRelay access (requires onboarding)
  — New to Twilio? See `twilio-account-setup`
  — Start onboarding at: [Console > Voice > ConversationRelay](https://console.twilio.com/us1/voice/conversation-relay) — access is **not** instant
- A voice-capable Twilio phone number
- `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` — see `twilio-iam-auth-setup`
- WebSocket server reachable via `wss://` (TLS required)
- An LLM integration (OpenAI, Anthropic, etc.)
- For placing calls: see `twilio-voice-outbound-calls`

**Onboarding:** Complete via Console > Voice > ConversationRelay > Onboarding. Select TTS/ASR providers:
- **TTS:** Deepgram, Amazon Polly, Google Cloud TTS, ElevenLabs
- **ASR:** Deepgram, Google Cloud STT

---

## Quickstart

**Step 1 — Return TwiML pointing to your WebSocket server**

**Python (Flask)**
```python
from flask import Flask
from twilio.twiml.voice_response import VoiceResponse, Connect, ConversationRelay

app = Flask(__name__)

@app.route("/voice", methods=["POST"])
def voice():
    response = VoiceResponse()
    connect = Connect()
    connect.conversation_relay(
        url="wss://yourapp.com/ws/voice",
        welcome_greeting="Hello! How can I help you today?"
    )
    response.append(connect)
    return str(response)
```

**Node.js (Express)**
```node
const { VoiceResponse } = require("twilio").twiml;

app.post("/voice", (req, res) => {
    const response = new VoiceResponse();
    const connect = response.connect();
    connect.conversationRelay({
        url: "wss://yourapp.com/ws/voice",
        welcomeGreeting: "Hello! How can I help you today?",
    });
    res.type("text/xml").send(response.toString());
});
```

**Step 2 — Handle WebSocket events and respond with text**

**Python (websockets)**
```python
import asyncio, json, websockets

async def handle_call(websocket):
    async for message in websocket:
        event = json.loads(message)
        if event["type"] == "prompt":
            ai_response = await call_llm(event["voicePrompt"])
            await websocket.send(json.dumps({"type": "text", "token": ai_response, "last": True}))

async def main():
    async with websockets.serve(handle_call, "0.0.0.0", 8080):
        await asyncio.Future()

asyncio.run(main())
```

**Node.js (ws)**
```node
const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", (ws) => {
    ws.on("message", async (data) => {
        const event = JSON.parse(data);
        if (event.type === "prompt") {
            const aiResponse = await callLLM(event.voicePrompt);
            ws.send(JSON.stringify({ type: "text", token: aiResponse, last: true }));
        }
    });
});
```

> **Security:** The `voicePrompt` field contains ASR-transcribed caller speech — it is untrusted external input. When passing to an LLM, isolate it as user input within a structured system prompt. Implement topic boundaries and output filtering to prevent the LLM from disclosing system instructions or speaking inappropriate content. ConversationRelay is a pure transport layer with no built-in content safety — any LLM output is spoken to the caller verbatim.

---

## Key Patterns

### WebSocket Message Types

**Received from Twilio:**

| Type | When | Key fields |
|------|------|-----------|
| `connected` | WebSocket opened | `callSid`, `streamSid` |
| `prompt` | User finished speaking | `voicePrompt` (transcript) |
| `interrupt` | User interrupted TTS | — |
| `dtmf` | User pressed keypad key | `digit` |
| `error` | An error occurred | `description` |

**Sent to Twilio:**

| Type | Purpose | Key fields |
|------|---------|-----------|
| `text` | Send TTS response | `token` (text), `last` (bool) |
| `interrupt` | Stop current TTS | — |
| `end` | Hang up the call | `reason` |

### Stream LLM Responses Token-by-Token

Lower latency by streaming as the LLM generates output — Twilio starts speaking before the full response is ready.

**Python**
```python
async for chunk in llm_stream:
    await websocket.send(json.dumps({"type": "text", "token": chunk, "last": False}))
await websocket.send(json.dumps({"type": "text", "token": "", "last": True}))
```

**Node.js**
```node
for await (const chunk of llmStream) {
    ws.send(JSON.stringify({ type: "text", token: chunk, last: false }));
}
ws.send(JSON.stringify({ type: "text", token: "", last: true }));
```

### Voice Configuration

**Python**
```python
connect.conversation_relay(
    url="wss://yourapp.com/ws/voice",
    voice="en-US-Neural2-F",
    language="en-US",
    transcription_provider="deepgram",
    speech_model="nova-2-phonecall",
    interrupt_by_dtmf=True,
)
```

**Node.js**
```node
connect.conversationRelay({
    url: "wss://yourapp.com/ws/voice",
    voice: "en-US-Neural2-F",
    language: "en-US",
    transcriptionProvider: "deepgram",
    speechModel: "nova-2-phonecall",
    interruptByDtmf: true,
});
```

---

## CANNOT

- **No raw audio access** — Text in, text out only. For raw audio, use `<Connect><Stream>` (Media Streams).
- **Cannot mix with Media Streams** — `<Connect><Stream>` and `<Connect><ConversationRelay>` are mutually exclusive on the same call. No error — one is silently ignored.
- **No custom STT/TTS engines** — Limited to Deepgram + Google (STT) and Deepgram + Amazon Polly + Google + ElevenLabs (TTS).
- **No mid-session voice/provider changes** — Voice and provider are set at TwiML time. Only `language` can be switched mid-session via WebSocket message.
- **No WebSocket auto-reconnection** — If the WebSocket drops, the call disconnects. Implement recovery via `<Connect action>` URL.
- **Voice only** — No SMS/messaging support. For omnichannel, use Conversation Orchestrator.
- **No built-in memory or context** — BYO conversation history and context management.
- **No LLM integration** — Pure transport layer. You bring your own LLM via the WebSocket server.
- **No server-side recording via REST API** — `record:true` on the Calls API is silently ignored. Must use `<Start><Recording>` before `<Connect>` in TwiML.
- **Not PCI compliant with Voice Intelligence v2** — Do not enable `intelligenceService` in PCI workflows.
- **ElevenLabs requires account enablement** — Accounts without ElevenLabs access get error 64101. Voice IDs (not human-readable names) are required.
- **Cannot use ConversationRelay without onboarding** — Not available immediately on a new account
- **Cannot use non-TLS WebSocket** — Server must be reachable via `wss://` (TLS required)
- **Cannot stream audio without `last: true`** — Twilio won't play audio until it sees a `last: true` token in the stream

---

## Next Steps

- **Place outbound calls:** `twilio-voice-outbound-calls`
- **Standard IVR without AI:** `twilio-voice-twiml`

© Twilio · MIT · openai/plugins

Similar skills

All skills for Backend and APIs →

From the same set422

The whole set →
building-native-ui A Codex skill for building Expo Router interfaces with guidance on routes, styling, components, animation, and native tabs. CX Codex GP ChatGPT 2installs building-mcp-server-on-cloudflare A skill that walks the agent through building a remote MCP server on Cloudflare Workers: tools, OAuth, deployment. Useful when you need to expose your own functions over MCP. CX Codex GP ChatGPT 2installs knowledge-update Injects up-to-date Vercel platform facts into the session and overrides stale model knowledge. Useful when your agent still reaches for Edge Functions or vercel.json. CX Codex GP ChatGPT 1installs eve Skill for working with eve, a framework for durable AI agents. Creates projects, debugs deployed agents, and picks architecture for eve-based applications. CX Codex GP ChatGPT 1installs twilio-send-message A skill that gives your agent the recipes for sending messages through Twilio's Programmable Messaging API — SMS, MMS, RCS and WhatsApp. Useful when a project needs notifications or alerts. CX Codex GP ChatGPT 1installs twilio-messaging-overview A navigation skill for Twilio Messaging: pick between SMS, WhatsApp, RCS and Messenger, then follow the setup order from first message to production monitoring. CX Codex GP ChatGPT 1installs twilio-account-setup Walks you from Twilio signup to your first sent message: credentials, phone number, SDK, subaccounts. CX Codex GP ChatGPT 1installs shopify-use-shopify-cli A skill that steers your agent toward the right Shopify CLI command and helps it run or fix things now: config validation, store operations, setup errors. CX Codex GP ChatGPT 1installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor