agentleFS
wittyreferencewittyreference/twilio-claude-plugin/skills/conversation-relay-reference/SKILL.md

conversation-relay-reference

Skill2 starsChanged 8 months agoMITView on GitHub

Twilio development skill: conversation-relay-reference

  • Reads credentials
  • Installs packages

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
  1. Very specific:

    Anthropic Message Format Gotcha: When passing conversation history to Anthropic's API, only role and content are allowed.

    line 175
  2. Distinctive:

    Keep only the last N messages:

    line 220
  3. Distinctive:

    Keep all messages. Risk of context overflow on long calls — only use for short interactions.

    line 250
  4. Distinctive:

    Start WebSocket server locally (port 8082)

    line 293
  5. Very specific:

    Start ngrok tunnel: ngrok http 8082 --domain=$NGROK_DOMAIN_RELAY

    line 294
  6. Very specific:

    Start Twilio serverless: npm run start:ngrok

    line 296
  7. Distinctive:

    Call your Twilio number to test

    line 297
  8. Very specific:

    When creating transcripts from Twilio recordings, use source_sid instead of media_url:

    line 329
  9. Distinctive:

    Language Operators run automatically: When operators (e.g., Conversation Summary, Sentiment Analysis) are configured on the Intelligence …

    line 358
  10. Distinctive:

    Use ngrok to expose local WebSocket server

    line 363
  11. Distinctive:

    Test DTMF handling if enabled

    line 367

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- 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

ProviderModelBest For
Anthropicclaude-sonnet-4-20250514Best balance of quality and latency
Anthropicclaude-haiku-4-5-20251001Fastest, good for simple interactions
OpenAIgpt-4oBest quality
OpenAIgpt-4o-miniFaster, 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

  1. Install ngrok: brew install ngrok (macOS) or download from ngrok.com
  2. Configure auth: ngrok config add-authtoken YOUR_AUTH_TOKEN
  3. Start WebSocket server locally: node websocket-server.js (port 8080)
  4. Expose with ngrok: ngrok http 8080
  5. 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.dev

ngrok 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_B

The relay URLs (AGENT_A_RELAY_URL, AGENT_B_RELAY_URL) in .env are already wired to these domains.

Development Workflow

  1. Start WebSocket server locally (port 8082)
  2. Start ngrok tunnel: ngrok http 8082 --domain=$NGROK_DOMAIN_RELAY
  3. CONVERSATION_RELAY_URL in .env already points to this domain
  4. Start Twilio serverless: npm run start:ngrok
  5. 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 through

Creating 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

  1. Set up a WebSocket server (locally or deployed)
  2. Use ngrok to expose local WebSocket server
  3. Configure the relay URL in your function
  4. Make test calls to verify the flow
  5. Test interruption scenarios
  6. Test DTMF handling if enabled

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.