conversation-relay-reference
Skill2 starsChanged 8 months agoMITView on GitHub
Twilio development skill: conversation-relay-reference
- Reads credentials
- Installs packages
In this repository66 other files it gives its agents.
- adversarial-reviewSkill
- agent-connectSkill
- agent-teams-guideSkill
- agent-testingSkill
- android-sdkSkill
- brainstormSkill
- branded-callingSkill
- callbacksSkill
- compliance-regulatorySkill
- conferenceSkill
- context-engineeringSkill
- context-hubSkill
- conversational-intelligenceSkill
- conversation-relaySkill
- conversationrelaySkill
- conversations-v2Skill
- customer-memorySkill
- deepgramSkill
- deep-validationSkill
- elastic-sip-trunkingSkill
- env-doctorSkill
- event-streamsSkill
- getting-startedSkill
- hooks-referenceSkill
- iamSkill
- ios-sdkSkill
- ivr-crawlerSkill
- ivr-migratorSkill
- lookupSkill
- media-streamsSkill
- memory-systemsSkill
- messaging-services-referenceSkill
- messaging-servicesSkill
- messagingSkill
- multi-agent-patternsSkill
- operational-gotchasSkill
- paymentsSkill
- paySkill
- phone-numbersSkill
- proxySkill
- real-time-transcriptionSkill
- recordingsSkill
- segmentSkill
- sendgrid-emailSkill
- sip-byocSkill
- sipSkill
- sync-referenceSkill
- syncSkill
- taskrouter-referenceSkill
- taskrouterSkill
- tdd-workflowSkill
- tool-boundariesSkill
- twilio-cliSkill
- twilio-invariantsSkill
- verify-referenceSkill
- verifySkill
- video-patternsSkill
- videoSkill
- voice-insightsSkill
- voice-referenceSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
11 rules. About 0 are common, 7 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 175
Anthropic Message Format Gotcha: When passing conversation history to Anthropic's API, only role and content are allowed.
- Distinctive: line 220
Keep only the last N messages:
- Distinctive: line 250
Keep all messages. Risk of context overflow on long calls — only use for short interactions.
- Distinctive: line 293
Start WebSocket server locally (port 8082)
- Very specific: line 294
Start ngrok tunnel: ngrok http 8082 --domain=$NGROK_DOMAIN_RELAY
- Very specific: line 296
Start Twilio serverless: npm run start:ngrok
- Distinctive: line 297
Call your Twilio number to test
- Very specific: line 329
When creating transcripts from Twilio recordings, use source_sid instead of media_url:
- Distinctive: line 358
Language Operators run automatically: When operators (e.g., Conversation Summary, Sentiment Analysis) are configured on the Intelligence …
- Distinctive: line 363
Use ngrok to expose local WebSocket server
- Distinctive: line 367
Test DTMF handling if enabled
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
<!-- ABOUTME: Complete reference for ConversationRelay patterns, LLM integration, and development setup. --><!-- ABOUTME: Companion to CLAUDE.md — contains code samples, configuration details, and integration guides. -->Conversation Relay Reference
For essential patterns and quick reference, see CLAUDE.md.
Full ConversationRelay Configuration
connect.conversationRelay({
url: 'wss://your-server.com/relay', // WebSocket endpoint
// TTS: ElevenLabs
ttsProvider: 'ElevenLabs', // 'ElevenLabs', 'Google', or 'Amazon'
voice: 'cgSgspJ2msm6clMCkdW9', // ElevenLabs Jessica
elevenlabsTextNormalization: 'on', // Natural number/date/currency speech
// STT: Deepgram Flux
transcriptionProvider: 'deepgram', // 'deepgram' or 'google'
speechModel: 'flux-general-en', // Deepgram Flux (optimized for voice agents)
// General
language: 'en-US', // Language code
profanityFilter: 'true', // Filter profanity
dtmfDetection: 'true', // Detect DTMF tones
interruptible: 'true', // Allow interruptions
welcomeGreeting: 'Hello, how can I help?', // Initial greeting
partialPrompts: 'true' // Enable partial transcripts
});Note: interruptByDtmf is NOT a valid ConversationRelay attribute. DTMF detection is controlled by dtmfDetection, and interruption behavior is controlled by interruptible.
WebSocket Message Protocol (Full Examples)
Incoming Messages (from Twilio)
Setup Message
{
"type": "setup",
"callSid": "CA...",
"sessionId": "KX...",
"from": "+1234567890",
"to": "+0987654321"
}Prompt Message (User Speech)
{
"type": "prompt",
"voicePrompt": "Hello, I need help with my account",
"last": true
}DTMF Message
{ "type": "dtmf", "digit": "1" }Interrupt Message
{ "type": "interrupt" }Outgoing Messages (to Twilio)
Text Response (TTS)
{ "type": "text", "token": "Hello! I'd be happy to help you with your account." }End Session
{ "type": "end" }WebSocket Server Implementation Pattern
// Example WebSocket handler (Node.js with ws library)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
let callContext = {};
ws.on('message', async (data) => {
const message = JSON.parse(data);
switch (message.type) {
case 'setup':
callContext = {
callSid: message.callSid,
from: message.from,
to: message.to
};
break;
case 'prompt':
if (message.last) {
// Process with your LLM
const response = await processWithLLM(message.voicePrompt);
ws.send(JSON.stringify({
type: 'text',
token: response
}));
}
break;
case 'dtmf':
// Handle DTMF digit
break;
case 'interrupt':
// User interrupted, stop current response
break;
}
});
ws.on('close', () => {
// Cleanup
});
});Integration with Claude/LLMs
Anthropic Claude Integration (Streaming — Recommended for Voice)
Streaming delivers tokens as they're generated, enabling natural real-time voice:
const Anthropic = require('@anthropic-ai/sdk');
const anthropic = new Anthropic();
async function processWithLLM(systemPrompt, messages, ws) {
const stream = await anthropic.messages.stream({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
system: systemPrompt,
messages: messages,
});
stream.on('text', (text) => {
ws.send(JSON.stringify({ type: 'text', token: text }));
});
const finalMessage = await stream.finalMessage();
return finalMessage.content[0].text;
}Anthropic Claude Integration (Non-Streaming)
async function processWithLLM(userMessage) {
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{ role: 'user', content: userMessage }
]
});
return response.content[0].text;
}Anthropic Message Format Gotcha: When passing conversation history to Anthropic's API, only role and content are allowed. Extra fields like timestamp will cause "Extra inputs are not permitted" errors:
// WRONG - will fail if messages have extra fields
messages: conversationHistory
// CORRECT - strip to only role and content
messages: conversationHistory.map(m => ({
role: m.role,
content: m.content
}))OpenAI Integration
const OpenAI = require('openai');
const openai = new OpenAI();
async function processWithLLM(userMessage) {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: userMessage }
]
});
return response.choices[0].message.content;
}Recommended Models
| Provider | Model | Best For |
| Anthropic | claude-sonnet-4-20250514 | Best balance of quality and latency |
| Anthropic | claude-haiku-4-5-20251001 | Fastest, good for simple interactions |
| OpenAI | gpt-4o | Best quality |
| OpenAI | gpt-4o-mini | Faster, lower cost |
Context Management Strategies
Voice calls can last many turns. Without context management, LLM context windows overflow on long calls.
Sliding Window (Recommended for Voice)
Keep only the last N messages:
function manageContext(messages) {
const WINDOW_SIZE = 20;
return messages.length > WINDOW_SIZE
? messages.slice(-WINDOW_SIZE)
: messages;
}Summary
Periodically summarize older messages and replace history:
async function manageContext(messages) {
if (messages.length > 30) {
const summary = await summarizeConversation(messages.slice(0, -10));
return [
{ role: 'user', content: `Previous conversation summary: ${summary}` },
...messages.slice(-10),
];
}
return messages;
}Full History
Keep all messages. Risk of context overflow on long calls — only use for short interactions.
Local Development with ngrok
For local WebSocket development, use ngrok to expose your local server.
Setup ngrok
- Install ngrok:
brew install ngrok(macOS) or download from ngrok.com - Configure auth:
ngrok config add-authtoken YOUR_AUTH_TOKEN - Start WebSocket server locally:
node websocket-server.js(port 8080) - Expose with ngrok:
ngrok http 8080 - Use ngrok URL:
wss://abc123.ngrok.io/relay
Stable Development URL
For consistent URL, use a custom domain (requires paid ngrok):
ngrok http 8080 --domain=your-domain.ngrok.devngrok Domain & Port Registry
Configure ngrok domains in your .env for local WebSocket development. Port assignments are in your local setup docs.
Agent-to-Agent Testing (Dual Tunnel Setup)
Agent-to-agent testing requires two separate ngrok tunnels — one per agent:
# Terminal A: Agent A (questioner) on port 8080
ngrok http 8080 --domain=$NGROK_DOMAIN_A
# Terminal B: Agent B (answerer) on port 8081
ngrok http 8081 --domain=$NGROK_DOMAIN_BThe relay URLs (AGENT_A_RELAY_URL, AGENT_B_RELAY_URL) in .env are already wired to these domains.
Development Workflow
- Start WebSocket server locally (port 8082)
- Start ngrok tunnel:
ngrok http 8082 --domain=$NGROK_DOMAIN_RELAY CONVERSATION_RELAY_URLin.envalready points to this domain- Start Twilio serverless:
npm run start:ngrok - Call your Twilio number to test
Debugging WebSocket Traffic
ngrok provides a web interface at http://localhost:4040 to inspect WebSocket traffic in real-time.
Conference Call Pattern (Full Code)
// 1. Configure each agent's phone with ConversationRelay webhook
// Agent A: agent-a-inbound → ConversationRelay to wss://agent-a-server
// Agent B: agent-b-inbound → ConversationRelay to wss://agent-b-server
// 2. Create conference and add customer
const customerCall = await client.calls.create({
to: customerPhone, // Phone with ConversationRelay webhook
from: servicePhone,
url: customerLegUrl, // TwiML: <Dial><Conference>name</Conference></Dial>
});
// 3. Add agent via Participants API
await client.conferences(conferenceSid)
.participants.create({
from: servicePhone,
to: agentPhone, // Phone with ConversationRelay webhook
});
// Agent's phone webhook fires → ConversationRelay on child leg
// Parent leg auto-joins conference → audio bridges throughCreating Transcripts from Recordings
When creating transcripts from Twilio recordings, use source_sid instead of media_url:
// WRONG - Intelligence API can't authenticate to api.twilio.com
const channel = {
media_properties: {
media_url: `https://api.twilio.com/.../Recordings/${recordingSid}.mp3`,
},
participants: [...]
};
// CORRECT - Use source_sid for Twilio recordings
const channel = {
media_properties: {
source_sid: recordingSid, // e.g., "RE1234567890abcdef"
},
participants: [
{ channel_participant: 1, user_id: 'caller' },
{ channel_participant: 2, user_id: 'agent' },
],
};
const transcript = await client.intelligence.v2.transcripts.create({
serviceSid: intelligenceServiceSid,
channel,
customerKey: callSid, // For correlation
});Language Operators run automatically: When operators (e.g., Conversation Summary, Sentiment Analysis) are configured on the Intelligence service in the Twilio Console, they automatically run on every transcript created via that service. No per-transcript operator invocation is needed.
Testing Conversation Relay
- Set up a WebSocket server (locally or deployed)
- Use ngrok to expose local WebSocket server
- Configure the relay URL in your function
- Make test calls to verify the flow
- Test interruption scenarios
- Test DTMF handling if enabled
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

