> For a complete index of all SignalWire documentation pages, fetch https://signalwire.com/docs/llms.txt

# AgentBase

> The central class for building AI-powered voice agents with SignalWire.

[swmlservice]: /docs/server-sdks/reference/python/agents/swml-service

[ai]: /docs/swml/reference/ai

[swml-reference]: /docs/swml/reference/ai

[agentserver]: /docs/server-sdks/reference/python/agents/agent-server

[add-skill]: /docs/server-sdks/reference/python/agents/agent-base/add-skill

[list-skills]: /docs/server-sdks/reference/python/agents/agent-base/list-skills

[configloader]: /docs/server-sdks/reference/python/agents/configuration/config-loader

[set-native-functions]: /docs/server-sdks/reference/python/agents/agent-base/native-functions

[addanswerverb]: /docs/server-sdks/reference/python/agents/agent-base/add-answer-verb

[addfunctioninclude]: /docs/server-sdks/reference/python/agents/agent-base/add-function-include

[addhint]: /docs/server-sdks/reference/python/agents/agent-base/add-hint

[addhints]: /docs/server-sdks/reference/python/agents/agent-base/add-hints

[addinternalfiller]: /docs/server-sdks/reference/python/agents/agent-base/add-internal-filler

[addlanguage]: /docs/server-sdks/reference/python/agents/agent-base/add-language

[addmcpserver]: /docs/server-sdks/reference/python/agents/agent-base/add-mcp-server

[addpatternhint]: /docs/server-sdks/reference/python/agents/agent-base/add-pattern-hint

[addpostaiverb]: /docs/server-sdks/reference/python/agents/agent-base/add-post-ai-verb

[addpostanswerverb]: /docs/server-sdks/reference/python/agents/agent-base/add-post-answer-verb

[addpreanswerverb]: /docs/server-sdks/reference/python/agents/agent-base/add-pre-answer-verb

[addpronunciation]: /docs/server-sdks/reference/python/agents/agent-base/add-pronunciation

[addskill]: /docs/server-sdks/reference/python/agents/agent-base/add-skill

[addswaigqueryparams]: /docs/server-sdks/reference/python/agents/agent-base/add-swaig-query-params

[asrouter]: /docs/server-sdks/reference/python/agents/agent-base/as-router

[clearpostaiverbs]: /docs/server-sdks/reference/python/agents/agent-base/clear-post-ai-verbs

[clearpostanswerverbs]: /docs/server-sdks/reference/python/agents/agent-base/clear-post-answer-verbs

[clearpreanswerverbs]: /docs/server-sdks/reference/python/agents/agent-base/clear-pre-answer-verbs

[clearswaigqueryparams]: /docs/server-sdks/reference/python/agents/agent-base/clear-swaig-query-params

[definecontexts]: /docs/server-sdks/reference/python/agents/agent-base/define-contexts

[definetool]: /docs/server-sdks/reference/python/agents/agent-base/define-tool

[enabledebugevents]: /docs/server-sdks/reference/python/agents/agent-base/enable-debug-events

[enablemcpserver]: /docs/server-sdks/reference/python/agents/agent-base/enable-mcp-server

[enablesiprouting]: /docs/server-sdks/reference/python/agents/agent-base/enable-sip-routing

[getapp]: /docs/server-sdks/reference/python/agents/agent-base/get-app

[getbasicauthcredentials]: /docs/server-sdks/reference/python/agents/agent-base/get-basic-auth-credentials

[getfullurl]: /docs/server-sdks/reference/python/agents/agent-base/get-full-url

[getname]: /docs/server-sdks/reference/python/agents/agent-base/get-name

[getpostprompt]: /docs/server-sdks/reference/python/agents/agent-base/get-post-prompt

[getprompt]: /docs/server-sdks/reference/python/agents/agent-base/get-prompt

[hasskill]: /docs/server-sdks/reference/python/agents/agent-base/has-skill

[listskills]: /docs/server-sdks/reference/python/agents/agent-base/list-skills

[manualsetproxyurl]: /docs/server-sdks/reference/python/agents/agent-base/manual-set-proxy-url

[setnativefunctions]: /docs/server-sdks/reference/python/agents/agent-base/native-functions

[ondebugevent]: /docs/server-sdks/reference/python/agents/agent-base/on-debug-event

[onsummary]: /docs/server-sdks/reference/python/agents/agent-base/on-summary

[promptaddsection]: /docs/server-sdks/reference/python/agents/agent-base/prompt-add-section

[promptaddsubsection]: /docs/server-sdks/reference/python/agents/agent-base/prompt-add-subsection

[promptaddtosection]: /docs/server-sdks/reference/python/agents/agent-base/prompt-add-to-section

[prompthassection]: /docs/server-sdks/reference/python/agents/agent-base/prompt-has-section

