DOCUMENTATION

Lua Scripting API

sip_realtime_ai v1.3.0 — programmable SIP calls and realtime AI sessions.

GETTING STARTED

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.

SIP / RTPLua call logicAI sessions
Available since v1.3.0. Lua is optional. For SIP, RTP, profiles and WSS configuration, see gateway documentation.
GETTING STARTED

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.

XMLEnable Lua
<lua>
  <param name="enabled" value="true"/>
  <param name="script" value="/etc/sip_realtime_ai/scripts/main.lua"/>
</lua>
TERMINALRestart and monitor
sudo systemctl restart sip-realtime-ai
sudo journalctl -u sip-realtime-ai -f

The script is loaded at startup. It must define on_incoming_call. Restart the service after changing the script; plan for interruption of active calls.

LUA API

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 valueTypeDescription
return "sales"stringAccept and select the named AI profile.
return nilnilReject with SIP 403; an empty string also rejects.
return {action="accept"}tableAccept without starting AI.
return {action="accept", profile="sales"}tableAccept with the named profile.
return {action="reject", code=486}tableReject with an integer SIP status between 400 and 699; default 403.
LUARoute by destination
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}
end

Use 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.

LUA API

Call object

PropertyTypeDescription
call.idstringSIP call UUID.
call.callerstringCaller identifier.
call.destinationstringDestination identifier.
call.profilestringProfile snapshot at callback invocation; may be empty.
call.reasonstringPresent 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.

LUA API

Lifecycle callbacks

CallbackReturnsDescription
on_incoming_call(call)string / table / nilRequired routing decision.
on_call_started(call)—Optional; SIP call established.
on_call_ended(call)—Optional; clean up script state. No timer context.
LUATrack calls
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)
end

Callback return values other than the routing decision are ignored. Keep per-call state keyed by UUID and clear it when the call ends.

LUA API

Call control

MethodReturnsDescription
call:hangup()booleanRequests SIP termination. Does not require AI readiness.
LUAEnd a call after 30 seconds
function on_incoming_call(call)
    return {action = "accept"}
end

function on_call_started(call)
    timer.after(30000, function()
        call:hangup()
    end)
end
LUA API

AI 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.

MethodReturnsDescription
call:start_ai(profile)booleanStarts a configured profile on a live call without active AI. True does not mean provider ready.
call:stop_ai()booleanDetaches/stops AI and clears playback while retaining SIP.
call:ai_active()booleanWhether an AI session is attached.
call:ai_ready()booleanWhether the active provider is ready.
Wait for on_ai_ready before sending text or provider updates. Handle both immediate false returns and asynchronous initialization failures.
LUA API

AI interaction

MethodReturnsDescription
call:send_text(text)booleanSends text using the active provider protocol.
call:update(json_string)booleanForwards provider-native JSON. Pass a string, not a Lua table.
call:break_audio()booleanInterrupts playback and requests provider interruption where supported.

These methods require a ready AI session. A true return indicates local acceptance, not provider confirmation.

LUASend text when ready
function on_ai_ready(call)
    call:send_text("Say hello to the caller.")
end
LUA API

AI callbacks

CallbackReturnsDescription
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.

LUAInspect a provider event
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
end
LUA API

Timers

FunctionReturnsDescription
timer.after(ms, callback)integer or nil, errorOne-shot timer; returns integer ID or nil, error if unavailable or limit reached.
timer.cancel(id)booleanCancels 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.

LUACancel a pending timer
function on_call_started(call)
    local id = timer.after(15000, function()
        call:hangup()
    end)
    if id then
        timer.cancel(id)
    end
end
LUA API

JSON API

APIReturns / typeDescription
json.decode(text)value or nil, errorJSON false is a valid result.
json.encode(value)string or nil, errorEncodes a Lua value as JSON.
json.array([table])tableCreates or marks a table as an array, including an empty array.
json.nullsentinelSentinel for explicit JSON null; preserves object fields and array positions.
LUAObjects, arrays and null
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.

LUA API

Logging

FunctionReturnsDescription
log.info(message)—Writes to stderr with the [LUA] prefix.

Avoid logging credentials or sensitive conversation content in production.

LUALog call identity
log.info("Call started: " .. call.id)
LUA API

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.

LUA API

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.

EXAMPLES

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.

FILESPackaged scripts
/usr/share/doc/sip-realtime-ai/examples/
├── main.lua
├── timers.lua
├── provider-switch.lua
├── recovery.lua
└── tool-calling.lua
TERMINALCopy a test script into the configuration directory
sudo install -o root -g sipai -m 640 \
  /usr/share/doc/sip-realtime-ai/examples/timers.lua \
  /etc/sip_realtime_ai/scripts/timers.lua

main.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.

EXAMPLES

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.
EXAMPLES

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.
EXAMPLES

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.
EXAMPLES

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.
HELP

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.