Swaig Function

View as Markdown

SWAIG Function API

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

1from signalwire_agents import AgentBase
2from signalwire_agents.core.function_result import SwaigFunctionResult
3
4agent = AgentBase(name="my-agent")
5
6@agent.tool(
7 description="Search for information",
8 parameters={
9 "type": "object",
10 "properties": {
11 "query": {"type": "string", "description": "Search query"}
12 },
13 "required": ["query"]
14 }
15)
16def search(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
17 query = args.get("query", "")
18 results = perform_search(query)
19 return SwaigFunctionResult(f"Found: {results}")

Decorator Parameters

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

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 Schema

Define parameters using JSON Schema in the decorator:

1@agent.tool(
2 description="Book a reservation",
3 parameters={
4 "type": "object",
5 "properties": {
6 "name": {"type": "string", "description": "Guest name"},
7 "party_size": {"type": "integer", "description": "Number of guests"},
8 "date": {"type": "string", "description": "Reservation date"},
9 "time": {"type": "string", "description": "Reservation time"},
10 "special_requests": {"type": "string", "description": "Special requests"}
11 },
12 "required": ["name", "party_size", "date"]
13 }
14)
15def book_reservation(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
16 name = args.get("name", "")
17 party_size = args.get("party_size", 1)
18 date = args.get("date", "")
19 time = args.get("time", "7:00 PM")
20 special_requests = args.get("special_requests")
21 # ... booking logic
22 return SwaigFunctionResult(f"Reservation booked for {name}")

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

1agent.define_tool(
2 name="search",
3 description="Search for information",
4 parameters={
5 "type": "object",
6 "properties": {
7 "query": {
8 "type": "string",
9 "description": "Search query"
10 },
11 "limit": {
12 "type": "integer",
13 "description": "Maximum results",
14 "default": 10
15 }
16 },
17 "required": ["query"]
18 },
19 handler=search_handler,
20 secure=False,
21 fillers=["Searching now..."]
22)

Handler Function Signature

Handler functions receive parsed arguments and raw data:

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

Raw Data Contents

The raw_data parameter contains:

1{
2 "function": "function_name",
3 "argument": {
4 "parsed": [{"name": "...", "value": "..."}]
5 },
6 "call_id": "uuid-call-id",
7 "global_data": {"key": "value"},
8 "meta_data": {"key": "value"},
9 "caller_id_name": "Caller Name",
10 "caller_id_number": "+15551234567",
11 "ai_session_id": "uuid-session-id"
12}

Accessing Raw Data

1@agent.tool(
2 description="Process order",
3 parameters={
4 "type": "object",
5 "properties": {
6 "order_id": {"type": "string", "description": "Order ID"}
7 },
8 "required": ["order_id"]
9 }
10)
11def process_order(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
12 raw_data = raw_data or {}
13 order_id = args.get("order_id", "")
14
15 # Get global data
16 global_data = raw_data.get("global_data", {})
17 user_id = global_data.get("user_id")
18
19 # Get caller info
20 caller_number = raw_data.get("caller_id_number")
21
22 # Get session info
23 call_id = raw_data.get("call_id")
24
25 return SwaigFunctionResult(f"Order {order_id} processed")

Secure Functions

Secure functions require token authentication per call:

1@agent.tool(
2 description="Access sensitive data",
3 secure=True,
4 parameters={
5 "type": "object",
6 "properties": {
7 "account_id": {"type": "string", "description": "Account ID"}
8 },
9 "required": ["account_id"]
10 }
11)
12def get_account_info(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
13 account_id = args.get("account_id", "")
14 # This function requires a valid token
15 return SwaigFunctionResult(f"Account info for {account_id}")

Fillers and Wait Files

Keep users engaged during processing:

1## Text fillers - AI speaks these while processing
2@agent.tool(
3 description="Search database",
4 fillers=[
5 "Let me search for that...",
6 "One moment please...",
7 "Checking our records..."
8 ],
9 parameters={
10 "type": "object",
11 "properties": {
12 "query": {"type": "string", "description": "Search query"}
13 },
14 "required": ["query"]
15 }
16)
17def search_database(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
18 query = args.get("query", "")
19 # ... search logic
20 return SwaigFunctionResult(f"Found results for {query}")
21
22## Wait file - Play audio while processing
23@agent.tool(
24 description="Long operation",
25 wait_file="https://example.com/hold_music.mp3",
26 parameters={
27 "type": "object",
28 "properties": {
29 "data": {"type": "string", "description": "Data to process"}
30 },
31 "required": ["data"]
32 }
33)
34def long_operation(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
35 data = args.get("data", "")
36 # ... long processing
37 return SwaigFunctionResult("Processing complete")

Return Value Requirements

IMPORTANT: All SWAIG functions MUST return SwaigFunctionResult:

1## Correct
2@agent.tool(
3 description="Get info",
4 parameters={
5 "type": "object",
6 "properties": {
7 "id": {"type": "string", "description": "Item ID"}
8 },
9 "required": ["id"]
10 }
11)
12def get_info(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
13 id = args.get("id", "")
14 return SwaigFunctionResult(f"Information for {id}")
15
16## WRONG - Never return plain strings
17@agent.tool(description="Get info")
18def get_info_wrong(args: dict, raw_data: dict = None) -> str:
19 return "Information retrieved" # This will fail!

Complete Example

1#!/usr/bin/env python3
2## order_functions_agent.py - Agent with various SWAIG function patterns
3from signalwire_agents import AgentBase
4from signalwire_agents.core.function_result import SwaigFunctionResult
5
6agent = AgentBase(name="order-agent", route="/orders")
7
8## Simple function
9@agent.tool(
10 description="Get order status",
11 parameters={
12 "type": "object",
13 "properties": {
14 "order_id": {"type": "string", "description": "Order ID to look up"}
15 },
16 "required": ["order_id"]
17 }
18)
19def get_order_status(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
20 order_id = args.get("order_id", "")
21 status = lookup_order(order_id)
22 return SwaigFunctionResult(f"Order {order_id} is {status}")
23
24## Function with multiple parameters
25@agent.tool(
26 description="Place a new order",
27 parameters={
28 "type": "object",
29 "properties": {
30 "product": {"type": "string", "description": "Product name"},
31 "quantity": {"type": "integer", "description": "Quantity to order"},
32 "shipping": {"type": "string", "description": "Shipping method"}
33 },
34 "required": ["product"]
35 }
36)
37def place_order(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
38 product = args.get("product", "")
39 quantity = args.get("quantity", 1)
40 shipping = args.get("shipping", "standard")
41 order_id = create_order(product, quantity, shipping)
42 return SwaigFunctionResult(f"Order {order_id} placed successfully")
43
44## Secure function with fillers
45@agent.tool(
46 description="Cancel an order",
47 secure=True,
48 fillers=["Let me process that cancellation..."],
49 parameters={
50 "type": "object",
51 "properties": {
52 "order_id": {"type": "string", "description": "Order ID to cancel"},
53 "reason": {"type": "string", "description": "Cancellation reason"}
54 },
55 "required": ["order_id"]
56 }
57)
58def cancel_order(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
59 order_id = args.get("order_id", "")
60 reason = args.get("reason")
61 cancel_result = do_cancel(order_id, reason)
62 return SwaigFunctionResult(f"Order {order_id} has been cancelled")
63
64## Function that returns actions
65@agent.tool(
66 description="Transfer to support",
67 parameters={
68 "type": "object",
69 "properties": {
70 "issue_type": {"type": "string", "description": "Type of issue"}
71 },
72 "required": ["issue_type"]
73 }
74)
75def transfer_to_support(args: dict, raw_data: dict = None) -> SwaigFunctionResult:
76 issue_type = args.get("issue_type", "general")
77 return (
78 SwaigFunctionResult("I'll transfer you to our support team")
79 .connect("+15551234567", final=True)
80 )
81
82if __name__ == "__main__":
83 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