[registerroutingcallback]: /docs/server-sdks/reference/python/agents/agent-base/register-routing-callback

[registersipusername]: /docs/server-sdks/reference/python/agents/agent-base/register-sip-username

[registerswaigfunction]: /docs/server-sdks/reference/python/agents/agent-base/register-swaig-function

[removeskill]: /docs/server-sdks/reference/python/agents/agent-base/remove-skill

[resetcontexts]: /docs/server-sdks/reference/python/agents/agent-base/reset-contexts

[run]: /docs/server-sdks/reference/python/agents/agent-base/run

[serve]: /docs/server-sdks/reference/python/agents/agent-base/serve

[serverless]: /docs/server-sdks/reference/python/agents/agent-base/serverless

[setdynamicconfigcallback]: /docs/server-sdks/reference/python/agents/agent-base/set-dynamic-config-callback

[setfunctionincludes]: /docs/server-sdks/reference/python/agents/agent-base/set-function-includes

[setglobaldata]: /docs/server-sdks/reference/python/agents/agent-base/set-global-data

[setinternalfillers]: /docs/server-sdks/reference/python/agents/agent-base/set-internal-fillers

[setlanguages]: /docs/server-sdks/reference/python/agents/agent-base/set-languages

[setparam]: /docs/server-sdks/reference/python/agents/agent-base/set-param

[setparams]: /docs/server-sdks/reference/python/agents/agent-base/set-params

[setpostprompt]: /docs/server-sdks/reference/python/agents/agent-base/set-post-prompt

[setpostpromptllmparams]: /docs/server-sdks/reference/python/agents/agent-base/set-post-prompt-llm-params

[setpostprompturl]: /docs/server-sdks/reference/python/agents/agent-base/set-post-prompt-url

[setpromptllmparams]: /docs/server-sdks/reference/python/agents/agent-base/set-prompt-llm-params

[setpromptpom]: /docs/server-sdks/reference/python/agents/agent-base/set-prompt-pom

[setprompttext]: /docs/server-sdks/reference/python/agents/agent-base/set-prompt-text

[setpronunciations]: /docs/server-sdks/reference/python/agents/agent-base/set-pronunciations

[setupgracefulshutdown]: /docs/server-sdks/reference/python/agents/agent-base/setup-graceful-shutdown

[setwebhookurl]: /docs/server-sdks/reference/python/agents/agent-base/set-web-hook-url

[updateglobaldata]: /docs/server-sdks/reference/python/agents/agent-base/update-global-data

[validatebasicauth]: /docs/server-sdks/reference/python/agents/agent-base/validate-basic-auth

[automapsipusernames]: /docs/server-sdks/reference/python/agents/agent-base/auto-map-sip-usernames

[definetools]: /docs/server-sdks/reference/python/agents/agent-base/define-tools

[enabledebugroutes]: /docs/server-sdks/reference/python/agents/agent-base/enable-debug-routes

[onfunctioncall]: /docs/server-sdks/reference/python/agents/agent-base/on-function-call

[onswmlrequest]: /docs/server-sdks/reference/python/agents/agent-base/on-swml-request

[ref-datamap]: /docs/server-sdks/reference/python/agents/data-map

`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`][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`][ai] verb.
See the [SWML reference][swml-reference] for the full specification of all
supported parameters and behaviors.

## **Properties**

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

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

Network interface the web server binds to.

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

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

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

Manager instance for loading and unloading skills. Access via
[`add_skill()`][add-skill] and
[`list_skills()`][list-skills] rather
than directly.

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

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.

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

Expiration time in seconds for SWAIG function authentication tokens.

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

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

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

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

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

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

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

Allow dynamic per-request override of input checking behavior.

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

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()`][set-native-functions].

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

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

SignalWire Signing Key (Dashboard → API Credentials). When set, webhook signature
validation is enforced on the `POST /`, `/swaig`, and `/post_prompt` endpoints, and
unsigned or invalidly-signed requests receive an HTTP `403`. Falls back to the
`SIGNALWIRE_SIGNING_KEY` environment variable when not passed. When unset, the SDK
logs a one-time startup warning.

If `True`, honor the `X-Forwarded-Proto` / `X-Forwarded-Host` headers when
reconstructing the request URL during signature validation. Defaults to `False`
because proxy headers are spoofable; opt in only when you control the proxy chain.

When `signing_key` is set, the `POST /`, `/swaig`, and `/post_prompt` endpoints are
signature-validated. The `X-SignalWire-Signature` request header carries the signature,
and `X-Twilio-Signature` is accepted as an alias for compatibility with legacy callers.

## **Decorators**

### tool

