What is Asterisk IVR?

Asterisk IVR (Interactive Voice Response) is an open-source, programmable telephony platform that automates inbound calls through intelligent voice menus, call routing, and AI-powered conversational interfaces. Built with AGI scripting (Python, Node.js, Perl) and ARI REST APIs, Asterisk IVR systems handle customer support, sales qualification, payment processing, and knowledge-base Q&A at scale.

How do AGI and ARI work together in IVR systems?

AGI (Asterisk Gateway Interface) is a scripting interface that processes individual calls in real-time; ARI (Asterisk REST Interface) is a stateless HTTP API that controls and monitors calls from external microservices. AGI excels at per-call logic; ARI excels at managing hundreds of concurrent calls from cloud services. Both integrate with databases, APIs, and AI models.

Home/Blog/Asterisk IVR Development
AsteriskIVR DevelopmentAGI ScriptingARIAI-PoweredVoice Systems

Asterisk IVR Development Guide 2026 — Building Custom Interactive Voice Systems

Master Asterisk IVR development from dialplan fundamentals to AI-powered conversational systems. Learn AGI scripting (Python/Node.js), ARI integration, and how CelloIP delivers 25+ enterprise systems annually. This guide covers real-world architectures, code examples, and production deployment strategies.

Kaushik Parmar — Founder & VoIP Architect
Apr 15, 20263,500+ words12 min read
25+
IVR Systems Delivered
12 wks
Avg Development Timeline
99.9%
System Uptime
48h
AGI Response Time

What is Asterisk IVR?

Asterisk IVR (Interactive Voice Response) is a customizable, open-source telephony platform that automates inbound call handling through intelligent voice menus and decision trees. Unlike proprietary systems (3CX, Avaya), Asterisk is fully programmable—you write AGI scripts (Python, Node.js, Perl, PHP, C) to control call flow, route intelligently, and integrate with databases, APIs, and AI models in real-time.

CelloIP has deployed 25+ Asterisk IVR systems for enterprises in healthcare, fintech, e-commerce, and SaaS. Our systems handle 100K+ calls/month, achieve 99.9% uptime, and reduce support costs by 40–60%.

Key Capabilities

  • Realtime call routing & voicemail
  • Dynamic menu generation via AGI
  • Database & API integration
  • GPT-4 / AI natural language
  • Multi-language support
  • Enterprise compliance (HIPAA, PCI, GDPR)

AGI Scripting: Building Call Logic

AGI (Asterisk Gateway Interface) is the core of dynamic IVR systems. When a call arrives, Asterisk spawns your AGI script (Python, Node.js, Perl, etc.) and pipes channel variables. Your script reads input (DTMF digits, speech), queries databases, makes API calls, and sends commands back to Asterisk (play sound, dial, hangup, etc.).

Python AGI Example

#!/usr/bin/env python3
import asterisk.agi as agi

agi = agi.AGI()
caller_id = agi.env['agi_callerid']
print(f"Call from {caller_id}")

# Play greeting
agi.appexec("Background", "en/hello")

# Collect digits (e.g., 1 for Sales, 2 for Support)
digit = agi.appexec("WaitForDigit", "5000")

if digit == "49":  # ASCII '1'
    agi.appexec("Dial", "SIP/sales@siptrunk")
elif digit == "50":  # ASCII '2'
    agi.appexec("Dial", "SIP/support@siptrunk")
else:
    agi.appexec("Hangup")

Node.js AGI Example

const {AGI} = require('asterisk.agi');
const agi = new AGI();

async function handleCall() {
  const callerId = agi.env.agi_callerid;
  console.log(`Call: ${callerId}`);

  // Play greeting
  await agi.background('en/hello');

  // Collect digit
  const digit = await agi.waitForDigit(5000);

  if (digit === '1') {
    await agi.dial('SIP/sales@trunk', 30);
  } else if (digit === '2') {
    await agi.dial('SIP/support@trunk', 30);
  }
  await agi.hangup();
}

