Asterisk Gateway Interface (AGI)
The Asterisk Gateway Interface, abbreviated as AGI, is an interface for adding functionality to Asterisk with many different programming languages. Perl, PHP, C, Pascal, Bourne Shell – it’s your choice, really.
- AGI may control the dial plan, called in extensions.conf.
- Async AGI Introduced in Asterisk 1.6, allows asynchronous AGI scripting.
- EAGI gives the application the possibility to access and control the sound channel in addition to interaction with the dial plan.
- FastAGI can be used to do the processing on a remote machine via a network connection.
- DeadAGI gives access to a dead channel, after hangup. Deprecated since Asterisk 1.6
Page Contents
Applications
- AGI, DeadAGI, and EAGI: Applications to use in extensions.conf
- FastAGI: Allows running of AGI applications on a remote machine (improves performance for Asterisk)
Dialing out
If the AGI application dials outward by executing Dial, the script will suspend contact with the Asterisk server until the Dial exits. If you’d like to have additional control after the Dial completes, be sure to pass the ‘g’ option to the Dial application.
If you want your application to initiate a call out without being started through the dialplan:
- Asterisk auto-dial out Move (not copy) a file into an Asterisk spool directory and a call will be placed
- Asterisk manager API Use the Originate command. Asterisk Manager API Action Originate
AGI Execution Environment
You can pass arguments to an AGI script, like so:
AGI(script.agi|arg1|arg2|…)
and then in PHP, for example, retrieve these arguments with the help of
$argv[1]
$argv[2]
NOTE: In newer versions of Asterisk, the format for passing parameters to an AGI script is as follows:
AGI(script.agi, arg1, arg2, …)
This works as well in call files:
Application: AGI
Data: script.agi, arg1, arg2, …
The AGI script communicates with Asterisk by sending AGI commands on standard output and receiving responses on standard input. The result typically takes this form:
<code> result=<result> [data]
where code is an HTTP-like response code (200 for success, 5xx for error); result is the result of the command (common values are -1 for error, and 0 for success); some commands return additional name=value pairs in data, while some return a string value in parentheses (especially “timeout” for a timed command.) Also note that if code is followed by a hyphen instead of a space, the response will span multiple lines; the last line of the response will start with code. The response is easily defined using a regular expression:
-+/^\d{3}(?: result=.*?(?: \(?.*\))?)|(?:-.*)$/+-
Result codes:
| Code | Example result text | Asterisk 1.2 | Asterisk 1.4 | Asterisk 1.6 |
|---|---|---|---|---|
| 200 | result=0 | Yes | Yes | Yes |
| 510 | Invalid or unknown command | No | No | Yes |
| 511 | Command Not Permitted on a dead channel | No | No | Yes |
| 520 | End of proper usage | Yes | Yes | Yes |
When Asterisk starts an AGI script, it feeds the channel variables to the script on standard input. The variable names are prefixed with “agi_” and are separated from their values by a colon and a space. Though the actual channel variables may be in the upper case, the names passed to an AGI script are all lower case. Global variables are not passed to the AGI script in this manner. You must get them using the “get variable” AGI command.
The variables passed by Asterisk are:
- agi_request – The filename of your script
- agi_channel – The originating channel (your phone)
- agi_language – The language code (e.g. “en”)
- agi_type – The originating channel type (e.g. “SIP” or “ZAP”)
- agi_uniqueid – A unique ID for the call
- agi_version – The version of Asterisk (since Asterisk 1.6)
- agi_callerid – The caller ID number (or “unknown”)
- agi_calleridname – The caller ID name (or “unknown”)
- agi_callingpres – The presentation for the callerid in a ZAP channel
- agi_callingani2 – The number which is defined in ANI2 see Asterisk Detailed Variable List (only for PRI Channels)
- agi_callington – The type of number used in PRI Channels see Asterisk Detailed Variable List
- agi_callingtns – An optional 4 digit number (Transit Network Selector) used in PRI Channels see Asterisk Detailed Variable List
- agi_dnid – The dialed number id (or “unknown”)
- agi_rdnis – The referring DNIS number (or “unknown”)
- agi_context – Origin context in extensions.conf
- agi_extension – The called number
- agi_priority – The priority it was executed as in the dial plan
- agi_enhanced – The flag value is 1.0 if started as an EAGI script, 0.0 otherwise
- agi_accountcode – Account code of the origin channel
- agi_threadid – Thread ID of the AGI script (since Asterisk 1.6)
In addition, since Asterisk 1.6, parameters to the script are sent as agi_arg_x where x indicates the position in the list of parameters, beginning at agi_arg_1.
An AGI script is also passed a number of environment variables which point to file-system directories which contain Asterisk files. These are:
- AST_CONFIG_DIR
- AST_CONFIG_FILE
- AST_MODULE_DIR
- AST_SPOOL_DIR
- AST_MONITOR_DIR
- AST_VAR_DIR
- AST_DATA_DIR
- AST_LOG_DIR
- AST_AGI_DIR
- AST_KEY_DIR
- AST_RUN_DIR
Return value
AGI script returns the following status in variable “AGISTATUS”:
- SUCCESS
- FAILURE
- HANGUP
AGI commands
- answer: Asserts answer
- asyncagi break: Break Async AGI loop (since Asterisk 1.6)
- channel status: Returns status of the connected channel
- control stream file: Send the given file, allowing playback to be controlled by the given digits, if any. (since Asterisk 1.2)
- database del: Removes database key/value
- database deltree: Removes database keytree/value
- database get: Gets database value
- database put: Adds/updates database value
- exec: Executes a given Application. (Applications are the functions you use to create a dial plan in extensions.conf ).
- get data: Gets data on a channel
- get full variable: Gets a channel variable, but understands complex variable names and builtin variables. (since Asterisk 1.2)
- get option: Behaves similar to STREAM FILE but used with a timeout option. (since Asterisk 1.2)
- get variable: Gets a channel variable
- hangup: Hangup the current channel
- noop: Does nothing
- receive char: Receives one character from channels supporting it
- receive text: Receives text from channels supporting it
- record file: Records to a given file
- say alpha: Says a given character string (since Asterisk 1.2)
- say date: Say a date (since Asterisk 1.2)
- say datetime: Say a formatted date and time (since Asterisk 1.2)
- say digits: Says a given digit string
- say number: Says a given number
- say phonetic: Say the given character string.
- say time: Say a time
- send image: Sends images to channels supporting it
- send text: Sends text to channels supporting it
- set autohangup: Autohangup channel in some time
- set callerid: Sets callerid for the current channel
- set context: Sets channel context
- set extension: Changes channel extension
- set music: Enable/Disable Music on hold generator, example “SET MUSIC ON default”
- set priority: Prioritizes the channel
- set variable: Sets a channel variable
- speech activate grammar: Activates a grammar (since Asterisk 1.6)
- speech create: Creates a speech object (since Asterisk 1.6)
- speech deactivate grammar: Deactivates a grammar (since Asterisk 1.6)
- speech destroy: Destroys a speech object (since Asterisk 1.6)
- speech load grammar: Loads a grammar (since Asterisk 1.6)
- speech recognize: Recognizes speech (since Asterisk 1.6)
- speech set: Sets a speech engine setting (since Asterisk 1.6)
- speech unload grammar: Unloads a grammar (since Asterisk 1.6)
- stream file: Sends audio file on channel
- tdd mode: Activates TDD mode on channels supporting it, to enable communication with TDDs.
- verbose: Logs a message to the asterisk verbose log
- wait for digit: Waits for a digit to be pressed
- Cam Farnells AGI Documentation – November 2002
- AGI Documentation
- AGI Documentation (with long descriptions)
- Use
show agi [agi-command]anddump agihtml <filename>at the Asterisk CLI to get information on the commands. For debugging purposes you can typeagi debugto see each command and response as they happen.
Libraries and Frameworks
Java
- Astive Toolkit is a Toolkit and Server for Java that provides an extensible architecture for developing, maintaining, and deploying telephony applications.
- Asterisk-java now also supports FastAGI in addition to the Manager API
- OrderlyCalls (successor to JAGIServer) offers full support for FastAGI and Manager in an easy-to-use Named Service environment. Includes Web Deployer for developing integrated VOIP-HTML applications.
- The Brazil Web Framework supports FastAGI and Manager directly though its HTML template system.
ActiveX
- AstOCX: An activex control for running AGI, FastAGI and DeadAGI on Windows platform.
Pascal/ObjectPascal
- TPasAGI is compatible with FreePascal/Lazarus as well as CodeGear/Borland Delphi. Use with Delphi supports only FastAGI from Windows computers while both AGI and FastAGI are supported for Lazarus/Freepascal on linux platforms. Released under LGPL License.
Perl
- Agispeedy-perl: faster agi application server include all agi library and support cluster & work looks like normal agi scripts
- Asterisk::config: Read and Write config files for Asterisk: http://search.cpan.org/~hoowa/
- Asterisk-config-syntax-highlight: Highlight Asterisk config syntax: http://search.cpan.org/~nsnake/
- Asterisk perl library: The Perl library for Asterisk AGI: http://asterisk.gnuinter.net/
- Asterisk perl agi: Asterisk::AGI – Simple Asterisk Gateway Interface Class: http://search.cpan.org/~jamesgol/asterisk-perl-1.01/lib/Asterisk/AGI.pm
- Callback daemon that handles pbx-internal callbacks (CCBS/CCNR). Also included are a number of perl modules as an alternative to Asterisk::Manager to handle the Asterisk Manager Interface (download page in German but documentation in English).
PHP
- Agispeedy: The Agispeedy is an AGI Application Server implemention in asterisk and written by Pure PHP
- PAGI and PAMI (for PHP, clean, modular, easy, OOP compatible interfaces and clients for asterisk manager and agi): http://github.com/marcelog/PAMI – http://github.com/marcelog/PAGI
- AgiPhp5
- AQL: AQL (Asterisk Config Query Language) is a SQL-like statement, which can be used to write and read asterisk config files library for PHP in an easy way.
- Asterisk AGI php: Advice on how to setup PHP scripts for AGI.
- Asterisk PHP (scripting within the dialplan – better than using AGI): http://eder.us/projects/asterisk_php/ Please note that while this is a good idea in concept, per the webpage is not suitable for production use as the implementation has serious threading bugs.)
- phpAGI: PHP classes for AGI and the Asterisk Manager Interface.
- PHP ASTLIB: A PHP 5 class for AGI. Built for easy extendability for handing FastAGI.
Python
- Fats http://sourceforge.net/projects/fats/ FastAGI & AMI for the Twisted framework, MIT license. Full code test covered, Mock Object pattern examples.
- PyAstre https://pypi.python.org/pypi/pyastre: Asterisk modules using Twisted framework.
- Python AGI http://sourceforge.net/projects/pyst
- Python AGI bindings py-Asterisk
- Manager interface with Plone/Zope atasterisk
- StarPy http://starpy.sourceforge.net/: Asterisk Twisted modules for AMI clients and FastAGI servers
Ruby
C
- AGIAddOns: Asterisk module to add additional AGI commands, such as PUT SOUNDFILE and GET SOUNDFILE, amongst others.
- AGI Audio File Transfer Addons: Based on AGIAddOns: adds the same AGI commands (although slightly modified), and updated to be compatible with newer versions of Asterisk
- CAGI: A C API for AGI. Based on PHPAGI.
- Quivr: A C API for AGI. ANSI C AGI Library.
.NET
- AsterNET Open source .NET AMI/AGI/FastAGI framework. Based on Asterisk.NET
- AMIConnector .NET Library: A .NET library for fast development of Applications using Asterisk AMI
- Asterisk Channels Live this is a windows project, which we can see all Asterisk channels. it is written in C# .
- MONO-TONE: A C# Class for running AGI and FastAGI on the Mono platform.
- nAsterisk: A .NET Asterisk Library.
Haskell
- Haskell AGI: Haskell library for AGI and FastAGI.
Xinetd.d ( generic )
The advantage of using xinetd.d is you don’t need to worry about the network connection. Xinetd.d launches your scripts for you and your scripts run like a AGI script that is on the same server ( with the exception of your files ).
In /etc/xinetd.d/voip :
service agi
{
socket_type = stream
protocol = tcp
wait = no
user = agi_user
server = /path/to/your/agi/script
instances = 25
nice = 10
only_from = 192.168.1.0/24 192.168.0.0/24
}
In /etc/services
agi 4573/tcp #This line MIGHT already exist, check before adding
NOTE : This option might be good for a software that is already developed without support for agi://
NOTE : This option offers no solution for transfering files ( if you need to )
Example AGI Applications
AGI Indexes
- The AGI Gallery A website indexing AGI scripts written by the community. Open Source and Commercial submissions accepted
Perl
- A pager like application that takes the input and send it through email/SMS
- A Perl EAGI which simply records and plays back
- A sample application for trouble ticket management with perldesk
- A simple calling card application
- Accept a 10-digit ISBN, look up and read back the price on Amazon.com
- Asterisk authenticate using voicemail passwords
- Asterisk click to call Create a web page button to setup a call. Uses Manager API.
- Asterisk tips Wake-Up Call Perl: Perl version of a wake-up call, one script, multiple calls, no daemon
- EdGuy@Pulver.com’s stuff from Astricon
- Warren’s asterisk-manager CDR replacement and call queue management (with call recording)
PHP
- Asterisk simple php lookup mysql database to set callerid name
- Asterisk simple php lookup up callerid name from Horde Turba
- Asterisk tips Airport Weather PHP – Script to speak (TTS) Airport weather using 3 digit input of airport codes. ORD = 673…
- Asterisk tips Wake-Up Call PHP – Make Wakeup Calls using a PHP script
- Asterisk tips Weather PHP – Modify this PHP script to use Cepstral TTS engine to read your local weather
- Junghanns.net: PHP example doing callback to a mobile phone: http://www.junghanns.net/en/callback.html
- Nerd Vittles complete collection of AGI scripts: weather, news, tide reports, reminders, and more
- PhoneSpamFilter – Automatically block telemarketer calls from making it through your Asterisk server using a PHP AGI script. http://www.phonespamfilter.com/automateasterisk.php
Bash and Ash
- Bash AGI: A Bash script that sets the callerID name from NANPA data for the NPA-NXX.
- MacinTalk AGI: A Bash script that does text to voice with MacinTalk.
- The distribution package of the LCDial.sh AGI script contains a sh-agi.inc file providing primitives, such as sh_agi_cmd, sh_agi_getvariable and sh_agi_log, to simplify the coding of AGI scripts for the bash and ash shell interpreters.
Haskell
- Guessing Game: Simple guessing game using AGI.
- Hit Counter: A simple demo using FastAGI and HAppS.
Notes
Fork and continue dialplan
If you don’t want Asterisk to wait until the script finishes you can fork the script off to return to dialplan excution: Here’s how to accomplish this in Perl:
open STDOUT, ‘>/dev/null’;
fork and exit;
Here is a fork and continue method for bash (found at http://asterisk.inmte.com/viewtopic.php?t=317&sid=d4284dd558dd93bd7f8f2ef70e1f2113):
/var/lib/asterisk/agi-bin/agi-test.agi:
#!/bin/bash
nohup /root/helloworld.sh 1>/dev/null 2>/dev/null &
exit 0
CLI output
For some reason, my AGI perl scripts cannot write to the CLI console using
standard error. I ran the agi-test.agi test script that came with asterisk
and verified that the problem was not with the code. Asterisk is always
started with 4 or more v’s, yet this the CLI output does not show up. Have
there been any major changes to AGI in the cvs-head? I am using Asterisk
CVS-D2005.08.05.
This is a known problem. Asterisk will only send STDERR from AGI
scripts to the actual console Asterisk is running on. You have to
switch to the actual console Asterisk is running on (tty9 I think) or
start asterisk in the foreground with “asterisk -cvvv”.
It’s a minor issue for most people.
We start asterisk under a detached screen with GNU screen. We use the
‘L’ flag to log to a text file if we want. Then we can “screen -r” to
the actual asterisk CLI any time we want.
The other obvious way to test is to set a variable & use NoOp(${VARIABLE}) to
see what is going on.
/usr/bin/screen -L -d -m -S asterisk /usr/sbin/asterisk -vvvvvvvvvvvvvvvvvvvvvgc
See http://www.gnu.org/software/screen/
Miscellaneous
- Using the verbose comand in an AGI you can feed information back to the console (the CLI ) in the same way that applications do. So by specifying different information to be returned at various verbosity levels the AGI will produce results similar to those of Asterisk applications. Make sure you read the return of the VERBOSE command (just like with any other AGI command) before issuing another AGI command. Be aware that VERBOSE will give trouble with quoted strings as e.g. in CALLERID (verbose will cut the string after the first space character).
- The EAGI extension will let you receive sound from the channel into your application. It will not let you send sound. EAGI is intended to allow you to write a script that passes sound to an external application – such as the Sphinx speech-to-text/speech recognition application (as the example script included with asterisk does). Your EAGI application must also listen for a text response. In the case of Sphinx this would be a string representing the captured speech.
- Always use AGI unless you specifically need EAGI functionality – unpredictable results may otherwise be obtained.
- Commands such as “send text” may cause your script to fail if accessed from a phone that has no capability for the requested media type.
- GET VARIABLE: Does not work with global variables. Does not work with some variables that are generated by modules.
Tutorials
- A Primer to AGI: Asterisk Gateway Interface from Packt Publishing
- A Technical Introduction to the Asterisk Gateway Interface (AGI)
- Example of AGI calls and AGI scripts in PHP and Java, tutorial by Apstel
AGI enhancements
asterisk-agi-audiotx
This is an extension module for the Asterisk Gateway Interface (AGI) that adds commands to allow the transfer of audio files to and from Asterisk via the AGI session. This is useful when using FastAGI from a remote host; sounds recorded by Asterisk may be retrieved by remote FastAGI-providing service, for example, or sound files required by the remote service may be dynamically added to the Asterisk server.
This module adds the following AGI commands:
- PUT SOUNDFILE <soundfile> <size>
- GET SOUNDFILE <soundfile>
- ISEXISTING SOUNDFILE <soundfile>
See also
- AGI calls in Visual Dialplan
- Asterisk
- Asterisk Appliances
- Asterisk cmd AGI
- PodCast – How to listen to podcasts with Asterisk