```python {7}
from signalwire import AgentBase
from signalwire.core.function_result import FunctionResult

agent = AgentBase(name="assistant", route="/assistant")
agent.set_prompt_text("You are a helpful assistant.")

@agent.tool(name=None, description=None, parameters=None, secure=True, fillers=None, webhook_url=None, required=None)
def my_tool(args, raw_data=None):
    return FunctionResult("Done.")

agent.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

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

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.

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

Require token validation on tool calls.

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

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

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

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

## **Examples**

### Instance decorator with type inference

```python {7}
from signalwire import AgentBase
from signalwire.core.function_result import FunctionResult

agent = AgentBase(name="assistant", route="/assistant")
agent.set_prompt_text("You are a helpful assistant.")

@agent.tool(description="Look up a customer's order status")
def check_order(args, raw_data=None):
    order_id = args.get("order_id")
    return FunctionResult(f"Order {order_id} shipped March 28.")

agent.serve()
```

### With explicit parameters

```python
from signalwire import AgentBase
from signalwire.core.function_result import FunctionResult

agent = AgentBase(name="assistant", route="/assistant")
agent.set_prompt_text("You are a helpful assistant.")

@agent.tool(
    name="search_products",
    description="Search the product catalog",
    parameters={
        "type": "object",
        "properties": {
            "query": {"type": "string", "description": "Search query"},
            "category": {"type": "string", "description": "Product category"}
        }
    },
    required=["query"],
    fillers={"en-US": ["Searching...", "Let me find that..."]}
)
def search_products(args, raw_data=None):
    query = args.get("query")
    return FunctionResult(f"Found 3 results for '{query}'.")

agent.serve()
```

### Class decorator (subclass)

```python
from signalwire import AgentBase
from signalwire.core.function_result import FunctionResult

class SupportAgent(AgentBase):
    @AgentBase.tool(description="Transfer to a human agent")
    def transfer_to_human(self, args, raw_data=None):
        return FunctionResult("Transferring now.").connect("+15551234567")

agent = SupportAgent(name="support", route="/support")
agent.serve()
```

### Typed parameters (auto-inferred schema)

```python
from signalwire import AgentBase
from signalwire.core.function_result import FunctionResult

agent = AgentBase(name="assistant", route="/assistant")
agent.set_prompt_text("You are a helpful assistant.")

@agent.tool(description="Calculate shipping cost")
def calculate_shipping(weight_kg: float, destination: str, express: bool = False):
    cost = weight_kg * 2.50 if not express else weight_kg * 5.00
    return FunctionResult(f"Shipping to {destination}: ${cost:.2f}")

agent.serve()
```

### Basic agent with a tool

```python {4}
from signalwire import AgentBase
from signalwire.core.function_result import FunctionResult

agent = AgentBase(name="support-agent", route="/support")

agent.add_language("English", "en-US", "rime.spore")
agent.set_prompt_text("You are a friendly customer support agent.")
agent.add_hints(["SignalWire", "SWML", "SWAIG"])
agent.set_params({"temperature": 0.7, "end_of_speech_timeout": 1000})

@agent.tool(description="Look up an order by ID")
def lookup_order(args, raw_data=None):
    order_id = args.get("order_id")
    return FunctionResult(f"Order {order_id} shipped on March 28.")

agent.run()
```

## **Methods**

Configure the answer verb that connects the call.

Add a remote function include to the SWAIG configuration.

Add a single speech recognition hint to improve transcription accuracy.

Add multiple speech recognition hints at once.

Add filler phrases for a specific native function and language.

Add a language configuration with voice settings for multilingual conversations.

Add an external MCP server for tool discovery and invocation.

Add a speech recognition hint with pattern matching and replacement.

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

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

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

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

Load and activate a skill on the agent.

Append query parameters to all SWAIG webhook URLs.

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

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

Remove all post-AI verbs from the call flow.

Remove all post-answer verbs from the call flow.

Remove all pre-answer verbs from the call flow.

Remove all SWAIG query parameters from the agent.

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

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

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

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

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

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

Enable SIP-based call routing for this agent.

Get the FastAPI application instance for use with deployment adapters.

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

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

Retrieve the per-language params dict previously set on an added language.

Get the agent's display name.

Retrieve the current post-prompt text.

Retrieve the current prompt configured on the agent.

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

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

Manually set the proxy URL base for webhook callbacks.

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

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

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

Handle post-prompt summaries generated after a conversation ends.

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

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

Add a subsection to an existing prompt section.

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

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

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

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

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

Unload a skill from the agent.

Remove all contexts from the agent, returning it to a no-contexts state.

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

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

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

Set a callback for per-request dynamic agent configuration.

Set the complete list of remote function includes.

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

Set filler phrases for native SWAIG functions.

Set or replace the per-language params on an already-added language.

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

Set a single AI parameter by key.

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

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

Set LLM parameters specifically for the post-prompt.

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

Set LLM parameters specifically for the main prompt.

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

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

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

Register signal handlers for graceful shutdown in containerized deployments.

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

Update the global data dictionary with new values.

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