### Build SDK Examples Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Compile all runnable examples included with the SDK using the `just` command. This is useful for verifying example code and understanding SDK usage. ```bash just sdk-build-examples ``` -------------------------------- ### Run Bundled Examples Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Instructions for running the SDK's bundled examples using Cargo, requiring an API key to be set as an environment variable. ```bash ELEVENLABS_API_KEY=your-key cargo run -p elevenlabs-sdk --example text_to_speech ELEVENLABS_API_KEY=your-key cargo run -p elevenlabs-sdk --example voices ELEVENLABS_API_KEY=your-key cargo run -p elevenlabs-sdk --example streaming ELEVENLABS_API_KEY=your-key cargo run -p elevenlabs-sdk --example websocket_tts ``` -------------------------------- ### CLI WebSocket Examples Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/design.md Examples of using the ElevenLabs CLI for WebSocket operations, including text-to-speech streaming and initiating conversations. ```bash # WebSocket examples elevenlabs ws tts --voice-id --model-id eleven_turbo_v2 --text "Hello" -o output.mp3 elevenlabs ws conversation --agent-id ``` -------------------------------- ### CLI REST Examples Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/design.md Examples of using the ElevenLabs CLI for REST operations, including text-to-speech conversion, streaming, and listing/getting voices, models, user info, and subscription details. ```bash # REST examples elevenlabs tts convert --voice-id --text "Hello" -o output.mp3 elevenlabs tts stream --voice-id --text "Hello" -o output.mp3 elevenlabs voices list elevenlabs voices get --voice-id elevenlabs models list elevenlabs user info elevenlabs user subscription ``` -------------------------------- ### Client Setup Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Demonstrates how to configure and initialize the ElevenLabsClient using either an explicit API key or environment variables, along with custom settings for base URL, timeout, and retries. ```APIDOC ## Client Setup — `ClientConfig` and `ElevenLabsClient` Build a `ClientConfig` using the fluent builder pattern (accepting an API key directly or from the `ELEVENLABS_API_KEY` environment variable), then pass it to `ElevenLabsClient::new`. The config supports a custom base URL, request timeout, max retry count, and retry backoff duration — all with sensible defaults. Once constructed, the `ElevenLabsClient` is the single entry-point to all service accessors and can be shared across tasks via a reference. ```rust use elevenlabs_sdk::{ClientConfig, ElevenLabsClient, ConfigError}; #[tokio::main] async fn main() -> Result<(), Box> { // Option 1: explicit API key with custom timeout and retry settings let config = ClientConfig::builder("sk-your-api-key-here") .base_url("https://api.elevenlabs.io") // optional override .timeout(std::time::Duration::from_secs(60)) .max_retries(5_u32) .retry_backoff(std::time::Duration::from_millis(500)) .build(); // Option 2: read ELEVENLABS_API_KEY (and optional ELEVENLABS_BASE_URL) from env let config = ClientConfig::from_env()?; let client = ElevenLabsClient::new(config)?; // All service accessors are zero-cost; the client can be used from multiple // async tasks by passing &client. println!("Client ready, base URL: {}", client.config().base_url); Ok(()) } ``` ``` -------------------------------- ### Quick Start: List Voices and Convert Text to Speech Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Initialize the client using an API key from environment variables, list available voices, and convert text to an MP3 audio file. ```rust use elevenlabs_sdk::{ClientConfig, ElevenLabsClient}; use elevenlabs_sdk::types::TextToSpeechRequest; #[tokio::main] async fn main() -> Result<(), Box> { // Create client from the ELEVENLABS_API_KEY environment variable let config = ClientConfig::from_env()?; let client = ElevenLabsClient::new(config)?; // List voices let voices = client.voices().list(None).await?; for voice in &voices.voices { println!("{}: {}", voice.voice_id, voice.name); } // Text-to-speech let request = TextToSpeechRequest::new("Hello, world!"); let audio = client .text_to_speech() .convert("21m00Tcm4TlvDq8ikWAM", &request, None, None) .await?; std::fs::write("output.mp3", &audio)?; Ok(()) } ``` -------------------------------- ### Client Setup with ClientConfig and ElevenLabsClient Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Demonstrates how to configure the ElevenLabs client using explicit API keys or environment variables. Supports custom base URLs, timeouts, and retry settings. ```rust use elevenlabs_sdk::{ClientConfig, ElevenLabsClient, ConfigError}; #[tokio::main] async fn main() -> Result<(), Box> { // Option 1: explicit API key with custom timeout and retry settings let config = ClientConfig::builder("sk-your-api-key-here") .base_url("https://api.elevenlabs.io") // optional override .timeout(std::time::Duration::from_secs(60)) .max_retries(5_u32) .retry_backoff(std::time::Duration::from_millis(500)) .build(); // Option 2: read ELEVENLABS_API_KEY (and optional ELEVENLABS_BASE_URL) from env let config = ClientConfig::from_env()?; let client = ElevenLabsClient::new(config)?; // All service accessors are zero-cost; the client can be used from multiple // async tasks by passing &client. println!("Client ready, base URL: {}", client.config().base_url); Ok(()) } ``` -------------------------------- ### Install ElevenLabs Rust SDK Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Add the elevenlabs-sdk and tokio dependencies to your Cargo.toml file. ```toml [dependencies] elevenlabs-sdk = "0.1.0" tokio = { version = "1", features = ["rt-multi-thread", "macros"] } ``` -------------------------------- ### ElevenLabs Client Initialization and Text-to-Speech Request Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-15-01-elevenlabs-rust-sdk/design.md Demonstrates how to initialize the ElevenLabs client with an API key and make a basic text-to-speech request. This example shows the builder pattern for specifying voice and text before sending the request. ```rust let client = ElevenLabsClient::new(api_key); let audio = client.text_to_speech() .voice_id("...") .text("Hello") .send().await?; ``` -------------------------------- ### Create Agent, Manage KB, Simulate Conversation, and More with AgentsService Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt This example demonstrates the core functionalities of the AgentsService, including creating an agent, adding a URL to its knowledge base, listing conversations, simulating a conversation with streaming, initiating an outbound Twilio call, checking live conversation counts, and obtaining a signed WebSocket URL. Ensure your ElevenLabs API key is set in the environment variable ELEVENLABS_API_KEY. ```rust use elevenlabs_sdk::{ClientConfig, ElevenLabsClient}; use elevenlabs_sdk::types::{ CreateAgentRequest, CreateKnowledgeBaseUrlRequest, SubmitBatchCallRequest, TwilioOutboundCallRequest, }; use futures_util::StreamExt; #[tokio::main] async fn main() -> elevenlabs_sdk::Result<()> { let client = ElevenLabsClient::new(ClientConfig::from_env()?)?; let agents = client.agents(); // --- Create an agent --- let create_req = CreateAgentRequest { name: Some("Support Bot".into()), conversation_config: None, platform_settings: None, workflow: None, tags: None, }; let agent = agents.create_agent(&create_req).await?; println!("Agent ID: {}", agent.agent_id); // --- Add a knowledge base document from a URL --- let kb_req = CreateKnowledgeBaseUrlRequest { url: "https://docs.example.com/faq".into(), name: Some("FAQ".into()), parent_folder_id: None, }; let doc = agents.create_knowledge_base_url(&kb_req).await?; println!("KB document: {}", doc.id); // --- List conversations for the agent --- let convs = agents.list_conversations(Some(&agent.agent_id), None).await?; println!("Conversations: {}", convs.conversations.len()); // --- Simulate a conversation (streaming) --- let sim_req = serde_json::json!({ "agent_id": agent.agent_id, "input": "Hello, can you help me?" }); let mut stream = agents.simulate_conversation_stream(&agent.agent_id, &sim_req).await?; while let Some(chunk) = stream.next().await { let bytes = chunk?; println!("Simulation chunk: {} bytes", bytes.len()); } // --- Trigger an outbound Twilio call --- let call_req = TwilioOutboundCallRequest { agent_id: agent.agent_id.clone(), agent_phone_number_id: "phone_number_id".into(), to_number: "+15551234567".into(), conversation_initiation_client_data: None, }; let call_resp = agents.twilio_outbound_call(&call_req).await?; println!("Call initiated: {} (SID: {:?})", call_resp.success, call_resp.call_sid); // --- Analytics: live conversation count --- let live = agents.get_live_count().await?; println!("Currently active conversations: {}", live.count); // --- Get signed WebSocket URL for client-side conversation --- let signed = agents.get_conversation_signed_url(&agent.agent_id).await?; println!("Signed URL: {}", signed.signed_url); Ok(()) } ``` -------------------------------- ### Text-to-Speech Conversion Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Demonstrates how to convert text to speech using the ElevenLabs Rust SDK. This example shows listing voices and then converting a given text to an MP3 audio file. ```APIDOC ## Text-to-Speech Conversion ### Description Convert text to speech using the ElevenLabs API. This example first lists available voices and then converts a specified text to an audio file. ### Method `client.text_to_speech().convert(voice_id, request, None, None)` ### Parameters #### Path Parameters - `voice_id` (string) - Required - The ID of the voice to use for synthesis. #### Request Body - `request` (TextToSpeechRequest) - Required - An object containing the text to synthesize and other optional parameters. ### Request Example ```rust,no_run use elevenlabs_sdk::types::TextToSpeechRequest; let request = TextToSpeechRequest::new("Hello, world!"); ``` ### Response #### Success Response (200) - `audio` (bytes) - The synthesized audio data. ### Response Example ```rust,no_run std::fs::write("output.mp3", &audio)?; ``` ``` -------------------------------- ### Get User Account Info with ElevenLabs SDK Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Demonstrates how to retrieve user account details, subscription tier, character limits, and usage statistics using the UserService. Allows fetching usage over a specified time range and filtering by type. ```rust use elevenlabs_sdk::{ClientConfig, ElevenLabsClient}; #[tokio::main] async fn main() -> elevenlabs_sdk::Result<()> { let client = ElevenLabsClient::new(ClientConfig::from_env()?)?; let user_svc = client.user(); // Basic user info let user = user_svc.get().await?; println!("User: {} ({})", user.first_name.as_deref().unwrap_or("N/A"), user.xi_api_key); // Subscription and quota details let sub = user_svc.get_subscription().await?; println!( "Plan: {} — {}/{} chars used", sub.tier, sub.character_count, sub.character_limit ); // Character usage over a time range let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as i64; let one_week_ago = now - 7 * 24 * 3600; let usage = user_svc .get_character_usage(one_week_ago, now, Some(true), Some("voice")) .await?; println!("Usage report: {} data points", usage.usage.len()); Ok(()) } ``` -------------------------------- ### Get Live Conversation Count Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Retrieves the current count of live, active conversations. ```APIDOC ## GET /agents/analytics/live-count ### Description Gets the number of currently active conversations. ### Method GET ### Endpoint /agents/analytics/live-count ### Response #### Success Response (200) - **count** (integer) - The number of live conversations. #### Response Example ```json { "count": 15 } ``` ``` -------------------------------- ### Get Signed WebSocket URL Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Generates a signed URL for establishing a WebSocket connection for client-side conversations. ```APIDOC ## GET /agents/{agent_id}/signed-websocket-url ### Description Gets a signed URL for client-side conversation via WebSocket. ### Method GET ### Endpoint /agents/{agent_id}/signed-websocket-url ### Parameters #### Path Parameters - **agent_id** (string) - Required - The ID of the agent for which to generate the URL. ### Response #### Success Response (200) - **signed_url** (string) - The signed URL for the WebSocket connection. #### Response Example ```json { "signed_url": "wss://elevenlabs.io/ws/agent-id-123?token=..." } ``` ``` -------------------------------- ### Get Formatted Transcript Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Retrieves a transcript for a dubbing project in a specified language and format (e.g., SRT, VTT, JSON). ```APIDOC ## Get Formatted Transcript ### Description Retrieves the transcript for a dubbing project in a specified language and format. Supported formats include SRT, VTT, and JSON. ### Method GET (implied by SDK method `get_transcript_formatted`) ### Endpoint `/dubbing/{dubbing_id}/transcript?language={language}&format={format}` (implied by SDK method `get_transcript_formatted`) ### Parameters #### Path Parameters - **dubbing_id** (String) - Required - The unique identifier of the dubbing project. #### Query Parameters - **language** (String) - Required - The language code of the transcript (e.g., "es"). - **format** (TranscriptFormat) - Required - The desired format for the transcript (e.g., `TranscriptFormat::Srt`). ### Response #### Success Response (200 OK) - **content** (String) - The transcript content in the requested format. #### Response Example ```json { "content": "1\n00:00:01,000 --> 00:00:05,000\nThis is the first segment." } ``` ``` -------------------------------- ### Get Dubbing Project Metadata Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Retrieves metadata for a specific dubbing project using its ID. This includes the current status of the project. ```APIDOC ## Get Dubbing Project Metadata ### Description Retrieves metadata for a specific dubbing project identified by its `dubbing_id`. This allows you to check the project's status and other relevant information. ### Method GET (implied by SDK method `get`) ### Endpoint `/dubbing/{dubbing_id}` (implied by SDK method `get`) ### Parameters #### Path Parameters - **dubbing_id** (String) - Required - The unique identifier of the dubbing project. ### Response #### Success Response (200 OK) - **status** (String) - The current status of the dubbing project (e.g., "processing", "completed"). #### Response Example ```json { "dubbing_id": "some_dubbing_id", "status": "processing", "name": "My Spanish Dub", "source_lang": "en", "target_lang": "es", "created_at": "2023-10-27T10:00:00Z", "expected_duration_sec": 120.5 } ``` ``` -------------------------------- ### WebSocket TTS Streaming Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Illustrates how to use the WebSocket API for real-time text-to-speech streaming. This example connects to the WebSocket, sends text, and receives audio chunks. ```APIDOC ## WebSocket TTS Streaming ### Description Utilize WebSocket for real-time, streaming text-to-speech. This example demonstrates connecting to the WebSocket endpoint, sending text, and processing received audio data chunks. ### Method `TtsWebSocket::connect(config, ws_config).await?` ### Parameters #### Request - `config` (ClientConfig) - Configuration for the client connection. - `ws_config` (TtsWsConfig) - Configuration for the WebSocket TTS stream, including voice ID, model ID, and settings. ### Request Example ```rust,no_run use elevenlabs_sdk::{ClientConfig, TtsWebSocket, TtsWsConfig}; let config = ClientConfig::from_env()?; let ws_config = TtsWsConfig { voice_id: "21m00Tcm4TlvDq8ikWAM".into(), model_id: "eleven_turbo_v2".into(), voice_settings: None, generation_config: None, output_format: None, }; let mut ws = TtsWebSocket::connect(&config, &ws_config).await?; ws.send_text("Hello from real-time streaming!").await?; ws.flush().await?; ``` ### Response #### Success Response - `resp` (TtsWebSocketResponse) - A response object containing audio data chunks or finalization status. ### Response Example ```rust,no_run while let Some(resp) = ws.recv().await? { if let Some(ref audio) = resp.audio { println!("Received audio chunk: {} chars base64", audio.len()); } if resp.is_final == Some(true) { break; } } ws.close().await?; ``` ``` -------------------------------- ### Adding a New Service - SDK Steps Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/AGENTS.md Outlines the steps required to add a new service to the ElevenLabs Rust SDK, including module creation, type definitions, re-exports, and client method additions. ```text 1. Add the service module in `crates/elevenlabs-sdk/src/services/.rs` 2. Add request/response types in `crates/elevenlabs-sdk/src/types/.rs` 3. Re-export from `services/mod.rs` and `types/mod.rs` 4. Add accessor method on `ElevenLabsClient` in `client.rs` 5. Re-export the service type from `lib.rs` 6. Add CLI command module in `bin/elevenlabs-bin-cli/src/commands/.rs` 7. Register the command in `cli.rs` and `main.rs` 8. Run `just sdk-test && just sdk-lint && just cli-lint` ``` -------------------------------- ### Generate SDK Documentation Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Generate API documentation for the SDK using the `just` command. This command compiles documentation from source code and comments. ```bash just sdk-doc ``` -------------------------------- ### Generate SDK Documentation Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/tasks.md Build documentation for the entire workspace, excluding external dependencies. Ensures doc comments are correctly rendered and no warnings are produced. ```bash cargo doc --workspace --no-deps ``` -------------------------------- ### Create and Manage Dubbing Projects with Rust SDK Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Demonstrates creating a dubbing project from a source URL, polling for its status, downloading the dubbed audio, and retrieving an SRT transcript. Ensure you have the ElevenLabs API key configured in your environment variables. ```rust use elevenlabs_sdk::{ ClientConfig, ElevenLabsClient, }; use elevenlabs_sdk::types::{ CreateDubbingRequest, DubSegmentsRequest, RenderDubbingRequest, RenderType, TranscriptFormat, }; #[tokio::main] async fn main() -> elevenlabs_sdk::Result<()> { let client = ElevenLabsClient::new(ClientConfig::from_env()?)?; let dubbing = client.dubbing(); // Create a dubbing project from a URL (no file upload) let create_req = CreateDubbingRequest { name: Some("My Spanish Dub".into()), source_url: Some("https://example.com/video.mp4".into()), source_lang: Some("en".into()), target_lang: Some("es".into()), num_speakers: Some(2), dubbing_studio: Some(true), ..Default::default() }; let dub = dubbing.create(&create_req, None).await?; println!("Created dubbing project: {} (expected: {:.0}s)", dub.dubbing_id, dub.expected_duration_sec); // Poll for project readiness then download dubbed audio let meta = dubbing.get(&dub.dubbing_id).await?; println!("Status: {}", meta.status); // Download the Spanish dubbed audio let audio = dubbing.get_audio(&dub.dubbing_id, "es").await?; std::fs::write("dubbed_es.mp4", &audio)?; // Get a formatted transcript let transcript = dubbing.get_transcript_formatted(&dub.dubbing_id, "es", TranscriptFormat::Srt).await?; println!("SRT transcript: {}", transcript.content); // Dubbing Studio: dub specific segments and render let dub_req = DubSegmentsRequest { segments: vec!["segment_id_1".into()], languages: Some(vec!["es".into()]), }; dubbing.dub_segments(&dub.dubbing_id, &dub_req).await?; let render_req = RenderDubbingRequest { render_type: RenderType::Mp4, normalize_volume: Some(true), }; let render = dubbing.render(&dub.dubbing_id, "es", &render_req).await?; println!("Render ID: {}", render.render_id); Ok(()) } ``` -------------------------------- ### Run Integration Tests Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Execute integration tests for the SDK against a mock server using `Prism`. This command is essential for testing the SDK's behavior in a controlled environment. ```bash just sdk-test-integration ``` -------------------------------- ### Display CLI Help Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/design.md Shows the help message for the elevenlabs CLI, listing all available subcommands. ```bash elevenlabs --help ``` -------------------------------- ### Run SDK Linting Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Perform static analysis on the SDK code using `clippy` via the `just` command. This helps maintain code quality and identify potential issues. ```bash just sdk-lint ``` -------------------------------- ### Common Tasks with Just Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/AGENTS.md Lists common development tasks executable via the 'just' task runner, covering testing, linting, documentation generation, and building for the SDK and CLI. ```bash just sdk-test # Run SDK unit tests just sdk-lint # Run clippy on SDK just sdk-doc # Generate SDK docs just sdk-build-examples # Build all SDK examples just sdk-check-coverage # Check endpoint coverage vs OpenAPI spec just sdk-test-integration # Integration tests with Prism mock server just cli-build # Build the CLI binary just cli-lint # Run clippy on CLI just cli-run # Run the CLI (pass args after --) just cli-install # Install the CLI locally just lint # Full workspace lint just test # Full workspace tests just format # Format everything ``` -------------------------------- ### Run SDK Unit Tests Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Execute the SDK's unit tests using the `just` command. Ensure all tests pass before committing changes. ```bash just sdk-test ``` -------------------------------- ### Build CLI with Just Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/tasks.md Build the elevenlabs-cli crate using the Just build tool. This is a convenience command for developers. ```bash just cli-build ``` -------------------------------- ### Run Full CI Pipeline Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/tasks.md Execute the comprehensive CI checklist, including formatting, linting, testing, and dependency checks. This command should pass for a clean project state. ```bash just ci ``` -------------------------------- ### Client Configuration Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Details on how to configure the ElevenLabs client, including using environment variables or the builder pattern. ```APIDOC ## Client Configuration ### Description Configure the ElevenLabs client using environment variables or a builder pattern to set API keys, base URLs, timeouts, and retry settings. ### Environment Variables | Variable | Description | Default | |----------|-------------|---------| | `ELEVENLABS_API_KEY` | API key (required) | — | | `ELEVENLABS_BASE_URL` | Custom base URL | `https://api.elevenlabs.io` | ### Builder Pattern #### Method `ClientConfigBuilder::default()...build()?` ### Request Example ```rust,no_run use elevenlabs_sdk::{ClientConfig, ClientConfigBuilder, ElevenLabsClient}; let config = ClientConfigBuilder::default() .api_key("your-api-key") .base_url("https://api.elevenlabs.io") .timeout(std::time::Duration::from_secs(60)) .max_retries(5) .build()?; let client = ElevenLabsClient::new(config)?; ``` ``` -------------------------------- ### Workspace Layout Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/AGENTS.md Illustrates the directory structure of the elevenlabs-sdk-rs project, detailing the placement of configuration files, scripts, binaries, and the core SDK crate. ```text elevenlabs-sdk-rs/ ├── Cargo.toml # Root workspace manifest (versions defined here) ├── Justfile # Task runner (just) ├── docs/openapi.json # ElevenLabs OpenAPI spec (source of truth) ├── scripts/check_coverage.py # Endpoint coverage checker ├── bin/ │ ├── elevenlabs-bin-cli/ # CLI binary (clap-based) │ │ └── src/ │ │ ├── main.rs # Entry point & command dispatch │ │ ├── cli.rs # Cli struct & Commands enum │ │ ├── context.rs # Client construction helper │ │ ├── output.rs # JSON output formatting │ │ └── commands/ # One module per API group (22 commands) │ └── leptos-csr-app/ # Frontend demo app (Leptos CSR) └── crates/ ├── common/ # Shared utilities └── elevenlabs-sdk/ # Core SDK crate ├── src/ │ ├── lib.rs # Public re-exports │ ├── client.rs # ElevenLabsClient (HTTP, retry) │ ├── config.rs # ClientConfig builder │ ├── auth.rs # API key handling │ ├── error.rs # Error types │ ├── middleware.rs # Request middleware │ ├── services/ # One module per API group (20 services) │ ├── types/ # Request/response structs (from OpenAPI) │ └── ws/ # WebSocket (TTS streaming, Conversational AI) ├── examples/ # Runnable examples └── tests/ # Integration tests (require Prism mock server) ``` -------------------------------- ### Text-to-Speech Conversion with ElevenLabs SDK Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Shows how to use the TextToSpeechService for converting text to speech. Supports full audio bytes, audio with timestamps, and streaming audio chunks. ```rust use elevenlabs_sdk::{ClientConfig, ElevenLabsClient}; use elevenlabs_sdk::types::{TextToSpeechRequest, OutputFormat}; use futures_util::StreamExt; #[tokio::main] async fn main() -> elevenlabs_sdk::Result<()> { let client = ElevenLabsClient::new(ClientConfig::from_env()?)?; let tts = client.text_to_speech(); // --- 1. Full audio bytes --- let req = TextToSpeechRequest::new("Hello, world!"); let audio_bytes = tts.convert("voice_id_here", &req, None, None).await?; std::fs::write("output.mp3", &audio_bytes)?; // --- 2. Audio with character-level timestamps --- let with_ts = tts.convert_with_timestamps("voice_id_here", &req, None, None).await?; println!("Base64 audio length: {}", with_ts.audio_base64.len()); if let Some(alignment) = with_ts.alignment { println!("First char: {:?}", alignment.characters.first()); } // --- 3. Streaming audio chunks --- let mut stream = tts .convert_stream("voice_id_here", &req, Some(OutputFormat::Mp3_44100_128), Some(2)) .await?; while let Some(chunk) = stream.next().await { let bytes = chunk?; // write bytes to file, send to playback buffer, etc. println!("Received {} bytes", bytes.len()); } Ok(()) } ``` -------------------------------- ### Check SDK Compilation Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/tasks.md Verify that the elevenlabs-sdk crate compiles successfully after potential dependency or feature changes. This is a prerequisite for further testing. ```bash cargo check -p elevenlabs-sdk ``` -------------------------------- ### Run SDK Unit Tests Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/design.md Executes all unit tests within the elevenlabs-sdk crate. All tests should pass. ```bash cargo test -p elevenlabs-sdk ``` -------------------------------- ### List Voices via CLI Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/design.md Fetches and displays a JSON list of available voices using the CLI. Requires an API key to be set. ```bash elevenlabs voices list ``` -------------------------------- ### Build CLI Crate Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/design.md Compiles the elevenlabs-cli crate. Ensure it builds without errors. ```bash cargo build -p elevenlabs-cli ``` -------------------------------- ### Configure Client with Builder Pattern Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Configure the ElevenLabs client using a builder pattern, specifying API key, base URL, timeout, and maximum retries. ```rust use elevenlabs_sdk::{ClientConfig, ClientConfigBuilder, ElevenLabsClient}; let config = ClientConfigBuilder::default() .api_key("your-api-key") .base_url("https://api.elevenlabs.io") .timeout(std::time::Duration::from_secs(60)) .max_retries(5) .build()?; let client = ElevenLabsClient::new(config)?; ``` -------------------------------- ### Create Knowledge Base Document from URL Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Adds a new document to the agent's knowledge base by providing a URL. ```APIDOC ## POST /agents/{agent_id}/knowledge-base/urls ### Description Creates a knowledge base document from a given URL. ### Method POST ### Endpoint /agents/{agent_id}/knowledge-base/urls ### Parameters #### Path Parameters - **agent_id** (string) - Required - The ID of the agent to associate the knowledge base with. #### Request Body - **url** (string) - Required - The URL of the document to add. - **name** (string) - Optional - The name for the knowledge base document. - **parent_folder_id** (string) - Optional - The ID of the parent folder for the document. ### Request Example ```json { "url": "https://docs.example.com/faq", "name": "FAQ", "parent_folder_id": null } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the created knowledge base document. #### Response Example ```json { "id": "kb-doc-id-456" } ``` ``` -------------------------------- ### Create Dubbing Project Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Creates a new dubbing project, either from a source URL or by uploading a media file. It supports specifying project name, source and target languages, number of speakers, and enabling Dubbing Studio. ```APIDOC ## Create Dubbing Project ### Description Creates a new dubbing project. You can provide a source URL for media or upload a file. This operation allows configuration of project name, languages, speaker count, and enables the Dubbing Studio. ### Method POST (implied by SDK method `create`) ### Endpoint `/dubbing` (implied by SDK method `create`) ### Parameters #### Request Body (CreateDubbingRequest) - **name** (Option) - Optional - The name of the dubbing project. - **source_url** (Option) - Optional - The URL of the source media file. - **source_lang** (Option) - Optional - The source language code (e.g., "en"). - **target_lang** (Option) - Optional - The target language code (e.g., "es"). - **num_speakers** (Option) - Optional - The number of speakers in the audio. - **dubbing_studio** (Option) - Optional - Whether to enable Dubbing Studio features. ### Request Example ```rust use elevenlabs_sdk::types::CreateDubbingRequest; let create_req = CreateDubbingRequest { name: Some("My Spanish Dub".into()), source_url: Some("https://example.com/video.mp4".into()), source_lang: Some("en".into()), target_lang: Some("es".into()), num_speakers: Some(2), dubbing_studio: Some(true), ..Default::default() }; // dubbing.create(&create_req, None).await?; ``` ### Response #### Success Response (200 OK) - **dubbing_id** (String) - The unique identifier for the created dubbing project. - **expected_duration_sec** (f32) - The estimated duration of the dubbed project in seconds. #### Response Example ```json { "dubbing_id": "some_dubbing_id", "expected_duration_sec": 120.5 } ``` ``` -------------------------------- ### Manage Speech History with ElevenLabs SDK Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Shows how to interact with the HistoryService to list, retrieve, download, and delete speech generation history items. Supports bulk downloading as a zip archive. Requires a valid voice ID for filtering. ```rust use elevenlabs_sdk::{ClientConfig, ElevenLabsClient}; use elevenlabs_sdk::types::DownloadHistoryItemsRequest; #[tokio::main] async fn main() -> elevenlabs_sdk::Result<()> { let client = ElevenLabsClient::new(ClientConfig::from_env()?)?; let history = client.history(); // List the most recent 10 history items, filtered by voice let page = history .list(Some(10), None, Some("voice_id_here")) .await?; println!("History items: {}", page.history.len()); if let Some(item) = page.history.first() { let item_id = &item.history_item_id; println!("First item: {} — {}", item_id, item.text.as_deref().unwrap_or("(no text)")); // Download audio for a specific history item let audio_bytes = history.get_audio(item_id).await?; std::fs::write("history_item.mp3", &audio_bytes)?; // Delete the history item let delete_resp = history.delete(item_id).await?; println!("Delete status: {}", delete_resp.status); } // Bulk-download multiple items as a zip if page.history.len() > 1 { let ids: Vec = page.history.iter().map(|h| h.history_item_id.clone()).collect(); let zip_bytes = history.download(&DownloadHistoryItemsRequest { history_item_ids: ids }).await?; std::fs::write("history_bulk.zip", &zip_bytes)?; } Ok(()) } ``` -------------------------------- ### Check Code Formatting Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/design.md Verifies that all code adheres to the project's formatting standards using nightly Rustfmt. Reports if formatting is not applied. ```bash cargo +nightly fmt --all -- --check ``` -------------------------------- ### Lint CLI with Just Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/tasks.md Run Clippy on the elevenlabs-cli crate using the Just lint command. Ensures code quality for the CLI. ```bash just cli-lint ``` -------------------------------- ### Check for Unused Dependencies Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-16-01-cli-and-ws-transport/tasks.md Run `cargo machete` to identify and report any unused dependencies across the workspace. Helps in keeping the project lean. ```bash cargo machete ``` -------------------------------- ### Text-to-Speech Service Implementation Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-15-01-elevenlabs-rust-sdk/design.md Provides methods for interacting with the text-to-speech API, including converting text to audio, streaming audio, and retrieving timestamp information. ```rust impl ElevenLabsClient { pub fn text_to_speech(&self) -> TextToSpeechService<'_> { TextToSpeechService { client: self } } } pub struct TextToSpeechService<'a> { client: &'a ElevenLabsClient, } impl<'a> TextToSpeechService<'a> { pub async fn convert(&self, voice_id: &str, req: &TextToSpeechRequest) -> Result { ... } pub async fn convert_stream(&self, voice_id: &str, req: &TextToSpeechRequest) -> Result>, ElevenLabsError> { ... } pub async fn convert_with_timestamps(&self, voice_id: &str, req: &TextToSpeechRequest) -> Result { ... } pub async fn convert_stream_with_timestamps(&self, voice_id: &str, req: &TextToSpeechRequest) -> Result>, ElevenLabsError> { ... } } ``` -------------------------------- ### Connect to Conversational AI WebSocket Source: https://context7.com/longcipher/elevenlabs-sdk-rs/llms.txt Establishes a WebSocket connection for real-time agent conversations. Requires a signed URL obtained from the AgentsService. Handles various conversation events like audio, transcripts, and interruptions. ```rust use elevenlabs_sdk::{ClientConfig, ConversationWebSocket, ConversationEvent}; #[tokio::main] async fn main() -> elevenlabs_sdk::Result<()> { let client = ElevenLabsClient::new(ClientConfig::from_env()?)?; // Get a signed WebSocket URL (valid for a short time) let signed = client.agents().get_conversation_signed_url("agent_id_here").await?; // Connect the WebSocket let (mut ws, mut events) = ConversationWebSocket::connect(&signed.signed_url).await?; // Send a text message (can also send audio PCM frames) ws.send_user_message("Hello, agent!").await?; // Process incoming events while let Some(event) = events.recv().await { match event { ConversationEvent::AgentAudio { audio_base64, .. } => { println!("Agent audio chunk: {} base64 chars", audio_base64.len()); } ConversationEvent::AgentTranscript { text } => { println!("Agent said: {}", text); } ConversationEvent::UserTranscript { text } => { println!("User transcript: {}", text); } ConversationEvent::Interruption => { println!("User interrupted the agent"); } ConversationEvent::Closed => break, _ => {} } } Ok(()) } ``` -------------------------------- ### Client Configuration Structure Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/specs/2026-02-15-01-elevenlabs-rust-sdk/design.md Defines the configuration parameters for the ElevenLabs client, including base URL, API key, and network settings like timeout and retries. ```rust pub struct ClientConfig { pub base_url: String, // Default: "https://api.elevenlabs.io" pub api_key: ApiKey, pub timeout: Duration, // Default: 30s pub max_retries: u32, // Default: 3 pub retry_backoff: Duration, // Default: 1s } pub struct ApiKey(String); // Newtype, Debug redacted pub struct ElevenLabsClient { config: ClientConfig, http: hpx::Client, // hpx HTTP client } ``` -------------------------------- ### Check Endpoint Coverage Source: https://github.com/longcipher/elevenlabs-sdk-rs/blob/master/README.md Verify that the SDK's endpoints are covered by integration tests against the OpenAPI specification using the `just` command. This ensures API completeness. ```bash just sdk-check-coverage ```