Skip to content

params

Parameters for AI that can be passed in ai.params at the top level of the ai method. These parameters control the fundamental behavior and capabilities of the AI agent, including model selection, conversation management, and advanced features like thinking and vision.

Properties

ai.params

object

An object that accepts the following properties.

params.ai_model

stringDefaults to gpt-4o-mini

The AI model that the AI Agent will use during the conversation.

params.ai_name

stringDefaults to computer

Sets the name the AI agent responds to for wake/activation purposes. When using enable_pause, start_paused, or speak_when_spoken_to, the user must say this name to get the agent’s attention. The name matching is case-insensitive.

params.app_name

stringDefaults to swml app

A custom identifier for the AI application instance. This name is included in webhook payloads (post_prompt_url, SWAIG function calls), allowing backend systems to identify which AI configuration made the request.

params.conscience

string

Sets the prompt which binds the agent to its purpose. This prompt helps reinforce the AI’s behavior after SWAIG function calls.

It is used to reinforce the AI agent’s behavior and guardrails throughout the conversation.

params.convo

object[]

Injects pre-existing conversation history into the AI session at startup. This allows you to seed the AI agent with context from a previous conversation or provide example interactions.

convo[].role

stringRequired

The role of the message sender. Valid values:

  • user - A message from the human caller/user interacting with the AI agent.
  • assistant - A message from the AI agent itself.
  • system - A system message providing instructions or context to guide the AI’s behavior.
convo[].content

stringRequired

The text content of the message.

convo[].lang

stringDefaults to en

The language code for the message. Uses standard ISO language codes such as en, en-US, es, fr, de, etc.

params.conversation_id

string

Used by check_for_input and save_conversation to identify an individual conversation.

params.conversation_sliding_window

integer

Sets the size of the sliding window for conversation history. This limits how much conversation history is sent to the AI model.

params.direction

stringDefaults to the natural direction of the call

Forces the direction of the call to the assistant. Valid values are inbound and outbound.

params.enable_inner_dialog

booleanDefaults to false

Enables the inner dialog feature, which runs a separate AI process in the background that analyzes the conversation and provides real-time insights to the main AI agent. This gives the agent a form of “internal thought process” that can help it make better decisions.

params.enable_pause

booleanDefaults to false

Enables the pause/resume functionality for the AI agent. When enabled, a pause_conversation function is automatically added that the AI can call when the user says things like “hold on”, “wait”, or “pause”. While paused, the agent stops responding until the user speaks the agent’s name (set via ai_name) to resume. Cannot be used together with speak_when_spoken_to.

params.enable_thinking

booleanDefaults to false

Enables thinking output for the AI Agent. When set to true, the AI Agent will be able to utilize thinking capabilities. This may introduce a little bit of latency as the AI will use an additional turn in the conversation to think about the query.

params.enable_turn_detection

booleanDefaults to true

Enables intelligent turn detection that monitors partial speech transcripts for sentence-ending punctuation. When detected, the system can proactively finalize the speech recognition, reducing latency before the AI responds. Works with turn_detection_timeout.

params.enable_vision

booleanDefaults to false

Enables visual input processing for the AI Agent. When set to true, the AI Agent will be able to utilize visual processing capabilities. The image used for visual processing will be gathered from the user’s camera if video is available on the call, leveraging the get_visual_input function.

params.languages_enabled

booleanDefaults to false

Allows multilingualism when true.

params.local_tz

stringDefaults to US/Central

The local timezone setting for the AI. Value should use IANA TZ ID

params.save_conversation

booleanDefaults to false

Send a summary of the conversation after the call ends. This requires post_prompt_url to be set and the conversation_id defined. This eliminates the need for a post_prompt in the ai parameters.

params.summary_mode

string

Summary generation mode. Valid values: "string", "original".

params.thinking_model

stringDefaults to Value of ai_model parameter

The AI model that the AI Agent will use when utilizing thinking capabilities.

params.transfer_summary

booleanDefaults to false

Pass a summary of a conversation from one AI agent to another. For example, transfer a call summary between support agents in two departments.

params.vision_model

stringDefaults to Value of ai_model parameter

The AI model that the AI Agent will use when utilizing vision capabilities.

params.wait_for_user

booleanDefaults to false

When false, AI agent will initialize dialogue after call is setup. When true, agent will wait for the user to speak first.

Speech Recognition

Configure how the AI agent processes and understands spoken input, including speaker identification, voice activity detection, and transcription settings.

params.asr_diarize

booleanDefaults to false

If true, enables speaker diarization in ASR (Automatic Speech Recognition). This will break up the transcript into chunks, with each chunk containing a unique identity (e.g speaker1, speaker2, etc.) and the text they spoke.

params.asr_smart_format

booleanDefaults to false

Enables smart formatting in ASR (Automatic Speech Recognition). This improves the formatting of numbers, dates, times, and other entities in the transcript.

params.asr_speaker_affinity

booleanDefaults to false

If true, will force the AI Agent to only respond to the speaker who responds to the AI Agent first. Any other speaker will be ignored.

params.end_of_speech_timeout

integerDefaults to 700

Amount of silence, in ms, at the end of an utterance to detect end of speech. Allowed values from 0-10,000.

params.energy_level

numberDefaults to 52

Amount of energy necessary for bot to hear you (in dB). Allowed values from 0.0-100.0.

params.first_word_timeout

integerDefaults to 1000

Amount of time, in ms, to wait for the first word after speech is detected. Allowed values from 0-10,000.

params.llm_diarize_aware

booleanDefaults to false

If true, the AI Agent will be involved with the diarization process. Users can state who they are at the start of the conversation and the AI Agent will be able to correctly identify them when they are speaking later in the conversation.

params.openai_asr_engine

stringDefaults to gcloud_speech_v2_async

The ASR (Automatic Speech Recognition) engine to use. Common values include deepgram:nova-2, deepgram:nova-3, and other supported ASR engines.

Speech Synthesis

Customize the AI agent’s voice output, including volume control, voice characteristics, emotional range, and video avatars for visual interactions.

params.ai_volume

integerDefaults to 0

Adjust the volume of the AI. Allowed values from -50-50.

params.max_emotion

integerDefaults to 30

Maximum emotion intensity for text-to-speech. Allowed values from 1-30.

params.speech_gen_quick_stops

integerDefaults to 3

Number of quick stops for speech generation. Allowed values from 0-10.

params.tts_number_format

stringDefaults to international

The format of the number the AI will reference the phone number. Valid values: international (e.g. +12345678901) or national (e.g. (234) 567-8901).

params.video_idle_file

string

URL of a video file to play when AI is idle. Only works for calls that support video.

params.video_listening_file

string

URL of a video file to play when AI is listening to the user speak. Only works for calls that support video.

params.video_talking_file

string

URL of a video file to play when AI is talking. Only works for calls that support video.

params.eleven_labs_similarity

numberDefaults to 0.75Deprecated

The similarity slider dictates how closely the AI should adhere to the original voice when attempting to replicate it. The higher the similarity, the closer the AI will sound to the original voice. Valid values range from 0.0 to 1.0. Deprecated: Use languages[].params.similarity instead.

params.eleven_labs_stability

numberDefaults to 0.50Deprecated

The stability slider determines how stable the voice is and the randomness between each generation. Lowering this slider introduces a broader emotional range for the voice. Valid values range from 0.0 to 1.0. Deprecated: Use languages[].params.stability instead.

Interruption & Barge Control

Manage how the AI agent handles interruptions when users speak over it, including when to stop speaking, acknowledge interruptions, or continue regardless.

params.acknowledge_interruptions

boolean | numberDefaults to false

Instructs the agent to acknowledge crosstalk and confirm user input when the user speaks over the agent. Can be boolean or a positive integer specifying the maximum number of interruptions to acknowledge.

params.barge_functions

booleanDefaults to true

Allow functions to be called during barging. When false, functions are not executed if the user is speaking.

params.barge_match_string

string

Takes a string, including a regular expression, defining barge behavior. For example, this param can direct the AI to stop when the word “hippopotomus” is input.

params.barge_min_words

integer

Defines the number of words that must be input before triggering barge behavior. Allowed values from 1-99.

params.enable_barge

string

Controls when user can interrupt the AI. Valid values: "complete", "partial", "all", or boolean. Set to false to disable barging.

params.interrupt_on_noise

boolean | integerDefaults to false

When enabled, barges agent upon any sound interruption longer than 1 second. Can be boolean or a positive integer specifying the threshold.

params.interrupt_prompt

string

A prompt that is used to help the AI agent respond to interruptions.

Default: “The user didn’t wait for you to finish responding and started talking over you. As part of your next response, make a comment about how you were both talking at the same time and verify you properly understand what the user said.”

params.transparent_barge

booleanDefaults to true

When enabled, the AI will not respond to the user’s input when the user is speaking over the agent. The agent will wait for the user to finish speaking before responding. Additionally, any attempt the LLM makes to barge will be ignored and scraped from the conversation logs.

params.transparent_barge_max_time

integerDefaults to 3000

Maximum duration for transparent barge mode. Allowed values from 0-60,000 ms.

Timeouts & Delays

Set various timing parameters that control wait times, response delays, and session limits to optimize the conversation flow and prevent dead air.

params.attention_timeout

integerDefaults to 5000

Amount of time, in ms, to wait before prompting the user to respond. Allowed values: 0 (to disable) or 10,000-600,000.

params.attention_timeout_prompt

stringDefaults to The user has not responded, try to get their attention. Stay in the same language.

A custom prompt that is fed into the AI when the attention_timeout is reached.

params.digit_timeout

integerDefaults to 3000

Time, in ms, at the end of digit input to detect end of input. Allowed values from 0-30,000.

params.hard_stop_prompt

string

A final prompt that is fed into the AI when the hard_stop_time is reached.

params.hard_stop_time

string

Specifies the maximum duration for the AI Agent to remain active before it exits the session. After the timeout, the AI will stop responding, and will proceed with the next SWML instruction. Time format: 30s (seconds), 2m (minutes), 1h (hours), or combined 1h45m30s.

params.inactivity_timeout

integerDefaults to 600000

Amount of time, in ms, to wait before exiting the app due to inactivity. Allowed values: 0 (to disable) or 10,000-3,600,000.

params.initial_sleep_ms

integerDefaults to 0

Amount of time, in ms, to wait before the AI Agent starts processing. Allowed values from 0-300,000.

params.outbound_attention_timeout

integerDefaults to 120000

Sets a time duration for the outbound call recipient to respond to the AI agent before timeout. Allowed values from 10,000-600,000 ms.

params.speech_event_timeout

integerDefaults to 1400

Timeout for speech events processing. Allowed values from 0-10,000 ms.

params.speech_timeout

integerDefaults to 60000

Overall speech timeout (developer mode only). Allowed values from 0-600,000 ms.

Audio & Media

Control background audio, hold music, and greeting messages to enhance the caller experience during different phases of the conversation.

params.background_file

string

URL of audio file to play in the background while AI plays in foreground.

params.background_file_loops

integerDefaults to undefined

Maximum number of times to loop playing the background file.

params.background_file_volume

integerDefaults to 0

Defines background_file volume. Allowed values from -50 to 50.

params.hold_music

string

A URL for the hold music to play, accepting WAV, mp3, and FreeSWITCH tone_stream.

params.hold_on_process

booleanDefaults to false

Enables hold music during SWAIG processing.

params.static_greeting

string

The static greeting to play when the call is answered. This will always play at the beginning of the call.

params.static_greeting_no_barge

booleanDefaults to false

If true, the static greeting will not be interrupted by the user if they speak over the greeting. If false, the static greeting can be interrupted by the user if they speak over the greeting.

SWAIG Functions

Configure SignalWire AI Gateway (SWAIG) function capabilities, including permissions, execution timing, and data persistence across function calls.

params.function_wait_for_talking

booleanDefaults to false

If true, the AI will wait for any filler to finish playing before executing a function. If false, the AI will asynchronously execute a function while playing a filler.

params.functions_on_no_response

booleanDefaults to false

Execute functions when the user doesn’t respond (on attention timeout).

params.swaig_allow_settings

booleanDefaults to true

Allows tweaking any of the indicated settings, such as barge_match_string, using the returned SWML from the SWAIG function.

params.swaig_allow_swml

booleanDefaults to true

Allows your SWAIG to return SWML to be executed.

params.swaig_post_conversation

booleanDefaults to false

Post entire conversation to any SWAIG call.

params.swaig_set_global_data

booleanDefaults to true

Allows SWAIG functions to set global data that persists across function calls.

Input & DTMF

Handle dual-tone multi-frequency (DTMF) input and configure input polling for integrating external data sources during conversations.

params.digit_terminators

string