handleCall().catch(err => {
  console.error('AGI Error:', err);
  agi.hangup();
});

When to use AGI

  • Per-call logic: Validate caller, query CRM, make decisions
  • Complex workflows: Multi-step forms, database transactions
  • External integrations: Call REST APIs, OpenAI, webhooks
  • High concurrency: AGI spawns 1 process per call (resource-intensive)

ARI: Asterisk REST Interface

ARI (Asterisk REST Interface) exposes Asterisk call events and control via HTTP/WebSocket APIs. Unlike AGI (which spawns a script per call), ARI lets you run a single microservice that monitors and controls thousands of calls asynchronously. Perfect for cloud deployments, mobile clients, and real-time dashboards.

ARI Workflow

  1. 1. WebSocket Subscribe: Connect to /ari/events
  2. 2. Listen for events: StasisStart, DTMF, HangUp
  3. 3. Control calls: POST /ari/channels/:id/play
  4. 4. Get state: GET /ari/channels/:id
  5. 5. Bridge calls: POST /ari/bridges

AGI vs ARI

Concurrency1 process/call1 service/1000s calls
ProtocolStdin/stdoutHTTP/WebSocket
LatencyHigherLower (async)
ScalingDifficultEasy (stateless)
// ARI Node.js Example: Handle StasisStart, collect DTMF
const ws = new WebSocket('ws://asterisk:8088/ari/events?app=my_app&token=secret');

ws.on('message', (event) => {
  const msg = JSON.parse(event);

  if (msg.type === 'StasisStart') {
    const channelId = msg.channel.id;
    console.log(`Call started: ${channelId}`);

    // Play greeting
    fetch(`http://asterisk:8088/ari/channels/${channelId}/play`, {
      method: 'POST',
      body: JSON.stringify({ media: 'sound:en/hello' })
    });
  }

  if (msg.type === 'ChannelDtmfReceived') {
    console.log(`DTMF: ${msg.digit}`);
    // Route based on digit...
  }
});

Dialplan Configuration

Dialplan is the entry point: it defines how inbound calls are routed before reaching AGI or ARI. Use Asterisk extensions.conf to match caller ID, time-of-day, or DID, then execute your IVR logic.

; extensions.conf
[from-trunk]
exten => +1234567890,1,Answer()
exten => +1234567890,n,Set(CHANNEL(language)=en)
exten => +1234567890,n,AGI(agi:///ivr_main.py,${CALLERID(num)})
exten => +1234567890,n,Hangup()

; Alternative: ARI/Stasis app
exten => +1234567890,1,Answer()
exten => +1234567890,n,Stasis(my_ivr_app,${CALLERID(num)})
exten => +1234567890,n,Hangup()

[from-internal]
exten => 5555,1,Set(QUEUE_LOG_CONTEXT=on)
exten => 5555,n,Queue(support_queue,t,,,300)
exten => 5555,n,Hangup()

AI-Powered IVR with GPT-4

Traditional IVR (DTMF menus) frustrates users. Modern IVR integrates GPT-4 for natural language understanding: caller speaks naturally, AI transcribes, understands intent, and responds. CelloIP specializes in sub-second latency AI IVR.

AI IVR Flow

1. Capture Voice

Asterisk detects speech, records to WAV

2. Speech-to-Text

OpenAI Whisper API: WAV → transcription

3. LLM Processing

GPT-4 + context → intent & response

4. Text-to-Speech

Google TTS: text → MP3 stream

5. Execute Action

Transfer, book appointment, or repeat

Example: Sales Qualification IVR

# Python + OpenAI + Asterisk
import openai, requests

async def gpt4_ivr(channel_id, transcript):
  # Step 1: Call GPT-4
  response = await openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
      {"role": "system", "content": "You are a sales agent. Ask 3 questions to qualify lead."},
      {"role": "user", "content": transcript}
    ]
  )

  reply = response.choices[0].message.content

  # Step 2: TTS (Google Cloud)
  tts_resp = requests.post(
    'https://texttospeech.googleapis.com/v1/text:synthesize',
    json={"input": {"text": reply}, "voice": {...}}
  )

  # Step 3: Play audio on channel
  audio_url = save_tts(tts_resp.audio_content)
  await ari_channel_play(channel_id, audio_url)

