Skip to content

signalwire/signalwire-rust

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

SignalWire SDK for Rust

Build AI voice agents, control live calls over WebSocket, and manage every SignalWire resource over REST -- all from one crate.

Documentation · Report an Issue · crates.io

Discord MIT License GitHub Stars


What's in this SDK

Capability What it does Quick link
AI Agents Build voice agents that handle calls autonomously -- the platform runs the AI pipeline, your code defines the persona, tools, and call flow Agent Guide
RELAY Client Control live calls and SMS/MMS in real time over WebSocket -- answer, play, record, collect DTMF, conference, transfer, and more RELAY docs
REST Client Manage SignalWire resources over HTTP -- phone numbers, SIP endpoints, Fabric AI agents, video rooms, messaging, and 18+ API namespaces REST docs
cargo add signalwire

AI Agents

Each agent is a self-contained microservice that generates SWML (SignalWire Markup Language) and handles SWAIG (SignalWire AI Gateway) tool calls. The SignalWire platform runs the entire AI pipeline (STT, LLM, TTS) -- your agent just defines the behavior.

use signalwire::agent::AgentBase;
use signalwire::swaig::FunctionResult;
use std::collections::HashMap;

fn main() {
    let agent = AgentBase::builder("my-agent", "/agent")
        .add_language("English", "en-US", "rime.spore")
        .prompt_add_section("Role", "You are a helpful assistant.")
        .define_tool("get_time", "Get the current time", |_args, _raw| {
            let now = chrono::Local::now().format("%H:%M:%S");
            FunctionResult::new(format!("The time is {now}"))
        })
        .build();

    agent.run();
}

Test locally without running a server:

cargo run --bin swaig-test -- --list-tools examples/simple_agent.rs
cargo run --bin swaig-test -- --dump-swml examples/simple_agent.rs
cargo run --bin swaig-test -- --exec get_time examples/simple_agent.rs

Agent Features

  • Prompt Object Model (POM) -- structured prompt composition via prompt_add_section()
  • SWAIG tools -- define functions with define_tool() that the AI calls mid-conversation, with native access to the call's media stack
  • Skills system -- add capabilities with one-liners: agent.add_skill("datetime", None)
  • Contexts and steps -- structured multi-step workflows with navigation control
  • DataMap tools -- tools that execute on SignalWire's servers, calling REST APIs without your own webhook
  • Dynamic configuration -- per-request agent customization for multi-tenant deployments
  • Call flow control -- pre-answer, post-answer, and post-AI verb insertion
  • Prefab agents -- ready-to-use archetypes (InfoGatherer, Survey, FAQ, Receptionist, Concierge)
  • Multi-agent hosting -- serve multiple agents on a single server with AgentServer
  • SIP routing -- route SIP calls to agents based on usernames
  • Session state -- persistent conversation state with global data and post-prompt summaries
  • Security -- auto-generated basic auth, function-specific HMAC tokens, SSL support
  • Serverless -- deploy to Lambda, Cloud Functions, Azure Functions

Agent Examples

The examples/ directory contains working examples:

Example What it demonstrates
simple_agent.rs POM prompts, SWAIG tools, multilingual support, LLM tuning
contexts_demo.rs Multi-persona workflow with context switching and step navigation
data_map_demo.rs Server-side API tools without webhooks
skills_demo.rs Loading built-in skills (datetime, math)
call_flow_and_actions_demo.rs Call flow verbs, debug events, FunctionResult actions
session_and_state_demo.rs OnSummary, global data, post-prompt summaries
multi_agent_server.rs Multiple agents on one server
lambda_agent.rs AWS Lambda deployment
comprehensive_dynamic_agent.rs Per-request dynamic configuration, multi-tenant routing

See examples/README.md for the full list organized by category.


RELAY Client

Real-time call control and messaging over WebSocket. The RELAY client connects to SignalWire via the Blade protocol and gives you async, imperative control over live phone calls and SMS/MMS.

