Agents

AgentBase

View as MarkdownOpen in Claude

AgentBase is the central class in the SignalWire AI Agents SDK. It provides a complete framework for building AI-powered voice agents, combining prompt management, tool definitions, skill loading, speech configuration, and web serving into a single composable interface.

Extends SWMLService and composes functionality from nine mixins: PromptMixin, ToolMixin, SkillMixin, AIConfigMixin, WebMixin, AuthMixin, ServerlessMixin, StateMixin, and MCPServerMixin.

All setter methods return self for fluent method chaining.

AgentBase generates a SWML document with the ai verb. See the SWML reference for the full specification of all supported parameters and behaviors.

Properties

name
str

The agent’s display name. Set at construction time. Used in logging, SIP username mapping, and the default prompt fallback.

route
strDefaults to /

HTTP route path where this agent is served. Used by AgentServer when hosting multiple agents on one process.

host
strDefaults to 0.0.0.0

Network interface the web server binds to.

port
int

Port the web server listens on. Defaults to the PORT environment variable, falling back to 3000.

agent_id
str

Unique identifier for this agent instance. Auto-generated as a UUID if not provided.

pom
PromptObjectModel | None

The Prompt Object Model instance used for structured prompt building. None when use_pom=False.

skill_manager
SkillManager

Manager instance for loading and unloading skills. Access via add_skill() and list_skills() rather than directly.

PROMPT_SECTIONS
dict | list | NoneDefaults to None

Class-level attribute. Subclasses can set this to declaratively define prompt sections instead of calling prompt_add_section() in the constructor.

basic_auth
Optional[tuple[str, str]]

Explicit (username, password) for HTTP Basic Auth on all endpoints. If not set, credentials are read from SWML_BASIC_AUTH_USER / SWML_BASIC_AUTH_PASSWORD env vars, or auto-generated on startup.

use_pom
boolDefaults to True

Enable Prompt Object Model for structured prompt building. Set to False to use plain text prompts only.

token_expiry_secs
intDefaults to 3600

Expiration time in seconds for SWAIG function authentication tokens.

auto_answer
boolDefaults to True

Automatically add an answer verb before the AI verb in the SWML document.

record_call
boolDefaults to False

Enable call recording. When True, a record_call verb is added to the SWML document.

record_format
strDefaults to mp4

Recording file format. Common values: "mp4", "wav".

record_stereo
boolDefaults to True

Record in stereo (separate channels for each party) when True.

default_webhook_url
Optional[str]

Base URL for SWAIG function webhooks. If not set, the SDK auto-detects from the incoming request or uses SWML_PROXY_URL_BASE.

suppress_logs
boolDefaults to False

Suppress SDK log output. Useful in testing or when integrating with external logging.

enable_post_prompt_override
boolDefaults to False

Allow dynamic per-request override of the post-prompt configuration.

check_for_input_override
boolDefaults to False

Allow dynamic per-request override of input checking behavior.

config_file
Optional[str]

Path to a JSON config file. If not provided, the SDK searches default paths. See ConfigLoader.

native_functions
Optional[list[str]]

List of native SWAIG function names to enable at construction time (e.g., ["check_time", "wait_for_user"]). Can also be set later via set_native_functions().

schema_path
Optional[str]

Path to a custom SWML schema file for validation. If not provided, the SDK searches default paths automatically.

schema_validation
boolDefaults to True

Enable SWML schema validation. Disable with False or SWML_SKIP_SCHEMA_VALIDATION=1 env var.

Decorators

tool

1from signalwire import AgentBase
2from signalwire.core.function_result import FunctionResult
3
4agent = AgentBase(name="assistant", route="/assistant")
5agent.set_prompt_text("You are a helpful assistant.")
6
7@agent.tool(name=None, description=None, parameters=None, secure=True, fillers=None, webhook_url=None, required=None)
8def my_tool(args, raw_data=None):
9 return FunctionResult("Done.")
10
11agent.serve()

The @tool decorator is the recommended way to define SWAIG functions. Use @agent.tool() on a standalone function, or @AgentBase.tool() on a method inside a subclass. Both forms accept the same parameters.

When parameters are not explicitly provided, the decorator automatically infers the JSON Schema from Python type hints on the function signature.

Parameters

name
Optional[str]

Function name exposed to the AI. Defaults to the decorated function’s __name__.

description
Optional[str]

What the function does. The AI reads this to decide when to call it. Defaults to the function’s docstring, or "Function {name}" as a fallback.

