WebSocket AMD Detection API

Version 2.0

Last Updated: February 5, 2026 Server Version: asr_server.py with 24K cascade models Protocol: WebSocket (RFC 6455)


Table of Contents

  1. Overview
  2. Authentication
  3. Connection
  4. Protocol Specification
  5. Request Format
  6. Response Format
  7. Error Handling
  8. Code Examples
  9. Performance Considerations
  10. API Rate Limits

Overview

The AMD (Answering Machine Detection) WebSocket API provides real-time voice classification for telephony applications. The service analyzes audio streams and classifies them as either automated answering machines (AMD) or live human speech (HUMAN).

Key Features

Service Endpoints

Purpose Protocol Default Port Endpoint
WebSocket API WS 2700 ws://{host}:2700/
Health Check HTTP 2710 http://{host}:2710/health
HAProxy Agent TCP 2720 tcp://{host}:2720

Authentication

API Key Management

API keys are validated by HAProxy using map files before requests reach the backend server.

HAProxy Configuration

frontend amd_api
    bind *:80

    # Extract API key from X-API-Key header
    http-request set-var(req.api_key) req.hdr(X-API-Key)

    # Validate API key against map file
    acl valid_api_key var(req.api_key),map_str(/etc/haproxy/api_keys.map) -m found

    # Reject if API key is invalid
    http-request deny if !valid_api_key

    # Forward to backend if valid
    default_backend asr_servers

backend asr_servers
    balance leastconn
    option tcp-check

    server asr1 10.0.0.10:2700 check agent-check agent-port 2720 agent-inter 5s
    server asr2 10.0.0.11:2700 check agent-check agent-port 2720 agent-inter 5s
    server asr3 10.0.0.12:2700 check agent-check agent-port 2720 agent-inter 5s

API Key Map File Format

File: /etc/haproxy/api_keys.map

# Format: <api_key> <client_identifier>
sk_live_abc123def456ghi789 customer_acme_corp
sk_live_xyz789uvw456rst123 customer_beta_inc
sk_test_dev123test456test789 internal_testing

Generating API Keys

API keys should be generated using a cryptographically secure method:

# Generate a new API key
openssl rand -hex 32 | awk '{print "sk_live_"$1}'

# Example output:
# sk_live_a3b4c5d6e7f8g9h0i1j2k3l4m5n6o7p8

Key Format: - Prefix: sk_live_ (production) or sk_test_ (testing) - Length: 64 characters total (prefix + 56 hex characters) - Character set: lowercase hexadecimal (a-f, 0-9)

API Key Rotation

To rotate keys:

  1. Generate new API key
  2. Add to HAProxy map file
  3. Reload HAProxy: systemctl reload haproxy
  4. Notify client of new key
  5. Remove old key after grace period

Connection

WebSocket Handshake

URL: ws://{host}:{port}/

Headers:

GET / HTTP/1.1
Host: api.example.com:2700
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
X-API-Key: sk_live_abc123def456ghi789

Note: X-API-Key header is validated by HAProxy before the WebSocket upgrade.

Connection Lifecycle

Client                  HAProxy                  ASR Server
  |                       |                          |
  |--- WS Handshake ----->|                          |
  |    (with API key)     |                          |
  |                       |--- Validate Key -------->|
  |                       |    (map lookup)          |
  |                       |                          |
  |<----- 101 Switching Protocols ------------------|
  |                       |                          |
  |--- Config Message --->|------------------------>|
  |                       |                          |
  |--- Audio Data ------->|------------------------>|
  |--- Audio Data ------->|------------------------>|
  |--- Audio Data ------->|------------------------>|
  |                       |                          |
  |--- EOF Message ------>|------------------------>|
  |                       |                          |
  |<----- Result ---------|<------------------------|
  |                       |                          |
  |--- Close ------------>|------------------------>|
  |<----- Close Ack ------|<------------------------|

Protocol Specification

Message Types

  1. Configuration Message (JSON text)
  2. Audio Data (Binary)
  3. EOF Signal (JSON text)
  4. Detection Result (JSON text)

Audio Requirements

Parameter Value
Sample Rate 8000 Hz
Bit Depth 16-bit signed integer
Channels Mono (1 channel)
Byte Order Little-endian
Format Raw PCM (no WAV header)
Encoding Linear PCM

Request Format

1. Configuration Message

Sent first after connection established.

