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

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

1from signalwire import AgentServer
2from signalwire import AgentBase
3
4def route_by_language(request, body):
5 """Route to different agents based on Accept-Language header."""
6 lang = request.headers.get("Accept-Language", "en")
7 if lang.startswith("es"):
8 return "/spanish-agent"
9 elif lang.startswith("fr"):
10 return "/french-agent"
11 return None # Default agent handles it
12
13english = AgentBase(name="english", route="/english-agent")
14english.set_prompt_text("You are a helpful assistant. Respond in English.")
15spanish = AgentBase(name="spanish", route="/spanish-agent")
16spanish.set_prompt_text("You are a helpful assistant. Respond in Spanish.")
17french = AgentBase(name="french", route="/french-agent")
18french.set_prompt_text("You are a helpful assistant. Respond in French.")
19
20server = AgentServer(port=3000)
21server.register(english)
22server.register(spanish)
23server.register(french)
24server.register_global_routing_callback(route_by_language, "/route")
25server.run()