Costs & Latency

OpenAI API
~$0.01 per call (Whisper + GPT-4)
Google TTS
~$0.005 per call (1000 chars free tier)
Total Latency
~2–3 seconds (acceptable for IVR)

Asterisk vs Alternatives

AspectAsteriskFreeSWITCH3CXAvaya
Development ApproachAGI + ARI + Dialplan (code + config)FreeSWITCH XML + mod_lua/mod_v8GUI-based (proprietary)Enterprise API (closed-source)
Scripting LanguagesPython, Node.js, Perl, PHP, CLua, JavaScript, Python (limited)C# (proprietary SDK)Java (proprietary)
REST APIARI (native REST)Custom HTTP (mod_http)REST (managed)SOAP/REST (enterprise)
AI IntegrationRealtime GPT-4/LLM via AGICustom mod_* (complex)Limited AI pluginsEnterprise AI (partnership)
CostFree (open-source)Free (open-source)Subscription-basedEnterprise licensing
ScalabilityHighly scalable (stateless AGI)Highly scalableLimited (proprietary)Enterprise-grade

Architecture & Production Code

A production Asterisk IVR system stacks: dialplan → AGI/ARI → external APIs → database. Here's a real architecture deployed by CelloIP for a SaaS customer:

Component Stack

Inbound:
  • • SIP Trunk (Twilio/Vonage)
  • • Asterisk Server (us-east-1)
  • • Dialplan Router
Logic Layer:
  • • Python AGI (per-call)
  • • Node.js ARI (stateless)
  • • Redis cache (session)
External APIs:
  • • OpenAI (GPT-4, Whisper)
  • • Google Cloud TTS
  • • Stripe (payments)
Backend:
  • • PostgreSQL (CRM/logs)
  • • Kafka (event stream)
  • • CloudFlare (CDN)
# Production AGI: Async call handling with retries
import asyncio, logging, psycopg2, openai
from datetime import datetime

async def ivr_handler(channel_id, caller_id, did):
    """Main IVR entrypoint."""
    logger = logging.getLogger(__name__)

    try:
        # 1. Verify caller in database
        conn = psycopg2.connect("dbname=customers")
        cur = conn.cursor()
        cur.execute("SELECT customer_id, tier FROM callers WHERE phone=%s", (caller_id,))
        result = cur.fetchone()
        conn.close()

        if not result:
            await play_audio(channel_id, 'sound:welcome_unknown')
            await collect_input(channel_id, 5)  # 5-digit customer ID
            return

        customer_id, tier = result

        # 2. Route based on tier
        if tier == 'premium':
            await play_audio(channel_id, 'sound:welcome_premium')
            await dial_extension(channel_id, 'SIP/support_vip@trunk')
        else:
            await play_audio(channel_id, 'sound:welcome_standard')
            await queue_call(channel_id, 'support_queue')

    except Exception as e:
        logger.error(f"AGI error: {e}")
        await play_audio(channel_id, 'sound:error_try_again')

async def play_audio(channel_id, media):
    """Queue audio playback."""
    # Implementation...
    pass

async def dial_extension(channel_id, target):
    """Transfer to extension."""
    # Implementation...
    pass

async def queue_call(channel_id, queue_name):
    """Queue for agent."""
    # Implementation...
    pass

Real-World Use Cases

Customer Support

Reduce support tickets by 40% with AI-powered issue routing and self-service troubleshooting.

Sales & Lead Qualification

Qualify inbound leads, book demos, and route to sales via GPT-4 conversational IVR.