parameters
Optional[dict[str, Any]]

Explicit JSON Schema for function parameters. If omitted, the schema is automatically inferred from Python type hints on the decorated function.

secure
boolDefaults to True

Require token validation on tool calls.

fillers
Optional[dict[str, list[str]]]

Filler phrases by language code, spoken while the function runs.

webhook_url
Optional[str]

External webhook URL. If set, SignalWire calls this URL instead of executing locally.

required
Optional[list[str]]

Required parameter names. Auto-inferred from type hints when not specified.

**swaig_fields
Any

Additional SWAIG fields (e.g., wait_file, meta_data).

Examples

Instance decorator with type inference

1from signalwire import AgentBase
2from signalwire.core.function_result import FunctionResult
3
4agent = AgentBase(name="assistant", route="/assistant")
5agent.set_prompt_text("You are a helpful assistant.")
6
7@agent.tool(description="Look up a customer's order status")
8def check_order(args, raw_data=None):
9 order_id = args.get("order_id")
10 return FunctionResult(f"Order {order_id} shipped March 28.")
11
12agent.serve()

With explicit parameters

1from signalwire import AgentBase
2from signalwire.core.function_result import FunctionResult
3
4agent = AgentBase(name="assistant", route="/assistant")
5agent.set_prompt_text("You are a helpful assistant.")
6
7@agent.tool(
8 name="search_products",
9 description="Search the product catalog",
10 parameters={
11 "type": "object",
12 "properties": {
13 "query": {"type": "string", "description": "Search query"},
14 "category": {"type": "string", "description": "Product category"}
15 }
16 },
17 required=["query"],
18 fillers={"en-US": ["Searching...", "Let me find that..."]}
19)
20def search_products(args, raw_data=None):
21 query = args.get("query")
22 return FunctionResult(f"Found 3 results for '{query}'.")
23
24agent.serve()

Class decorator (subclass)

1from signalwire import AgentBase
2from signalwire.core.function_result import FunctionResult
3
4class SupportAgent(AgentBase):
5 @AgentBase.tool(description="Transfer to a human agent")
6 def transfer_to_human(self, args, raw_data=None):
7 return FunctionResult("Transferring now.").connect("+15551234567")
8
9agent = SupportAgent(name="support", route="/support")
10agent.serve()

Typed parameters (auto-inferred schema)

1from signalwire import AgentBase
2from signalwire.core.function_result import FunctionResult
3
4agent = AgentBase(name="assistant", route="/assistant")
5agent.set_prompt_text("You are a helpful assistant.")
6
7@agent.tool(description="Calculate shipping cost")
8def calculate_shipping(weight_kg: float, destination: str, express: bool = False):
9 cost = weight_kg * 2.50 if not express else weight_kg * 5.00
10 return FunctionResult(f"Shipping to {destination}: ${cost:.2f}")
11
12agent.serve()

Basic agent with a tool

1from signalwire import AgentBase
2from signalwire.core.function_result import FunctionResult
3
4agent = AgentBase(name="support-agent", route="/support")
5
6agent.add_language("English", "en-US", "rime.spore")
7agent.set_prompt_text("You are a friendly customer support agent.")
8agent.add_hints(["SignalWire", "SWML", "SWAIG"])
9agent.set_params({"temperature": 0.7, "end_of_speech_timeout": 1000})
10
11@agent.tool(description="Look up an order by ID")
12def lookup_order(args, raw_data=None):
13 order_id = args.get("order_id")
14 return FunctionResult(f"Order {order_id} shipped on March 28.")
15
16agent.run()

Methods

add_answer_verb

Configure the answer verb that connects the call.

add_function_include

Add a remote function include to the SWAIG configuration.

add_hint

Add a single speech recognition hint to improve transcription accuracy.

add_hints

Add multiple speech recognition hints at once.

add_internal_filler

Add filler phrases for a specific native function and language.

add_language

Add a language configuration with voice settings for multilingual conversations.

add_mcp_server

Add an external MCP server for tool discovery and invocation.

add_pattern_hint

Add a speech recognition hint with pattern matching and replacement.

add_post_ai_verb

Add a SWML verb to run after the AI conversation ends.

add_post_answer_verb

Add a SWML verb to run after the call is answered but before the AI starts.

add_pre_answer_verb

Add a SWML verb to run before the call is answered.

add_pronunciation

