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.

AgentBase uses composition internally, assembling functionality from PromptManager, SwmlBuilder, SessionManager, ContextBuilder, and SkillManager. All setter methods return this 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.

Constructor

1import { AgentBase } from '@signalwire/sdk';
2
3const agent = new AgentBase({
4 name: 'support',
5 route: '/support',
6});

Constructor Parameters

name
stringRequired

Display name of the agent. Used in logging, SIP username mapping, and the default prompt fallback.

route
stringDefaults to /

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

host
stringDefaults to 0.0.0.0

Network interface the HTTP server binds to.

port
number

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

basicAuth
[string, string]

Explicit [username, password] tuple 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.

usePom
booleanDefaults to true

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

tokenExpirySecs
numberDefaults to 900

Expiration time in seconds for SWAIG function authentication tokens.

autoAnswer
booleanDefaults to true

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

recordCall
booleanDefaults to false

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

recordFormat
stringDefaults to mp4

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

recordStereo
booleanDefaults to true

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

defaultWebhookUrl
string

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

nativeFunctions
string[]

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

agentId
string

Unique identifier for this agent instance. Auto-generated as a random hex string if not provided.

suppressLogs
boolean

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

Properties

name
string

The agent’s display name. Set at construction time.

route
string

HTTP route path where this agent is served.

host
string

Network interface the HTTP server binds to.

port
number

Port the HTTP server listens on.

agentId
string

Unique identifier for this agent instance.

Static Members

PROMPT_SECTIONS
Array<{ title: string; body?: string; bullets?: string[]; numbered?: boolean }>

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

Examples

Basic agent with a tool

1import { AgentBase, FunctionResult } from '@signalwire/sdk';
2
3const agent = new AgentBase({ name: 'support-agent', route: '/support' });
4
5agent.addLanguage({ name: 'English', code: 'en-US', voice: 'rime.spore' });
6agent.setPromptText('You are a friendly customer support agent.');
7agent.addHints(['SignalWire', 'SWML', 'SWAIG']);
8agent.setParams({ temperature: 0.7, end_of_speech_timeout: 1000 });
9
10agent.defineTool({
11 name: 'check_order',
12 description: 'Look up the status of a customer order',
13 parameters: {
14 type: 'object',
15 properties: {
16 order_id: { type: 'string', description: 'The order ID to look up' },
17 },
18 },
19 required: ['order_id'],
20 handler: async (args) => {
21 const orderId = args.order_id;
22 return new FunctionResult(`Order ${orderId} shipped on March 28.`);
23 },
24});
25
26await agent.run();

Subclass with declarative prompt sections

1import { AgentBase, FunctionResult } from '@signalwire/sdk';
2
3class SupportAgent extends AgentBase {
4 static override PROMPT_SECTIONS = [
5 {
6 title: 'Role',
7 body: 'You are a customer support agent for Acme Corp.',
8 },
9 {
10 title: 'Guidelines',
11 bullets: ['Be polite and professional', 'Escalate billing disputes'],
12 },
13 ];
14
15 protected override defineTools(): void {
16 this.defineTool({
17 name: 'transfer_call',
18 description: 'Transfer the caller to a live agent',
19 handler: async () => {
20 return new FunctionResult('Transferring now.').connect('+15551234567');
21 },
22 });
23 }
24}
25
26const agent = new SupportAgent({ name: 'support', route: '/support' });
27await agent.run();

Methods

addAnswerVerb

Configure the answer verb that connects the call.

addFunctionInclude

Add a remote function include to the SWAIG configuration.

addHint

Add a single speech recognition hint to improve transcription accuracy.

addHints

Add multiple speech recognition hints at once.

addInternalFiller

Add filler phrases for a specific function and language.

addLanguage

Add a language configuration with voice settings for multilingual conversations.

addMcpServer

Add an external MCP server for tool discovery and invocation.

addPatternHint

Add a speech recognition hint with pattern matching and replacement.

addPostAiVerb

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

addPostAnswerVerb

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

addPreAnswerVerb

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

addPronunciation

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

addSkill

Load and activate a skill on the agent.

addSwaigQueryParams

Append query parameters to all SWAIG webhook URLs.

asRouter

Get the agent’s Hono app for mounting as a sub-router.

clearPostAiVerbs

Remove all post-AI verbs from the call flow.

clearPostAnswerVerbs

Remove all post-answer verbs from the call flow.

clearPreAnswerVerbs

Remove all pre-answer verbs from the call flow.

defineContexts

Define multi-step conversation contexts and workflows.

defineTool

Define a SWAIG tool that the AI can invoke during conversations.

defineTypedTool

Define a tool with a typed handler and automatic schema inference.

defineTools

Override hook that registers tools during construction.

enableDebugEvents

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

enableMcpServer

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

enableSipRouting

Enable SIP-based call routing for this agent.

extractSipUsername

Extract a SIP username from a request body (static method).

getApp

Get the Hono application instance.

getBasicAuthCredentials

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

getFullUrl

Get the full URL for this agent’s endpoint.

getMcpServers

Get the list of configured MCP servers.

getName

Get the agent’s display name.

getPostPrompt

Retrieve the current post-prompt text.

getPrompt

Retrieve the current rendered prompt text.

getRegisteredTools

Get summaries of all registered tools.

getTool

Look up a registered tool by name.

handleMcpRequest

Handle an MCP JSON-RPC 2.0 request.

hasSkill

Check whether a specific skill is currently loaded.

isMcpServerEnabled

Check if the MCP server endpoint is enabled.

listSkills

List all currently loaded skills.

manualSetProxyUrl

Manually set the proxy URL base for webhook callbacks.

setNativeFunctions

Set the list of native platform functions.

onDebugEvent

Lifecycle hook for debug events received at /debug_events.

onFunctionCall

Pre-execution hook called before each SWAIG function invocation.

onSummary

Handle post-prompt summaries generated after a conversation ends.

onSwmlRequest

Lifecycle hook called on every SWML request before rendering.

promptAddSection

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

promptAddSubsection

Add a subsection to an existing prompt section.

promptAddToSection

Append content to an existing prompt section.

promptHasSection

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

registerSipUsername

Register a SIP username to route calls to this agent.

registerSwaigFunction

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

removeSkill

Unload a skill from the agent.

renderSwml

Render the complete SWML document.

run

Start the HTTP server (alias for serve).

serve

Start the Hono HTTP server to serve SWML and SWAIG endpoints.

setDynamicConfigCallback

Set a callback for per-request dynamic agent configuration.

setGlobalData

Replace the global data object available to the AI.

setLanguages

Replace all language configurations at once.

setParam

Set a single AI parameter by key.

setParams

Configure AI model parameters such as temperature and timeouts.

setPostPrompt

Set the post-prompt for generating call summaries.

setPostPromptLlmParams

Set LLM parameters for the post-prompt.

setPostPromptUrl

Override the URL where post-prompt summaries are delivered.

setPromptLlmParams

Set LLM parameters for the main prompt.

setPromptText

Set the agent’s system prompt as raw text.

setupGracefulShutdown

Register signal handlers for graceful shutdown (static method).

setWebHookUrl

Override the default webhook URL for SWAIG function calls.

updateGlobalData

Merge data into the global data object.

validateBasicAuth

Custom basic-auth validation hook.