AgentsAgentBase

register_routing_callback

View as MarkdownOpen in Claude

Register a callback function for dynamic request routing. When a request arrives at the specified path, the callback inspects the POST body and decides whether to route the request to a different endpoint or let normal processing continue.

This is primarily used for SIP-based routing where the destination depends on the incoming SIP URI. For simpler SIP routing based on agent name matching, use enable_sip_routing() instead.

The callback path is registered immediately but the actual FastAPI route is created when serve() is called or when as_router() generates the router. Register all callbacks before starting the server.

Parameters

callback_fn
Callable[[dict[str, Any], dict[str, Any]], str | None]Required

A function that receives the parsed JSON body and the request headers, both as a dictcallback_fn(body, headers). Return a route string to redirect the request (using HTTP 307 to preserve the POST method and body), or return None to continue with normal SWML document serving.

path
strDefaults to /sip

The URL path where this routing endpoint is created. The path is normalized to start with / and trailing slashes are stripped.

Returns

None

Example

from signalwire import AgentBase
from signalwire.core.swml_service import SWMLService
agent = AgentBase(name="router", route="/")
agent.set_prompt_text("You are a helpful assistant.")
def route_sip_call(body, headers):
username = SWMLService.extract_sip_username(body)
if username == "sales":
return "/agents/sales"
elif username == "support":
return "/agents/support"
return None
agent.register_routing_callback(route_sip_call, path="/sip")
agent.serve()