Function Result

View as Markdown

SwaigFunctionResult API

Complete API reference for SwaigFunctionResult, the class for returning responses and actions from SWAIG functions.

Class Definition

1from signalwire_agents.core.function_result import SwaigFunctionResult
2
3class SwaigFunctionResult:
4 """Wrapper around SWAIG function responses."""

Constructor

1SwaigFunctionResult(
2 response: Optional[str] = None, # Text for AI to speak
3 post_process: bool = False # Let AI respond before actions
4)

Core Concept

ComponentPurpose
responseText the AI should say back to the user
actionList of structured actions to execute
post_processLet AI respond once more before executing actions

Post-Processing Behavior:

  • post_process=False (default): Execute actions immediately
  • post_process=True: AI responds first, then actions execute

Basic Methods

set_response

1def set_response(self, response: str) -> 'SwaigFunctionResult'

Set the response text.

set_post_process

1def set_post_process(self, post_process: bool) -> 'SwaigFunctionResult'

Set post-processing behavior.

add_action

1def add_action(self, name: str, data: Any) -> 'SwaigFunctionResult'

Add a single action.

add_actions

1def add_actions(self, actions: List[Dict[str, Any]]) -> 'SwaigFunctionResult'

Add multiple actions.

Call Control Actions

connect

1def connect(
2 self,
3 destination: str, # Phone number or SIP address
4 final: bool = True, # Permanent (True) or temporary (False)
5 from_addr: Optional[str] = None # Caller ID override
6) -> 'SwaigFunctionResult'

Transfer the call to another destination.

1## Permanent transfer
2return SwaigFunctionResult("Transferring you now").connect("+15551234567")
3
4## Temporary transfer (returns to agent when far end hangs up)
5return SwaigFunctionResult("Connecting you").connect("+15551234567", final=False)
6
7## With custom caller ID
8return SwaigFunctionResult("Transferring").connect(
9 "support@company.com",
10 final=True,
11 from_addr="+15559876543"
12)

hangup

1def hangup(self) -> 'SwaigFunctionResult'

End the call.

1return SwaigFunctionResult("Goodbye!").hangup()

hold

1def hold(self, timeout: int = 300) -> 'SwaigFunctionResult'

Put the call on hold (max 900 seconds).

1return SwaigFunctionResult("Please hold").hold(timeout=120)

stop

1def stop(self) -> 'SwaigFunctionResult'

Stop agent execution.

1return SwaigFunctionResult("Stopping now").stop()

Speech Actions

say

1def say(self, text: str) -> 'SwaigFunctionResult'

Make the agent speak specific text.

1return SwaigFunctionResult().say("Important announcement!")

wait_for_user

1def wait_for_user(
2 self,
3 enabled: Optional[bool] = None, # Enable/disable
4 timeout: Optional[int] = None, # Seconds to wait
5 answer_first: bool = False # Special mode
6) -> 'SwaigFunctionResult'

Control how agent waits for user input.

1return SwaigFunctionResult("Take your time").wait_for_user(timeout=30)

Data Actions

update_global_data

1def update_global_data(self, data: Dict[str, Any]) -> 'SwaigFunctionResult'

Update global session data.

1return SwaigFunctionResult("Account verified").update_global_data({
2 "verified": True,
3 "user_id": "12345"
4})

remove_global_data

1def remove_global_data(self, keys: Union[str, List[str]]) -> 'SwaigFunctionResult'

Remove keys from global data.

1return SwaigFunctionResult("Cleared").remove_global_data(["temp_data", "cache"])

set_metadata

1def set_metadata(self, data: Dict[str, Any]) -> 'SwaigFunctionResult'

Set metadata scoped to the function’s token.

1return SwaigFunctionResult("Saved").set_metadata({"last_action": "search"})

remove_metadata

1def remove_metadata(self, keys: Union[str, List[str]]) -> 'SwaigFunctionResult'

Remove metadata keys.

Media Actions

play_background_file