{
  "config": {
    "sample_rate": 8000,
    "VID": "V1234567890123456789",
    "phone": "+15551234567",
    "country_code": "1",
    "immediate_detection": false
  }
}

Parameters:

Field Type Required Description
sample_rate integer Yes Audio sample rate in Hz (must be 8000)
VID string Yes Voice ID for tracking (20-25 chars recommended)
phone string No Caller phone number
country_code string No Country calling code
immediate_detection boolean No If true, return first confident detection (default: false)

VID Format Recommendation: - Pattern: V{YYY}{MM}{UNIX_TIMESTAMP}{RANDOM} - Example: V1022011234567890123 - Purpose: Unique identifier for logging and debugging

2. Audio Data Messages

Send raw 16-bit PCM audio as binary WebSocket messages.

Recommended Chunk Size: 8000-16000 samples (1-2 seconds)

Example (Python):

import numpy as np

# Audio data as int16 array
audio_chunk = np.array([...], dtype=np.int16)

# Convert to bytes and send
await websocket.send(audio_chunk.tobytes())

Example (JavaScript):

// Audio data as Int16Array
const audioChunk = new Int16Array([...]);

// Convert to ArrayBuffer and send
websocket.send(audioChunk.buffer);

3. EOF Message

Signal end of audio stream.

{"eof": 1}

Must be sent to trigger final classification and response.


Response Format

Detection Result

{
  "classification": "AMD",
  "amd_conf": 0.9234,
  "human_conf": 0.0766,
  "greeting_class": "welcome_voicemail",
  "greeting_conf": 0.8912,
  "model_history": "4k:HUMAN:0.10:0.90:1;8k:HUMAN:0.15:0.85:1;16k:AMD:0.65:0.35:0;24k:AMD:0.92:0.08:0;32k:welcome_voicemail:0.89"
}

Response Fields:

Field Type Description
classification string Final classification: "AMD" or "HUMAN"
amd_conf float AMD confidence score (0.0 - 1.0)
human_conf float HUMAN confidence score (0.0 - 1.0)
greeting_class string Greeting type (only if AMD detected)
greeting_conf float Greeting classification confidence
model_history string Cascade execution trace

Greeting Classes

When classification is "AMD", the greeting_class field identifies the specific greeting type:

Class Description
welcome_voicemail Standard voicemail greeting
please_leave_your_message "Please leave your message"
please_leave_your_message_for "Please leave a message for..."
hello_leave_message_tone "Hello, leave a message after the tone"
your_call_forwarded_voicemail "Your call has been forwarded..."
thank_you_for_calling Business greeting
busy_try_later "The person you're calling is busy"
cant_take_call_now "Can't take your call right now"
subscriber_not_available "The subscriber is not available"
network_analytics Carrier network announcement
google_voice_screening Google Voice screening
honeypot Spam trap/honeypot detection
ivr_press_button IVR menu system
ringing Ring tone only
disconnected Disconnected/out of service
mailbox_full Mailbox full message
sorry_voicemail_not_setup Voicemail not configured
click_noise Click/silence followed by hangup
other Unclassified AMD audio

And 9 additional classes for language/regional variants

Model History Format

The model_history field provides a trace of the cascade execution:

Format: {stage}:{class}:{amd_conf}:{human_conf}:{exit};...

Example:

4k:HUMAN:0.10:0.90:1;8k:HUMAN:0.15:0.85:1;16k:AMD:0.65:0.35:0;24k:AMD:0.92:0.08:0

Fields: - stage: Model identifier (4k, 8k, 12k, 16k, 24k, 32k) - class: Classification at this stage (AMD or HUMAN) - amd_conf: AMD confidence score - human_conf: HUMAN confidence score - exit: Early exit flag (1 = exited here, 0 = continued)

Interpretation: - If exit=1, the cascade stopped at this stage - If exit=0, the cascade continued to the next stage - The last stage in the history is where the final decision was made


Error Handling

WebSocket Close Codes

Code Name Description Action
1000 Normal Closure Connection closed normally None required
1001 Going Away Server shutting down Reconnect after delay
1002 Protocol Error Invalid message format Fix client code
1006 Abnormal Closure Network/proxy issue Check network, retry
1011 Internal Error Server error Contact support

Error Response Format

If an error occurs during processing, the server may send:

{
  "error": "Invalid audio format",
  "code": "INVALID_AUDIO",
  "details": "Expected 16-bit PCM, received 8-bit"
}

Common Errors

