register_global_routing_callback

View as MarkdownOpen in Claude

Register a custom routing callback on every registered agent at the specified path. When a request arrives at that path on any agent, the callback is invoked to determine whether to redirect the request to a different agent route.

This is the low-level mechanism that powers setup_sip_routing(). Use it directly when you need custom routing logic beyond SIP username matching — for example, routing based on HTTP headers, query parameters, or request body content.

Parameters

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

A function that receives the parsed request body and the request headers, both as a dictcallback_fn(body, headers). Return a route string (e.g., "/sales") to redirect, or None to let the current agent handle the request.

path
strRequired

The URL path where the callback is triggered (e.g., "/route"). Leading slashes are added and trailing slashes are stripped automatically.

Returns

None

Example

from signalwire import AgentServer
from signalwire import AgentBase
def route_by_language(body, headers):
"""Route to different agents based on Accept-Language header."""
lang = headers.get("Accept-Language", "en")
if lang.startswith("es"):
return "/spanish-agent"
elif lang.startswith("fr"):
return "/french-agent"
return None # Default agent handles it
english = AgentBase(name="english", route="/english-agent")
english.set_prompt_text("You are a helpful assistant. Respond in English.")
spanish = AgentBase(name="spanish", route="/spanish-agent")
spanish.set_prompt_text("You are a helpful assistant. Respond in Spanish.")
french = AgentBase(name="french", route="/french-agent")
french.set_prompt_text("You are a helpful assistant. Respond in French.")
server = AgentServer(port=3000)
server.register(english)
server.register(spanish)
server.register(french)
server.register_global_routing_callback(route_by_language, "/route")
server.run()