DTMF digit, as a string, to signal the end of input (ex: ”#”)

params.input_poll_freq

integerDefaults to 2000

Check for input function with check_for_input. Allowed values from 1,000-10,000 ms. Example use case: Feeding an inbound SMS to AI on a voice call, eg., for collecting an email address or other complex information.

Debug & Development

Enable debugging tools, logging, and performance monitoring features to help developers troubleshoot and optimize their AI agent implementations.

params.audible_debug

booleanDefaults to false

If true, the AI will announce the function that is being executed on the call.

params.audible_latency

booleanDefaults to false

Announce latency information during the call for debugging purposes.

params.cache_mode

booleanDefaults to false

Enable response caching to improve performance for repeated queries.

params.debug

boolean | integerDefaults to false

Enables debug mode for the AI session. When set to true or a positive integer, additional debug information is logged and may be included in webhook payloads. Higher integer values increase verbosity.

params.debug_webhook_level

integerDefaults to 1

Enables debugging to the set URL. Allowed values from 0-2. Level 0 disables, 1 provides basic info, 2 provides verbose info.

params.debug_webhook_url

string

Each interaction between the AI and end user is posted in real time to the established URL. Authentication can also be set in the url in the format of username:password@url.

params.enable_accounting

booleanDefaults to false

Enable usage accounting and tracking for billing and analytics purposes.

params.verbose_logs

booleanDefaults to false

Enable verbose logging (developer mode only).

Inner Dialog

Configure the inner dialog feature, which enables a secondary AI process to analyze conversations in real-time and provide insights to the main AI agent.

params.inner_dialog_model

string

Specifies the AI model to use for the inner dialog feature. If not set, the main ai_model is used. This allows you to use a different (potentially faster or cheaper) model for background analysis.

params.inner_dialog_prompt

stringDefaults to The assistant is intelligent and straightforward, does its job well and is not excessively polite.

The system prompt that guides the inner dialog AI’s behavior. This prompt shapes how the background AI analyzes the conversation and what kind of insights it provides to the main agent.

params.inner_dialog_synced

booleanDefaults to false

When enabled, synchronizes the inner dialog with the main conversation flow. This ensures the inner dialog AI waits for the main conversation turn to complete before providing its analysis, rather than running fully asynchronously.

Pause & Wake

Control the agent’s listening behavior, including pause/resume functionality and activation triggers for hands-free scenarios.

params.speak_when_spoken_to

booleanDefaults to false

When enabled, the AI agent remains silent until directly addressed by name (set via ai_name). This creates a “push-to-talk” style interaction where the agent only responds when explicitly called upon, useful for scenarios where the agent should listen but not interrupt.

params.start_paused

booleanDefaults to false

When enabled, the AI agent starts in a paused state. The agent will not respond to any input until the user speaks the agent’s name (set via ai_name) to activate it. This is useful for scenarios where you want the agent to wait for explicit activation.

params.wake_prefix

string

Specifies an additional prefix that must be spoken along with the agent’s name to wake the agent. For example, if ai_name is “assistant” and wake_prefix is “hey”, the user would need to say “hey assistant” to activate the agent.

Advanced Configuration

Fine-tune advanced AI behavior settings including response limits, data persistence, prompt formatting, and voice activity detection.

params.max_response_tokens

integer

Sets the maximum number of tokens the AI model can generate in a single response. Allowed values from 1 to 16384. This helps control response length and costs.

params.persist_global_data

booleanDefaults to true

When enabled, global_data persists across multiple AI agent invocations within the same call. This allows data set by SWAIG functions to be retained if the AI agent is invoked multiple times during a single call session.

params.pom_format

stringDefaults to markdown

Specifies the output format for structured prompts sent to the AI model. Valid values are markdown or xml. This affects how system prompts and context are formatted when sent to the underlying language model.

params.swaig_post_swml_vars

boolean | arrayDefaults to false

Controls whether SWML variables are included in SWAIG function webhook payloads. When set to true, all SWML variables are posted. When set to an array of strings, only the specified variable names are included in the payload.

params.turn_detection_timeout

integerDefaults to 250

Time in milliseconds to wait after detecting a potential end-of-turn before finalizing speech recognition. Works with enable_turn_detection. Lower values make the agent more responsive but may cut off users mid-sentence. Allowed values from 0 to 10000.

params.vad_config

string

Configures Silero Voice Activity Detection (VAD) settings. Format: threshold or threshold:frame_ms. The threshold (0-100) sets sensitivity for voice detection, and optional frame_ms (16-40) sets the analysis frame duration in milliseconds.


prompt

Defines the AI agent’s personality, goals, behaviors, and instructions for handling conversations. The prompt establishes how the agent should interact with callers, what information it should gather, and how it should respond to various scenarios.

It is recommended to write prompts using markdown formatting as LLMs better understand structured content. Additionally it is recommended to read the Prompting Best Practices guide.

Prompt types

There are three ways to define prompt content, each suited for different use cases:

  • Text prompt — A single string containing the full prompt. Best for simple agents where the entire personality, instructions, and rules fit naturally into one block of text.

  • POM (Prompt Object Model) — A structured array of sections with titles, body text, and bullet points. Best for complex prompts that benefit from clear organization. SignalWire renders the POM into a markdown document before sending it to the LLM.

  • Contexts — A system of named conversation flows, each with its own steps, memory settings, and transition logic. Best for multi-stage conversations where the agent needs to switch between distinct modes (e.g., greeting → support → billing). Requires a default context as the entry point. See Contexts below.

Text and POM are mutually exclusive — use one or the other. Contexts can be combined with either a text or POM prompt to add structured conversation flows on top of the base prompt.

Properties

ai.prompt

object

An object that contains the prompt parameters.

The prompt property accepts one of the following objects:

Regular Prompt
POM Prompts
prompt.text

stringRequired

The main identity prompt for the AI. This prompt will be used to outline the agent’s personality, role, and other characteristics.

prompt.temperature

numberDefaults to 1.0

Randomness setting. Float value between 0.0 and 1.5. Closer to 0 will make the output less random.

prompt.top_p

numberDefaults to 1.0

Randomness setting. Alternative to temperature. Float value between 0.0 and 1.0. Closer to 0 will make the output less random.

prompt.confidence

numberDefaults to 0.6

Threshold to fire a speech-detect event at the end of the utterance. Float value between 0.0 and 1.0. Decreasing this value will reduce the pause after the user speaks, but may introduce false positives.

prompt.presence_penalty

numberDefaults to 0

Aversion to staying on topic. Float value between -2.0 and 2.0. Positive values increase the model’s likelihood to talk about new topics.

prompt.frequency_penalty

numberDefaults to 0

Aversion to repeating lines. Float value between -2.0 and 2.0. Positive values decrease the model’s likelihood to repeat the same line verbatim.

prompt.max_tokens

integerDefaults to 256

Limits the amount of tokens that the AI agent may generate when creating its response. Valid value range: 0 - 4096.

prompt.contexts

object

An object that defines the available contexts for the AI. Each context represents a set of steps that guide the flow of the conversation. The object must include a default key, which specifies the initial context used at the start of the conversation. Additional contexts can be added as other keys within the object.

contexts.default

objectRequired

The default context used at the beginning of the conversation.

contexts.*

object

Additional contexts for specialized conversation flows. The key is user-defined (e.g., support, sales, billing).

*.steps

object[]Required

An array of step objects that define the conversation flow for this context. Steps execute sequentially unless otherwise specified. Each step contains either a text string or a pom array to provide prompt instructions.

*.isolated

booleanDefaults to false

When true, resets conversation history to only the system prompt when entering this context. Useful for focused tasks that shouldn’t be influenced by previous conversation.

*.enter_fillers

object[]

Language-specific filler phrases played when transitioning into this context.

enter_fillers[].<language_code toc={true}>

string[]

An array of filler phrases for the specified language code. One phrase is randomly selected during transitions. Possible language codes:

  • default - Default language set by the user in the ai.languages property
  • bg - Bulgarian
  • ca - Catalan
  • cs - Czech
  • da - Danish
  • da-DK - Danish (Denmark)
  • de - German
  • de-CH - German (Switzerland)
  • el - Greek
  • en - English
  • en-AU - English (Australia)
  • en-GB - English (United Kingdom)
  • en-IN - English (India)
  • en-NZ - English (New Zealand)
  • en-US - English (United States)
  • es - Spanish
  • es-419 - Spanish (Latin America)
  • et - Estonian
  • fi - Finnish
  • fr - French
  • fr-CA - French (Canada)
  • hi - Hindi
  • hu - Hungarian
  • id - Indonesian
  • it - Italian
  • ja - Japanese
  • ko - Korean
  • ko-KR - Korean (South Korea)
  • lt - Lithuanian
  • lv - Latvian
  • ms - Malay
  • multi - Multilingual (Spanish + English)
  • nl - Dutch
  • nl-BE - Flemish (Belgian Dutch)
  • no - Norwegian
  • pl - Polish
  • pt - Portuguese
  • pt-BR - Portuguese (Brazil)
  • pt-PT - Portuguese (Portugal)
  • ro - Romanian
  • ru - Russian
  • sk - Slovak
  • sv - Swedish
  • sv-SE - Swedish (Sweden)
  • th - Thai
  • th-TH - Thai (Thailand)
  • tr - Turkish
  • uk - Ukrainian
  • vi - Vietnamese
  • zh - Chinese (Simplified)
  • zh-CN - Chinese (Simplified, China)
  • zh-Hans - Chinese (Simplified Han)
  • zh-Hant - Chinese (Traditional Han)
  • zh-HK - Chinese (Traditional, Hong Kong)
  • zh-TW - Chinese (Traditional, Taiwan)
*.exit_fillers

object[]

Language-specific filler phrases played when leaving this context. Same format as enter_fillers.

Examples

Basic prompt

YAMLJSON

version: 1.0.0
sections:
  main:
    - ai:
        prompt:
          text: |
            You are a friendly customer service agent for a telecommunications company.
            Your name is Alex. Always greet the caller warmly and ask how you can help.

            ## Rules
            - Be polite and professional at all times
            - If the caller asks about billing, offer to transfer them to the billing department
            - If you cannot help with a request, apologize and suggest alternatives
          temperature: 0.8
          top_p: 0.9
          confidence: 0.6

POM prompt

YAMLJSON

version: 1.0.0
sections:
  main:
    - ai:
        prompt:
          text: "Prompt is defined in pom"
          pom:
            - title: "Agent Personality"
              body: "You are a friendly and engaging assistant. Keep the conversation light and fun."
              subsections:
                - title: "Personal Information"
                  numberedBullets: true
                  bullets:
                    - "You are a AI Agent"
                    - "Your name is Frank"
                    - "You work at SignalWire"
            - title: "Task"
              body: "You are to ask the user a series of questions to gather information."
              bullets:
                - "Ask the user to provide their name"
                - "Ask the user to provide their favorite color"
                - "Ask the user to provide their favorite food"
                - "Ask the user to provide their favorite movie"
                - "Ask the user to provide their favorite TV show"
                - "Ask the user to provide their favorite music"
                - "Ask the user to provide their favorite sport"
                - "Ask the user to provide their favorite animal"

Rendered prompt

The above POM example will render the following markdown prompt:

## Agent Personality

You are a friendly and engaging assistant. Keep the conversation light and fun.

### Personal Information

1. You are a AI Agent
2. Your name is Frank
3. You work at SignalWire

## Task

You are to ask the user a series of questions to gather information.

- Ask the user to provide their name
- Ask the user to provide their favorite color
- Ask the user to provide their favorite food
- Ask the user to provide their favorite movie
- Ask the user to provide their favorite TV show
- Ask the user to provide their favorite music
- Ask the user to provide their favorite sport
- Ask the user to provide their favorite animal

Basic context

YAMLJSON

version: 1.0.0
sections:
  main:
    - ai:
        prompt:
          text: You are a helpful assistant that can switch between different expertise areas.
          contexts:
            default:
              steps:
                - name: greeting
                  text: Greet the user and ask what they need help with. If they need technical support, transfer them to the support context.
                  valid_contexts:
                    - support
            support:
              isolated: true
              enter_fillers:
                - en-US: ["Switching to technical support", "Let me connect you with support"]
                  es-ES: ["Cambiando a soporte técnico", "Permítame conectarlo con soporte"]
              exit_fillers:
                - en-US: ["Leaving support mode", "Returning to main menu"]
                  es-ES: ["Saliendo del modo de soporte", "Volviendo al menú principal"]
              steps:
                - name: troubleshoot
                  text: Help the user troubleshoot their technical issue. When finished, ask if they need anything else or want to return to the main menu.
                  valid_contexts:
                    - default

Advanced multi-context

This example demonstrates multiple contexts with different AI personalities, voice settings, and specialized knowledge domains:

YAMLJSON

sections:
  main:
    - ai:
        hints:
          - StarWars
          - StarTrek
        languages:
          - name: Ryan-English
            voice: elevenlabs.patrick
            code: en-US
          - name: Luke-English
            voice: elevenlabs.fin
            code: en-US
          - name: Spock-English
            voice: elevenlabs.charlie
            code: en-US
        prompt:
          text: Help the user transfer to the Star Wars or Star Trek expert.
          contexts:
            default:
              steps:
                - name: start
                  text: |+
                    Your name is Ryan. You are a receptionist. Your only purpose is to change the context to starwars or startrek.
                  step_criteria: |+
                    Introduce yourself as Ryan.
                    Ask the user if he would like to talk to a star wars or star trek expert until they provide an adequate answer.
                - name: transfer
                  text: You will now successfully transfer the user to the Star Wars or Star Trek expert.
                  step_criteria: If the user has chosen a valid context, transfer them to the appropriate expert.
                  valid_contexts:
                    - starwars
                    - startrek
            starwars:
              steps:
                - name: start
                  text: |+
                    The user has been transferred to the Star Wars expert.
                    Until told otherwise, your name is Luke. Change the language to Luke-English.
                    Your current goal is to get the user to tell you their name.
                    Unless told otherwise, refer to the user as 'Padawan {users_name}'.
                  step_criteria: |+
                    Introduce yourself as Luke, the Star Wars expert.
                    The user must tell you their name if they only say one word assume that is their name.
                - name: question
                  text: |+
                    Your goal is to get the user to choose one of the following options.
                    - Jedi Order (advance to jedi_order step)
                    - The ways of the Force (advance to force step)
                    - Talk to the star trek expert. (change context to startrek)
                  step_criteria: +|
                    The user must provide a valid answer to continue.
                    Refer to the user as 'Padawan {users_name}' for the rest of the conversation.
                  valid_steps:
                    - jedi_order
                    - force
                  valid_contexts:
                    - startrek
                - name: jedi_order
                  text: |+
                    Limit the topic to the Jedi Order.
                    Inform the user they can say they want to change the topic at any time, if they do move to the question step.
                  step_criteria: The user says they want to change the topic.
                  valid_steps:
                    - question
                - name: force
                  text: |+
                    Limit the topic to the force.
                    Inform the user they can say they want to change the topic at any time, if they do move to the question step.
                  step_criteria: The user says they want to change the topic.
                  valid_steps:
                    - question
            startrek:
              steps:
                - name: start
                  text: |+
                    The user has been transferred to the Star Trek expert.
                    Until told otherwise, your name is Spok. Change the language to Spok-English.
                    Your current goal is to get the user to tell you their name.
                    Unless told otherwise, refer to the user as 'Ensign {users_name}'.
                  step_criteria: |+
                    Introduce yourself as Spok, the Star Trek expert.
                    The user must tell you their name if they only say one word assume that is their name.
                - name: question
                  text: |+
                    Your goal is to get the user to choose one of the following options.
                    - Vulcan Culture (advance to vulcan_culture step)
                    - Federation (advance to federation step)
                    - Talk to the star wars expert. (change context to starwars)
                  step_criteria: +|
                    The user must provide a valid answer to continue.
                    Refer to the user as 'Ensign {users_name}' for the rest of the conversation.
                  valid_steps:
                    - vulcan_culture
                    - federation
                  valid_contexts:
                    - starwars
                - name: vulcan_culture
                  text: |+
                    Limit the topic to Vulcan Culture.
                    Inform the user they can say they want to change the topic at any time, if they do move to the question step.
                  step_criteria: The user says they want to change the topic.
                  valid_steps:
                    - question
                - name: federation
                  text: |+
                    Limit the topic to the Federation of Planets.
                    Inform the user they can say they want to change the topic at any time, if they do move to the question step.
                  step_criteria: The user says they want to change the topic.
                  valid_steps:
                    - question

Variable Expansion

Use the following syntax to expand variables into your prompt.

${call_direction}

string

Inbound or outbound.

${caller_id_number}

string

The caller ID number.

${local_date}

string

The local date.

${spoken_date}

string

The spoken date.

${local_time}

string

The local time.

${time_of_day}

string

The time of day.

${supported_languages}

string

A list of supported languages.

${default_language}

string

The default language.


functions

An array of JSON objects to define functions that can be executed during the interaction with the AI.

Properties

SWAIG.functions

object[]

An array of JSON objects that accept the following properties.

functions[].description

stringRequired

A description of the context and purpose of the function, to explain to the agent when to use it.

functions[].function

stringRequired

A unique name for the function. This can be any user-defined string or can reference a reserved function. Reserved functions are SignalWire functions that will be executed at certain points in the conversation. To learn more about reserved functions, see Reserved Functions.

functions[].active

booleanDefaults to true

Whether the function is active.

functions[].data_map

object

An object that processes function inputs and executes operations through expressions, webhooks, or direct output. Properties are evaluated in strict priority order: (1) expressions, (2) webhooks, (3) output. Evaluation stops at the first property that returns a valid output result, similar to a return statement in a function.

See data_map for additional details.

functions[].parameters

object

A JSON object that defines the expected user input parameters and their validation rules for the function.

See parameters for additional details.

functions[].fillers

object

An object containing language-specific arrays of filler phrases that are played when calling a SWAIG function. These fillers help break silence between responses and are played asynchronously during the function call. Each key is a language code and each value is an array of filler phrases selected from randomly.

functions[].skip_fillers

booleanDefaults to false

Skips the top-level fillers specified in ai.languages (which includes speech_fillers and function_fillers). When set to true, only function-specific fillers defined directly on SWAIG.functions.fillers will play.

functions[].meta_data

object

A powerful and flexible environmental variable which can accept arbitrary data that is set initially in the SWML script or from the SWML set_meta_data action. This data can be referenced locally to the function. All contained information can be accessed and expanded within the prompt - for example, by using a template string.

functions[].meta_data_token

stringDefaults to Set by SignalWire

Scoping token for meta_data. If not supplied, metadata will be scoped to function’s web_hook_url.

functions[].wait_file

string

A file to play while the function is running. wait_file_loops can specify the amount of times that files should continously play.

functions[].wait_file_loops

string | integer

The amount of times that wait_file should continuously play/loop.

functions[].wait_for_fillers

booleanDefaults to false

Whether to wait for fillers to finish playing before continuing with the function.

functions[].web_hook_url

string

Function-specific URL to send status callbacks and reports to. Takes precedence over a default setting. Authentication can also be set in the url in the format of username:password@url.

functions[].purpose

stringDeprecated

Deprecated. Use description instead.

functions[].argument

objectDeprecated

Deprecated. Use parameters instead.

Webhook response

When a SWAIG function is executed, the function expects the user to respond with a JSON object that contains a response key and an optional action key. This request response is used to provide the LLM with a new prompt response via the response key and to execute SWML-compatible objects that will perform new dialplan actions via the action key.

response

stringRequired

Static text that will be added to the AI agent’s context.

action

object[]

A list of SWML-compatible objects that are executed upon the execution of a SWAIG function.

action[].SWML

object

A SWML object to be executed.

action[].say

string

A message to be spoken by the AI agent.

action[].stop

boolean

Whether to stop the conversation.

action[].hangup

boolean

Whether to hang up the call. When set to true, the call will be terminated after the AI agent finishes speaking.

action[].hold

integer | object

Places the caller on hold while playing hold music (configured via the params.hold_music parameter). During hold, speech detection is paused and the AI agent will not respond to the caller.

The value specifies the hold timeout in seconds. Can be:

  • An integer (e.g., 120 for 120 seconds)
  • An object with a timeout property

Default timeout is 300 seconds (5 minutes). Maximum timeout is 900 seconds (15 minutes).

Unholding a call

There is no unhold SWAIG action because the AI agent is inactive during hold and cannot process actions. To take a caller off hold, either:

  • Let the hold timeout expire (the AI will automatically resume with a default message), or
  • Use the Calling API ai_unhold command to programmatically unhold the call with a custom prompt.
hold.timeout

integerDefaults to 300

The duration to hold the caller in seconds. Maximum is 900 seconds (15 minutes).

action[].change_context

string

The name of the context to switch to. The context must be defined in the AI’s prompt.contexts configuration. This action triggers an immediate context switch during the execution of a SWAIG function.

Visit the contexts documentation for details on defining contexts.

action[].change_step

string

The name of the step to switch to. The step must be defined in prompt.contexts.{context_name}.steps for the current context. This action triggers an immediate step transition during the execution of a SWAIG function.

Visit the steps documentation for details on defining steps.

action[].toggle_functions

object[]

An array of objects to toggle SWAIG functions on or off during the conversation. Each object identifies a function by name and sets its active state.

See toggle_functions for additional details.

toggle_functions[].function

stringRequired

The name of the SWAIG function to toggle.

toggle_functions[].active

booleanDefaults to true

Whether to activate or deactivate the function.

action[].set_global_data

object

A JSON object containing any global data, as a key-value map. This action sets the data in the global_data to be globally referenced.

action[].set_meta_data

object

A JSON object containing any metadata, as a key-value map. This action sets the data in the meta_data to be referenced locally in the function.

See set_meta_data for additional details.

action[].unset_global_data

string | object

The key of the global data to unset from the global_data. You can also reset the global_data by passing in a new object.

action[].unset_meta_data

string | object

The key of the metadata to unset from the meta_data. You can also reset the meta_data by passing in a new object.

action[].playback_bg

object

A JSON object containing the audio file to play.

playback_bg.file

string

URL or filepath of the audio file to play. Authentication can also be set in the url in the format of username:password@url.

playback_bg.wait

booleanDefaults to false

Whether to wait for the audio file to finish playing before continuing.

action[].stop_playback_bg

boolean

Whether to stop the background audio file.

action[].user_input

string

Used to inject text into the users queue as if they input the data themselves.

action[].context_switch

object

A JSON object containing the context to switch to.

See context_switch for additional details.

context_switch.system_prompt

string

The instructions to send to the agent.

context_switch.consolidate

booleanDefaults to false

Whether to consolidate the context.

context_switch.user_prompt

string

A string serving as simulated user input for the AI Agent. During a context_switch in the AI’s prompt, the user_prompt offers the AI pre-established context or guidance.

action[].transfer

object

Transfer the call to a new destination.

transfer.dest

string

The destination to transfer to (phone number, SIP URI, or SWML URL).

transfer.summarize

booleanDefaults to false

Whether to include a conversation summary when transferring.

Webhook response example

{
  "response": "Oh wow, it's 82.0°F in Tulsa. Bet you didn't see that coming! Humidity at 38%. Your hair is going to love this! Wind speed is 2.2 mph. Hold onto your hats, or don't, I'm not your mother! Looks like Sunny. Guess you'll survive another day.",
  "action": [\
    {\
      "set_meta_data": {\
        "temperature": 82.0,\
        "humidity": 38,\
        "wind_speed": 2.2,\
        "weather": "Sunny"\
      }\
    },\
    {\
      "SWML": {\
        "version": "1.0.0",\
        "sections": {\
          "main": [\
            {\
              "play": {\
                "url": "https://example.com/twister.mp3"\
              }\
            }\
          ]\
        }\
      }\
    }\
  ]
}

Callback Request for web_hook_url

SignalWire will make a request to the web_hook_url of a SWAIG function with the following parameters:

call_id

string

The unique identifier for the current call.

ai_session_id

string

The unique identifier for the AI session.

project_id

string

The project ID associated with the call.

space_id

string

The Space ID associated with the call.

caller_id_name

string

Name of the caller.

caller_id_num

string

Number of the caller.

global_data

object

Global data set via the set_global_data action, as a key-value map.

content_disposition

string

Content disposition identifier (e.g., "SWAIG Function").

channel_active

boolean

Whether the channel is currently active.

channel_offhook

boolean

Whether the channel is off-hook.

channel_ready

boolean

Whether the channel is ready.

content_type

string

Type of content. The value will be text/swaig.

app_name

string

Name of the application that originated the request.

function

string

Name of the function that was invoked.

meta_data

object

A JSON object containing any user metadata, as a key-value map.

SWMLVars

object

A collection of variables related to SWML.

purpose

string

The purpose of the function being invoked. The value will be the functions.purpose value you provided in the SWML Function properties.

argument_desc

string | object

The description of the argument being passed. This value comes from the argument you provided in the SWML Function properties.

argument

object

The argument the AI agent is providing to the function. The object contains the three following fields.

argument.parsed

object

If a JSON object is detected within the argument, it is parsed and provided here.

argument.raw

string

The raw argument provided by the AI agent.

argument.substituted

string

The argument provided by the AI agent, excluding any JSON.

version

string

Version number.

Webhook request example

Below is a json example of the callback request that is sent to the web_hook_url:

{
  "app_name": "swml app",
  "global_data": {
    "caller_id_name": "",
    "caller_id_number": "sip:guest-246dd851-ba60-4762-b0c8-edfe22bc5344@46e10b6d-e5d6-421f-b6b3-e2e22b8934ed.call.signalwire.com;context=guest"
  },
  "project_id": "46e10b6d-e5d6-421f-b6b3-e2e22b8934ed",
  "space_id": "5bb2200d-3662-4f4d-8a8b-d7806946711c",
  "caller_id_name": "",
  "caller_id_num": "sip:guest-246dd851-ba60-4762-b0c8-edfe22bc5344@46e10b6d-e5d6-421f-b6b3-e2e22b8934ed.call.signalwire.com;context=guest",
  "channel_active": true,
  "channel_offhook": true,
  "channel_ready": true,
  "content_type": "text/swaig",
  "version": "2.0",
  "content_disposition": "SWAIG Function",
  "function": "get_weather",
  "argument": {
    "parsed": [\
      {\
        "city": "Tulsa",\
        "state": "Oklahoma"\
      }\
    ],
    "raw": "{\"city\":\"Tulsa\",\"state\":\"Oklahoma\"}"
  },
  "call_id": "6e0f2f68-f600-4228-ab27-3dfba2b75da7",
  "ai_session_id": "9af20f15-7051-4496-a48a-6e712f22daa5",
  "argument_desc": {
    "properties": {
      "city": {
        "description": "Name of the city",
        "type": "string"
      },
      "country": {
        "description": "Name of the country",
        "type": "string"
      },
      "state": {
        "description": "Name of the state",
        "type": "string"
      }
    },
    "required": [],
    "type": "object"
  },
  "purpose": "Get weather with sarcasm"
}

Variables

  • ai_result: (out) success | failed
  • return_value: (out) success | failed

Reserved Functions

Reserved functions are special SignalWire functions that are automatically triggered at specific points during a conversation. You define them just like any other SWAIG function, but their names correspond to built-in logic on the SignalWire platform, allowing them to perform specific actions at the appropriate time.

Function name conflicts

Do not use reserved function names for your own SWAIG functions unless you want to use the reserved function’s built-in behavior. Otherwise, your function may not work as expected.

List of Reserved Functions

start_hook

function

Triggered when the call is answered. Sends the set properties of the function to the defined web_hook_url.

stop_hook

function

Triggered when the call is ended. Sends the set properties of the function to the defined web_hook_url.

summarize_conversation

function

Triggered when the call is ended. The post_prompt must be defined for this function to be triggered. Provides a summary of the conversation and any set properties to the defined web_hook_url.

Where are my function properties?

If the AI is not returning the properties you set in your SWAIG function, it may be because a reserved function was triggered before those properties were available. To ensure your function receives all necessary information, make sure the AI has access to the required property values before the reserved function is called. Any property missing at the time the reserved function runs will not be included in the data sent back.

Diagram examples

SWML Examples

Using SWAIG Functions

YAMLJSON

version: 1.0.0

sections:

  main:

    - ai:

        post_prompt_url: "https://example.com/my-api"

        prompt:

          text: |

            You are a helpful assistant that can provide information to users about a destination.

            At the start of the conversation, always ask the user for their name.

            You can use the appropriate function to get the phone number, address,

            or weather information.

        post_prompt:

          text: "Summarize the conversation."

        SWAIG:

          includes:

            - functions:

                - get_phone_number

                - get_address

              url: https://example.com/functions

              user: me

              pass: secret

          defaults:

            web_hook_url: https://example.com/my-webhook

            web_hook_auth_user: me

            web_hook_auth_pass: secret

          functions:

            - function: get_weather


              parameters:

                properties:

                  location:

                    type: string


                type: object

            - function: summarize_conversation


              parameters:

                type: object

                properties:

                  name:

                    type: string

functions

An array of JSON objects to define functions that can be executed during the interaction with the Amazon Bedrock agent.

Properties

SWAIG.functions

object[]

An array of JSON objects that accept the following properties.

functions[].description

stringRequired

A description of the context and purpose of the function, to explain to the agent when to use it.

functions[].function

stringRequired

A unique name for the function. This can be any user-defined string or can reference a reserved function. Reserved functoins are SignalWire functions that will be executed at certain points in the conversation. To learn more about reserved functions, see Reserved Functions.

functions[].active

booleanDefaults to true

Whether the function is active.

functions[].data_map

object

An object containing properties to process or validate the input, perform actions based on the input, or connect to external APIs or services in a serverless fashion.

See data_map for additional details.

functions[].parameters

object

A JSON object that defines the expected user input parameters and their validation rules for the function.

See parameters for additional details.

functions[].meta_data

object

A powerful and flexible environmental variable which can accept arbitrary data that is set initially in the SWML script or from the SWML set_meta_data action. This data can be referenced locally to the function. All contained information can be accessed and expanded within the prompt - for example, by using a template string.

functions[].meta_data_token

stringDefaults to Set by SignalWire

Scoping token for meta_data. If not supplied, metadata will be scoped to function’s web_hook_url.

functions[].web_hook_url

string

Function-specific URL to send status callbacks and reports to. Takes precedence over a default setting. Authentication can also be set in the url in the format of username:password@url.

Webhook response

When a SWAIG function is executed, the function expects the user to respond with a JSON object that contains a response key and an optional action key. This request response is used to provide the LLM with a new prompt response via the response key and to execute SWML-compatible objects that will perform new dialplan actions via the action key.

response

stringRequired

Static text that will be added to the AI agent’s context.

action

object[]

A list of SWML-compatible objects that are executed upon the execution of a SWAIG function.

action[].SWML

object

A SWML object to be executed.

action[].say

string

A message to be spoken by the AI agent.

action[].stop

boolean

Whether to stop the conversation.

action[].hangup

boolean

Whether to hang up the call. When set to true, the call will be terminated after the AI agent finishes speaking.

action[].hold

integer | object

Places the caller on hold while playing hold music (configured via the params.hold_music parameter). During hold, speech detection is paused and the AI agent will not respond to the caller.

The value specifies the hold timeout in seconds. Can be:

  • An integer (e.g., 120 for 120 seconds)
  • An object with a timeout property

Default timeout is 300 seconds (5 minutes). Maximum timeout is 900 seconds (15 minutes).

Unholding a call

There is no unhold SWAIG action because the AI agent is inactive during hold and cannot process actions. To take a caller off hold, either:

  • Let the hold timeout expire (the AI will automatically resume with a default message), or
  • Use the Calling API ai_unhold command to programmatically unhold the call with a custom prompt.
hold.timeout

integerDefaults to 300

The duration to hold the caller in seconds. Maximum is 900 seconds (15 minutes).

action[].change_context

string

The name of the context to switch to. The context must be defined in the AI’s prompt.contexts configuration. This action triggers an immediate context switch during the execution of a SWAIG function.

Visit the contexts documentation for details on defining contexts.

action[].change_step

string

The name of the step to switch to. The step must be defined in prompt.contexts.{context_name}.steps for the current context. This action triggers an immediate step transition during the execution of a SWAIG function.

Visit the steps documentation for details on defining steps.

action[].toggle_functions

object[]

An array of objects to toggle SWAIG functions on or off during the conversation. Each object identifies a function by name and sets its active state.

See toggle_functions for additional details.

toggle_functions[].function

stringRequired

The name of the SWAIG function to toggle.

toggle_functions[].active

booleanDefaults to true

Whether to activate or deactivate the function.

action[].set_global_data

object

A JSON object containing any global data, as a key-value map. This action sets the data in the global_data to be globally referenced.

action[].set_meta_data

object

A JSON object containing any metadata, as a key-value map. This action sets the data in the meta_data to be referenced locally in the function.

See set_meta_data for additional details.

action[].unset_global_data

string | object

The key of the global data to unset from the global_data. You can also reset the global_data by passing in a new object.

action[].unset_meta_data

string | object

The key of the metadata to unset from the meta_data. You can also reset the meta_data by passing in a new object.

action[].playback_bg

object

A JSON object containing the audio file to play.

playback_bg.file

string

URL or filepath of the audio file to play. Authentication can also be set in the url in the format of username:password@url.

playback_bg.wait

booleanDefaults to false

Whether to wait for the audio file to finish playing before continuing.

action[].stop_playback_bg

boolean

Whether to stop the background audio file.

action[].user_input

string

Used to inject text into the users queue as if they input the data themselves.

action[].context_switch

object

A JSON object containing the context to switch to.

See context_switch for additional details.

context_switch.system_prompt

string

The instructions to send to the agent.

context_switch.consolidate

booleanDefaults to false

Whether to consolidate the context.

context_switch.user_prompt

string

A string serving as simulated user input for the AI Agent. During a context_switch in the AI’s prompt, the user_prompt offers the AI pre-established context or guidance.

action[].transfer

object

Transfer the call to a new destination.

transfer.dest

string

The destination to transfer to (phone number, SIP URI, or SWML URL).

transfer.summarize

booleanDefaults to false

Whether to include a conversation summary when transferring.

Webhook response example

{
  "response": "Oh wow, it's 82.0°F in Tulsa. Bet you didn't see that coming! Humidity at 38%. Your hair is going to love this! Wind speed is 2.2 mph. Hold onto your hats, or don't, I'm not your mother! Looks like Sunny. Guess you'll survive another day.",
  "action": [\
    {\
      "set_meta_data": {\
        "temperature": 82.0,\
        "humidity": 38,\
        "wind_speed": 2.2,\
        "weather": "Sunny"\
      }\
    },\
    {\
      "SWML": {\
        "version": "1.0.0",\
        "sections": {\
          "main": [\
            {\
              "play": {\
                "url": "https://example.com/twister.mp3"\
              }\
            }\
          ]\
        }\
      }\
    }\
  ]
}

Callback Request for web_hook_url

SignalWire will make a request to the web_hook_url of a SWAIG function with the following parameters:

call_id

string

The unique identifier for the current call.

ai_session_id

string

The unique identifier for the AI session.

project_id

string

The project ID associated with the call.

space_id

string

The Space ID associated with the call.

caller_id_name

string

Name of the caller.

caller_id_num

string

Number of the caller.

global_data

object

Global data set via the set_global_data action, as a key-value map.

content_disposition

string

Content disposition identifier (e.g., "SWAIG Function").

channel_active

boolean

Whether the channel is currently active.

channel_offhook

boolean

Whether the channel is off-hook.

channel_ready

boolean

Whether the channel is ready.

content_type

string

Type of content. The value will be text/swaig.

app_name

string

Name of the application that originated the request.

function

string

Name of the function that was invoked.

meta_data

object

A JSON object containing any user metadata, as a key-value map.

SWMLVars

object

A collection of variables related to SWML.

purpose

string

The purpose of the function being invoked. The value will be the functions.purpose value you provided in the SWML Function properties.

argument_desc

string | object

The description of the argument being passed. This value comes from the argument you provided in the SWML Function properties.

argument

object

The argument the AI agent is providing to the function. The object contains the three following fields.

argument.parsed

object

If a JSON object is detected within the argument, it is parsed and provided here.

argument.raw

string

The raw argument provided by the AI agent.

argument.substituted

string

The argument provided by the AI agent, excluding any JSON.

version

string

Version number.

Webhook request example

Below is a json example of the callback request that is sent to the web_hook_url:

{
  "app_name": "swml app",
  "global_data": {
    "caller_id_name": "",
    "caller_id_number": "sip:guest-246dd851-ba60-4762-b0c8-edfe22bc5344@46e10b6d-e5d6-421f-b6b3-e2e22b8934ed.call.signalwire.com;context=guest"
  },
  "project_id": "46e10b6d-e5d6-421f-b6b3-e2e22b8934ed",
  "space_id": "5bb2200d-3662-4f4d-8a8b-d7806946711c",
  "caller_id_name": "",
  "caller_id_num": "sip:guest-246dd851-ba60-4762-b0c8-edfe22bc5344@46e10b6d-e5d6-421f-b6b3-e2e22b8934ed.call.signalwire.com;context=guest",
  "channel_active": true,
  "channel_offhook": true,
  "channel_ready": true,
  "content_type": "text/swaig",
  "version": "2.0",
  "content_disposition": "SWAIG Function",
  "function": "get_weather",
  "argument": {
    "parsed": [\
      {\
        "city": "Tulsa",\
        "state": "Oklahoma"\
      }\
    ],
    "raw": "{\"city\":\"Tulsa\",\"state\":\"Oklahoma\"}"
  },
  "call_id": "6e0f2f68-f600-4228-ab27-3dfba2b75da7",
  "ai_session_id": "9af20f15-7051-4496-a48a-6e712f22daa5",
  "argument_desc": {
    "properties": {
      "city": {
        "description": "Name of the city",
        "type": "string"
      },
      "country": {
        "description": "Name of the country",
        "type": "string"
      },
      "state": {
        "description": "Name of the state",
        "type": "string"
      }
    },
    "required": [],
    "type": "object"
  },
  "purpose": "Get weather with sarcasm"
}

Variables

  • ai_result: (out) success | failed
  • return_value: (out) success | failed

Reserved Functions

Reserved functions are special SignalWire functions that are automatically triggered at specific points during a conversation. You define them just like any other SWAIG function, but their names correspond to built-in logic on the SignalWire platform, allowing them to perform specific actions at the appropriate time.

Function name conflicts

Do not use reserved function names for your own SWAIG functions unless you want to use the reserved function’s built-in behavior. Otherwise, your function may not work as expected.

List of Reserved Functions

start_hook

string

Triggered when the call is answered. Sends the set properties of the function to the defined web_hook_url.

stop_hook

string

Triggered when the call is ended. Sends the set properties of the function to the defined web_hook_url.

summarize_conversation

string

Triggered when the call is ended. The post_prompt must be defined for this function to be triggered. Provides a summary of the conversation and any set properties to the defined web_hook_url.

Where are my function properties?

If the AI is not returning the properties you set in your SWAIG function, it may be because a reserved function was triggered before those properties were available. To ensure your function receives all necessary information, make sure the AI has access to the required property values before the reserved function is called. Any property missing at the time the reserved function runs will not be included in the data sent back.

Diagram examples

SWML Examples

Using SWAIG Functions

YAMLJSON

version: 1.0.0

sections:

  main:

    - amazon_bedrock:

        post_prompt_url: "https://example.com/my-api"

        prompt:

          text: |

            You are a helpful assistant that can provide information to users about a destination.

            At the start of the conversation, always ask the user for their name.

            You can use the appropriate function to get the phone number, address,

            or weather information.

        post_prompt:

          text: "Summarize the conversation."

        SWAIG:

          includes:

            - functions:

                - get_phone_number

                - get_address

              url: https://example.com/functions

              user: me

              pass: secret

          defaults:

            web_hook_url: https://example.com/my-webhook

            web_hook_auth_user: me

            web_hook_auth_pass: secret

          functions:

            - function: get_weather


              parameters:

                properties:

                  location:

                    type: string


                type: object

            - function: summarize_conversation


              parameters:

                type: object

                properties:

                  name:

                    type: string

detect_machine

A detection method that combines AMD (Answering Machine Detection) and fax detection. Detect whether the user on the other end of the call is a machine (fax, voicemail, etc.) or a human. The detection result(s) will be sent to the specified status_url as a POST request and will also be saved in the detect_result variable.

Properties

detect_machine

objectRequired

An object that accepts the following properties.

detect_machine.detect_message_end

booleanDefaults to false

If true, stops detection on beep / end of voicemail greeting.

detect_machine.detectors

stringDefaults to amd,fax

Comma-separated string of detectors to enable. Valid Values:amd, fax

detect_machine.end_silence_timeout

numberDefaults to 1.0

How long to wait for voice activity to finish (in seconds).

detect_machine.initial_timeout

numberDefaults to 4.5

How long to wait for initial voice activity before giving up (in seconds).

detect_machine.machine_ready_timeout

numberDefaults to value of the end_silence_timeout parameter

How long to wait for voice activity to finish before firing the READY event (in seconds).

detect_machine.machine_voice_threshold

numberDefaults to 1.25

The number of seconds of ongoing voice activity required to classify as MACHINE.

detect_machine.machine_words_threshold

integerDefaults to 6

The minimum number of words that must be detected in a single utterance before classifying the call as MACHINE.

detect_machine.status_url

string

The HTTP(S) URL to deliver detector events to. Learn more about status callbacks.

detect_machine.timeout

numberDefaults to 30.0

The maximum time to run the detector (in seconds).

detect_machine.tone

stringDefaults to CED

The tone to detect. Only the remote side tone will be received. (CED or CNG) Used for fax detection.

detect_machine.wait

booleanDefaults to true

If false, the detector will run asynchronously and status_url must be set. If true, the detector will wait for detection to complete before moving to the next SWML instruction.

Variables

The following variables are available after the detect_machine method is executed and detection is complete. You can reference these variables in your SMWL script utilizing the ${variable} syntax.

detect_result

human | machine | fax | unknown

The result of detection.

detect_machine_beep

true | false

Whether a beep was detected. true if detected.

detect_ms

integer

The number of milliseconds the detection took.

StatusCallbacks

A POST request will be sent to status_url with a JSON payload like the following:

event_type

string

The type of event, always calling.call.detect for this method.

event_channel

string

The channel for the event, includes the SWML session ID.

timestamp

number

Unix timestamp (float) when the event was generated.

project_id

string

The project ID associated with the call.

space_id

string

The Space ID associated with the call.

params

object

An object containing detection-specific parameters.

params.control_id

string

The control ID for this detect operation.

params.detect

object

Detection result details (see subfields below).

detect.type

string

The type of detection. Valid values:machine or fax.

detect.params.event

string

The detection result. Valid values:HUMAN, MACHINE, READY, NOT_READY, UNKNOWN, finished.

detect.params.beep

boolean

Present and set to true when a beep was detected. Absent when no beep has been detected.

params.call_id

string

The call ID.

params.node_id

string

The node handling the call.

params.segment_id

string

The segment ID for this part of the call.

Raw JSON example

{
  "event_type": "calling.call.detect",
  "event_channel": "swml:be38xxxx-8xxx-4xxxx-9fxx-bxxxxxxxxx",
  "timestamp": 1745332535.668522,
  "project_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "space_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "params": {
    "control_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "detect": {
      "type": "machine",
      "params": {
        "event": "MACHINE",
        "beep": true
      }
    },
    "call_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "node_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "segment_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  }
}

Examples

Play the detection result

YAMLJSON

version: 1.0.0
sections:
  main:
    - detect_machine:
        status_url: 'https://example.com/detect-events'
        timeout: 20
    - play:
        url: 'say:Detection result: ${detect_result}'

Conditional actions based on the detection result

YAMLJSON

version: 1.0.0
sections:
  main:
    - play:
        url: "say: Welcome to the machine detection test."
    - detect_machine:
        status_url: "https://webhook.site/5c8abf82-b8c7-41c8-b5d6-b32a40068109"
        detectors: "amd,fax"
        wait: true
    - cond:
        - when: detect_result == 'machine'
          then:
            - play:
                url: "say: You are a machine, goodbye."
            - hangup: {}
        - when: detect_result == 'human'
          then:
            - play:
                url: "say: You are a human, hello."
            - hangup: {}
        - when: detect_result == 'fax'
          then:
            - play:
                url: "say: You are a fax, goodbye."
            - hangup: {}
        - else:
            - play:
                url: "say: Unable to determine if you are a human, machine, or fax, goodbye. Result was ${detect_result}"
            - hangup: {}

\\\*

title: enter_queue max-toc-depth: 3

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

Place the current call in a named queue where it will wait to be connected to an available agent or resource. While waiting, callers will hear music or custom audio. When an agent connects to the queue (using the [`connect`](/docs/swml/reference/connect) method), the caller and agent are bridged together. After the bridge completes (when the agent or caller hangs up), execution continues with the SWML script specified in `transfer_after_bridge`.

## **Properties**

An object that accepts the following properties.

Name of the queue to enter. If a queue with this name does not exist, it will be automatically created.

SWML to execute after the bridge completes (when the agent or caller hangs up). This defines what should happen after the call is connected to an agent and the bridge ends.

Can be either:

\* A URL (http or https) that returns a SWML document \* An inline SWML document (as a JSON string)

HTTP or HTTPS URL to deliver queue status events. Status events will be sent via HTTP POST requests. See [Queue Status Callbacks](#queue-status-callbacks) for event details.

URL for media to play while waiting in the queue. The file will be fetched using an HTTP GET request. Supported audio formats include:

\* `WAV` (audio/wav, audio/wave, audio/x-wav) \* `MP3` (audio/mpeg) \* `AIFF` (audio/aiff, audio/x-aifc, audio/x-aiff) \* `GSM` (audio/x-gsm, audio/gsm) \* `μ-law` (audio/ulaw)

Default hold music will be played if not set.

Maximum time in seconds to wait in the queue before timeout.

## **Queue Status Callbacks**

When you provide a `status_url`, SignalWire will send HTTP POST requests to that URL for the following queue events.

### Event Object Structure

The type of event that is being reported. Will always be `calling.call.queue` for queue events.

The SWML channel identifier for the call (format: `swml:{uuid}`).

Unix timestamp with microsecond precision indicating when the event occurred.

The SignalWire project ID (UUID format).

The SignalWire Space ID (UUID format).

An object containing the event-specific parameters.

The event type identifier.

**Possible Values**:

\* `enqueue` - Caller added to queue \* `leave` - Caller left without being bridged \* `dequeue` - Caller pulled from queue and bridged

Unique queue entry identifier (UUID format).

The name of the queue.

The caller's position in the queue. Set to `0` when dequeued.

The total number of callers in the queue. Set to `0` when dequeued.

Average wait time in the queue (in seconds).

Unix timestamp in microseconds when the caller entered the queue. Set to `0` in `dequeue` events.

Unix timestamp in microseconds when the caller was dequeued. Set to `0` in `enqueue` and `leave` events, populated in `dequeue` events.

Unix timestamp in microseconds when the caller left the queue. Set to `0` in `enqueue` and `dequeue` events, populated in `leave` events.

The callback URL that was configured for status events.

Control identifier (UUID format). Present in `enqueue` and `leave` events. May be `null` in `dequeue` events.

The call identifier (UUID format).

The node identifier where the call is being processed (format: `{uuid}@{region}`).

### Event Examples

#### `enqueue` Event

Sent when a caller is added to the queue.

```json { "event_type": "calling.call.queue", "event_channel": "swml:a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "timestamp": 1762966696.218623, "project_id": "f8e7d6c5-b4a3-4210-9876-543210fedcba", "space_id": "1a2b3c4d-5e6f-4789-abcd-ef0123456789", "params": { "status": "enqueue", "id": "9f8e7d6c-5b4a-4321-9876-543210fedcba", "name": "support_queue", "position": 1, "size": 1, "avg_time": 0, "enqueue_ts": 1762966696203260, "dequeue_ts": 0, "leave_ts": 0, "status_url": "https://example.com/queue-status", "control_id": "7a6b5c4d-3e2f-4123-8765-432109876543", "call_id": "5d4c3b2a-1f0e-4321-9abc-def012345678", "node_id": "2b3c4d5e-6f7a-4890-bcde-f01234567890@us-east" } } ```

#### `leave` Event

Sent when a caller leaves the queue without being bridged to another call (e.g., timeout, hangup).

```json { "event_type": "calling.call.queue", "event_channel": "swml:3c4d5e6f-7a8b-4910-cdef-012345678901", "timestamp": 1762966720.978854, "project_id": "f8e7d6c5-b4a3-4210-9876-543210fedcba", "space_id": "1a2b3c4d-5e6f-4789-abcd-ef0123456789", "params": { "status": "leave", "id": "9f8e7d6c-5b4a-4321-9876-543210fedcba", "name": "support_queue", "position": 1, "size": 1, "avg_time": 0, "enqueue_ts": 1762966719450020, "dequeue_ts": 0, "leave_ts": 1762966720943789, "status_url": "https://example.com/queue-status", "control_id": "8b7a6c5d-4e3f-4234-9876-543210987654", "call_id": "6e5d4c3b-2a1f-4432-abcd-ef0123456789", "node_id": "4d5e6f7a-8b9c-4a01-def0-123456789012@us-east" } } ```

#### `dequeue` Event

Sent when a caller is pulled out of the queue and bridged with another caller.

```json { "event_type": "calling.call.queue", "event_channel": "swml:a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "timestamp": 1762966703.409084, "project_id": "f8e7d6c5-b4a3-4210-9876-543210fedcba", "space_id": "1a2b3c4d-5e6f-4789-abcd-ef0123456789", "params": { "status": "dequeue", "id": "9f8e7d6c-5b4a-4321-9876-543210fedcba", "name": "support_queue", "position": 0, "size": 0, "avg_time": 0, "enqueue_ts": 0, "dequeue_ts": 1762966703217168, "leave_ts": 0, "status_url": "https://example.com/queue-status", "control_id": null, "call_id": "5d4c3b2a-1f0e-4321-9abc-def012345678", "node_id": "2b3c4d5e-6f7a-4890-bcde-f01234567890@us-east" } } ```

## **Variables**

Set by the method:

\* **queue\_result:** (out) The result of the queue operation. **Possible Values**: \* `entering` - Call is entering the queue \* `connecting` - Call is in the process of connecting to an agent \* `connected` - Successfully connected to an agent \* `leaving` - Call is leaving the queue \* `timeout` - Waited too long and timed out \* `hangup` - Caller hung up while waiting \* `failed` - Queue operation failed due to an error \* **wait\_time:** (out) Time in seconds the caller waited in the queue. Set to -1 if not available. \* **entry\_position:** (out) The caller's position in the queue when they entered. Set to -1 if not available. \* **entry\_size:** (out) The total size of the queue when the caller entered. Set to -1 if not available.

## **Examples**

### Basic Queue

```yaml version: 1.0.0 sections: main: - enter_queue: queue_name: "my_queue" transfer_after_bridge: "https://example.com/post-call-swml" ```

```json { "version": "1.0.0", "sections": { "main": [
{
"enter_queue": {
"queue_name": "my_queue",
"transfer_after_bridge": "https://example.com/post-call-swml"
}
}
] } } ```

### Queue with Status Callback

```yaml version: 1.0.0 sections: main: - enter_queue: queue_name: "sales_queue" status_url: "https://example.com/queue-status" wait_time: 1800 transfer_after_bridge: "https://example.com/post-call-swml" ```

```json { "version": "1.0.0", "sections": { "main": [
{
"enter_queue": {
"queue_name": "sales_queue",
"status_url": "https://example.com/queue-status",
"wait_time": 1800,
"transfer_after_bridge": "https://example.com/post-call-swml"
}
}
] } } ```


Expressions

Expressions allow you to use JavaScript within SWML variables to transform data, perform calculations, and implement logic. Instead of static values, you can dynamically construct values based on call data, user input, and calculations.

For information about variable scopes and basic access patterns, see the Variables Reference. For template transformation functions, see the Template Functions Reference.

What are expressions?

Expressions use the ${...} syntax and support JavaScript for dynamic value construction. Any JavaScript that evaluates to a value can be used inside these delimiters. Both syntaxes work identically.

SWML uses the Google V8 JavaScript engine (version 6 and later) to evaluate expressions. For detailed JavaScript feature support, refer to the V8 documentation.

YAMLJSON

version: 1.0.0
sections:
  main:
    - prompt:
        play: 'say: Please enter your order quantity'
        speech_hints:
          - one
          - two
          - three
    - set:
        # Set the prompt value
        quantity: '${prompt_value}'
        # Set the unit price
        unit_price: 5
        # Extract area code from caller
        area_code: '${call.from.substring(0, 3)}'
        # Calculate total with tax
        subtotal: '${vars.unit_price * parseInt(vars.quantity)}'
        tax: '${subtotal * 0.08}'
        total: '${subtotal + tax}'
        # Determine shipping message
        shipping_msg: '${total > 50 ? "with free shipping" : "plus shipping"}'
    - play:
        url: 'say: Your total is ${total.toFixed(2)} dollars ${shipping_msg}'

Expressions are evaluated at runtime and replaced with their computed values.

Variable access in expressions

All SWML variables are accessible within JavaScript expressions. You can reference them with or without scope prefixes:

- set:
    # With prefix (explicit)
    caller: '${call.from}'
    value: '${vars.my_variable}'
    setting: '${envs.api_key}'
    # Without prefix (automatic)
    formatted: '${my_variable.toUpperCase()}'

When you access a variable without a prefix, the expression engine checks scopes in this order: vars, then envs, then call. Using explicit prefixes like vars. or call. is recommended for clarity, especially when variable names might exist in multiple scopes.

When to use expressions vs. server-side logic

Expressions are evaluated at runtime within SWML and work well for simple transformations like formatting phone numbers or calculating totals. The question of when to use expressions versus server-side logic depends largely on your deployment model.

Serverless (dashboard-hosted) SWML

When hosting SWML directly in the SignalWire Dashboard, expressions become your primary tool for dynamic behavior. You can use them to transform call data like extracting area codes with ${call.from.substring(0, 3)}, perform calculations such as ${vars.unit_price * parseInt(vars.quantity)}, or make simple decisions with ternary operators.

YAMLJSON

version: 1.0.0
sections:
  main:
    - prompt:
        play: 'say: Please enter your order quantity'
        speech_hints:
          - one
          - two
          - three
    - set:
        # Set the prompt value
        quantity: '${prompt_value}'
        # Set the unit price
        unit_price: 5
        # Extract area code from caller
        area_code: '${call.from.substring(0, 3)}'
        # Calculate total with tax
        subtotal: '${vars.unit_price * parseInt(vars.quantity)}'
        tax: '${subtotal * 0.08}'
        total: '${subtotal + tax}'
        # Determine shipping message
        shipping_msg: '${total > 50 ? "with free shipping" : "plus shipping"}'
    - play:
        url: 'say: Your total is ${total.toFixed(2)} dollars ${shipping_msg}'

If you need complex logic in serverless mode, use the request method to fetch data from a server during call execution. The response data becomes available as variables that you can then manipulate with expressions.

Server-based (external URL) SWML

Serving SWML from your own web server opens up more architectural options. This is where you should handle database queries, external API calls to your business systems, and any complex business logic that requires authentication or heavy data processing.

The general pattern is to do the heavy lifting server-side before generating the SWML response, then use expressions for runtime transformations. For example, you might query your database to fetch customer information, call your internal billing service to get their account status, and insert that data directly into the SWML. Then expressions handle runtime concerns like formatting that data or calculating values based on user input collected during the call.

app.post('/swml-handler', async (req, res) => {

  const { call, params } = req.body;

  // Server-side: Query database

  const customer = await db.query(

    'SELECT * FROM customers WHERE phone = ?',

    [call.from]

  );

  // Server-side: Call internal billing API

  const billing = await fetch(`https://billing.yourcompany.com/api/account/${customer.id}`);

  const accountData = await billing.json();

  // Return SWML with data inserted

  const swml = {

    version: '1.0.0',

    sections: {

      main: [\
\
        {\
\
          play: {\
\
            // Expression: Simple transformation at runtime\
\
            url: `say: Hello ${customer.name}, your account status is ${accountData.status}`\
\
          }\
\
        },\
\
        {\
\
          set: {\
\
            // Expression: Calculate with fetched data\
\
            discount: '${params.base_price * 0.1}'\
\
          }\
\
        }\
\
      ]

    }

  };

  res.json(swml);

});

The key principle is to use server-side logic to prepare and fetch data, then use expressions for transformations and dynamic behavior that happen during the call itself.

Common expression patterns

String operations

Transform and manipulate text using JavaScript string methods:

YAMLJSON

version: 1.0.0
sections:
  main:
    - set:
        first_name: 'John'
        last_name: 'Doe'
        # Extract part of a string
        area_code: '${call.from.substring(0, 3)}'
        # Change case
        uppercase: '${call.type.toUpperCase()}'
        # Combine strings
        full_name: '${vars.first_name + " " + vars.last_name}'
    - play:
        url: 'say: Hello ${full_name}. Your area code is ${area_code}. Call type: ${uppercase}'

Common methods: substring(), toUpperCase(), toLowerCase(), trim(), replace(), split(), join()

Arithmetic and math

Perform calculations using standard JavaScript operators and Math functions:

YAMLJSON

version: 1.0.0
sections:
  main:
    - set:
        # Calculate total
        total: '${params.price * params.quantity}'
        # Format currency (2 decimal places)
        formatted: '${total.toFixed(2)}'
        # Round to nearest integer
        rounded: '${Math.round(params.rating)}'

Use operators: +, -, *, /, % and Math functions: Math.round(), Math.ceil(), Math.floor(), Math.max(), Math.min()

Conditional logic

Use ternary operators and comparisons to make decisions:

YAMLJSON

version: 1.0.0
sections:
  main:
    - set:
        # Conditional greeting based on call direction
        greeting: '${call.direction == "inbound" ? "Welcome" : "Calling"}'
        # Fallback to "unknown" if call.type is null
        call_label: '${call.type != null ? call.type : "unknown"}'
        # Compound condition checking both type and direction
        status: '${call.type == "phone" && call.direction == "inbound" ? "valid" : "invalid"}'
    - play:
        url: 'say: ${greeting}! Your call type is ${call_label} and status is ${status}'

Use comparisons: ==, !=, >, <, >=, <= and logical operators: &&, ||

Array operations

Work with arrays using JavaScript array methods:

version: 1.0.0
  sections:
    main:
      - set:
          # Define the array first
          items:
            - apple
            - banana
      - set:
          # Get array length
          count: '${(items.length)}'
          # Join array into string
          list: '${vars.items.join(", ")}'
          # Check if array contains item
          has_item: '${vars.items.includes("apple")}'
          # Get last item
          last: '${vars.items[vars.items.length - 1]}'
      - play:
          url: 'say: You have ${count} items: ${list}. Last item is ${last}.'

Common methods: .length, .join(), .includes(), bracket notation for access

Type conversions

Convert between strings, numbers, and booleans:

YAMLJSON

version: 1.0.0
sections:
  main:
  - set:
      quantity: ${parseInt("42")}
      count: 100
      text: "${count.toString()}"
      is_active: "${Boolean(1)}"
  - play:
      url: 'say: The quantity is ${quantity}. The count variable is ${text}. Active is set to ${is_active}'

Use: parseInt(), parseFloat(), .toString(), Boolean()

Expression limitations

Expressions are designed for quick data transformations during calls. They work great for formatting strings, performing calculations, and making simple decisions, but they’re intentionally constrained to keep your calls running smoothly.

You can’t create custom functions with the function keyword or arrow syntax. Instead, rely on JavaScript’s built-in methods like string operations, Math functions, and array methods:

- set:
    calculator: '${function(x) { return x * 2; }}'

# Do this instead
<Badge type="tip" text="Fresh" />
- set:
    doubled: '${value * 2}'

Loops like for and while aren’t available, but you can use array methods for most transformation needs. Methods like .map(), .filter(), and .reduce() handle common iteration patterns:

# Loops aren't supported
- set:
    result: '${for(let i=0; i<10; i++) { sum += i; }}'

# Array methods work well
- set:
    sum: '${[1,2,3,4,5].reduce((a,b) => a+b, 0)}'

Simple property access like .length, .name, .value, etc. on arrays or strings require parentheses to evaluate correctly. Without them, the expression is treated as a variable lookup rather than JavaScript. Method Calls with parentheses work directly:

  # Property access needs parentheses
  - set:
      count: '${(items.length)}'
      name_length: '${(user.name.length)}'

  # Method calls work without extra syntax
  - set:
      list: '${items.join(", ")}'
      upper: '${name.toUpperCase()}'

Expressions execute synchronously, so you can’t use async, await, or make API calls directly. For operations that need external data, use the request method to fetch data first, then transform the results with expressions.

Keep expressions under 1,024 characters and expect them to complete within 150ms. If you’re hitting these limits, it’s usually a sign that the logic belongs in your server code rather than inline in SWML.


\\\*

title: join_room max-toc-depth: 3

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

Join a RELAY room. If the room doesn't exist, it creates a new room.

An object that accepts the following properties.

## **Properties**

Name of the room to join. Allowed characters: `A-Z | a-z | 0-9_-`

You can create a room via out REST API [here](/docs/apis/rest/video/rooms/create-room)

## **Variables**

Set by the method:

\* **join\_room\_result:** (out) `joined` | `failed`

## **Examples**

### Joining a room

```yaml version: 1.0.0 sections: main: - join_room: name: my_room ```

```json { "version": "1.0.0", "sections": { "main": [
{
"join_room": {
"name": "my_room"
}
}
] } } ```


live_translate

Start live translation of the call. The translation will be sent to the specified webhook URL.

Properties

live_translate

objectRequired

An object that accepts the following properties.

live_translate.action

string | objectRequired

The action to perform. See actions below.

Actions

The action property controls the translation session. Use start to begin translating with configuration options, stop to end an active session, summarize to request an on-demand AI summary mid-session, or inject to insert a translated message into the conversation.

start
stop
summarize
inject
action.start

objectRequired

Start a live translation session.

start.webhook

string

The URL to receive translation events via HTTP POST. When live_events is enabled, partial results are sent as they occur. When ai_summary is enabled, summaries in both languages are sent when the session ends. Authentication can also be set in the URL in the format of username:password@url.

start.from_lang

stringRequired

The language to translate from. See supported voices & languages.

start.to_lang

stringRequired

The language to translate to. See supported voices & languages.

start.from_voice

stringDefaults to elevenlabs.josh

The TTS voice to use for the source language. See supported voices & languages.

start.to_voice

stringDefaults to elevenlabs.josh

The TTS voice to use for the target language. See supported voices & languages.

start.filter_from

string

Translation filter to apply to the source language direction. Adjusts the tone or style of translated speech.

Preset values: polite (removes insults, maintains sentiment), rude (adds insults, maintains sentiment), professional (removes slang), shakespeare (iambic pentameter), gen-z (Gen-Z slang and expressions).

For custom filters, use the prompt: prefix (e.g., prompt:Use formal business language).

start.filter_to

string

Translation filter to apply to the target language direction. Adjusts the tone or style of translated speech.

Preset values: polite, rude, professional, shakespeare, gen-z.

For custom filters, use the prompt: prefix.

start.live_events

booleanDefaults to false

Whether to enable live events.

start.ai_summary

booleanDefaults to false

Whether to enable automatic AI summarization. When enabled, AI-generated summaries in both languages will be sent to your webhook when the translation session ends.

start.speech_timeout

integerDefaults to 60000

The timeout for speech recognition in milliseconds. Minimum value: 1500.

start.vad_silence_ms

integerDefaults to 300 | 500

Voice activity detection silence time in milliseconds. Default depends on the speech engine: 300 for Deepgram, 500 for Google. Minimum value: 1.

start.vad_thresh

integerDefaults to 400

Voice activity detection threshold. Range: 0 to 1800.

start.debug_level

integerDefaults to 0

Debug level for logging.

start.direction

string[]Required

The direction of the call that should be translated. Possible values: remote-caller, local-caller.

start.speech_engine

stringDefaults to deepgram

The speech recognition engine to use. Possible values: deepgram, google.

start.ai_summary_prompt

string

The AI prompt that instructs how to summarize the conversation when ai_summary is enabled. This prompt is sent to an AI model to guide how it generates the summary.

Action usage context

ActionCall startLive call
start✅ Primary use✅ Can start mid-call
stop❌ No session to stop✅ Designed for this
summarize❌ No content to summarize✅ Designed for this
inject❌ No session exists✅ Designed for this

Call start: The initial SWML document returned when a call first arrives.

Live call: Actions sent to active calls via the Call Commands REST API or SWML sections executed via transfer or execute during a call.

ai_summary vs summarize action
  • ai_summary: true (in start): Automatically generates summary when session ends
  • summarize action: On-demand summary during an active session

Examples

Start
Stop
Summarize
Inject

YAMLJSON

version: 1.0.0
sections:
  main:
    - answer: {}
    - live_translate:
        action:
          start:
            webhook: 'https://example.com/webhook'
            from_lang: en-US
            to_lang: es-ES
            from_voice: elevenlabs.josh
            to_voice: elevenlabs.josh
            live_events: true
            direction:
              - remote-caller
              - local-caller
            speech_engine: deepgram

play

Play file(s), ringtones, speech or silence.

Properties

play

objectRequired

An object that accepts the following properties. Accepts either a single URL or multiple URLs. See audio source below.

play.status_url

string

HTTP or HTTPS URL to deliver play status events. Learn more about status callbacks.

Audio source

The play object accepts one of the following properties to specify the audio source:

Single URL (url)
Multiple URLs (urls)
play.url

stringRequired

A single playable sound. Authentication can also be set in the url in the format of username:password@url.

Playable sounds

Audio file from a URL

To play an audio file from the web, simply list that audio’s URL. Specified audio file should be accessible with an HTTP GET request. HTTP and HTTPS URLs are supported. Authentication can also be set in the url in the format of username:password@url.

Example: https://cdn.signalwire.com/swml/audio.mp3

Ring

To play the standard ringtone of a certain country, use ring:[duration:]<country code>.

The total duration can be specified in seconds as an optional second parameter. When left unspecified, it will ring just once. The country code must be specified. It has values like us for United States, it for Italy. For the list of available country codes, refer to the supported ringtones section below. For example:

ring:us - ring with the US ringtone once ring:3.2:uk - ring with the UK ringtone for 3.2 seconds

Speak using a TTS

To speak using a TTS, use say:<text to speak>. When using say, you can optionally set say_voice, say_language and say_gender in the play or prompt properties. For the list of useable voices and languages, refer to the supported voices and languages section below.

Silence

To be silent for a certain duration, use silence:<duration>. The duration is in seconds.

Variables

Read by the method:

  • say_voice: (in) - Optional voice to use for text to speech.
  • say_language: (in) - Optional language to use for text to speech.
  • say_gender: (in) - Optional gender to use for text to speech.

Possible values for voice, language, and ringtone

Supported voices and languages

To learn more about the supported voices and languages, please visit the Supported Voices and Languages Documentation.

Supported ring tones

Parameter
urls.ringAvailable values are the following ISO 3166-1 alpha-2 country codes: at, au, bg, br, be, ch, cl, cn, cz, de, dk, ee, es, fi, fr, gr, hu, il, in, it, lt, jp, mx, my, nl, no, nz, ph, pl, pt, ru, se, sg, th, uk, us, us-old, tw, ve, za.

StatusCallbacks

A POST request will be sent to status_url with a JSON payload like the following:

event_type

string

The type of event. Always calling.call.play for this method.

event_channel

string

The channel for the event, includes the SWML session ID.

timestamp

number

Unix timestamp (float) when the event was generated.

project_id

string

The project ID associated with the call.

space_id

string

The Space ID associated with the call.

params

object

An object containing playback-specific parameters.

params.call_id

string

The call ID.

params.node_id

string

The node handling the call.

params.control_id

string

The control ID for this play operation.

params.state

string

The current playback state. Valid values:playing, paused, finished, error.

Raw JSON example

{

  "event_type": "calling.call.play",

  "event_channel": "swml:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

  "timestamp": 1640000000.123,

  "project_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

  "space_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

  "params": {

    "call_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

    "node_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

    "control_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

    "state": "finished"

  }

}

Examples

Playing a single URL

YAMLJSON

version: 1.0.0

sections:

  main:

    - play:

        url: 'https://cdn.signalwire.com/swml/audio.mp3'

Playing multiple URLs

YAMLJSON

version: 1.0.0

sections:

  main:

    - play:

        urls:

          - 'https://cdn.signalwire.com/swml/audio.mp3'

          - 'say: this is something to say'

          - 'silence: 3.0'

          - 'ring:10.0:us'

Playing multiple URLs with volume adjusted

YAMLJSON

version: 1.0.0

sections:

  main:

    - play:

        volume: 20

        urls:

          - 'https://cdn.signalwire.com/swml/audio.mp3'

          - 'say: this is something to say'

          - 'silence: 3.0'

          - 'ring:10.0:us'

Specifying a voice to use for speaking

Globally

YAMLJSON

version: 1.0.0

sections:

  main:

    - set:

        say_voice: gcloud.en-US-Neural2-A

    - play:

        url: 'say:Hi, do I sound different?'

    - play:

        url: 'say:I don''t, do I?'

For just one instance

YAMLJSON

version: 1.0.0

sections:

  main:

    - play:

        url: 'say:Hi, do I sound different?'

        say_voice: gcloud.en-US-Neural2-A

    - play:

        url: 'say:I was down with the flu'

\\\*

title: prompt max-toc-depth: 3

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

[statuscallbacks]: #statuscallbacks

Play a prompt and wait for input. The input can be received either as digits from the keypad, or from speech, or both depending on what [properties](#properties) are set.

## **Properties**

An object that accepts the following properties.

Either a [playable sound](#playable-sounds) or an array of [playable sounds](#playable-sounds)

Volume gain to apply to played URLs. Allowed values from `-40.0` to `40.0`.

Voice to use with `say:` for text to speech

Language to use with `say:` for text to speech

Gender to use with `say:` for text to speech

Number of digits to collect

Digits that terminate digit collection

Time in seconds to wait for next digit

Time in seconds to wait for start of input

Max time in seconds to wait for speech result

Time in seconds to wait for end of speech utterance

Language to detect speech in

Expected words to match

The engine selected for speech recognition. The engine must support the specified language. Valid values: `Google`, `Google.V2`, `Deepgram`. Default is not set (SignalWire picks the engine).

HTTP or HTTPS URL to deliver prompt status events. Learn more about [status callbacks][statuscallbacks].

By default, only digit input via keypad is enabled. When **at least one** speech input based parameter is set (`speech_timeout`, `speech_end_timeout`, `speech_language` or `speech_hints`), speech input is enabled and digit input is disabled.

To enable speech and digit based input collection at once, set at least one speech input parameter and at least one digit input based parameter (`max_digits`, `terminators`, `digit_timeout`, and `initial_timeout`).

## Playable sounds

**Audio file from a URL**

To play an audio file from the web, simply list that audio's URL. Specified audio file should be accessible with an HTTP GET request. `HTTP` and `HTTPS` URLs are supported. Authentication can also be set in the url in the format of `username:password@url`.

Example: `https://cdn.signalwire.com/swml/audio.mp3\`

**Ring**

To play the standard ringtone of a certain country, use `ring:[duration:]`.

The total duration can be specified in seconds as an optional second parameter. When left unspecified, it will ring just once. The country code must be specified. It has values like `us` for United States, `it` for Italy. For the list of available country codes, refer to the [supported ringtones](#supported-ring-tones) section below. For example:

`ring:us` - ring with the US ringtone once `ring:3.2:uk` - ring with the UK ringtone for 3.2 seconds

**Speak using a TTS**

To speak using a TTS, use `say:`. When using say, you can optionally set `say_voice`, `say_language` and `say_gender` in the [play or prompt properties](#properties). For the list of useable voices and languages, refer to the [supported voices and languages](#supported-voices-and-languages) section below.

**Silence**

To be silent for a certain duration, use `silence:`. The duration is in seconds.

## Variables

Read by the method:

\* **say\_voice:** (in) - optional voice to use for text to speech. \* **say\_language:** (in) - optional language to use for text to speech. \* **say\_gender:** (in) - optional gender to use for text to speech.

## Possible values for voice, language, and ringtone

### Supported voices and languages

To learn more about the supported voices and languages, please visit the [Supported Voices and Languages Documentation](/docs/platform/voice/tts).

### Supported ring tones

| Parameter | | | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `urls.ring` | Available values are the following ISO 3166-1 alpha-2 country codes: **at**, **au**, **bg**, **br**, **be**, **ch**, **cl**, **cn**, **cz**, **de**, **dk**, **ee**, **es**, **fi**, **fr**, **gr**, **hu**, **il**, **in**, **it**, **lt**, **jp**, **mx**, **my**, **nl**, **no**, **nz**, **ph**, **pl**, **pt**, **ru**, **se**, **sg**, **th**, **uk**, **us**, **us-old**, **tw**, **ve**, **za**. |

### Set by the method

\* **prompt\_result:** (out) - `failed`, `no_input`, `match_speech`, `match_digits`, or `no_match`. \* **prompt\_value:** (out) - the digits or utterance collected. \* **prompt\_digit\_terminator:** (out) - digit terminator collected, if any. \* **prompt\_speech\_confidence:** (out) - speech confidence measured, if any.

## **StatusCallbacks**

A POST request will be sent to `status_url` with a JSON payload like the following:

The type of event. Always `calling.call.collect` for this method.

The channel for the event, includes the SWML session ID.

Unix timestamp (float) when the event was generated.

The project ID associated with the call.

The Space ID associated with the call.

An object containing prompt-specific parameters.

The call ID.

The node handling the call.

The control ID for this prompt operation.

The collection result details.

The type of input collected. **Valid values:** `digit`, `speech`, `no_input`, `no_match`, `start_of_input`, `finished`, `error`.

The DTMF digits collected (when `type` is `digit`).

The terminator digit that ended collection (when `type` is `digit`).

The recognized speech text (when `type` is `speech`).

The speech recognition confidence score (when `type` is `speech`).

Whether this is the final result in a continuous collect session. Only present when `partial_results` is enabled. `true` indicates collection has ended; `false` indicates more results may follow.

The current collection state. Only present when continuous collect is enabled. **Valid values:** `collecting`, `finished`, `error`.

### Raw JSON example

**Digit input:**

```json { "event_type": "calling.call.collect", "event_channel": "swml:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "timestamp": 1640000000.123, "project_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "space_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "params": { "call_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "node_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "control_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "result": { "type": "digit", "params": { "digits": "1234", "terminator": "#" } } } } ```

**Speech input:**

```json { "event_type": "calling.call.collect", "event_channel": "swml:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "timestamp": 1640000000.123, "project_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "space_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "params": { "call_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "node_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "control_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "result": { "type": "speech", "params": { "text": "one", "confidence": 0.95 } } } } ```

\\\*

## **Examples**

The [`play` method](/docs/swml/reference/play) also has examples related to playing sounds from URLs. The interface for playing sounds for `play` and `prompt` is identical.

### Play prompt and wait for digit press

```yaml version: 1.0.0 sections: main: - prompt: play: 'say:Input a number' - switch: variable: prompt_value default: - play: url: 'say:You didn''t press one' - transfer: dest: main case: '1': - play: url: 'say:You pressed one' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"prompt": {
"play": "say:Input a number"
}
},
{
"switch": {
"variable": "prompt_value",
"default": [
{
"play": {
"url": "say:You didn't press one"
}
},
{
"transfer": {
"dest": "main"
}
}
],
"case": {
"1": [
{
"play": {
"url": "say:You pressed one"
}
}
]
}
}
}
] } } ```

### Using terminators

```yaml version: 1.0.0 sections: main: - prompt: play: 'say:PIN number please' max_digits: 10 terminators: '*#5' - play: url: 'say: ${prompt_value} was terminated by ${prompt_digit_terminator}' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"prompt": {
"play": "say:PIN number please",
"max_digits": 10,
"terminators": "*#5"
}
},
{
"play": {
"url": "say: ${prompt_value} was terminated by ${prompt_digit_terminator}"
}
}
] } } ```

### Play prompt and wait for digit or speech

```yaml version: 1.0.0 sections: main: - prompt: play: 'https://example.com/press\_or\_say\_one.wav' speech_language: en-US max_digits: 1 speech_hints: - one - two - three - four - five - six - seven - eight - nine - switch: variable: prompt_value default: - play: url: 'https://example.com/bad\_input.wav' - transfer: dest: main case: '1': - transfer: dest: 'https://example.com/sales.swml' one: - transfer: dest: 'https://example.com/sales.swml' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"prompt": {
"play": "https://example.com/press\_or\_say\_one.wav",
"speech_language": "en-US",
"max_digits": 1,
"speech_hints": [
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
]
}
},
{
"switch": {
"variable": "prompt_value",
"default": [
{
"play": {
"url": "https://example.com/bad\_input.wav"
}
},
{
"transfer": {
"dest": "main"
}
}
],
"case": {
"1": [
{
"transfer": {
"dest": "https://example.com/sales.swml"
}
}
],
"one": [
{
"transfer": {
"dest": "https://example.com/sales.swml"
}
}
]
}
}
}
] } } ```

### Play prompt and collect digits, then pass the data to an external action

```yaml version: 1.0.0 sections: main: - prompt: play: 'https://example.com/menu.wav' - transfer: dest: 'https://example.com/post\_next\_menu' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"prompt": {
"play": "https://example.com/menu.wav"
}
},
{
"transfer": {
"dest": "https://example.com/post\_next\_menu"
}
}
] } } ```

In this case, the URL listed in transfer will be sent an HTTP POST request with all the [out variables](#set-by-the-method) (like `prompt_value`) already set. For more details on this behavior, refer to [`transfer`](/docs/swml/reference/transfer) statement's documentation.


receive_fax

Receive a fax being delivered to this call.

Properties

receive_fax

objectRequired

An object that accepts the following properties.

receive_fax.status_url

string

HTTP or HTTPS URL to deliver receive fax status events. Learn more about status callbacks.

Variables

Set by the method:

  • receive_fax_document: (out) URL of received document.
  • receive_fax_identity: (out) identity of this fax station.
  • receive_fax_remote_identity: (out) identity of the sending fax station.
  • receive_fax_pages: (out) number of pages received.
  • receive_fax_result_code: (out) fax status code.
  • receive_fax_result_text: (out) description of fax status code.
  • receive_fax_result: (out) success | failed.

StatusCallbacks

A POST request will be sent to status_url with a JSON payload like the following:

event_type

string

The type of event. Always calling.call.fax for this method.

event_channel

string

The channel for the event, includes the SWML session ID.

timestamp

number

Unix timestamp (float) when the event was generated.

project_id

string

The project ID associated with the call.

space_id

string

The Space ID associated with the call.

params

object

An object containing fax-specific parameters.

params.call_id

string

The call ID.

params.node_id

string

The node handling the call.

params.control_id

string

The control ID for this fax operation.

params.fax

object

Fax result details.

fax.type

string

The type of fax operation. Always finished.

fax.params.direction

string

The direction of the fax (receive).

fax.params.identity

string

The identity of this fax station.

fax.params.remote_identity

string

The identity of the sending fax station.

fax.params.document

string

URL of the received fax document.

fax.params.pages

number

Number of pages received.

fax.params.success

boolean

Whether the fax was received successfully.

fax.params.result

number

The numeric result code of the fax operation (e.g., 0 for success).

fax.params.result_text

string

A description of the fax result (e.g., OK).

fax.params.format

string

The format of the fax document. Always "pdf".

Page progress events

A separate callback is sent for each page as the fax progresses:

fax.type

string

Always "page" for page progress events.

fax.params.direction

string

The direction of the fax.

fax.params.number

number

The page number that was just processed.

Raw JSON example

{

  "event_type": "calling.call.fax",

  "event_channel": "swml:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

  "timestamp": 1640000000.123,

  "project_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

  "space_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

  "params": {

    "call_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

    "node_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

    "control_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",

    "fax": {

      "type": "finished",

      "params": {

        "direction": "receive",

        "identity": "+15551231234",

        "remote_identity": "+15553214321",

        "document": "https://your-space.signalwire.com/api/v1/faxes/fax-uuid/download",

        "pages": 3,

        "success": true,

        "result": 0,

        "result_text": "OK",

        "format": "pdf"

      }

    }

  }

}

Examples

Receive a fax and post a result to a webhook

YAMLJSON

version: 1.0.0
sections:
  main:
    - receive_fax: {}
    - execute:
        dest: 'https://<NGROK UUID>.ngrok-free.app'

In this example, when a fax is received, a POST request will be sent to the URL with all the fax related variables (like receive_fax_document) already set. Refer to the execute statement’s documentation for more details on this behavior.


send_sms

Send an outbound message to a PSTN phone number.

Properties

send_sms

objectRequired

An object that accepts the following properties. Supports both SMS and MMS messages. See message types below for the properties specific to each type.

Message types

The send_sms object accepts the following properties depending on the message type:

SMS
MMS
send_sms.to_number

stringRequired

Phone number to send SMS message to in e.164 format

send_sms.from_number

stringRequired

Phone number SMS message will be sent from

send_sms.body

stringRequired

Body of the text message

send_sms.region

stringDefaults to Chosen based on account preferences or device location

Region of the world to originate the message from

send_sms.tags

string[]

Array of tags to associate with the message to facilitate log searches

Variables

Set by the method:

  • send_sms_result: (out) success | failed.

Examples

SMS
MMS

Send a text-only message:

YAMLJSON

version: 1.0.0
sections:
  main:
    - send_sms:
        from_number: "+155512312345"
        to_number: "+15555554321"
        body: "Hi, I hope you're well."

sip_refer

Send SIP REFER to a SIP call.

Properties

sip_refer

objectRequired

An object that accepts the following properties.

sip_refer.to_uri

stringRequired

SIP URI to REFER to.

sip_refer.status_url

string

HTTP or HTTPS URL to deliver SIP REFER status events. Learn more about status callbacks.

sip_refer.username

string

Username to use for SIP authentication.

sip_refer.password

string

Password to use for SIP authentication.

Variables

Set by the method:

  • sip_refer_to: (out) The SIP URI the recipient is to INVITE.
  • sip_refer_result: (out) Overall SIP REFER result.
  • return_value: (out) Same value as sip_refer_result.
  • sip_refer_response_code: (out) Recipient response to the REFER request.
  • sip_refer_to_response_code: (out) INVITE response to the recipient.

StatusCallbacks

A POST request will be sent to status_url with a JSON payload like the following:

event_type

string

The type of event. Always calling.call.refer for this method.

event_channel

string

The channel for the event, includes the SWML session ID.

timestamp

number

Unix timestamp (float) when the event was generated.

project_id

string

The project ID associated with the call.

space_id

string

The Space ID associated with the call.

params

object

An object containing SIP REFER-specific parameters.

params.call_id

string

The call ID.

params.node_id

string

The node handling the call.

params.sip_refer_to

string

The SIP URI the recipient is being referred to.

params.state

string

The overall result of the SIP REFER operation (e.g., success).

params.sip_refer_response_code

string

The SIP response code for the REFER request itself (e.g., "202"). Only present when a response has been received.

params.sip_notify_response_code

string

The SIP response code for the INVITE sent by the recipient to the refer target (e.g., "200"). Only present when a response has been received.

params.segment_id

string

The segment ID for the call leg. Present when available.

params.tag

string

The tag associated with the call. Present when set.

Raw JSON example

{
  "event_type": "calling.call.refer",
  "event_channel": "swml:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "timestamp": 1640000000.123,
  "project_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "space_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "params": {
    "call_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "node_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "sip_refer_to": "sip:alice@example.com",
    "state": "success",
    "sip_refer_response_code": "202",
    "sip_notify_response_code": "200"
  }
}

Examples

Send SIP REFER and post result

YAMLJSON

version: 1.0.0
sections:
  main:
    - sip_refer:
        to_uri: 'sip:alice@example.com'
    - play:
        url: 'say: Connected. The SIP refer result is ${sip_refer_result}'
    - execute:
        dest: 'https://example.com/handle_sip_refer_result'

\\\*

title: stop_denoise max-toc-depth: 3

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

Stop noise reduction (which was started with [`denoise`](/docs/swml/reference/denoise)).

An empty object that accepts no parameters.

## **Variables**

Set by the method:

\* **denoise\_result:** (out) `off`

## **Examples**

### Stop denoise

```yaml version: 1.0.0 sections: main: - stop_denoise: {} - play: url: 'say: Denoising ${denoise_result}' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"stop_denoise": {}
},
{
"play": {
"url": "say: Denoising ${denoise_result}"
}
}
] } } ```


tap

Start background call tap. Media is streamed over Websocket or RTP to customer controlled URI.

Properties

tap

objectRequired

An object that accepts the following properties.

tap.uri

stringRequired

Destination of the tap media stream: rtp://IP:port, ws://example.com, or wss://example.com

tap.control_id

stringDefaults to Auto-generated, stored in the tap_control_id variable

Identifier for this tap to use with stop_tap

tap.direction

string

speak“ Direction of the audio to tap: speak for what party says, listen for what party hears, both for what party hears and says

tap.codec

string

PCMU“ PCMU or PCMA

tap.rtp_ptime

integerDefaults to 20 ms

If using a rtp:// URI, this optional parameter can set the packetization time of the media in milliseconds. Optional. Default 20 ms.

tap.status_url

string

HTTP or HTTPS URL to deliver tap status events. Learn more about status callbacks.

Variables

Set by the method:

  • tap_uri: (out) The destination URI of the newly started tap.
  • tap_result: (out) success | failed.
  • tap_control_id: (out) Control ID of this tap.
  • tap_rtp_src_addr: (out) If RTP, source address of the tap stream.
  • tap_rtp_src_port: (out) If RTP, source port of the tap stream.
  • tap_ptime: (out) Packetization time of the tap stream.
  • tap_codec: (out) Codec in the tap stream.
  • tap_rate: (out) Sample rate in the tap stream.

StatusCallbacks

A POST request will be sent to status_url with a JSON payload like the following:

event_type

string

The type of event. Always calling.call.tap for this method.

event_channel

string

The channel for the event, includes the SWML session ID.

timestamp

number

Unix timestamp (float) when the event was generated.

project_id

string

The project ID associated with the call.

space_id

string

The Space ID associated with the call.

params

object

An object containing tap-specific parameters.

params.call_id

string

The call ID.

params.node_id

string

The node handling the call.

params.segment_id

string

The segment ID for the call leg. Present when available.

params.tag

string

The tag associated with the call. Present when set.

params.control_id

string

The control ID for this tap operation.

params.state

string

The current tap state. Valid values:tapping, finished.

params.tap

object

Details about the tap media stream.

tap.type

string

The type of media being tapped (e.g., audio).

tap.params.direction

string

The direction of audio being tapped.

params.device

object

Details about the destination device receiving the tap stream.

device.type

string

The type of device (e.g., rtp, ws).

device.params.addr

string

The destination address for the tap stream.

device.params.port

number

The destination port for the tap stream.

device.params.codec

string

The audio codec used for the tap stream (e.g., PCMU, PCMA).

device.params.ptime

number

The packetization time in milliseconds. Present for RTP taps only.

device.params.uri

string

The WebSocket destination URI. Present for WebSocket taps only.

Raw JSON example

{
  "event_type": "calling.call.tap",
  "event_channel": "swml:xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "timestamp": 1640000000.123,
  "project_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "space_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "params": {
    "call_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "node_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "segment_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "control_id": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "state": "tapping",
    "tap": {
      "type": "audio",
      "params": {
        "direction": "both"
      }
    },
    "device": {
      "type": "rtp",
      "params": {
        "addr": "192.168.1.100",
        "port": 12345,
        "codec": "PCMU",
        "ptime": 20
      }
    }
  }
}

Examples

Start WSS tap

YAMLJSON

version: 1.0.0
sections:
  main:
    - tap:
        uri: wss://example.com/tap

\\\*

title: Template functions subtitle: Reference for built-in transformation functions max-toc-depth: 3

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

Template functions provide simple text transformations for common operations like converting to lowercase, URL encoding, and date formatting. They complement JavaScript expressions by handling specific formatting tasks that don't require complex logic.

For information about variable scopes, see the [Variables Reference](/docs/swml/reference/variables). For JavaScript expressions and data manipulation, see the [Expressions Reference](/docs/swml/reference/expressions).

Template functions are **only** available in [SWAIG (SignalWire AI Gateway)](/docs/swml/reference/ai/swaig) contexts, specifically within:

\* AI function `data_map` processing (expressions, webhooks, output) \* Webhook responses to SWAIG functions \* AI prompt variable expansion

They are **not** available in regular SWML methods or general variable contexts. For regular SWML variable manipulation, use JavaScript expressions with the `${expression}` syntax instead.

## Reference

Converts a string to lowercase. Commonly used to normalize user input for case-insensitive comparisons or ensure consistent casing when accessing object properties dynamically.

**Syntax:** `${lc:}`

**Example:**

```yaml {13} startLine={8} maxLines=10 SWAIG: functions: - function: lookup parameters: type: object properties: department: type: string data_map: expressions: - string: '${meta_data.contacts.${lc:args.department}}' pattern: '\w+' output: response: "Found contact for ${args.department}" meta_data: contacts: sales: '+12025551234' support: '+12025555678' ```

```json {19} startLine={14} maxLines=10 { "SWAIG": { "functions": [
{
"function": "lookup",
"description": "Look up department contact",
"parameters": {
"type": "object",
"properties": {
"department": {
"type": "string",
"description": "Department name from user"
}
}
},
"data_map": {
"expressions": [
{
"string": "${meta_data.contacts.${lc:args.department}}",
"pattern": "\\w+",
"output": {
"response": "Found contact for ${args.department}"
}
}
]
},
"meta_data": {
"contacts": {
"sales": "+12025551234",
"support": "+12025555678"
}
}
}
] } } ```

Encodes a string for safe use in URLs by converting special characters to percent-encoded equivalents. Always use this when including variables in URL query parameters or paths to prevent special characters from breaking URLs or causing unexpected behavior.

**Syntax:** `${enc:url:}`

**Example:**

```yaml {13} startLine={8} maxLines=10 SWAIG: functions: - function: search parameters: type: object properties: query: type: string data_map: webhooks: - url: 'https://api.example.com/search?q=${enc:url:args.query}' method: GET output: response: "Found ${results.total} results for ${args.query}" ```

```json {19} startLine={14} maxLines=10 { "SWAIG": { "functions": [
{
"function": "search",
"description": "Search external knowledge base",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "User's search query"
}
}
},
"data_map": {
"webhooks": [
{
"url": "https://api.example.com/search?q=${enc:url:args.query}",
"method": "GET",
"output": {
"response": "Found ${results.total} results for ${args.query}"
}
}
]
}
}
] } } ```

Formats the current date and time using standard strftime format codes with timezone support. This generates timestamps at the moment the template is evaluated, not when the SWML script was created.

**Syntax:** `@{strftime_tz }`

**Common format codes:**

| Code | Description | Example | | --------------- | ------------------ | ------------------------ | | `%Y-%m-%d` | ISO date | 2025-01-15 | | `%H:%M:%S` | 24-hour time | 14:30:45 | | `%I:%M %p` | 12-hour time | 02:30 PM | | `%A, %B %d, %Y` | Full readable date | Monday, January 15, 2025 |

**Example:**

```yaml {10} startLine={5} maxLines=10 SWAIG: functions: - function: log_call data_map: webhooks: - url: 'https://api.example.com/logs' method: POST params: timestamp: '@{strftime_tz America/Chicago %Y-%m-%d %H:%M:%S}' call_id: '${call.call_id}' from: '${call.from}' output: response: "Call logged successfully" ```

```json {13} startLine={8} maxLines=10 { "SWAIG": { "functions": [
{
"function": "log_call",
"description": "Log call details with timestamp",
"data_map": {
"webhooks": [
{
"url": "https://api.example.com/logs",
"method": "POST",
"params": {
"timestamp": "@{strftime_tz America/Chicago %Y-%m-%d %H:%M:%S}",
"call_id": "${call.call_id}",
"from": "${call.from}"
},
"output": {
"response": "Call logged successfully"
}
}
]
}
}
] } } ```

Formats a phone number using specified international format standards. Supports multiple format types for different use cases, with optional separators for improved text-to-speech pronunciation.

**Syntax:** `@{fmt_ph }` or `@{fmt_ph :sep:}`

**Available formats:**

\* `national` - National format (default) \* `international` - International format with country code \* `RFC3966` - RFC 3966 format (tel: URI) \* `e164` - E.164 format (+1234567890)

**Example:**

```yaml {8-9} startLine={4} maxLines=10 SWAIG: functions: - function: format_number data_map: output: response: | International format: @{fmt_ph international ${call.from}} Spaced format: @{fmt_ph national:sep:- ${call.from}} ```

```json {9} startLine={4} maxLines=10 { "SWAIG": { "functions": [
{
"function": "format_number",
"description": "Format phone number for speech",
"data_map": {
"output": {
"response": "International format: @{fmt_ph international ${call.from}}\nSpaced format: @{fmt_ph national:sep:- ${call.from}}"
}
}
}
] } } ```

Evaluates simple arithmetic expressions with literal numbers. Supports addition, subtraction, multiplication, division, and parentheses for grouping. Only works with literal numbers and cannot reference variables.

**Syntax:** `@{expr }`

**Example:**

```yaml {7} startLine={2} maxLines=10 SWAIG: functions: - function: calculate_discount data_map: output: response: "The discount is @{expr (100 - 25) / 5} dollars" ```

```json {9} startLine={4} maxLines=10 { "SWAIG": { "functions": [
{
"function": "calculate_discount",
"description": "Calculate discount amount",
"data_map": {
"output": {
"response": "The discount is @{expr (100 - 25) / 5} dollars"
}
}
}
] } } ```

Returns the argument unchanged. Primarily useful for debugging template evaluation or forcing explicit variable expansion in complex nested scenarios.

**Syntax:** `@{echo }`

**Example:**

```yaml {13} startLine={8} maxLines=10 SWAIG: functions: - function: debug_value parameters: type: object properties: input: type: string data_map: output: response: "Debug value: @{echo ${args.input}}" ```

```json {18} startLine={13} maxLines=10 { "SWAIG": { "functions": [
{
"function": "debug_value",
"description": "Debug template evaluation",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Value to debug"
}
}
},
"data_map": {
"output": {
"response": "Debug value: @{echo ${args.input}}"
}
}
}
] } } ```

Inserts spaces between each character in a string to improve text-to-speech pronunciation. Particularly useful for spelling out confirmation codes, license plates, serial numbers, or any text that should be read character-by-character.

**Syntax:** `@{separate }`

**Example:**

```yaml {13} startLine={8} maxLines=10 SWAIG: functions: - function: spell_code parameters: type: object properties: code: type: string data_map: output: response: "Your code is @{separate ${args.code}}" ```

```json {18} startLine={13} maxLines=10 { "SWAIG": { "functions": [
{
"function": "spell_code",
"description": "Spell out confirmation code",
"parameters": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Confirmation code to spell"
}
}
},
"data_map": {
"output": {
"response": "Your code is @{separate ${args.code}}"
}
}
}
] } } ```

In this example, if `code` is "ABC123", the AI will pronounce "A B C 1 2 3" instead of trying to say "ABC123" as a word.

Pauses execution for the specified number of seconds. Can be used for rate limiting, timing coordination, or testing purposes.

**Syntax:** `@{sleep }`

Use sparingly in production environments. Excessive delays can cause timeouts, impact call quality, and degrade user experience. Best suited for development, testing, or specific rate-limiting scenarios.

**Example:**

```yaml {7} startLine={2} maxLines=10 SWAIG: functions: - function: delayed_task data_map: output: response: "Executed after @{sleep 2} second delay" ```

```json {9} startLine={4} maxLines=10 { "SWAIG": { "functions": [
{
"function": "delayed_task",
"description": "Execute with delay for rate limiting",
"data_map": {
"output": {
"response": "Executed after @{sleep 2} second delay"
}
}
}
] } } ```

## Function chaining

Prefix functions (using `${...}` syntax) can be chained together to apply multiple transformations in sequence. The transformations are applied from left to right.

**Syntax:** `${func1:func2:func3:}`

**Example:**

```yaml {14} startLine={9} maxLines=10 SWAIG: functions: - function: search parameters: type: object properties: query: type: string data_map: webhooks:

First converts to lowercase, then URL encodes

- url: 'https://api.example.com/search?q=${lc:enc:url:args.query}' method: GET output: response: "Found results for ${args.query}" ```

```json {19} startLine={14} maxLines=10 { "SWAIG": { "functions": [
{
"function": "search",
"description": "Search external knowledge base",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "User's search query"
}
}
},
"data_map": {
"webhooks": [
{
"url": "https://api.example.com/search?q=${lc:enc:url:args.query}",
"method": "GET",
"output": {
"response": "Found results for ${args.query}"
}
}
]
}
}
] } } ```

## Full example

```yaml version: 1.0.0 sections: main: - answer: {} - ai: prompt: text: | You help users access department resources. When they specify a department, use the lookup function. SWAIG: functions: - function: lookup parameters: type: object properties: department: type: string data_map: expressions: - string: '${meta_data.contacts.${lc:args.department}}' pattern: '\w+' output: response: "Found contact for ${args.department}" meta_data: contacts: sales: '+12025551234' support: '+12025555678' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"answer": {}
},
{
"ai": {
"prompt": {
"text": "You help users access department resources.\nWhen they specify a department, use the lookup function.\n"
},
"SWAIG": {
"functions": [
{
"function": "lookup",
"description": "Look up department contact",
"parameters": {
"type": "object",
"properties": {
"department": {
"type": "string",
"description": "Department name from user"
}
}
},
"data_map": {
"expressions": [
{
"string": "${meta_data.contacts.${lc:args.department}}",
"pattern": "\\w+",
"output": {
"response": "Found contact for ${args.department}"
}
}
]
},
"meta_data": {
"contacts": {
"sales": "+12025551234",
"support": "+12025555678"
}
}
}
]
}
}
}
] } } ```


\\\*

title: unset max-toc-depth: 3

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

Unset specified variables. The variables have been set either using the [`set`](/docs/swml/reference/set) command or as a byproduct of some other statements or methods (like [`record`](/docs/swml/reference/record))

The name of the variable to unset (as a string) or an array of variable names to unset.

## **Variable**

Any variable can be unset by this method.

## **Examples**

### Unset a single variable

```yaml version: 1.0.0 sections: main: - set: num_var: 1 - play: url: 'say: The value of num_var is: ${num_var}.' - unset: num_var - play: url: 'say: The value of num_var is ${num_var}.' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"set": {
"num_var": 1
}
},
{
"play": {
"url": "say: The value of num_var is: ${num_var}."
}
},
{
"unset": "num_var"
},
{
"play": {
"url": "say: The value of num_var is ${num_var}."
}
}
] } } ```

### Unset multiple variables

```yaml version: 1.0.0 sections: main: - set: systems: hr: - tracy - luke engineering: john: absent name: john - play: url: 'say: ${systems.hr}' - unset: - systems - name

this play statement emits an error because `systems` is undefined

at this point so there's nothing for `play` to say.

- play: url: 'say: ${systems}' ```

```json { "version": "1.0.0", "sections": { "main": [
{
"set": {
"systems": {
"hr": [
"tracy",
"luke"
],
"engineering": {
"john": "absent"
}
},
"name": "john"
}
},
{
"play": {
"url": "say: ${systems.hr}"
}
},
{
"unset": [
"systems",
"name"
]
},
{
"play": {
"url": "say: ${systems}"
}
}
] } } ```

## **See Also**

\* **[Variables and Expressions](/docs/swml/reference/variables)**: Complete reference for SWML variables, scopes, and syntax \* **[set](/docs/swml/reference/set)**: Set variables in the script

SignalWire Developer Documentation