Add a pronunciation rule to correct how the AI speaks a specific word or phrase.

add_skill

Load and activate a skill on the agent.

add_swaig_query_params

Append query parameters to all SWAIG webhook URLs.

as_router

Get the agent’s endpoints as a FastAPI APIRouter for mounting in larger applications.

auto_map_sip_usernames

Automatically register SIP usernames derived from the agent’s name and route.

clear_post_ai_verbs

Remove all post-AI verbs from the call flow.

clear_post_answer_verbs

Remove all post-answer verbs from the call flow.

clear_pre_answer_verbs

Remove all pre-answer verbs from the call flow.

clear_swaig_query_params

Remove all SWAIG query parameters from the agent.

define_contexts

Define multi-step conversation contexts and workflows for complex agent interactions.

define_tool

Programmatically define a SWAIG tool that the AI can invoke during conversations.

define_tools

Override hook that returns the list of SWAIG tools available to the AI.

enable_debug_events

Enable real-time debug event webhooks from the AI module during calls.

enable_debug_routes

Enable debug and testing routes on the agent’s HTTP server.

enable_mcp_server

Expose the agent’s tools as an MCP server endpoint.

enable_sip_routing

Enable SIP-based call routing for this agent.

get_app

Get the FastAPI application instance for use with deployment adapters.

get_basic_auth_credentials

Retrieve the agent’s Basic Auth credentials and their origin.

get_full_url

Get the full URL for this agent’s endpoint, including host, port, and route.

get_name

Get the agent’s display name.

get_post_prompt

Retrieve the current post-prompt text.

get_prompt

Retrieve the current prompt configured on the agent.

has_skill

Check whether a specific skill is currently loaded on the agent.

list_skills

List the names of all currently loaded skills on the agent.

manual_set_proxy_url

Manually set the proxy URL base for webhook callbacks.

set_native_functions

Enable built-in native functions that execute directly on the SignalWire platform.

on_debug_event

Register a callback for debug events received at the /debug_events endpoint.

on_function_call

Override hook called when a SWAIG function is invoked during a conversation.

on_summary

Handle post-prompt summaries generated after a conversation ends.

on_swml_request

Override hook for customizing the SWML document on a per-request basis.

prompt_add_section

Add a new section to the agent’s structured prompt.

prompt_add_subsection

Add a subsection to an existing prompt section.

prompt_add_to_section

Append content to an existing prompt section or create it if it does not exist.

prompt_has_section

Check whether a named section exists in the agent’s prompt.

register_routing_callback

Register a callback for dynamic request routing based on SIP URIs or POST data.

register_sip_username

Register a specific SIP username to route calls to this agent.

register_swaig_function

Register a raw SWAIG function dictionary, typically from a DataMap.

remove_skill

Unload a skill from the agent.

run

Smart entry point that auto-detects the runtime environment and starts the agent accordingly.

serve

Start a FastAPI/uvicorn web server to serve this agent’s SWML and SWAIG endpoints.

handle_serverless_request

Handle requests in serverless environments like AWS Lambda, Google Cloud Functions, and Azure Functions.

set_dynamic_config_callback

Set a callback for per-request dynamic agent configuration.

set_function_includes

Set the complete list of remote function includes.

set_global_data

Merge data into the global data dictionary available to the AI throughout a conversation.

set_internal_fillers

Set filler phrases for native SWAIG functions.

set_languages

Replace all language configurations at once with a list of raw language dictionaries.

set_param

Set a single AI parameter by key.

set_params

Configure AI model parameters such as temperature, timeouts, and speech recognition settings.

set_post_prompt

Set the post-prompt used for generating call summaries after a conversation ends.

set_post_prompt_llm_params

Set LLM parameters specifically for the post-prompt.

set_post_prompt_url

Override the default URL where post-prompt summaries are delivered.

set_prompt_llm_params

Set LLM parameters specifically for the main prompt.

set_prompt_pom

Set the prompt using a raw Prompt Object Model dictionary structure.

set_prompt_text

Set the agent’s system prompt as a raw text string.

set_pronunciations

Replace all pronunciation rules at once with a list of raw rule dictionaries.

setup_graceful_shutdown

Register signal handlers for graceful shutdown in containerized deployments.

set_web_hook_url

Override the default webhook URL used for SWAIG function calls in the SWML document.

update_global_data

Update the global data dictionary with new values.

validate_basic_auth

Validate HTTP Basic Auth credentials against the agent’s stored credentials.