AgentsAgentBase

handle_request

View as MarkdownOpen in Claude

Dispatch a request over plain values instead of FastAPI objects. Performs proxy detection, basic auth, the routing callback check, and on_swml_request() modification, then renders the SWML document, mirroring the response the FastAPI routes produce for the same request. Basic auth is always on: pass basic_auth to the constructor and send a matching Authorization header, or the call returns 401.

Use it to serve an agent from a framework the SDK has no adapter for. For the supported serverless platforms, use handle_serverless_request().

Parameters

method
strRequired

HTTP method, such as "GET" or "POST".

url
strRequired

The full request URL. Used for proxy detection and to match a registered routing callback path.

headers
dict[str, Any]Required

Request headers as a plain dictionary.

body
dict[str, Any] | NoneDefaults to None

The already-parsed JSON body for POST requests.

Returns

tuple[int, dict[str, Any], str](status_code, response_headers, body).

  • 200 with the SWML document as a JSON string.
  • 307 with a Location header and an empty body when a routing callback returned a destination.
  • 401 with WWW-Authenticate: Basic and a JSON error when basic auth fails.

Example

import base64
import json
from signalwire import AgentBase
agent = AgentBase(name="dispatch", route="/dispatch", basic_auth=("dispatch", "s3cret"))
agent.set_prompt_text("You are Ada, the dispatcher for Bayview Taxi.")
credentials = base64.b64encode(b"dispatch:s3cret").decode()
status, headers, body = agent.handle_request(
"POST",
"https://bayview-taxi.example.com/dispatch",
{
"content-type": "application/json",
"authorization": f"Basic {credentials}",
},
{"call": {"call_id": "abc-123"}},
)
print(status, json.loads(body)["sections"]["main"][0])