SignalWire SWML Service Guide
Introduction
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 powerful capabilities out of the box.
Installation
The SWMLService
class is part of the SignalWire AI Agent SDK. Install it using pip:
pip install signalwire-agents
Basic Usage
Here's a simple example of creating an SWML service:
from signalwire_agents.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_answer_verb()
# Add play verb for greeting
self.add_verb("play", {
"url": "say:Hello, thank you for calling our service."
})
# Add hangup verb
self.add_hangup_verb()
# Create and start the service
service = SimpleVoiceService()
service.run()
Centralized Logging System
The SWMLService
class includes a centralized logging system based on structlog
that provides structured, JSON-formatted logs. This logging system is automatically set up when you import the module, so you don't need to configure it in each service or example.
How It Works
- When
swml_service.py
is imported, it configuresstructlog
(if not already configured) - Each
SWMLService
instance gets a logger bound to its service name - All logs include contextual information like service name, timestamp, and log level
- Logs are formatted as JSON for easy parsing and analysis
Using the Logger
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))
Log Levels
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
Suppressing Logs
To suppress logs when running a service, you can set the log level:
import logging
logging.getLogger().setLevel(logging.WARNING) # Only show warnings and above
You can also pass suppress_logs=True
when initializing an agent or service:
service = SWMLService(
name="my-service",
suppress_logs=True
)
SWML Document Creation
The SWMLService
class provides methods for creating and manipulating SWML documents.
Document Structure
SWML documents have the following basic structure:
{
"version": "1.0.0",
"sections": {
"main": [
{ "verb1": { /* configuration */ } },
{ "verb2": { /* configuration */ } }
],
"section1": [
{ "verb3": { /* configuration */ } }
]
}
}
Document Methods
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
Common Verb Shortcuts
add_answer_verb(max_duration=None, codecs=None)
: Add an answer verbadd_hangup_verb(reason=None)
: Add a hangup verbadd_ai_verb(prompt_text=None, prompt_pom=None, post_prompt=None, post_prompt_url=None, swaig=None, params=None)
: Add an AI verb
Verb Handling
The SWMLService
class provides validation for SWML verbs using the SignalWire schema.
Verb Validation
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"
})
Custom Verb Handlers
You can register custom verb handlers for specialized verb processing:
from signalwire_agents.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())
Web Service Features
The SWMLService
class includes built-in web service capabilities for serving SWML documents.
Endpoints
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 as above but with trailing slashPOST /route/
: Same as above but with trailing slash
Where route
is the route path specified when creating the service.
Authentication
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_USER
SWML_BASIC_AUTH_PASSWORD
Dynamic SWML Generation
You can override the on_swml_request
method to customize SWML documents based on request data:
def on_swml_request(self, request_data=None):
if not request_data:
return None
# Customize document based on request_data
self.reset_document()
self.add_answer_verb()
# 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 None
Custom Routing Callbacks
The SWMLService
class allows you to register custom routing callbacks that can examine incoming requests and determine where they should be routed.
Registering a Routing Callback
You can use the register_routing_callback
method to register a function that will be called to process requests to a specific path:
def my_routing_callback(request, body):
"""
Process incoming requests and determine routing
Args:
request: FastAPI Request object
body: Parsed JSON body 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")
How Routing Works
- 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_request
method
Serving Different Content for Different Paths
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 None