Error Code Cause Solution
INVALID_CONFIG Missing or malformed config Check config JSON format
INVALID_AUDIO Wrong audio format Use 8kHz 16-bit mono PCM
BUFFER_TOO_SMALL Insufficient audio Send at least 0.5s of audio
TIMEOUT No audio received Check network latency
AUTH_FAILED Invalid API key Verify API key with provider

Code Examples

Python Example (asyncio + websockets)

import asyncio
import websockets
import json
import numpy as np
import soundfile as sf

async def detect_amd(audio_file, api_key, immediate=False):
    """
    Detect AMD using WebSocket API.

    Args:
        audio_file: Path to audio file (8kHz, 16-bit, mono)
        api_key: API key for authentication
        immediate: Use immediate detection mode

    Returns:
        dict: Detection result
    """
    uri = "ws://api.example.com:2700/"
    headers = {"X-API-Key": api_key}

    async with websockets.connect(uri, extra_headers=headers) as ws:
        # Send configuration
        config = {
            "config": {
                "sample_rate": 8000,
                "VID": f"V{int(asyncio.get_event_loop().time() * 1000)}",
                "immediate_detection": immediate
            }
        }
        await ws.send(json.dumps(config))

        # Load audio file
        audio, sr = sf.read(audio_file)

        # Resample if needed
        if sr != 8000:
            from scipy import signal
            audio = signal.resample(audio, int(len(audio) * 8000 / sr))

        # Convert to int16
        audio_int16 = (audio * 32767).astype(np.int16)

        # Send audio in chunks
        chunk_size = 8000  # 1 second
        for i in range(0, len(audio_int16), chunk_size):
            chunk = audio_int16[i:i+chunk_size]
            await ws.send(chunk.tobytes())
            await asyncio.sleep(0.1)  # Small delay between chunks

        # Send EOF
        await ws.send(json.dumps({"eof": 1}))

        # Receive result
        result = await ws.recv()
        return json.loads(result)

# Usage
async def main():
    api_key = "sk_live_abc123def456ghi789"

    # Normal mode (full cascade)
    result = await detect_amd("recording.wav", api_key, immediate=False)
    print(f"Classification: {result['classification']}")
    print(f"Confidence: AMD={result['amd_conf']:.2%}, HUMAN={result['human_conf']:.2%}")

    if result['classification'] == 'AMD':
        print(f"Greeting: {result['greeting_class']}")

    print(f"Model History: {result['model_history']}")

asyncio.run(main())

Node.js Example (ws library)

const WebSocket = require('ws');
const fs = require('fs');
const wav = require('node-wav');

async function detectAMD(audioFile, apiKey, immediate = false) {
    return new Promise((resolve, reject) => {
        const ws = new WebSocket('ws://api.example.com:2700/', {
            headers: {
                'X-API-Key': apiKey
            }
        });

        ws.on('open', () => {
            // Send configuration
            const config = {
                config: {
                    sample_rate: 8000,
                    VID: `V${Date.now()}`,
                    immediate_detection: immediate
                }
            };
            ws.send(JSON.stringify(config));

            // Load and send audio
            const buffer = fs.readFileSync(audioFile);
            const result = wav.decode(buffer);

            // Convert to Int16Array
            const audioData = new Int16Array(result.channelData[0].length);
            for (let i = 0; i < result.channelData[0].length; i++) {
                audioData[i] = Math.max(-32768, Math.min(32767,
                    result.channelData[0][i] * 32767));
            }

            // Send audio
            ws.send(audioData.buffer);

            // Send EOF
            ws.send(JSON.stringify({eof: 1}));
        });

        ws.on('message', (data) => {
            const result = JSON.parse(data);
            resolve(result);
            ws.close();
        });

        ws.on('error', (error) => {
            reject(error);
        });
    });
}

// Usage
(async () => {
    const apiKey = 'sk_live_abc123def456ghi789';

    try {
        const result = await detectAMD('recording.wav', apiKey);
        console.log(`Classification: ${result.classification}`);
        console.log(`Confidence: AMD=${(result.amd_conf * 100).toFixed(2)}%, HUMAN=${(result.human_conf * 100).toFixed(2)}%`);

        if (result.classification === 'AMD') {
            console.log(`Greeting: ${result.greeting_class}`);
        }
    } catch (error) {
        console.error('Error:', error);
    }
})();

cURL Example (WebSocket via websocat)

# Install websocat
# brew install websocat  # macOS
# apt install websocat   # Ubuntu

