Beyond SIP INFO: Programmable SIP and Realtime AI with WebSocket and Lua
Connecting a SIP call directly to a realtime AI provider is only part of building a voice AI application. External applications also need to know what is happening during a call and interact with the AI session as the conversation evolves.
This is why we extended sip_realtime_ai beyond SIP INFO, first introducing a WebSocket EventBus for external control and monitoring, and now adding an embedded Lua 5.4 engine in version 1.3.0. The result is a standalone programmable SIP application server for realtime voice AI, without a mandatory FreeSWITCH, Asterisk or middleware deployment.
SIP INFO: a useful starting point
Our initial approach was to expose application commands through SIP INFO. A SIP endpoint can send text to the AI session using send_text or modify session settings using update, according to the selected provider's protocol.
However, SIP INFO is tied to a SIP dialog. It is useful for an application that participates in the call, but less convenient for an independent monitoring service, CRM or application backend that needs visibility across multiple calls.
Rather than extending SIP signaling to handle every application-level requirement, we introduced a separate communication channel. SIP INFO remains available alongside the new interface.
A WebSocket EventBus, not just another control API
The gateway now includes a WebSocket server that allows external applications to maintain persistent connections independently of SIP sessions. The EventBus distributes call and AI events to subscribed clients while also supporting command-response communication.
- WebSocket and secure WebSocket (WSS) connections with Bearer token authentication.
- Multiple simultaneous clients and active call discovery.
- Subscriptions to all calls or individual calls identified by UUID.
- Realtime call lifecycle events and provider-native AI messages.
- Remote call control and command-response correlation using request IDs.
One application can monitor all calls while another subscribes only to a particular conversation. Neither needs to participate in the SIP dialog or carry the voice media.
Separating signaling, media and application control
The architecture keeps signaling, media and application logic separate:
- Signaling plane: SIP establishes and terminates calls, with SIP INFO available for in-dialog commands.
- Media plane: RTP or SRTP carries telephone audio, while the gateway exchanges realtime audio with the selected AI provider.
- Application control and event plane: the WebSocket EventBus exposes events and supported commands to external applications.
- Embedded application logic: Lua scripts execute inside the server and control the SIP call and its AI session through the native call API.
The WebSocket monitoring connection is not an audio relay. The gateway continues to manage the media path directly, including audio conversion and playback. Application backends can focus on business logic rather than forwarding voice packets.
Realtime visibility into AI conversations
Monitoring is not limited to SIP call states. The EventBus also exposes provider-native messages, including transcripts, conversation events, tool and function calls, and interruptions where available.
This applies to the five supported integrations: OpenAI Realtime, Google Gemini Live, ElevenLabs Agents, Azure Voice Live and Grok Voice. Event structures and capabilities remain provider-specific.
Audio payloads are filtered from the event stream. For example, OpenAI audio delta messages and ElevenLabs audio events are excluded, while Gemini messages containing audio are sanitized to preserve relevant non-audio content. This keeps the event channel focused on application data without forwarding large encoded audio payloads.
From active calls to live subscriptions
After establishing an authenticated WebSocket connection, an application receives a server.connected event. It can use list_calls to discover active calls and subscribe to receive events for all calls or a specific call UUID.
Call lifecycle events such as call.created, call.started and call.ended allow applications to maintain their own view of active conversations. Clients can also unsubscribe when they no longer need a particular event stream.
Command responses include the request ID, allowing applications to associate responses with their original requests while asynchronous events continue to arrive on the same connection.
Building applications around the gateway
The EventBus provides a foundation for live monitoring dashboards, CRM integrations, transcript processing and external business workflows. An application can observe a provider-native tool call, execute its own business logic and interact with the AI session using the supported control interface and the provider's protocol.
The gateway does not impose a generic tool execution framework. Tool definitions and result handling remain specific to the selected AI provider, while the application retains control over its business logic.
By separating application control from SIP signaling and voice media, sip_realtime_ai becomes more than a SIP-to-AI media gateway: it provides a programmable interface for integrating realtime voice conversations into larger systems.
Version 1.3.0: application logic inside the SIP server
External control is useful, but not every decision needs to leave the gateway. With embedded Lua 5.4, developers can implement call routing, session management and event-driven workflows directly inside sip_realtime_ai.
- Accept or reject incoming SIP calls, select a provider profile, or accept a call without starting AI.
- React to call lifecycle callbacks and terminate calls through the call API.
- Schedule and cancel per-call timers with automatic cleanup when a call ends.
- Start and stop AI sessions independently of the SIP dialog.
- React to AI readiness, session failures and filtered provider-native messages.
- Send text, update provider sessions, interrupt playback and encode or decode JSON.
Lua is optional. Existing deployments can continue to use configured provider profiles, SIP INFO and WebSocket control without enabling scripting.
The SIP call and the AI session have independent lifecycles
A central feature of the new architecture is that an established SIP call does not have to be tied to a single AI session. A script can accept the call first, start an AI session later, stop it, and start another session using a different profile or provider.
The call retains its UUID and SIP dialog while the gateway manages the transition between AI sessions. This allows applications to select different agents during a conversation, change providers according to application policy, or recover from a failed AI session without requiring the caller to redial.
Switching creates a new provider session; conversation history is not automatically transferred between providers. Applications can manage context explicitly through the relevant provider protocol.
Script-defined AI failover
When a fatal AI session failure is reported, the failed session is detached before on_ai_error(call, error) is invoked. A successful error callback can keep the SIP call alive and decide how to recover.
For example, the following Lua callback schedules a recovery attempt using a configured fallback profile. It limits recovery to one attempt per call and terminates the call if recovery cannot be started.
local recovering = {}
function on_ai_error(call, err)
if recovering[call.id] then
call:hangup()
return
end
recovering[call.id] = true
timer.after(3000, function()
if not call:start_ai("fallback") then
call:hangup()
end
end)
end
function on_call_ended(call)
recovering[call.id] = nil
endThe fallback profile must be configured in the gateway. The recovery policy belongs to the application, not to a hard-coded provider selection algorithm. Without a successful error callback, the gateway terminates the call. Not every provider error message represents a fatal session failure.
Provider-native tools and JSON in Lua
The on_ai_message(call, message) callback receives filtered provider-native JSON messages. Scripts can use json.decode() to inspect events and json.encode() to construct provider-specific responses.
For example, an ElevenLabs client tool call can be handled locally in Lua and its result returned using call:update() with the provider's expected JSON structure. Tool definitions and result formats remain provider-specific, just as they do with external WebSocket applications.
Simple application logic can therefore run inside the SIP server, while workflows requiring external systems can remain in an application connected to the EventBus.
Embedded Lua and WebSocket EventBus work together
Lua does not replace the EventBus. A local script can manage routing, timers and AI session transitions while an authenticated WebSocket client independently monitors call lifecycle events and provider messages.
This makes it possible to keep call-level decisions close to the media path while retaining external visibility for dashboards, CRM integrations and other application services. Neither the Lua script nor the monitoring client needs to relay audio packets.
Validated with live calls and lifecycle tests
During development of v1.3.0, live SIP calls were used to verify switching from ElevenLabs to Gemini, recovery from an OpenAI authentication failure using ElevenLabs, and provider-native tool execution. WebSocket monitoring was also verified during a Lua-controlled provider transition.
Separate AddressSanitizer/UndefinedBehaviorSanitizer and ThreadSanitizer builds each completed a 1,000-call SIPp lifecycle test with up to ten concurrent calls. Additional tests covered timer isolation, cancellation, active-call shutdown and live AI session transitions. These tests validate the exercised paths rather than establish a production capacity limit.
Explore sip_realtime_ai
Learn more about the standalone SIP-to-AI gateway, or see the sip_realtime_ai documentation for configuration, WebSocket monitoring and call control. The documentation also covers the embedded Lua API, and the distributed example scripts demonstrate timers, provider switching, recovery and tool calling.