1def play_background_file(
2 self,
3 filename: str, # Audio/video URL
4 wait: bool = False # Suppress attention-getting
5) -> 'SwaigFunctionResult'

Play background audio.

1return SwaigFunctionResult().play_background_file(
2 "https://example.com/music.mp3",
3 wait=True
4)

stop_background_file

1def stop_background_file(self) -> 'SwaigFunctionResult'

Stop background playback.

Recording Actions

record_call

1def record_call(
2 self,
3 control_id: Optional[str] = None, # Recording identifier
4 stereo: bool = False, # Stereo recording
5 format: str = "wav", # "wav", "mp3", or "mp4"
6 direction: str = "both", # "speak", "listen", or "both"
7 terminators: Optional[str] = None, # Digits to stop recording
8 beep: bool = False, # Play beep before recording
9 input_sensitivity: float = 44.0, # Input sensitivity
10 initial_timeout: float = 0.0, # Wait for speech start
11 end_silence_timeout: float = 0.0, # Silence before ending
12 max_length: Optional[float] = None, # Max duration
13 status_url: Optional[str] = None # Status webhook URL
14) -> 'SwaigFunctionResult'

Start call recording.

1return SwaigFunctionResult("Recording started").record_call(
2 control_id="main_recording",
3 stereo=True,
4 format="mp3"
5)

stop_record_call

1def stop_record_call(
2 self,
3 control_id: Optional[str] = None # Recording to stop
4) -> 'SwaigFunctionResult'

Stop recording.

Messaging Actions

send_sms

1def send_sms(
2 self,
3 to_number: str, # Destination (E.164)
4 from_number: str, # Sender (E.164)
5 body: Optional[str] = None, # Message text
6 media: Optional[List[str]] = None, # Media URLs
7 tags: Optional[List[str]] = None, # Tags for searching
8 region: Optional[str] = None # Origin region
9) -> 'SwaigFunctionResult'

Send SMS message.

1return SwaigFunctionResult("Confirmation sent").send_sms(
2 to_number="+15551234567",
3 from_number="+15559876543",
4 body="Your order has been confirmed!"
5)

Payment Actions

pay

1def pay(
2 self,
3 payment_connector_url: str, # Payment endpoint (required)
4 input_method: str = "dtmf", # "dtmf" or "voice"
5 payment_method: str = "credit-card",
6 timeout: int = 5, # Digit timeout
7 max_attempts: int = 1, # Retry attempts
8 security_code: bool = True, # Prompt for CVV
9 postal_code: Union[bool, str] = True, # Prompt for zip
10 charge_amount: Optional[str] = None, # Amount to charge
11 currency: str = "usd",
12 language: str = "en-US",
13 voice: str = "woman",
14 valid_card_types: str = "visa mastercard amex",
15 ai_response: Optional[str] = None # Post-payment response
16) -> 'SwaigFunctionResult'

Process payment.

1return SwaigFunctionResult("Processing payment").pay(
2 payment_connector_url="https://pay.example.com/process",
3 charge_amount="49.99",
4 currency="usd"
5)

Context Actions

swml_change_step

1def swml_change_step(self, step_name: str) -> 'SwaigFunctionResult'

Change conversation step.

1return SwaigFunctionResult("Moving to confirmation").swml_change_step("confirm")

swml_change_context

1def swml_change_context(self, context_name: str) -> 'SwaigFunctionResult'

Change conversation context.

1return SwaigFunctionResult("Switching to support").swml_change_context("support")

switch_context

1def switch_context(
2 self,
3 system_prompt: Optional[str] = None, # New system prompt
4 user_prompt: Optional[str] = None, # User message to add
5 consolidate: bool = False, # Summarize conversation
6 full_reset: bool = False # Complete reset
7) -> 'SwaigFunctionResult'

Advanced context switching.

Conference Actions

join_room

1def join_room(self, name: str) -> 'SwaigFunctionResult'

Join a RELAY room.

join_conference