# Send request
(
  echo '{"config":{"sample_rate":8000,"VID":"TEST001"}}'
  cat audio.raw
  echo '{"eof":1}'
) | websocat -H="X-API-Key: sk_live_abc123def456ghi789" \
    ws://api.example.com:2700/

Performance Considerations

Cascade Execution Times

Mode Typical Latency Accuracy Use Case
Full Cascade 3-4 seconds ~99% Maximum accuracy required
Immediate Detection 0.5-1 second ~94-96% Latency-sensitive applications

Cascade Stages

Stage Audio Duration Exit Threshold Accuracy
4K 0.5s HUMAN ≥ 0.991 ~88%
8K 1.0s HUMAN ≥ 0.9985 ~92%
12K 1.5s HUMAN ≥ 0.99 ~95%
16K 2.0s HUMAN ≥ 0.98 ~97%
24K 3.0s HUMAN ≥ 0.997 or AMD ≥ 0.85 ~99%
32K 4.0s Final + Greeting ~99.5%

Network Recommendations

Optimization Tips

  1. Chunking: Send audio in 1-2 second chunks for optimal streaming
  2. Immediate Mode: Use for latency-critical applications
  3. Connection Pooling: Reuse connections when possible
  4. Audio Pre-processing: Ensure audio is already at 8kHz to avoid resampling overhead
  5. Compression: Audio is small (16KB/s), compression not needed

API Rate Limits

Rate limits are enforced per API key by HAProxy.

Default Limits

Limit Type Value Window
Requests per second 100 1 second
Concurrent connections 50 -
Total requests per day 100,000 24 hours

Rate Limit Headers

Response includes rate limit information:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1633024800

Exceeding Rate Limits

Response when limit exceeded:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json

{
  "error": "Rate limit exceeded",
  "limit": 100,
  "retry_after": 5
}

Custom Rate Limits

Contact support to increase rate limits for production workloads.


Support & Contact

Getting Help

Health Monitoring

Check service health:

curl http://api.example.com:2710/health

Expected response:

status:ok cpu_percent:12.3 avg_proc_ms:8.45 ...

Debug Mode

For debugging, check WebSocket connection:

# Test WebSocket connectivity
websocat -v ws://api.example.com:2700/

Appendix A: Audio Format Conversion

Convert MP3 to PCM

# Using ffmpeg
ffmpeg -i input.mp3 -ar 8000 -ac 1 -f s16le -acodec pcm_s16le output.raw

# Using sox
sox input.mp3 -r 8000 -c 1 -e signed-integer -b 16 output.raw

Convert WAV to PCM

# Extract raw PCM from WAV
ffmpeg -i input.wav -f s16le -acodec pcm_s16le -ar 8000 -ac 1 output.raw

Python Conversion

import soundfile as sf
import numpy as np

# Read any audio format
audio, sr = sf.read('input.mp3')

# Resample to 8kHz if needed
if sr != 8000:
    from scipy import signal
    audio = signal.resample(audio, int(len(audio) * 8000 / sr))

# Convert to mono if stereo
if len(audio.shape) > 1:
    audio = audio.mean(axis=1)

# Convert to int16
audio_int16 = (audio * 32767).astype(np.int16)

# Save as raw PCM
audio_int16.tofile('output.raw')

Appendix B: HAProxy API Key Map Management

Adding New API Keys

# Add to map file
echo "sk_live_new_key_here customer_name" >> /etc/haproxy/api_keys.map

# Reload HAProxy (no downtime)
systemctl reload haproxy

Revoking API Keys

# Remove from map file
sed -i '/sk_live_old_key_here/d' /etc/haproxy/api_keys.map

# Reload HAProxy
systemctl reload haproxy

Automated Key Rotation Script

#!/bin/bash
# rotate_api_key.sh

OLD_KEY="$1"
CUSTOMER="$2"
MAP_FILE="/etc/haproxy/api_keys.map"

# Generate new key
NEW_KEY=$(openssl rand -hex 32 | awk '{print "sk_live_"$1}')

# Add new key
echo "$NEW_KEY $CUSTOMER" >> "$MAP_FILE"

# Reload HAProxy
systemctl reload haproxy

# Output new key
echo "New API key for $CUSTOMER: $NEW_KEY"
echo "Old key ($OLD_KEY) still active. Remove after grace period."

Document Version: 2.0 Last Updated: February 5, 2026 Copyright: © 2026 AMD Detection Service License: Proprietary - For authorized API users only