Appointment Scheduling

Automate booking, cancellations, and reminders. Reduce no-shows by 25%.

Payment Processing

PCI-compliant payment IVR. Collect DTMF, validate, and process via Stripe/Square.

Knowledge Base Q&A

Deploy GPT-4 trained on your docs. Callers ask questions; AI responds naturally.

Survey & Feedback

Collect CSAT, NPS, and qualitative feedback via multi-language IVR.

Frequently Asked Questions

What is Asterisk IVR and how does it differ from traditional phone systems?

Asterisk IVR (Interactive Voice Response) is an open-source telephony platform that automates customer interactions through voice menus, call routing, and intelligent decision trees. Unlike traditional PBX systems, Asterisk IVR is customizable, programmable via AGI/ARI APIs, and can integrate real-time AI (GPT-4) for natural language understanding. CelloIP has delivered 25+ enterprise IVR systems that reduce support costs by 40-60%.

How long does it take to develop a custom Asterisk IVR system?

Typical timelines: Basic IVR (4–6 weeks), Advanced multi-language IVR (8–12 weeks), AI-powered IVR with GPT-4 (10–14 weeks). Timeline depends on complexity, number of call flows, integrations (CRM/database), and testing requirements. CelloIP delivers most projects in 12 weeks or less.

What is AGI scripting and why is it important?

AGI (Asterisk Gateway Interface) is a framework for writing external scripts that process calls in real-time. Scripts run in Python, Node.js, Perl, or PHP, and handle logic like "if digit 1 pressed, transfer to sales; if 2, play menu." AGI is the core of intelligent IVR systems because it enables dynamic call routing, database queries, and AI integration—things dialplan alone cannot do.

Can I integrate GPT-4 or other AI models into my Asterisk IVR?

Yes. Asterisk AGI can call OpenAI API (GPT-4) in real-time to understand natural language. For example: (1) Capture caller voice input (AGI speech-to-text), (2) Send to GPT-4 API, (3) Execute intent-based action, (4) Speak response via TTS. CelloIP specializes in GPT-4 IVR integration with sub-second latency.

What is ARI and how is it different from AGI?

ARI (Asterisk REST Interface) exposes Asterisk call events and control via HTTP REST API. Unlike AGI (which spawns a script per call), ARI lets you run a single microservice that controls multiple calls asynchronously. ARI is preferred for cloud deployments, WebSocket integrations, and scaling to thousands of concurrent calls.

What are typical IVR use cases and ROI?

Top use cases: Customer support (reduce agent calls by 30-50%), appointment scheduling, payment processing, surveys, order tracking, emergency response. Average ROI: 200–400% within 18 months. CelloIP clients report average 45% reduction in support costs and 90%+ first-call resolution rates.

How do I ensure my Asterisk IVR is compliant (GDPR, HIPAA, PCI-DSS)?

Compliance strategies: (1) Encrypt sensitive data in AGI scripts, (2) Use secure API endpoints (HTTPS/TLS), (3) Implement call recording encryption, (4) Audit call logs, (5) Mask PCI data in logs. CelloIP ensures all IVR systems meet enterprise compliance standards.

What is your pricing for Asterisk IVR development?

CelloIP offers three models: (1) Fixed-Price: Basic IVR $15K–$30K, Advanced $40K–$80K. (2) Dedicated Developer: $5K–$8K/month. (3) Team Augmentation: $12K–$20K/month for 2–3 developers. Quote includes design, development, testing, deployment, and 3 months post-launch support.

Ready to Build Your Asterisk IVR?

Fixed-Price Project

Complete IVR design, development, deployment & 3-month support. Ideal for startups.

$40K – $120K

Dedicated Developer

Full-time developer (40h/week) focused on your IVR system. Month-to-month commitment.

$5K – $8K/month

Team Augmentation

2–3 developers augmenting your internal team. Agile, iterative delivery.

$12K – $20K/month