1def join_conference(
2 self,
3 name: str, # Conference name (required)
4 muted: bool = False, # Join muted
5 beep: str = "true", # Beep config
6 start_on_enter: bool = True, # Start when joining
7 end_on_exit: bool = False, # End when leaving
8 max_participants: int = 250, # Max attendees
9 record: str = "do-not-record" # Recording mode
10) -> 'SwaigFunctionResult'

Join audio conference.

Tap/Stream Actions

tap

1def tap(
2 self,
3 uri: str, # Destination URI (required)
4 control_id: Optional[str] = None,
5 direction: str = "both", # "speak", "hear", "both"
6 codec: str = "PCMU", # "PCMU" or "PCMA"
7 rtp_ptime: int = 20
8) -> 'SwaigFunctionResult'

Start media tap/stream.

stop_tap

1def stop_tap(self, control_id: Optional[str] = None) -> 'SwaigFunctionResult'

Stop media tap.

SIP Actions

sip_refer

1def sip_refer(self, to_uri: str) -> 'SwaigFunctionResult'

Send SIP REFER for call transfer.

Advanced Actions

execute_swml

1def execute_swml(
2 self,
3 swml_content, # String, Dict, or SWML object
4 transfer: bool = False # Exit agent after execution
5) -> 'SwaigFunctionResult'

Execute raw SWML.

1swml_doc = {
2 "version": "1.0.0",
3 "sections": {
4 "main": [{"play": {"url": "https://example.com/audio.mp3"}}]
5 }
6}
7return SwaigFunctionResult().execute_swml(swml_doc)

toggle_functions

1def toggle_functions(
2 self,
3 function_toggles: List[Dict[str, Any]]
4) -> 'SwaigFunctionResult'

Enable/disable specific functions.

1return SwaigFunctionResult("Functions updated").toggle_functions([
2 {"function": "transfer_call", "active": True},
3 {"function": "cancel_order", "active": False}
4])

Settings Actions

update_settings

1def update_settings(self, settings: Dict[str, Any]) -> 'SwaigFunctionResult'

Update AI runtime settings.

1return SwaigFunctionResult().update_settings({
2 "temperature": 0.5,
3 "confidence": 0.8
4})

set_end_of_speech_timeout

1def set_end_of_speech_timeout(self, milliseconds: int) -> 'SwaigFunctionResult'

Adjust speech detection timeout.

Method Chaining

All methods return self for chaining:

1return (
2 SwaigFunctionResult("Processing your order")
3 .update_global_data({"order_id": "12345"})
4 .send_sms(
5 to_number="+15551234567",
6 from_number="+15559876543",
7 body="Order confirmed!"
8 )
9 .swml_change_step("confirmation")
10)

to_dict Method

1def to_dict(self) -> Dict[str, Any]

Convert to SWAIG response format. Called automatically when returning from functions.

Action Execution Order

Actions execute in the order they’re added. Some actions are terminal and end the call flow:

Terminal ActionsNon-Terminal Actions
.connect(final=True).update_global_data()
.hangup().send_sms()
.swml_transfer(final=True).say()
.set_metadata()

Best practice: Put terminal actions last so preceding actions can execute.

1# Good: data saved before transfer
2return (
3 SwaigFunctionResult("Transferring...")
4 .update_global_data({"transferred": True})
5 .send_sms(to_number=phone, from_number=agent_num, body="Call transferred")
6 .connect("+15551234567", final=True) # Terminal - goes last
7)

See Also

TopicReference
Defining SWAIG functionsSWAIG Function API
Results and actions guideResults & Actions
Call transfer optionsCall Transfers
State managementState Management

Common Patterns

Conditional transfer:

1if caller_verified:
2 return SwaigFunctionResult("Connecting...").connect("+15551234567")
3else:
4 return SwaigFunctionResult("Please verify your identity first.")

Multi-action response:

1return (
2 SwaigFunctionResult("Order confirmed!")
3 .update_global_data({"order_id": order_id})
4 .send_sms(to_number=phone, from_number="+15559876543", body=f"Order {order_id} confirmed")
5 .swml_change_step("confirmation")
6)