Lua Scripting API
sip_realtime_ai v1.3.0 — programmable SIP calls and realtime AI sessions.
Overview
Embedded Lua 5.4 makes sip_realtime_ai a programmable SIP-to-AI gateway. Route incoming calls, control the SIP lifecycle, start and stop AI sessions independently, switch providers during a call, implement recovery policies and respond to provider-native tool requests.
Configuration
Add or update the Lua section in /etc/sip_realtime_ai/sip_realtime_ai.xml. The default is disabled. Set an absolute script path readable by the sipai service user.
<lua>
<param name="enabled" value="true"/>
<param name="script" value="/etc/sip_realtime_ai/scripts/main.lua"/>
</lua>sudo systemctl restart sip-realtime-ai
sudo journalctl -u sip-realtime-ai -fThe script is loaded at startup. It must define on_incoming_call. Restart the service after changing the script; plan for interruption of active calls.
Incoming call routing
on_incoming_call(call) is required. At this stage the table contains only caller and destination; no call-control methods or timer context are available.
| Return value | Type | Description |
|---|---|---|
return "sales" | string | Accept and select the named AI profile. |
return nil | nil | Reject with SIP 403; an empty string also rejects. |
return {action="accept"} | table | Accept without starting AI. |
return {action="accept", profile="sales"} | table | Accept with the named profile. |
return {action="reject", code=486} | table | Reject with an integer SIP status between 400 and 699; default 403. |
function on_incoming_call(call)
if call.destination == "sales" then
return "sales"
elseif call.destination == "support" then
return {action = "accept", profile = "support"}
end
return {action = "reject", code = 404}
endUse configured profile names. Invalid return types, actions or profile values are routing errors. The router also parses an optional rejection reason (1–128 bytes, no control characters); use standard SIP status codes rather than relying on custom wire reason phrases.
Call object
| Property | Type | Description |
|---|---|---|
call.id | string | SIP call UUID. |
call.caller | string | Caller identifier. |
call.destination | string | Destination identifier. |
call.profile | string | Profile snapshot at callback invocation; may be empty. |
call.reason | string | Present in the ended callback: terminated. |
Lifecycle callbacks receive a fresh table with UUID-bound methods. A captured call table can be used by its timers; fields are snapshots, not live properties. Operations on a call that no longer exists fail.
Lifecycle callbacks
| Callback | Returns | Description |
|---|---|---|
on_incoming_call(call) | string / table / nil | Required routing decision. |
on_call_started(call) | — | Optional; SIP call established. |
on_call_ended(call) | — | Optional; clean up script state. No timer context. |
function on_incoming_call(call)
return "sales"
end
function on_call_started(call)
log.info("Call started: " .. call.id)
end
function on_call_ended(call)
log.info("Call ended: " .. call.id)
endCallback return values other than the routing decision are ignored. Keep per-call state keyed by UUID and clear it when the call ends.
Call control
| Method | Returns | Description |
|---|---|---|
call:hangup() | boolean | Requests SIP termination. Does not require AI readiness. |
function on_incoming_call(call)
return {action = "accept"}
end
function on_call_started(call)
timer.after(30000, function()
call:hangup()
end)
endAI session management
The SIP/RTP session and AI session have separate lifecycles. Stop an AI session and start another profile without establishing a new SIP call. A new provider session does not automatically inherit conversation history.
| Method | Returns | Description |
|---|---|---|
call:start_ai(profile) | boolean | Starts a configured profile on a live call without active AI. True does not mean provider ready. |
call:stop_ai() | boolean | Detaches/stops AI and clears playback while retaining SIP. |
call:ai_active() | boolean | Whether an AI session is attached. |
call:ai_ready() | boolean | Whether the active provider is ready. |
AI interaction
| Method | Returns | Description |
|---|---|---|
call:send_text(text) | boolean | Sends text using the active provider protocol. |
call:update(json_string) | boolean | Forwards provider-native JSON. Pass a string, not a Lua table. |
call:break_audio() | boolean | Interrupts playback and requests provider interruption where supported. |
These methods require a ready AI session. A true return indicates local acceptance, not provider confirmation.
function on_ai_ready(call)
call:send_text("Say hello to the caller.")
endAI callbacks
| Callback | Returns | Description |
|---|---|---|
on_ai_ready(call) | — | Optional; provider session ready. |
on_ai_error(call, error) | — | Optional; reported session failure, with error string. Failed session is detached before recovery. |
on_ai_message(call, message) | — | Optional; filtered provider-native JSON string, not the WSS envelope. |
For a reported fatal session failure, a successful error callback can keep SIP alive and implement recovery. Without a successful error callback the gateway terminates the call. Not every provider error message is a fatal session failure.
function on_ai_message(call, message)
local event, err = json.decode(message)
if err then
log.info(err)
return
end
if event and event.type == "interruption" then
log.info("AI interrupted: " .. call.id)
end
endTimers
| Function | Returns | Description |
|---|---|---|
timer.after(ms, callback) | integer or nil, error | One-shot timer; returns integer ID or nil, error if unavailable or limit reached. |
timer.cancel(id) | boolean | Cancels a pending timer belonging to the current call. |
Delay must be an integer from 1 to 86,400,000 ms. Up to 32 pending timers per call and 4096 globally. Callbacks take no arguments; capture the call in a closure. Timers are removed before execution and cancelled on call termination. Nested timers are supported. Timers are unavailable at script load, incoming routing and ended callbacks.
function on_call_started(call)
local id = timer.after(15000, function()
call:hangup()
end)
if id then
timer.cancel(id)
end
endJSON API
| API | Returns / type | Description |
|---|---|---|
json.decode(text) | value or nil, error | JSON false is a valid result. |
json.encode(value) | string or nil, error | Encodes a Lua value as JSON. |
json.array([table]) | table | Creates or marks a table as an array, including an empty array. |
json.null | sentinel | Sentinel for explicit JSON null; preserves object fields and array positions. |
local payload = json.encode({
items = json.array(),
enabled = true,
optional = json.null
})
log.info(payload)Empty unmarked tables encode as objects; contiguous positive integer keys encode as arrays. Mixed or sparse tables, unsupported values, non-finite numbers and excessive nesting (including cycles) are rejected. Numbers use double precision. Limits: 256 KiB input/output, depth 32 (root depth zero), 8192 value nodes. Embedded NUL is unsupported. Argument type errors may raise Lua errors.
Logging
| Function | Returns | Description |
|---|---|---|
log.info(message) | — | Writes to stderr with the [LUA] prefix. |
Avoid logging credentials or sensitive conversation content in production.
log.info("Call started: " .. call.id)Execution model
One persistent Lua state is owned by the Sofia-SIP event thread. Callbacks execute serially and share script globals. Keep handlers short; the instruction hook aborts execution at 10,000 Lua instructions per invocation, including script initialization and timer callbacks. JSON conversion has separate limits.
No Lua standard libraries are loaded, including base functions, OS, IO, package, math, string and table libraries. Language syntax, local functions, closures and table constructors remain available. Do not use require, print, pairs, os.time or external HTTP calls. This is an embedded control API, not a general-purpose Lua runtime or a security sandbox for untrusted scripts.
WebSocket integration
Lua call logic and authenticated WSS monitoring can operate concurrently. Provider messages delivered to Lua use the gateway audio-filtering path; the external Event Bus wraps messages in an ai.message envelope. Neither interface is an audio transport. Coordinate external commands and Lua policies to avoid conflicting actions.
See WebSocket Event Bus documentation for subscriptions, authentication and external commands.
Installed examples
The Debian package installs the following scripts. Select one by setting the absolute XML script path, restart the service, then place a SIP call to the configured listener. Configure the required profiles first.
/usr/share/doc/sip-realtime-ai/examples/
├── main.lua
├── timers.lua
├── provider-switch.lua
├── recovery.lua
└── tool-calling.luasudo install -o root -g sipai -m 640 \
/usr/share/doc/sip-realtime-ai/examples/timers.lua \
/etc/sip_realtime_ai/scripts/timers.luamain.lua demonstrates basic routing to the configured sales profile and logs call start and end. It is also installed as the default configuration script.
Set the script parameter to /etc/sip_realtime_ai/scripts/timers.lua and restart. Use a test deployment; some examples intentionally terminate calls.
Timer isolation
timers.lua- Required profiles
- None
- Behavior
- Accepts SIP without AI. Logs timers after 3, 15 and 20 seconds.
- Expected result
- Hang up before 15 seconds; only the first timer should execute. With overlapping calls, ending one must not cancel the other call’s timers.
Live provider switching
provider-switch.lua- Required profiles
- elevenlabs, gemini
- Behavior
- Starts ElevenLabs, stops it after 15 seconds and starts Gemini two seconds later. Ends the call after 45 seconds.
- Expected result
- Both providers become ready in sequence; the SIP UUID remains unchanged. Conversation history is not transferred automatically.
AI failure recovery
recovery.lua- Required profiles
- sales (deliberately failing), elevenlabs (working)
- Behavior
- On asynchronous AI failure, schedules recovery after three seconds. A second failure or immediate start rejection ends the call. Test timeout: 40 seconds.
- Expected result
- The failed AI session is detached and the SIP call remains active during recovery. This is a script-defined policy, not built-in automatic failover.
Provider-native tool calling
tool-calling.lua- Required profiles
- elevenlabs with get_current_time client tool
- Behavior
- Sends a text request, handles client_tool_call and returns client_tool_result using json.encode and call:update. Ends the call after 30 seconds.
- Expected result
- The agent receives the fixed demonstration result (10:30 AM), not the actual time. Other providers require their own event formats.
Troubleshooting
Script fails to load: check absolute path, permissions, syntax and required on_incoming_call function.
AI does not start: check profile name and credentials, immediate boolean result and on_ai_error logs.
Timer unavailable: check callback context and pending timer limits.
Tool result not accepted: check provider-native schema, tool call ID and AI readiness.
Instruction budget exceeded: shorten callback logic; do not use busy loops.