- Introduction
- Installation
- Basic Usage
- Centralized Logging System
- SWML Document Creation
- Verb Handling
- Web Service Features
- Custom Routing Callbacks
- Advanced Usage
- API Reference
- Examples
The SWMLService class provides a foundation for creating and serving SignalWire Markup Language (SWML) documents. It serves as the base class for all SignalWire services, including AI Agents, and handles common tasks such as:
- SWML document creation and manipulation
- Schema validation
- Web service functionality
- Authentication
- Centralized logging
The class is designed to be extended for specific use cases, while providing a full set of capabilities out of the box.
The SWMLService class is part of the SignalWire AI Agent SDK. Install it using pip:
pip install signalwire-sdkHere's a simple example of creating an SWML service:
from signalwire.core.swml_service import SWMLService
class SimpleVoiceService(SWMLService):
def __init__(self, host="0.0.0.0", port=3000):
super().__init__(
name="voice-service",
route="/voice",
host=host,
port=port
)
# Build the SWML document
self.build_document()
def build_document(self):
# Reset the document to start fresh
self.reset_document()
# Add answer verb
self.add_verb("answer", {})
# Add play verb for greeting
self.add_verb("play", {
"url": "say:Hello, thank you for calling our service."
})
# Add hangup verb
self.add_verb("hangup", {})
# Create and start the service
service = SimpleVoiceService()
service.serve()The SWMLService class includes a centralized logging system based on structlog that provides structured logs. Importing the module attaches a null handler, so the SDK stays silent by default. serve() turns logging output on for you by calling configure_logging(); call it yourself earlier if you need logs before that.
Logging in an SWMLService works this way:
- Importing
swml_service.pyattaches aNullHandlerto thesignalwirelogger, so nothing prints until logging is configured serve()callsconfigure_logging()for you; call it yourself first if you need logging output before that- Each
SWMLServiceinstance gets a logger bound to its service name - All logs include contextual information like service name, timestamp, and log level
- Logs are formatted as colored console text by default, or as JSON when
SIGNALWIRE_LOG_FORMAT=jsonis set
Every SWMLService instance has a log attribute that can be used for logging:
# Basic logging
self.log.info("service_started")
# Logging with context
self.log.debug("document_created", size=len(document))
# Error logging
try:
# Some operation
pass
except Exception as e:
self.log.error("operation_failed", error=str(e))The following log levels are available (in increasing order of severity):
debug: Detailed information for debugginginfo: General information about operationwarning: Warning about potential issueserror: Error information when operations failcritical: Critical error that might cause the application to terminate
The SDK's logger does not propagate to the root logger, so raising the root logger's level has no effect on it. To raise the level, set SIGNALWIRE_LOG_LEVEL before the service starts:
export SIGNALWIRE_LOG_LEVEL=warning # Only show warnings and abovesuppress_logs is a narrower, older setting: it silences five specific log lines, not the SDK's logging generally. AgentBase logs one at startup, naming the schema path it found. The /post_prompt endpoint logs three for each request it handles. The fifth reports an LLM parameter that fails to apply while the SWML document is rendered. No other log call in the SDK checks it; use SIGNALWIRE_LOG_LEVEL or configure_logging() to control log output generally.
Passing suppress_logs=True when initializing an agent silences those five lines:
from signalwire import AgentBase
agent = AgentBase(
name="my-service",
suppress_logs=True
)The SWMLService class provides methods for creating and manipulating SWML documents.
SWML documents have the following basic structure:
{
"version": "1.0.0",
"sections": {
"main": [
{ "verb1": { /* configuration */ } },
{ "verb2": { /* configuration */ } }
],
"section1": [
{ "verb3": { /* configuration */ } }
]
}
}These methods build and read the document:
reset_document(): Reset the document to an empty stateadd_verb(verb_name, config): Add a verb to the main sectionadd_section(section_name): Add a new sectionadd_verb_to_section(section_name, verb_name, config): Add a verb to a specific sectionget_document(): Get the current document as a dictionaryrender_document(): Get the current document as a JSON string
A verb's body is an object for most verbs. A few take a string, number or array, and add_verb and add_verb_to_section keep it as given:
self.add_verb("label", "start")
self.add_verb("unset", ["temp_a", "temp_b"])
self.add_verb("sleep", 2000) # milliseconds; -1 sleeps until the call ends
self.add_verb("return", "done")Each verb also has a method of its own, taking the body positionally or its options as keywords: self.label("start"), self.connect({"to": "+15551234567"}) or self.connect(to="+15551234567"). return is a Python keyword, so its method is return_(). On a SWMLBuilder the same methods return the builder, for chaining.
The SWMLService class provides validation for SWML verbs using the SignalWire schema.
When adding a verb, the service validates it against the schema to ensure it has the correct structure and parameters.
# This will validate the configuration against the schema
self.add_verb("play", {
"url": "say:Hello, world!",
"volume": 5
})
# This would fail validation (invalid parameter)
self.add_verb("play", {
"invalid_param": "value"
})A body that doesn't fit the verb raises SchemaValidationError, and nothing is added. A sleep duration must be a positive number of milliseconds or -1. With validation off (schema_validation=False), any JSON body is added as given.
An explicit schema_path that can't be loaded, because it's missing or isn't valid JSON, raises ValueError when the service is created, naming the path and the cause.
You can register custom verb handlers for specialized verb processing:
from signalwire.core.swml_handler import SWMLVerbHandler
class CustomPlayHandler(SWMLVerbHandler):
def __init__(self):
super().__init__("play")
def validate_config(self, config):
# Custom validation logic
return True, []
def build_config(self, **kwargs):
# Custom configuration building
return kwargs
service.register_verb_handler(CustomPlayHandler())The SWMLService class includes built-in web service capabilities for serving SWML documents.
By default, a service provides the following endpoints:
GET /route: Return the SWML documentPOST /route: Process request data and return the SWML documentGET /route/: Same asGET /route, but with a trailing slashPOST /route/: Same asPOST /route, but with a trailing slash
Where route is the route path specified when creating the service.
Basic authentication is automatically set up for all endpoints. Credentials are generated if not provided, or can be specified:
service = SWMLService(
name="my-service",
basic_auth=("username", "password")
)You can also set credentials using environment variables:
SWML_BASIC_AUTH_USERSWML_BASIC_AUTH_PASSWORD
You can override the on_request method to customize SWML documents based on request data:
def on_request(self, request_data=None, callback_path=None):
if not request_data:
return None
# Customize document based on request_data
self.reset_document()
self.add_verb("answer", {})
# Add custom verbs based on request_data
if request_data.get("caller_type") == "vip":
self.add_verb("play", {
"url": "say:Welcome VIP caller!"
})
else:
self.add_verb("play", {
"url": "say:Welcome caller!"
})
# Return modifications to the document
# or None to use the document we've built without modifications
return NoneThe SWMLService class allows you to register custom routing callbacks that can examine incoming requests and determine where they should be routed.
You can use the register_routing_callback method to register a function that will be called to process requests to a specific path. The callback receives the parsed request body and the request headers, both as plain dictionaries:
def my_routing_callback(body, headers):
"""
Process incoming requests and determine routing
Args:
body: Parsed JSON body as a dictionary
headers: Request headers as a dictionary
Returns:
Optional[str]: If a string is returned, the request will be redirected to that URL.
If None is returned, the request will be processed normally.
"""
# Example: Route based on a field in the request body
if "customer_id" in body:
customer_id = body["customer_id"]
return f"/customer/{customer_id}"
# Process request normally
return None
# Register the callback for a specific path
service.register_routing_callback(my_routing_callback, path="/customer")Routing proceeds in these steps:
- When a request is received at the registered path, the routing callback is executed
- The callback inspects the request and can decide whether to redirect it
- If the callback returns a URL string, the request is redirected with HTTP 307 (temporary redirect)
- If the callback returns
None, the request is processed normally by theon_requestmethod
You can use the callback_path parameter passed to on_request to serve different content for different paths:
def on_request(self, request_data=None, callback_path=None):
"""
Called when SWML is requested
Args:
request_data: Optional dictionary containing the parsed POST body
callback_path: Optional callback path from the request
Returns:
Optional dict to modify/augment the SWML document
"""
# Serve different content based on the callback path
if callback_path == "/customer":
return {
"sections": {
"main": [
{"answer": {}},
{"play": {"url": "say:Welcome to customer service!"}}
]
}
}
elif callback_path == "/product":
return {
"sections": {
"main": [
{"answer": {}},
{"play": {"url": "say:Welcome to product support!"}}
]
}
}
# Default content
return NoneHere's an example of a service that uses routing callbacks to handle different types of requests:
from signalwire.core.swml_service import SWMLService
from typing import Dict, Any, Optional
class MultiSectionService(SWMLService):
def __init__(self):
super().__init__(
name="multi-section",
route="/main"
)
# Create the main document
self.reset_document()
self.add_verb("answer", {})
self.add_verb("play", {"url": "say:Hello from the main service!"})
self.add_verb("hangup", {})
# Register customer and product routes
self.register_customer_route()
self.register_product_route()
def register_customer_route(self):
def customer_callback(body: Dict[str, Any], headers: Dict[str, Any]) -> Optional[str]:
# Check if we need to route to a specific customer ID
if "customer_id" in body:
customer_id = body["customer_id"]
# In a real implementation, you might redirect to another service
# Here we just log it and process normally
print(f"Processing request for customer ID: {customer_id}")
return None
# Register the callback at the /customer path
self.register_routing_callback(customer_callback, path="/customer")
# Create the customer SWML section
self.add_section("customer_section")
self.add_verb_to_section("customer_section", "answer", {})
self.add_verb_to_section("customer_section", "play",
{"url": "say:Welcome to customer service!"})
self.add_verb_to_section("customer_section", "hangup", {})
def register_product_route(self):
def product_callback(body: Dict[str, Any], headers: Dict[str, Any]) -> Optional[str]:
# Check if we need to route to a specific product ID
if "product_id" in body:
product_id = body["product_id"]
print(f"Processing request for product ID: {product_id}")
return None
# Register the callback at the /product path
self.register_routing_callback(product_callback, path="/product")
# Create the product SWML section
self.add_section("product_section")
self.add_verb_to_section("product_section", "answer", {})
self.add_verb_to_section("product_section", "play",
{"url": "say:Welcome to product support!"})
self.add_verb_to_section("product_section", "hangup", {})
def on_request(self, request_data=None, callback_path=None):
# Serve different content based on the callback path
if callback_path == "/customer":
return {
"sections": {
"main": self.get_document()["sections"]["customer_section"]
}
}
elif callback_path == "/product":
return {
"sections": {
"main": self.get_document()["sections"]["product_section"]
}
}
return NoneIn this example:
- The service registers two custom route paths:
/customerand/product - Each path has its own callback function to handle routing decisions
- The
on_requestmethod uses thecallback_pathto determine which content to serve - Different SWML sections are served for different paths
You can get a FastAPI router for the service to include in a larger application:
from fastapi import FastAPI
app = FastAPI()
service = SWMLService(name="my-service")
router = service.as_router()
app.include_router(router, prefix="/voice")AgentServer.register() takes a plain SWMLService as well as agents, so a call flow without AI, such as an IVR menu, can share a server with them. SIP routing can send calls to it like any agent:
from signalwire import AgentBase, AgentServer, SWMLService
support = AgentBase(name="support", route="/support")
support.prompt_add_section("Role", "You help callers with their accounts.")
menu = SWMLService(name="menu", route="/menu")
menu.add_verb("answer", {})
menu.add_verb("hangup", {})
server = AgentServer()
server.register(support, "/support")
server.register(menu, "/menu")
server.setup_sip_routing(route="/sip")
server.register_sip_username("menu", "/menu")
server.run()The service answers at its route with or without a trailing slash, checks its own basic auth credentials, and serves its /swaig endpoint and routing callbacks. The agent endpoints (/post_prompt, /check_for_input and /debug) aren't served for it. AgentServer's CGI and Lambda modes need agents.
You can specify a custom path to the schema file. A path that can't be loaded raises ValueError:
service = SWMLService(
name="my-service",
schema_path="/path/to/schema.json"
)SWMLService.__init__ accepts these parameters:
name: Service name/identifier (required)route: HTTP route path (default: "/")host: Host to bind to (default: "0.0.0.0")port: Port to bind to (default: 3000)basic_auth: Optional tuple of (username, password)schema_path: Optional path to schema.jsonconfig_file: Optional path to a JSON configuration fileschema_validation: Enable SWML schema validation (default: True)
The same document methods listed earlier are the public API:
reset_document()add_verb(verb_name, config)add_section(section_name)add_verb_to_section(section_name, verb_name, config)get_document()render_document()
These methods control the running service:
as_router(): Get a FastAPI router for the serviceserve(): Start the servicestop(): Stop the serviceget_basic_auth_credentials(include_source=False): Get the basic auth credentialson_request(request_data=None, callback_path=None): Called when SWML is requestedregister_routing_callback(callback_fn, path="/sip"): Register a callback for request routing
This shortcut works for any verb:
add_verb(verb_name, config): Add any SWML verb with configuration
This service answers, plays a greeting, and records a message:
from signalwire.core.swml_service import SWMLService
class VoicemailService(SWMLService):
def __init__(self, host="0.0.0.0", port=3000):
super().__init__(
name="voicemail",
route="/voicemail",
host=host,
port=port
)
# Build the SWML document
self.build_voicemail_document()
def build_voicemail_document(self):
"""Build the voicemail SWML document"""
# Reset the document
self.reset_document()
# Add answer verb
self.add_verb("answer", {})
# Add play verb for greeting
self.add_verb("play", {
"url": "say:Hello, you've reached the voicemail service. Please leave a message after the beep."
})
# Play a beep
self.add_verb("play", {
"url": "https://example.com/beep.wav"
})
# Record the message
self.add_verb("record", {
"format": "mp3",
"stereo": False,
"max_length": 120, # 2 minutes max
"terminators": "#"
})
# Thank the caller
self.add_verb("play", {
"url": "say:Thank you for your message. Goodbye!"
})
# Hang up
self.add_verb("hangup", {})
self.log.debug("voicemail_document_built")This service builds a different document for each department, based on the request data:
class CallRouterService(SWMLService):
def on_request(self, request_data=None, callback_path=None):
# If there's no request data, use default routing
if not request_data:
self.log.debug("no_request_data_using_default")
return None
# Create a new document
self.reset_document()
self.add_verb("answer", {})
# Get routing parameters
department = request_data.get("department", "").lower()
# Add play verb for greeting
self.add_verb("play", {
"url": f"say:Thank you for calling our {department} department. Please hold."
})
# Route based on department
phone_numbers = {
"sales": "+15551112222",
"support": "+15553334444",
"billing": "+15555556666"
}
# Get the appropriate number or use default
to_number = phone_numbers.get(department, "+15559990000")
# Connect to the department
self.add_verb("connect", {
"to": to_number,
"timeout": 30,
"answer_on_bridge": True
})
# Add fallback message and hangup
self.add_verb("play", {
"url": "say:We're sorry, but all of our agents are currently busy. Please try again later."
})
self.add_verb("hangup", {})
return None # Use the document we've builtFor more examples, see the examples directory in the SignalWire AI Agent SDK repository.