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[[Request, dict[str, Any]], Optional[str]]Required

A function that receives a FastAPI Request and the parsed JSON body as a dict. 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

1from signalwire import AgentBase
2from signalwire.core.swml_service import SWMLService
3
4agent = AgentBase(name="router", route="/")
5agent.set_prompt_text("You are a helpful assistant.")
6
7def route_sip_call(request, body):
8 username = SWMLService.extract_sip_username(body)
9 if username == "sales":
10 return "/agents/sales"
11 elif username == "support":
12 return "/agents/support"
13 return None
14
15agent.register_routing_callback(route_sip_call, path="/sip")
16agent.serve()