### Queue Examples Source: https://developer.signalwire.com/swml/methods/enter_queue Examples demonstrating how to use the queue functionality, including basic queue setup and queues with status callbacks. ```APIDOC ## Queue Examples ### Basic Queue #### YAML Example: ```yaml version: 1.0.0 sections: main: - enter_queue: queue_name: "my_queue" transfer_after_bridge: "https://example.com/post-call-swml" ``` #### JSON Example: ```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 Example: ```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 Example: ```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" } } ] } } ``` ``` -------------------------------- ### Basic Agent Setup with SignalWire LLM SDK Source: https://developer.signalwire.com/sdks/agents-sdk/examples/by-feature This example provides a minimal setup for a SignalWire LLM agent. It initializes the agent, defines its role, specifies the language model, and includes the standard run command. ```python from signalwire_agents import AgentBase agent = AgentBase(name="basic", route="/basic") agent.prompt_add_section("Role", "You are a helpful assistant.") agent.add_language("English", "en-US", "rime.spore") if __name__ == "__main__": agent.run() ``` -------------------------------- ### Create a Minimal Agent with SignalWire LLM SDK Source: https://developer.signalwire.com/sdks/agents-sdk/examples/by-feature This example demonstrates the basic setup for creating a SignalWire LLM agent. It initializes an agent, sets its role, adds language support, and starts the agent's execution. ```python from signalwire_agents import AgentBase agent = AgentBase(name="hello", route="/hello") agent.prompt_add_section("Role", "You are a friendly assistant.") agent.add_language("English", "en-US", "rime.spore") if __name__ == "__main__": agent.run() ``` -------------------------------- ### Listen for RoomSessionMember Joins Source: https://developer.signalwire.com/sdks/realtime-sdk/video/room-session-member This example demonstrates how to initialize the SignalWire client, access the video client, and set up a listener for when a room starts. Inside the room started listener, it further sets up a listener for when a member joins, logging the RoomSessionMember object to the console. ```javascript import { SignalWire } from "@signalwire/realtime-api"; // Intialize the SignalWire Client const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }) // Access the video client from the SignalWire client const videoClient = client.video; // Setup listerner for when a room starts await videoClient.listen({ onRoomStarted: async (roomsession) => { roomsession.listen({ onMemberJoined: (member) => { console.log("RoomSessionMember:", member); }, }); } }); ``` -------------------------------- ### Room Playback Example Source: https://developer.signalwire.com/sdks/realtime-sdk/video/roomsession This example demonstrates how to wait for a room to start, play audio, and then retrieve playback details when a new member joins. ```APIDOC ## Room Playback Example ### Description This example demonstrates how to wait for a room to start, play audio, and then retrieve playback details when a new member joins. ### Method N/A (Client-side JavaScript example) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript import { SignalWire } from "@signalwire/realtime-api"; // Initialize the SignalWire client const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }) // Access the video client from the main client const videoClient = client.video; // Setup listener for when a room starts await videoClient.listen({ onRoomStarted: async (roomSession) => { console.log("Room started", roomSession.displayName); // play wait music await roomSession.play({ url: "https://cdn.signalwire.com/default-music/welcome.mp3", listen: { onStarted: () => console.log("Playback started"), onUpdated: (playback) => console.log("Playback updated", playback.state), onEnded: () => console.log("Playback ended") } }).onStarted(); // Setup listener for when a member joins await roomSession.listen({ onMemberJoined: async (member) => { console.log("Member joined", member.name); // get roomSessions playbacks let roomPlaybacks = await roomSession.getPlaybacks(); // loop through playbacks and print out state, url, and id roomPlaybacks.playbacks.forEach((playback) => { console.log(playback.state, playback.url, playback.id); }); }, onMemberLeft: (member) => { console.log("Member left", member.name); }, }); }, onRoomEnded: async (roomSession) => { console.log("Room ended", roomSession.displayName); } }); ``` ### Response #### Success Response (200) N/A (Client-side JavaScript example) #### Response Example N/A ``` -------------------------------- ### Multi-Agent Server Setup in Python Source: https://developer.signalwire.com/sdks/agents-sdk/examples/by-complexity A basic Python script to set up a server that hosts multiple specialized LLM agents. This example demonstrates the foundational structure for a multi-agent system. ```python #!/usr/bin/env python3 ``` -------------------------------- ### Minimal Production Setup Source: https://developer.signalwire.com/sdks/agents-sdk/api/agent-base Provides a configuration example for a minimal production setup, emphasizing security and compliance. ```APIDOC ## Minimal Production Setup ### Description Configuration for a minimal production environment, including basic authentication and call recording. ### Request Example ```python agent = AgentBase( name="support", route="/support", basic_auth=("user", "pass"), # Always use auth in production record_call=True, # Enable for compliance record_stereo=True # Separate channels for analysis ) ``` ``` -------------------------------- ### Video Room Session Playback Example Source: https://developer.signalwire.com/sdks/realtime-sdk/video/room-session-playback This example demonstrates how to initialize the SignalWire client, access the video client, listen for room start events, play audio, set volume, and listen for member join/leave events. ```APIDOC ## POST /video/rooms/{room_id}/play ### Description Starts playing audio or video within a video room session. This endpoint allows for playback of media files and provides options for event listeners. ### Method POST ### Endpoint /video/rooms/{room_id}/play ### Parameters #### Path Parameters - **room_id** (string) - Required - The unique identifier of the video room. #### Query Parameters None #### Request Body - **url** (string) - Required - The URL of the media file to play. - **listen** (object) - Optional - An object containing callback functions for playback events. - **onStarted** (function) - Callback function when playback starts. - **onEnded** (function) - Callback function when playback ends. - **onUpdated** (function) - Callback function when playback status is updated. ### Request Example ```json { "url": "https://cdn.signalwire.com/default-music/welcome.mp3", "listen": { "onStarted": "() => console.log('Playback started')", "onEnded": "() => console.log('Playback ended')" } } ``` ### Response #### Success Response (200) - **playback_id** (string) - The unique identifier for the playback instance. - **status** (string) - The current status of the playback (e.g., 'playing', 'ended'). #### Response Example ```json { "playback_id": "some_playback_id", "status": "playing" } ``` ``` -------------------------------- ### Listen for Collect Session Start with SignalWire Source: https://developer.signalwire.com/sdks/realtime-sdk/voice/call This example demonstrates how to detect the beginning of a collect session in SignalWire. The `onCollectStarted` callback is invoked when a collect operation is initiated, providing a `CallCollect` object. This allows for setup or logging at the start of user input gathering. ```javascript // Example usage within a call object: // call.listen({ onCollectStarted: Callback }); ``` -------------------------------- ### Start Audio Stream with SignalWire SDKs Source: https://developer.signalwire.com/compatibility-api/cxml/voice/stream These code examples demonstrate how to initiate an audio stream to a WebSocket server using SignalWire's SDKs in various programming languages. They show how to configure the stream URL and optionally add parameters for authentication or metadata. The generated TwiML (or equivalent) is then printed. ```javascript const { RestClient } = require("@signalwire/compatibility-api"); const response = new RestClient.LaML.VoiceResponse(); const start = response.start(); start.stream({ name: "Example Audio Stream", url: "wss://your-application.com/audiostream", }); console.log(response.toString()); ``` ```csharp using System; using Twilio.TwiML; using Twilio.TwiML.Voice; class Example { static void Main() { var response = new VoiceResponse(); var start = new Start(); start.Stream(name: "Example Audio Stream", url: "wss://your-application.com/audiostream"); response.Append(start); Console.WriteLine(response.ToString()); } } ``` ```python from signalwire.voice_response import Parameter, VoiceResponse, Start, Stream response = VoiceResponse() start = Start() stream = Stream(url='wss://your-application.com/audiostream') stream.parameter(name='FirstName', value='Jane') stream.parameter(name='LastName', value='Doe') start.append(stream) response.append(start) print(response) ``` ```ruby require 'signalwire/sdk' response = Signalwire::Sdk::VoiceResponse.new response.start do |start| start.stream(url: 'wss://your-application.com/audiostream') do |stream| stream.parameter(name: 'FirstName', value: 'Jane') stream.parameter(name: 'LastName', value: 'Doe') end end puts response ``` -------------------------------- ### Get Available Room Layouts Source: https://developer.signalwire.com/sdks/realtime-sdk/video/roomsession This example demonstrates how to retrieve a list of available layouts for a SignalWire video room. It assumes an active RoomSession and is typically called after the room has started. ```javascript import { SignalWire } from "@signalwire/realtime-api"; // Initialize the SignalWire client const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }) // Access the video client from the main client const videoClient = client.video; // Setup listener for when a room starts await videoClient.listen({ onRoomStarted: async (roomsession) => { console.log("Room started", roomsession.displayName); const layouts = await roomsession.getLayouts(); console.log("Layouts", layouts.layouts); } }) ``` -------------------------------- ### Set and Get Room Metadata in JavaScript Source: https://developer.signalwire.com/sdks/realtime-sdk/video/roomsession This example shows how to set and retrieve metadata for a SignalWire video room. It initializes the client, listens for room start events, sets custom metadata, and then fetches that metadata. ```javascript import { SignalWire } from "@signalwire/realtime-api"; // Initialize the SignalWire client const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }) // Access the video client from the main client const videoClient = client.video; // Setup listener for when a room starts await videoClient.listen({ onRoomStarted: async (roomSession) => { console.log("Room started", roomSession.displayName); // Set the room meta console.log("Setting room meta"); await roomSession.setMeta({ "foo": "bar", "roomName": roomSession.displayName }); // Get the room meta let roomMeta = await roomSession.getMeta() console.log("Room meta", roomMeta); }, onRoomEnded: async (roomSession) => { console.log("Room ended", roomSession.displayName); } }); ``` -------------------------------- ### Starting and Stopping Streams Source: https://developer.signalwire.com/compatibility-api/cxml/voice/stream Examples of XML configurations for starting and stopping named streams. ```APIDOC ## Stream Management (Start/Stop) ### Description Demonstrates how to start and stop streams by assigning them a unique name. ### Method N/A (XML Configuration) ### Endpoint N/A (XML Configuration) ### Request Example (Start Stream) ```xml ``` ### Request Example (Stop Stream) ```xml ``` ### Response N/A (XML Configuration) ``` -------------------------------- ### Quick Start: sw-search CLI Usage Source: https://developer.signalwire.com/sdks/agents-sdk/api/cli-sw-search Demonstrates basic commands for building, searching, and validating a search index using the sw-search CLI. This includes creating an index from a directory, performing a search query, and entering an interactive search shell. ```bash ## Build index from documentation sw-search ./docs --output knowledge.swsearch ## Search the index sw-search search knowledge.swsearch "how to create an agent" ## Interactive search shell sw-search search knowledge.swsearch --shell ## Validate index sw-search validate knowledge.swsearch ``` -------------------------------- ### Task Client Setup Source: https://developer.signalwire.com/sdks/realtime-sdk/task/client Demonstrates how to initialize a SignalWire Realtime Client and access the Task client. ```APIDOC ## Task Client Setup ### Description Initializes a SignalWire Realtime Client and accesses the Task client namespace. ### Method ```javascript import { SignalWire } from "@signalwire/realtime-api"; const client = await SignalWire({ project: "ProjectID Here", token: "Token Here"}); const taskClient = client.task; ``` ### Request Example ```javascript import { SignalWire } from "@signalwire/realtime-api"; const client = await SignalWire({ project: "ProjectID Here", token: "Token Here"}); const taskClient = client.task; ``` ``` -------------------------------- ### Create a SWML Script for Incoming Calls (YAML) Source: https://developer.signalwire.com/voice/getting-started/making-and-receiving-phone-calls This SWML script defines a simple behavior for incoming calls, playing a greeting message. It's a basic example to get started with handling inbound calls via SWML. ```yaml version: 1.0.0 sections: main: - play: say:Hello from SignalWire! ``` -------------------------------- ### Video Client Setup Source: https://developer.signalwire.com/sdks/realtime-sdk/video/client Demonstrates how to initialize the SignalWire Realtime Client and access the Video client namespace. ```APIDOC ## POST /client/video ### Description Initializes the SignalWire Realtime Client and provides access to the Video client. ### Method POST ### Endpoint /client/video ### Parameters #### Query Parameters - **project** (string) - Required - Your SignalWire Project ID. - **token** (string) - Required - Your SignalWire API Token. ### Request Example ```javascript import { SignalWire } from "@signalwire/realtime-api"; const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }); const videoClient = client.video; ``` ### Response #### Success Response (200) - **videoClient** (object) - An instance of the Video client. #### Response Example ```json { "videoClient": { /* Video client object */ } } ``` ``` -------------------------------- ### Start Denoise using JSON Source: https://developer.signalwire.com/swml/methods/denoise This JSON example shows the equivalent of the YAML example for starting the denoise function in the SignalWire LLM API. It configures the workflow to begin noise reduction and announce the outcome. ```json { "version": "1.0.0", "sections": { "main": [ { "answer": {} }, { "denoise": {} }, { "play": { "url": "say: Denoising ${denoise_result}" } } ] } } ``` -------------------------------- ### SignalWire SDK Integration Example Source: https://developer.signalwire.com/platform/call-fabric/subscribers Examples demonstrating how to integrate the SignalWire SDK for authentication, making calls, and receiving calls. ```APIDOC ## SignalWire SDK Integration Example ### Description Examples demonstrating how to integrate the SignalWire SDK for authentication, making calls, and receiving calls. ### Code Snippets #### 1. Client Initialization ```javascript import { SignalWire } from "@signalwire/js"; // Initialize the client with your token const client = await SignalWire({ token: "" // Replace with your actual token }); // Client is now ready to make and receive calls console.log("SignalWire client initialized"); ``` #### 2. Making a Call ```javascript import { SignalWire } from "@signalwire/js"; // Initialize the client const client = await SignalWire({ token: "" }); // Make a call to another subscriber const call = await client.dial({ to: "/private/jane-doe", rootElement: document.getElementById("videoContainer") }); // Handle call events call.on("call.state", (state) => { console.log("Call state:", state); }); ``` #### 3. Receiving a Call ```javascript import { SignalWire } from "@signalwire/js"; // Define the incoming call handler const handleIncomingCall = async (notification) => { const { invite } = notification; console.log("Incoming call from:", invite.from); // Accept the call const call = await invite.accept({ rootElement: document.getElementById("videoContainer") }); }; // Initialize the client with the handler const client = await SignalWire({ token: "", incomingCallHandlers: { all: handleIncomingCall } }); ``` ``` -------------------------------- ### Run the SignalWire Agent (Bash) Source: https://developer.signalwire.com/sdks/agents-sdk/quickstart This command executes the Python script to start the SignalWire AI agent. The agent will begin listening on a local server, typically port 3000, and display startup information including authentication credentials. ```bash python my_first_first_agent.py ``` -------------------------------- ### Initialize Video Client with SignalWire Source: https://developer.signalwire.com/sdks/realtime-sdk/video/client Demonstrates how to set up a SignalWire Video client. It requires creating a SignalWire Realtime Client instance first, then accessing the video namespace. ```javascript import { SignalWire } from "@signalwire/realtime-api"; const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }) const videoClient = client.video; ``` -------------------------------- ### Create Basic Video Room with HTML and JavaScript Source: https://developer.signalwire.com/video/getting-started/video-first-steps This HTML file sets up a basic video room using the SignalWire JavaScript SDK. It includes necessary script imports, a div for video display, and a JavaScript function to connect to a video room using an authentication token obtained via an Axios POST request. This is suitable for demonstration purposes. ```html
``` -------------------------------- ### Install FreeSWITCH Development Branch (Debian) Source: https://developer.signalwire.com/freeswitch/FreeSWITCH-Explained/Installation/Linux/Deprecated-Installation-Instructions/27590677 Installs the development branch of FreeSWITCH from the official Debian repository. This is not recommended for production environments. It adds the unstable repository, imports the GPG key, and installs the freeswitch-meta-all package. ```bash apt-get update && apt-get install -y gnupg2 wget lsb-release software-properties-common apt-transport-https USERNAME=FSAUSERPASSWORD=FSAPASSwget --http-user=$USERNAME --http-password=$PASSWORD -O - https://fsa.freeswitch.com/repo/deb/fsa/pubkey.gpg | apt-key add -echo "machine fsa.freeswitch.com login $USERNAME password $PASSWORD" > /etc/apt/auth.confecho "deb https://fsa.freeswitch.com/repo/deb/fsa/ `lsb_release -sc` unstable" > /etc/apt/sources.list.d/freeswitch.listecho "deb-src https://fsa.freeswitch.com/repo/deb/fsa/ `lsb_release -sc` unstable" >> /etc/apt/sources.list.d/freeswitch.listapt-get update && apt-get install -y freeswitch-meta-all ``` -------------------------------- ### Say 'Hello World' using SignalWire SDKs Source: https://developer.signalwire.com/compatibility-api/cxml/voice/say Examples of how to use the Say verb to have the SignalWire API speak 'Hello World'. This is demonstrated across multiple programming languages. ```xml Hello World. ``` ```javascript const { RestClient } = require("@signalwire/compatibility-api"); const response = new RestClient.LaML.VoiceResponse(); response.say("Hello World."); console.log(response.toString()); ``` ```csharp using Twilio.TwiML; using System; class Example { static void Main() { var response = new VoiceResponse(); response.Say("Hello World."); Console.WriteLine(response.ToString());; } } ``` ```python from signalwire.voice_response import VoiceResponse, Say response = VoiceResponse() response.say('Hello World.') print(response) ``` ```ruby require 'signalwire/sdk' response = Signalwire::Sdk::VoiceResponse.new do |response| response.say(message: 'Hello World.') end puts response.to_s ``` -------------------------------- ### Install FreeSWITCH Latest Release Branch (Debian) Source: https://developer.signalwire.com/freeswitch/FreeSWITCH-Explained/Installation/Linux/Deprecated-Installation-Instructions/27590677 Installs the latest stable release of FreeSWITCH from the official Debian repository. It adds the repository, imports the GPG key, and installs the freeswitch-meta-all package. Ensure you have the correct USERNAME and PASSWORD for the repository. ```bash apt-get update && apt-get install -y gnupg2 wget lsb-release software-properties-common apt-transport-https USERNAME=FSAUSERPASSWORD=FSAPASSwget --http-user=$USERNAME --http-password=$PASSWORD -O - https://fsa.freeswitch.com/repo/deb/fsa/pubkey.gpg | apt-key add -echo "machine fsa.freeswitch.com login $USERNAME password $PASSWORD" > /etc/apt/auth.confecho "deb https://fsa.freeswitch.com/repo/deb/fsa/ `lsb_release -sc` 1.8" > /etc/apt/sources.list.d/freeswitch.listecho "deb-src https://fsa.freeswitch.com/repo/deb/fsa/ `lsb_release -sc` 1.8" >> /etc/apt/sources.list.d/freeswitch.listapt-get update && apt-get install -y freeswitch-meta-all ``` -------------------------------- ### Initialize and Use PubSub Client Source: https://developer.signalwire.com/sdks/browser-sdk/pubsub/client Demonstrates how to initialize the PubSub.Client with a token, subscribe to channels, listen for incoming messages, and publish messages to a channel. Requires the '@signalwire/js' library. ```javascript import { PubSub } from "@signalwire/js"; const pubSubClient = new PubSub.Client({ token: "", // get this from the REST APIs }); await pubSubClient.subscribe(["mychannel1", "mychannel2"]); pubSubClient.on("message", (message) => { console.log("Received", message.content, "on", message.channel, "at", message.publishedAt); }); await pubSubClient.publish({ channel: "mychannel1", content: "hello world", }); ``` -------------------------------- ### Video Streaming Example Source: https://developer.signalwire.com/sdks/realtime-sdk/video/roomsession This example demonstrates how to start a stream in a SignalWire room, wait for it to begin, and then stop it after a specified duration. It assumes an active RoomSession. ```APIDOC ## POST /video/rooms/:id/stream ### Description Starts a media stream within a specified video room. ### Method POST ### Endpoint `/video/rooms/:id/stream` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the room. #### Query Parameters None #### Request Body - **url** (string) - Required - The RTMP URL to stream to. ### Request Example ```json { "url": "rtmp://example.com/stream" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the stream. - **state** (string) - The current state of the stream (e.g., "active", "stopped"). #### Response Example ```json { "id": "stream-12345", "state": "active" } ``` ## POST /video/rooms/:id/stream/:streamId/stop ### Description Stops an active media stream within a specified video room. ### Method POST ### Endpoint `/video/rooms/:id/stream/:streamId/stop` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the room. - **streamId** (string) - Required - The unique identifier of the stream to stop. #### Query Parameters None #### Request Body None ### Request Example (No request body) ### Response #### Success Response (200) - **id** (string) - The unique identifier of the stream. - **state** (string) - The final state of the stream (e.g., "stopped"). #### Response Example ```json { "id": "stream-12345", "state": "stopped" } ``` ``` -------------------------------- ### Access FreeSWITCH CLI Source: https://developer.signalwire.com/freeswitch/FreeSWITCH-Explained/Installation/Linux/Deprecated-Installation-Instructions/27590677 Command to access the FreeSWITCH command-line interface after installation. The -rRS flags are used for remote, reload, and system access. ```bash fs_cli -rRS ``` -------------------------------- ### Create a Simple Hello World Agent (Python) Source: https://developer.signalwire.com/sdks/agents-sdk/examples/by-complexity This Python script demonstrates the creation of the simplest possible agent. It initializes an agent with a name and route, adds a role description, and specifies a language. The agent is then run. ```python #!/usr/bin/env python3 ## hello_world_agent.py - Simplest possible agent from signalwire_agents import AgentBase agent = AgentBase(name="hello", route="/hello") agent.prompt_add_section("Role", "Say hello and have a friendly conversation.") agent.add_language("English", "en-US", "rime.spore") if __name__ == "__main__": agent.run() ``` -------------------------------- ### Complete C2CButton Configuration Example in JavaScript Source: https://developer.signalwire.com/tools/c2c/technical-reference This comprehensive example demonstrates the configuration of the `C2CButton` with various parameters, including core settings and callback functions for managing the call lifecycle. It covers `beforeCallStartFn`, `afterCallStartFn`, `beforeCallLeaveFn`, `afterCallLeaveFn`, and `onCallError`. ```javascript sw.c2c.spawn('C2CButton', { // Core parameters destination: '/public/support', buttonParentSelector: '#click2call', callParentSelector: '#call', innerHTML: '', // Callback parameters beforeCallStartFn: () => { console.log('Preparing to start call...'); document.getElementById('loading').style.display = 'block'; return true; }, afterCallStartFn: () => { console.log('Call connected!'); document.getElementById('loading').style.display = 'none'; document.getElementById('click2call').style.display = 'none'; }, beforeCallLeaveFn: () => { return confirm('Are you sure you want to end this call?'); }, afterCallLeaveFn: () => { console.log('Call ended.'); document.getElementById('click2call').style.display = 'block'; document.getElementById('feedback-form').style.display = 'block'; }, onCallError: (error) => { console.error('Call error:', error); document.getElementById('loading').style.display = 'none'; alert('Sorry, we couldn't connect your call. Please try again later.'); } }); ``` -------------------------------- ### Install Skill Dependencies Source: https://developer.signalwire.com/sdks/agents-sdk/appendix/troubleshooting This bash command demonstrates how to install additional packages required by certain SignalWire agent skills. For example, installing `signalwire-agents[search]` provides the necessary dependencies for search-related skills. ```bash ## Some skills require additional packages pip install "signalwire-agents[search]" ``` -------------------------------- ### Setup SignalWire Chat Client Source: https://developer.signalwire.com/sdks/realtime-sdk/chat/client Demonstrates how to initialize a SignalWire Realtime Client and access the Chat client namespace. This is the first step to using any chat functionality. ```javascript import { SignalWire } from "@signalwire/realtime-api"; const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }) const chatClient = client.chat; ``` -------------------------------- ### Install FreeSWITCH with Memory Sanitizer Source: https://developer.signalwire.com/platform/integrations/freeswitch/freeswitch-memory-address-and-memory-pool-sanitizer Installs the FreeSWITCH packages with memory address and pool sanitization enabled. This involves adding a custom repository, updating package lists, and installing the 'freeswitch-all' package. ```shell read -p "FSA username: " USERNAME && read -p "FSA password: " PASSWORD && echo "deb https://$USERNAME:$PASSWORD@fsa.freeswitch.com/repo/deb/fsa-asan `lsb_release -sc` unstable" > /etc/apt/sources.list.d/freeswitch.list && echo "deb-src https://$USERNAME:$PASSWORD@fsa.freeswitch.com/repo/deb/fsa-asan `lsb_release -sc` unstable" >> /etc/apt/sources.list.d/freeswitch.list && wget --http-user=$USERNAME --http-password=$PASSWORD -O - https://fsa.freeswitch.com/repo/deb/fsa/pubkey.gpg | apt-key add - && apt-get install -q -y -f apt-transport-https wget software-properties-common && echo "machine fsa.freeswitch.com login $USERNAME password $PASSWORD" > /etc/apt/auth.conf && apt-get update && apt-get install -y freeswitch-all && systemctl start freeswitch && fs_cli ``` -------------------------------- ### Accessing Parameters in Skill Setup (Python) Source: https://developer.signalwire.com/sdks/agents-sdk/skills/understanding-skills Shows how a skill can access and utilize parameters passed during its initialization. The `setup` method is used to retrieve these parameters and configure the skill instance. ```python def setup(self) -> bool: self.api_key = self.params.get("api_key") self.max_results = self.params.get("max_results", 3) return True ``` -------------------------------- ### Start and Pause Room Recording Source: https://developer.signalwire.com/sdks/realtime-sdk/video/roomsession-recording This example demonstrates how to start a room recording and then pause it after a specified delay. It initializes the SignalWire client, listens for room start events, initiates a recording, and uses setTimeout to call the pause method. ```javascript import { SignalWire } from "@signalwire/realtime-api"; // Initialize the SignalWire client const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }); // Access video client from the main client const videoClient = client.video; // Setup listener for when a room starts await videoClient.listen({ onRoomStarted: async (roomSession) => { console.log("Room started", roomSession.displayName); let roomRecording = roomSession.startRecording({ listen: { onStarted: () => { console.log("Recording started"); }, onEnded: (recording) => { console.log(`Recording ended. Recording State: ${recording.state}. Recording Id: ${recording.id}`); }, } }) await roomSession.listen({ onRecordingUpdated: (recording) => { console.log(`Recording State: ${recording.state}. Recording Id: ${recording.id}`); }, onMemberJoined: async (member) => { console.log("Member joined", member.name); }, onMemberLeft: (member) => { console.log("Member left", member.name); }, }) // Pausing the recording after 5 seconds setTimeout(async () => { console.log("Stopping recording"); await roomRecording.pause(); }, 5000); }, onRoomEnded: async (roomSession) => { console.log("Room ended", roomSession.displayName); } }); ``` -------------------------------- ### Create and Run an Agent (Python) Source: https://developer.signalwire.com/sdks/agents-sdk/api/agent-base Demonstrates how to create a basic agent using the AgentBase class, add language support, configure a prompt section, and run the agent. This is a foundational example for agent initialization. ```python agent = AgentBase(name="my-agent", route="/agent") agent.add_language("English", "en-US", "rime.spore") agent.prompt_add_section("Role", "You are a helpful assistant.") agent.run() ``` -------------------------------- ### Start MCP Gateway using CLI Source: https://developer.signalwire.com/sdks/agents-sdk/advanced/mcp-gateway Starts the MCP Gateway service using the installed command-line interface tool. It requires a configuration file path as an argument. ```bash mcp-gateway -c config.json ``` -------------------------------- ### SWML Integration Example (Play Method) Source: https://developer.signalwire.com/voice/tts/cartesia Example of using Cartesia voices with the `play` method in SWML. ```APIDOC ### SWML - Play Method Alternatively, use the [`say_voice`](/swml/methods/play.md#parameters) parameter of the [`play`](/swml/methods/play.md) SWML method to select a voice for basic TTS. ```yaml version: 1.0.0 sections: main: - set: say_voice: "cartesia.a167e0f3-df7e-4d52-a9c3-f949145efdab" - play: "say:Greetings. This is the Customer Support Man voice from Cartesia's Sonic text-to-speech model." ``` ``` -------------------------------- ### List Video Room Sessions - GET Request Source: https://developer.signalwire.com/platform/basics/guides/how-to-test-api-requests-on-postman Demonstrates how to list all room sessions from the Video API using a GET request. The example shows the request URL and how to use environment variables in Postman. ```HTTP GET https://{{Space}}/api/video/room_sessions ``` -------------------------------- ### Complete Weather Skill Example Source: https://developer.signalwire.com/sdks/agents-sdk/api/skill-base A comprehensive example of a 'WeatherSkill' that integrates with external weather APIs. It demonstrates setup, tool registration, API calls, and parameter schema definition. ```python from signalwire_agents.core.skill_base import SkillBase from signalwire_agents.core.function_result import SwaigFunctionResult from typing import Dict, Any, List import os class WeatherSkill(SkillBase): """Skill for weather lookups.""" SKILL_NAME = "weather" SKILL_DESCRIPTION = "Provides weather information" SKILL_VERSION = "1.0.0" REQUIRED_PACKAGES = ["requests"] REQUIRED_ENV_VARS = ["WEATHER_API_KEY"] def setup(self) -> bool: """Initialize the weather skill.""" # Validate dependencies if not self.validate_packages(): return False if not self.validate_env_vars(): return False # Store API key self.api_key = os.getenv("WEATHER_API_KEY") return True def register_tools(self) -> None: """Register weather tools.""" self.define_tool( name="get_weather", description="Get current weather for a location", handler=self._get_weather, parameters={ "type": "object", "properties": { "location": { "type": "string", "description": "City name or zip code" } }, "required": ["location"] } ) def _get_weather(self, args: Dict, raw_data: Dict) -> SwaigFunctionResult: """Handle weather lookup.""" import requests location = args.get("location") url = f"https://api.weather.com/v1/current?q={location}&key={self.api_key}" try: response = requests.get(url) data = response.json() return SwaigFunctionResult( f"Weather in {location}: {data['condition']}, {data['temp']}°F" ) except Exception as e: return SwaigFunctionResult(f"Unable to get weather: {str(e)}") def get_hints(self) -> List[str]: """Speech recognition hints.""" return ["weather", "temperature", "forecast", "sunny", "rainy"] def get_prompt_sections(self) -> List[Dict[str, Any]]: """Add weather instructions to prompt.""" return [{ "title": "Weather Information", "body": "You can check weather for any location using the get_weather function." }] @classmethod def get_parameter_schema(cls): schema = super().get_parameter_schema() schema.update({ "units": { "type": "string", "description": "Temperature units", "default": "fahrenheit", "enum": ["fahrenheit", "celsius"] } }) return schema ``` -------------------------------- ### Chat Client Setup Source: https://developer.signalwire.com/sdks/realtime-sdk/chat/client Demonstrates how to initialize a SignalWire Realtime Client and access the Chat client. ```APIDOC ## Chat Client Setup ### Description Initializes a SignalWire Realtime Client and accesses the chat namespace to obtain a Chat client instance. ### Method `SignalWire` constructor and `client.chat` property access ### Endpoint N/A (Client-side initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { SignalWire } from "@signalwire/realtime-api"; const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }); const chatClient = client.chat; ``` ### Response #### Success Response (200) N/A (Client-side initialization) #### Response Example N/A ``` -------------------------------- ### Purge Existing FreeSWITCH Packages Source: https://developer.signalwire.com/platform/integrations/freeswitch/freeswitch-memory-address-and-memory-pool-sanitizer Removes all installed FreeSWITCH packages and cleans the package cache. This ensures a clean slate for installing the new sanitized version. ```shell apt-get purge *freeswitch* apt-get autoremove apt-get autoclean ``` -------------------------------- ### Debugging Agent Configuration with curl Source: https://developer.signalwire.com/sdks/agents-sdk/quickstart Demonstrates how to use curl to access the agent's debug endpoint. This endpoint provides detailed information about the agent's configuration, including registered functions, prompt settings, voice configurations, and authentication credentials. ```bash ## Use the Basic Auth credentials from your agent's startup output ## (or set via SWML_BASIC_AUTH_USER and SWML_BASIC_AUTH_PASSWORD env vars) curl -u "$SWML_BASIC_AUTH_USER:$SWML_BASIC_AUTH_PASSWORD" http://localhost:3000/debug ``` -------------------------------- ### Example: Fetch Conversations and Addresses (Vanilla JS) Source: https://developer.signalwire.com/sdks/browser-sdk/signalwire-client/client A complete HTML example demonstrating the instantiation of the SignalWire client and subsequent calls to fetch conversations and addresses. This code is intended to be run directly in a browser. ```html ``` -------------------------------- ### Start and Stop Recording in SignalWire Video Room (JavaScript) Source: https://developer.signalwire.com/sdks/realtime-sdk/video/roomsession This example shows how to start a recording in a SignalWire video room upon it starting, listen for recording events, and then stop the recording after a delay. It requires SignalWire client initialization and assumes an active room session. ```javascript import { SignalWire } from "@signalwire/realtime-api"; // Initialize the SignalWire client const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }); // Access video client from the main client const videoClient = client.video; // Setup listener for when a room starts await videoClient.listen({ onRoomStarted: async (roomSession) => { console.log("Room started", roomSession.displayName); let roomRecording = roomSession.startRecording({ listen: { onStarted: () => { console.log("Recording started"); }, onUpdated: (recording) => { console.log("Recording updated", recording.state); }, onEnded: (recording) => { console.log(`Recording ended. Recording State: ${recording.state}. Recording Id: ${recording.id}`); }, } }) setTimeout( () => { roomRecording.stop(); }, 5000); // Setup listener for when a member joins await roomSession.listen({ onMemberJoined: async (member) => { console.log("Member joined", member.name); }, onMemberLeft: (member) => { console.log("Member left", member.name); }, }); }, onRoomEnded: async (roomSession) => { console.log("Room ended", roomSession.displayName); } }); ``` -------------------------------- ### Start, Pause, and Resume Room Recording Source: https://developer.signalwire.com/sdks/realtime-sdk/video/roomsession-recording This example illustrates starting a room recording, pausing it, and then resuming it after a period. It includes initialization, event listening, and timed calls to pause and resume methods. ```javascript import { SignalWire } from "@signalwire/realtime-api"; // Initialize the SignalWire client const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" }); // Access video client from the main client const videoClient = client.video; // Setup listener for when a room starts await videoClient.listen({ onRoomStarted: async (roomSession) => { console.log("Room started", roomSession.displayName); let roomRecording = roomSession.startRecording({ listen: { onStarted: () => { console.log("Recording started"); }, onEnded: (recording) => { console.log(`Recording ended. Recording State: ${recording.state}. Recording Id: ${recording.id}`); }, } }) await roomSession.listen({ onRecordingUpdated: (recording) => { console.log(`Recording State: ${recording.state}. Recording Id: ${recording.id}`); }, onMemberJoined: async (member) => { console.log("Member joined", member.name); }, onMemberLeft: (member) => { console.log("Member left", member.name); }, }) // Pause the recording after 5 seconds setTimeout(async () => { console.log("Pausing recording"); await roomRecording.pause(); // Resume the recording after 5 seconds setTimeout(() => { console.log("Resuming recording"); roomRecording.resume(); }, 5000); }, 5000); }, onRoomEnded: async (roomSession) => { console.log("Room ended", roomSession.displayName); } }); ``` -------------------------------- ### Manage Video Rooms with SignalWire SDK Source: https://developer.signalwire.com/sdks/realtime-sdk/v3 This example illustrates how to interact with SignalWire Video Rooms using the Video SDK. It shows how to monitor room events like 'room.started' and member join events, and how to retrieve a list of active room sessions. ```javascript import { Video } from "@signalwire/realtime-api"; const video = new Video.Client({ project: "your-project-id", token: "your-api-token" }); // Monitor room events video.on("room.started", async (roomSession) => { console.log("Room started:", roomSession.name); roomSession.on("member.joined", (member) => { console.log("Member joined:", member.name); }); }); // Get active room sessions const { roomSessions } = await video.getRoomSessions(); ```