The AMD Detection API provides real-time streaming answering machine detection for telephony applications via WebSocket connections.
What you'll need:
Basic flow:
WebSocket URL:
wss://api.amdy.io/amd/v2
Protocol: WebSocket (secure) Authentication: X-API-Key header
Your API key is provided when you sign up for the service. Include it in the WebSocket connection headers:
X-API-Key: sk_live_your_api_key_here
API Key Format:
sk_live_...sk_test_...Keep your API key secure:
The API performs detection after EACH audio chunk based on the accumulated buffer length:
'' = Still AMD or
uncertain, CONTINUE STREAMING"HUMAN" = Human detected, STOP
STREAMING"AMD" = AMD detected (final),
STOP STREAMING| Buffer Length | Model Used | Typical Response |
|---|---|---|
| < 4000 samples | None | Empty (keep streaming) |
| 4000-7999 | 4K model | Empty or "HUMAN" (if confident) |
| 8000-11999 | 8K model | Empty or "HUMAN" (if confident) |
| 12000-15999 | 12K model | Empty or "HUMAN" (if confident) |
| 16000-23999 | 16K model | Empty or "HUMAN" (if confident) |
| 24000-31999 | 24K model | Empty, "HUMAN", or "AMD" |
| ≥ 32000 | 32K model | "AMD" with greeting type |
With immediate_detection: true:
Connect with your API key in the headers:
Python:
import websockets
headers = {"X-API-Key": "sk_live_your_api_key_here"}
ws = await websockets.connect("wss://api.amdy.io/amd/v2", extra_headers=headers)
Node.js:
const WebSocket = require('ws');
const ws = new WebSocket('wss://api.amdy.io/amd/v2', {
headers: {
'X-API-Key': 'sk_live_your_api_key_here'
}
});
Required: Send configuration message immediately after connection:
{
"config": {
"sample_rate": 8000,
"VID": "V2611041620235448017",
"immediate_detection": false
}
}
Parameters:
| Field | Type | Required | Description |
|---|---|---|---|
sample_rate |
integer | Yes | Must be 8000 |
VID |
string | Yes | Unique ID for this call. Must start with V, be
at least 8 characters, and contain only letters and digits after the
V (no dashes, spaces or symbols). Recommended:
V + YYMMDDHHMMSS + your own digits, e.g.
V2611041620235448017. VIDs in any other format are still
processed for detection, but no audio recording is
saved and the recording lookup cannot find the call |
phone |
string | No | Caller phone number |
country_code |
string | No | Country calling code |
immediate_detection |
boolean | No | Fast mode (default: false) |
CRITICAL: Check for response after EACH chunk!
Python example:
import asyncio
import numpy as np
# Audio chunk size (1 second = 8000 samples)
chunk_size = 8000
async def stream_and_detect(ws, audio_int16):
"""Stream audio and check for detection after each chunk."""
for i in range(0, len(audio_int16), chunk_size):
chunk = audio_int16[i:i+chunk_size]
# Send audio chunk
await ws.send(chunk.tobytes())
# IMPORTANT: Check for response after EACH chunk
try:
response = await asyncio.wait_for(ws.recv(), timeout=0.5)
if response: # Non-empty response
result = json.loads(response)
print(f"Detection: {result['classification']}")
return result # STOP streaming
else:
# Empty response - continue streaming
print(f"Chunk {i//chunk_size + 1}: Still detecting...")
except asyncio.TimeoutError:
# No response yet - continue streaming
print(f"Chunk {i//chunk_size + 1}: No response, continue...")
continue
# If we streamed all audio without detection, send EOF
await ws.send(json.dumps({"eof": 1}))
final_result = await ws.recv()
return json.loads(final_result)
Node.js example:
async function streamAndDetect(ws, audioBuffer) {
const chunkSize = 8000; // 1 second
let offset = 0;
return new Promise((resolve, reject) => {
// Listen for responses
ws.on('message', (data) => {
const response = data.toString();
if (response) {
// Non-empty response - detection complete
const result = JSON.parse(response);
console.log(`Detection: ${result.classification}`);
resolve(result);
} else {
// Empty response - send next chunk
console.log(`Chunk ${offset/chunkSize + 1}: Still detecting...`);
sendNextChunk();
}
});
function sendNextChunk() {
if (offset < audioBuffer.length) {
const chunk = audioBuffer.slice(offset, offset + chunkSize);
ws.send(chunk);
offset += chunkSize;
} else {
// All audio sent, send EOF
ws.send(JSON.stringify({eof: 1}));
}
}
// Start streaming
sendNextChunk();
});
}
1. Empty Response (continue streaming):
''
Action: Send next audio chunk
2. HUMAN Detection (stop streaming):
{
"classification": "HUMAN",
"human_conf": 0.9234,
"amd_conf": 0.0766,
"model_history": "4k:HUMAN:0.08:0.92:1"
}
Action: Stop streaming, handle as human call
3. AMD Detection (stop streaming):
{
"classification": "AMD",
"amd_conf": 0.9234,
"human_conf": 0.0766,
"greeting_class": "welcome_voicemail",
"greeting_conf": 0.8912,
"model_history": "4k:AMD:0.10:0.90:0;24k:AMD:0.92:0.08:1"
}
Action: Stop streaming, handle as answering machine
Best for: Maximum accuracy applications
{"config": {"sample_rate": 8000, "VID": "...", "immediate_detection": false}}
Behavior:
Response pattern:
Chunk 1 (4k): '' (empty - continue)
Chunk 2 (8k): '' (empty - continue)
Chunk 3 (12k): '' (empty - continue)
Chunk 4 (16k): '' (empty - continue)
Chunk 5 (24k): {"classification": "HUMAN", ...} STOP
Best for: Latency-sensitive applications
{"config": {"sample_rate": 8000, "VID": "...", "immediate_detection": true}}
Behavior:
Response pattern:
Chunk 1 (4k): {"classification": "HUMAN", "human_conf": 0.87, ...} STOP
Use immediate mode when:
import asyncio
import websockets
import json
import numpy as np
import soundfile as sf
async def detect_amd_streaming(audio_file, api_key, immediate=False):
"""
Stream audio and detect AMD in real-time.
Stops streaming as soon as detection is received.
"""
uri = "wss://api.amdy.io/amd/v2"
headers = {"X-API-Key": api_key}
async with websockets.connect(uri, extra_headers=headers) as ws:
# 1. Send configuration
config = {
"config": {
"sample_rate": 8000,
"VID": f"CALL_{int(asyncio.get_event_loop().time() * 1000)}",
"immediate_detection": immediate
}
}
await ws.send(json.dumps(config))
print(f"Config sent (immediate={immediate})")
# 2. Load audio
audio, sr = sf.read(audio_file)
if sr != 8000:
from scipy import signal
audio = signal.resample(audio, int(len(audio) * 8000 / sr))
audio_int16 = (audio * 32767).astype(np.int16)
# 3. Stream chunks and check for detection
chunk_size = 8000 # 1 second
chunk_num = 0
for i in range(0, len(audio_int16), chunk_size):
chunk = audio_int16[i:i+chunk_size]
chunk_num += 1
# Send chunk
await ws.send(chunk.tobytes())
print(f"Sent chunk {chunk_num} ({len(chunk)} samples)")
# Wait for response (with timeout)
try:
response = await asyncio.wait_for(ws.recv(), timeout=0.5)
if response: # Non-empty = detection complete
result = json.loads(response)
print(f"\n✓ Detection received after chunk {chunk_num}!")
print(f" Classification: {result['classification']}")
print(f" Confidence: {result.get('amd_conf' if result['classification'] == 'AMD' else 'human_conf', 0):.2%}")
if result['classification'] == 'AMD':
print(f" Greeting: {result.get('greeting_class', 'N/A')}")
return result
else:
# Empty response = continue streaming
print(f" → Empty response, continue streaming...")
except asyncio.TimeoutError:
# No response = continue streaming
print(f" → No response, continue...")
continue
# If all audio sent without detection, send EOF
print("\nAll audio streamed, sending EOF...")
await ws.send(json.dumps({"eof": 1}))
final_result = await ws.recv()
result = json.loads(final_result)
print(f"\n✓ Final detection: {result['classification']}")
return result
# Usage
async def main():
api_key = "sk_live_your_api_key_here"
print("=== Standard Mode (Maximum Accuracy) ===")
result1 = await detect_amd_streaming("call.wav", api_key, immediate=False)
print("\n=== Immediate Mode (Fast Detection) ===")
result2 = await detect_amd_streaming("call.wav", api_key, immediate=True)
asyncio.run(main())
const WebSocket = require('ws');
const fs = require('fs');
const wav = require('node-wav');
async function detectAMDStreaming(audioFile, apiKey, immediate = false) {
return new Promise((resolve, reject) => {
const ws = new WebSocket('wss://api.amdy.io/amd/v2', {
headers: {'X-API-Key': apiKey}
});
let chunkNum = 0;
const chunkSize = 8000; // 1 second
let audioBuffer;
let offset = 0;
ws.on('open', () => {
// 1. Send configuration
const config = {
config: {
sample_rate: 8000,
VID: `CALL_${Date.now()}`,
immediate_detection: immediate
}
};
ws.send(JSON.stringify(config));
console.log(`Config sent (immediate=${immediate})`);
// 2. Load audio
const buffer = fs.readFileSync(audioFile);
const result = wav.decode(buffer);
// Convert to Int16Array
audioBuffer = new Int16Array(result.channelData[0].length);
for (let i = 0; i < result.channelData[0].length; i++) {
audioBuffer[i] = Math.max(-32768, Math.min(32767,
result.channelData[0][i] * 32767));
}
// 3. Start streaming
sendNextChunk();
});
function sendNextChunk() {
if (offset < audioBuffer.length) {
chunkNum++;
const chunk = audioBuffer.slice(offset, offset + chunkSize);
ws.send(chunk.buffer);
console.log(`Sent chunk ${chunkNum} (${chunk.length} samples)`);
offset += chunkSize;
// Note: Response will come via 'message' event
} else {
// All audio sent, send EOF
console.log('\nAll audio streamed, sending EOF...');
ws.send(JSON.stringify({eof: 1}));
}
}
ws.on('message', (data) => {
const response = data.toString();
if (response) {
// Non-empty response = detection complete
const result = JSON.parse(response);
console.log(`\n✓ Detection received after chunk ${chunkNum}!`);
console.log(` Classification: ${result.classification}`);
const conf = result.classification === 'AMD' ? result.amd_conf : result.human_conf;
console.log(` Confidence: ${(conf * 100).toFixed(2)}%`);
if (result.classification === 'AMD') {
console.log(` Greeting: ${result.greeting_class || 'N/A'}`);
}
ws.close();
resolve(result);
} else {
// Empty response = continue streaming
console.log(' → Empty response, continue streaming...');
sendNextChunk();
}
});
ws.on('error', reject);
});
}
// Usage
(async () => {
const apiKey = 'sk_live_your_api_key_here';
console.log('=== Standard Mode (Maximum Accuracy) ===');
const result1 = await detectAMDStreaming('call.wav', apiKey, false);
console.log('\n=== Immediate Mode (Fast Detection) ===');
const result2 = await detectAMDStreaming('call.wav', apiKey, true);
})();
When classification is "AMD", the API
provides detailed greeting classification with 28 possible types.
{
"classification": "AMD",
"amd_conf": 0.9234,
"human_conf": 0.0766,
"greeting_class": "welcome_voicemail",
"greeting_conf": 0.8912
}
The greeting_class field identifies the specific type of
answering machine or automated message:
| Greeting Class | Final Classification | Description |
|---|---|---|
busy_try_later |
BUSYAMD |
"The person you're calling is busy, try later" |
cant_take_call_now |
CANTTAKEAMD |
"Can't take your call right now" |
click_noise |
CLICKAMD |
Click/silence followed by hangup |
disconnected |
DISCONNECTEDAMD |
Disconnected/out of service message |
google_voice_screening |
GVOICEAMD |
Google Voice call screening |
googlesub |
GOOGLESUBAMD |
Google subscriber message |
hello_leave_message_tone |
HELLOMSGAMD |
"Hello, leave a message after the tone" |
honeypot |
HONEYPOTAMD |
Honeypot detection system (anti-spam trap) |
human |
HUMAN |
Human-sounding greeting (overrides AMD detection) |
ivr_press_button |
IVRAMD |
IVR menu system ("Press 1 for...") |
magicjack |
MAGICJACKAMD |
MagicJack voicemail system |
mailbox_full |
MAILBOXFULLAMD |
"This mailbox is full" |
network_analytics |
NETWORKAMD |
Carrier network analytics announcement |
other |
AMD |
Unclassified answering machine |
please_leave_your_message |
PLVMSFASAMD |
"Please leave your message" |
please_leave_your_message_for |
PLVMSFORAMD |
"Please leave a message for..." |
porfavor_spanish |
SPANISHAMD |
Spanish language voicemail |
ringing |
RINGINGAMD |
Ring tone only (no answer) |
sorry_voicemail_not_setup |
VMNOTSETUPAMD |
"Voicemail has not been set up" |
subscriber_not_available |
SUBNOTAVAILAMD |
"The subscriber is not available" |
thank_you_for_calling |
THANKYOUAMD |
Business greeting message |
unknown_short |
SILENCEAMD |
Short audio or silence (insufficient content) |
welcome_voicemail |
WELCOMEVMAMD |
Standard voicemail welcome message |
your_call_forwarded_voicemail |
FASAMD |
"Your call has been forwarded to voicemail" |
your_call_forwarded_voicemail_v2 |
FASV2AMD |
Call forwarded message (variant 2) |
your_call_forwarded_voicemail_v3 |
FASV3AMD |
Call forwarded message (variant 3) |
your_call_forwarded_voicemail_v4 |
FASV4AMD |
Call forwarded message (variant 4) |
your_call_forwarded_with_number |
VERIZONAMD |
Verizon-style forwarding with callback number |
If the greeting classifier detects
greeting_class: "human", the final classification is
changed to "HUMAN" even if the AMD cascade initially
detected AMD. This is a safety mechanism to prevent hanging up on real
people.
Standard Voicemail:
{
"classification": "AMD",
"greeting_class": "welcome_voicemail",
"greeting_conf": 0.92
}
IVR System:
{
"classification": "AMD",
"greeting_class": "ivr_press_button",
"greeting_conf": 0.88
}
Human Rescue:
{
"classification": "HUMAN",
"greeting_class": "human",
"greeting_conf": 0.95
}
Honeypot/Spam Trap:
{
"classification": "AMD",
"greeting_class": "honeypot",
"greeting_conf": 0.94
}
| Code | Error | Action |
|---|---|---|
| 1000 | Normal closure | None required |
| 1001 | Server shutdown | Retry after 5 seconds |
| 1002 | Protocol error | Check message format |
| 1006 | Connection lost | Retry with backoff |
| 1008 | Policy violation | Check API key |
| 1011 | Server error | Contact support |
"No response received after chunks"
"Detection takes too long"
immediate_detection: true for faster results"Empty responses forever"
import asyncio
async def detect_with_retry(audio_file, api_key, max_retries=3):
for attempt in range(max_retries):
try:
return await detect_amd_streaming(audio_file, api_key)
except Exception as e:
if attempt == max_retries - 1:
raise
wait_time = 2 ** attempt
print(f"Retry {attempt + 1}/{max_retries} in {wait_time}s...")
await asyncio.sleep(wait_time)
# Convert any format to 8kHz PCM
ffmpeg -i input.mp3 -ar 8000 -ac 1 -f s16le -acodec pcm_s16le output.raw
import soundfile as sf
import numpy as np
from scipy import signal
def convert_to_pcm(input_file):
audio, sr = sf.read(input_file)
if len(audio.shape) > 1:
audio = audio.mean(axis=1)
if sr != 8000:
audio = signal.resample(audio, int(len(audio) * 8000 / sr))
return (audio * 32767).astype(np.int16)
wss:// (not
ws://)| Limit Type | Value |
|---|---|
| Concurrent connections | 50 |
| Requests per second | 100 |
| Daily requests | 100,000 |
Rate limit headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1738800000
wss://api-test.amdy.io/amd/v2
sk_test_0000000000000000000000000000000000000000000000000000
Document Version: 2.0 Last Updated: February 5, 2026 Support: [email protected]