use signalwire::relay::RelayClient;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RelayClient::builder()
        .project(&env::var("SIGNALWIRE_PROJECT_ID")?)
        .token(&env::var("SIGNALWIRE_API_TOKEN")?)
        .space(&env::var("SIGNALWIRE_SPACE")?)
        .contexts(vec!["default".into()])
        .build()?;

    client.on_call(|call| async move {
        call.answer().await?;
        let action = call.play(vec![serde_json::json!({
            "type": "tts",
            "text": "Welcome to SignalWire!"
        })]).await?;
        action.wait().await?;
        call.hangup().await?;
        Ok(())
    });

    println!("Waiting for inbound calls ...");
    client.run().await?;
    Ok(())
}
  • 57+ calling methods (play, record, collect, detect, tap, stream, AI, conferencing, and more)
  • SMS/MMS messaging with delivery tracking
  • Action objects with wait(), stop(), pause(), resume()
  • Auto-reconnect with exponential backoff

See the RELAY documentation for the full guide, API reference, and examples.


REST Client

Async REST client for managing SignalWire resources and controlling calls over HTTP. No WebSocket required.

use signalwire::rest::RestClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RestClient::from_env()?;

    client.fabric().ai_agents().create(serde_json::json!({
        "name": "Support Bot",
        "prompt": {"text": "You are helpful."}
    })).await?;

    client.calling().dial(serde_json::json!({
        "from": "+15559876543",
        "to": "+15551234567",
        "url": "https://example.com/call-handler"
    })).await?;

    let results = client.phone_numbers().search(
        &[("area_code", "512")]
    ).await?;
    println!("{results:#?}");

    Ok(())
}
  • 21 namespaced API surfaces: Fabric (13 resource types), Calling (37 commands), Video, Datasphere, Compat (Twilio-compatible), Phone Numbers, SIP, Queues, Recordings, and more
  • Connection pooling via reqwest::Client
  • serde_json::Value returns -- raw JSON, no wrapper objects

See the REST documentation for the full guide, API reference, and examples.


Installation

Add to your Cargo.toml:

[dependencies]
signalwire = "1"

Or with cargo:

cargo add signalwire

Requires Rust edition 2024 (rustc 1.85+).

Documentation

Full reference documentation is available at developer.signalwire.com/sdks/agents-sdk.

Guides are also available in the docs/ directory:

Getting Started

  • Agent Guide -- creating agents, prompt configuration, dynamic setup
  • Architecture -- SDK architecture and core concepts
  • SDK Features -- feature overview, SDK vs raw SWML comparison

Core Features

Skills and Extensions

Deployment

Reference

Environment Variables

Variable Used by Description
SIGNALWIRE_PROJECT_ID RELAY, REST Project identifier
SIGNALWIRE_API_TOKEN RELAY, REST API token
SIGNALWIRE_SPACE RELAY, REST Space hostname (e.g. example.signalwire.com)
SWML_BASIC_AUTH_USER Agents Basic auth username (default: auto-generated)
SWML_BASIC_AUTH_PASSWORD Agents Basic auth password (default: auto-generated)
SWML_PROXY_URL_BASE Agents Base URL when behind a reverse proxy
SWML_SSL_ENABLED Agents Enable HTTPS (true, 1, yes)
SWML_SSL_CERT_PATH Agents Path to SSL certificate
SWML_SSL_KEY_PATH Agents Path to SSL private key
SIGNALWIRE_LOG_LEVEL All Logging level (debug, info, warn, error)
SIGNALWIRE_LOG_MODE All Set to off to suppress all logging

Testing

# Run the test suite
cargo test

# Run with verbose output
cargo test -- --nocapture

# Run tests for a specific module
cargo test logging
cargo test agent
cargo test relay
cargo test rest

# Coverage (requires cargo-tarpaulin)
cargo tarpaulin --out html

License

MIT -- see LICENSE for details.

About

SignalWire Rust SDK

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors