Skip to main content

Swaig Function

SWAIG Function API

Summary: API reference for defining SWAIG functions using decorators and programmatic methods.

Overview

SWAIG (SignalWire AI Gateway) functions are the primary way for AI agents to perform actions and retrieve information during conversations.

SWAIG Function Flow:

User speaks → AI decides to call function → Webhook invoked → Result
  1. AI determines a function should be called based on conversation
  2. SignalWire invokes the webhook with function arguments
  3. Function executes and returns SwaigFunctionResult
  4. AI uses the result to continue the conversation

Decorator Syntax

Basic Usage

from signalwire_agents import AgentBase
from signalwire_agents.core.function_result import SwaigFunctionResult

agent = AgentBase(name="my-agent")

@agent.tool(description="Search for information")
def search(query: str) -> SwaigFunctionResult:
results = perform_search(query)
return SwaigFunctionResult(f"Found: {results}")

Decorator Parameters

@agent.tool(
name: str = None, # Function name (default: function name)
description: str = "", # Function description (required)
secure: bool = False, # Require token authentication
fillers: List[str] = None, # Phrases to say while processing
wait_file: str = None, # Audio URL to play while processing
meta_data: Dict = None, # Custom metadata
meta_data_token: str = None # Token for metadata access
)

Decorator Parameter Details

ParameterTypeDescription
namestrOverride function name
descriptionstrWhat the function does (shown to AI)
secureboolRequire per-call token authentication
fillersList[str]Phrases like "Let me check on that..."
wait_filestrHold music URL during processing
meta_dataDictStatic metadata for the function
meta_data_tokenstrToken scope for metadata access

Parameter Types

Function parameters are automatically converted to JSON Schema:

@agent.tool(description="Book a reservation")
def book_reservation(
name: str, # Required string
party_size: int, # Required integer
date: str, # Required string
time: str = "7:00 PM", # Optional with default
special_requests: str = None # Optional, nullable
) -> SwaigFunctionResult:
...

Generated parameter schema:

{
"type": "object",
"properties": {
"name": {"type": "string", "description": "name parameter"},
"party_size": {"type": "integer", "description": "party_size parameter"},
"date": {"type": "string", "description": "date parameter"},
"time": {"type": "string", "description": "time parameter"},
"special_requests": {"type": "string", "description": "special_requests parameter"}
},
"required": ["name", "party_size", "date"]
}

Type Mapping

Python TypeJSON Schema TypeNotes
strstringBasic string
intintegerWhole numbers
floatnumberDecimal numbers
boolbooleanTrue/False
listarrayList of items
dictobjectKey-value pairs
Optional[T]T (nullable)Optional parameter

Programmatic Definition

define_tool Method

agent.define_tool(
name="search",
description="Search for information",
parameters={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query"
},
"limit": {
"type": "integer",
"description": "Maximum results",
"default": 10
}
},
"required": ["query"]
},
handler=search_handler,
secure=False,
fillers=["Searching now..."]
)

Handler Function Signature

Handler functions receive parsed arguments and raw data:

def my_handler(
args: Dict[str, Any], # Parsed function arguments
raw_data: Dict[str, Any] # Complete POST data
) -> SwaigFunctionResult:
# args contains: {"query": "...", "limit": 10}
# raw_data contains full request including metadata
return SwaigFunctionResult("Result")

Raw Data Contents

The raw_data parameter contains:

{
"function": "function_name",
"argument": {
"parsed": [{"name": "...", "value": "..."}]
},
"call_id": "uuid-call-id",
"global_data": {"key": "value"},
"meta_data": {"key": "value"},
"caller_id_name": "Caller Name",
"caller_id_number": "+15551234567",
"ai_session_id": "uuid-session-id"
}

Accessing Raw Data

@agent.tool(description="Process order")
def process_order(order_id: str, args=None, raw_data=None) -> SwaigFunctionResult:
# Get global data
global_data = raw_data.get("global_data", {})
user_id = global_data.get("user_id")

# Get caller info
caller_number = raw_data.get("caller_id_number")

# Get session info
call_id = raw_data.get("call_id")

return SwaigFunctionResult(f"Order {order_id} processed")

Secure Functions

Secure functions require token authentication per call:

@agent.tool(
description="Access sensitive data",
secure=True
)
def get_account_info(account_id: str) -> SwaigFunctionResult:
# This function requires a valid token
return SwaigFunctionResult(f"Account info for {account_id}")

Fillers and Wait Files

Keep users engaged during processing:

## Text fillers - AI speaks these while processing
@agent.tool(
description="Search database",
fillers=[
"Let me search for that...",
"One moment please...",
"Checking our records..."
]
)
def search_database(query: str) -> SwaigFunctionResult:
...

## Wait file - Play audio while processing
@agent.tool(
description="Long operation",
wait_file="https://example.com/hold_music.mp3"
)
def long_operation(data: str) -> SwaigFunctionResult:
...

Return Value Requirements

IMPORTANT: All SWAIG functions MUST return SwaigFunctionResult:

## Correct
@agent.tool(description="Get info")
def get_info(id: str) -> SwaigFunctionResult:
return SwaigFunctionResult("Information retrieved")

## WRONG - Never return plain strings
@agent.tool(description="Get info")
def get_info(id: str) -> str:
return "Information retrieved" # This will fail!

Complete Example

#!/usr/bin/env python3
## order_functions_agent.py - Agent with various SWAIG function patterns
from signalwire_agents import AgentBase
from signalwire_agents.core.function_result import SwaigFunctionResult

agent = AgentBase(name="order-agent", route="/orders")

## Simple function
@agent.tool(description="Get order status")
def get_order_status(order_id: str) -> SwaigFunctionResult:
status = lookup_order(order_id)
return SwaigFunctionResult(f"Order {order_id} is {status}")

## Function with multiple parameters
@agent.tool(description="Place a new order")
def place_order(
product: str,
quantity: int = 1,
shipping: str = "standard"
) -> SwaigFunctionResult:
order_id = create_order(product, quantity, shipping)
return SwaigFunctionResult(f"Order {order_id} placed successfully")

## Secure function with fillers
@agent.tool(
description="Cancel an order",
secure=True,
fillers=["Let me process that cancellation..."]
)
def cancel_order(order_id: str, reason: str = None) -> SwaigFunctionResult:
cancel_result = do_cancel(order_id, reason)
return SwaigFunctionResult(f"Order {order_id} has been cancelled")

## Function that returns actions
@agent.tool(description="Transfer to support")
def transfer_to_support(issue_type: str) -> SwaigFunctionResult:
return (
SwaigFunctionResult("I'll transfer you to our support team")
.connect("+15551234567", final=True)
)

if __name__ == "__main__":
agent.run()

See Also

TopicReference
Function results and actionsSwaigFunctionResult API
Serverless API integrationDataMap API
Testing functionsswaig-test CLI
Defining functions guideDefining Functions

Troubleshooting

IssueSolution
Function not appearing in --list-toolsEnsure decorator has description parameter
Function not being calledCheck webhook URL accessibility; use swaig-test --exec to test locally
Wrong parameters receivedVerify parameter types match expected JSON schema types
Return value ignoredMust return SwaigFunctionResult, not plain string