Building Voice Agents with ElevenLabs Conversational AI - NextGenBeing
Back to discoveries

Building Voice Agents with ElevenLabs Conversational AI

Learn how to build production real-time voice agents with ElevenLabs Conversational AI using signed URLs, WebSockets, React hooks, and client tools.

AI News 14 min read
Bekzod Erkinov

Bekzod Erkinov

Nov 25, 2026 • 0 views
Building Voice Agents with ElevenLabs Conversational AI
Photo by Jumping Jax on Unsplash
Size:
Height:
14 min read 5,190 words Focus mode: Eye care:

Listen to Article

Loading...
0:00 / 0:00
0:00 0:00
Low High
0% 100%
⏸ Paused ▶️ Now playing... Ready to play ✓ Finished
Table of contents · 8 sections

Building Voice Agents with ElevenLabs Conversational AI

Gluing together independent speech-to-text models, large language model streams, and text-to-speech synthesizers introduces latency spikes, awkward turn-taking, and complex WebSocket plumbing. By adopting a dedicated full-duplex voice pipeline, developers can deliver natural, sub-second vocal interactions with robust interruptibility and bidirectional UI synchronization. This guide demonstrates how to architect, secure, and implement an interactive voice assistant using production-grade patterns.

Some links in this post are affiliate links; see our disclosure.

Pick it if / Skip it if

  • Pick it if: You need expressive, human-like voice agents inside web or mobile apps, sub-second turnaround times, turnkey Voice Activity Detection (VAD), and bidirectional UI synchronization via client tools.
  • Skip it if: You are building purely telephony systems requiring deep SIP trunk orchestration across arbitrary third-party speech engines, or if your application requires a native speech-to-speech foundation model for non-verbal acoustic reasoning.

What Is ElevenLabs Conversational AI?

Historically, building an interactive voice agent required manual orchestration across three disconnected subsystems. An application captured microphone audio, streamed chunks to an automatic speech recognition (ASR) service, accumulated transcripts, forwarded them to a large language model (LLM), and piped the resulting text tokens to a text-to-speech (TTS) engine. Each network hop accumulated latency, while edge cases like mid-sentence interruptions, background noise filtering, and half-duplex turn-taking required hundreds of lines of brittle state machine code.

ElevenLabs Conversational AI (also known as ElevenAgents) collapses this stack into an integrated, managed conversational runtime. Rather than requiring developers to manually stitch together transcription, reasoning, and synthesis services, the platform provides an end-to-end bidirectional pipeline accessible over WebSockets. As documented in the ElevenLabs Conversational AI Documentation, the service integrates server-side Voice Activity Detection (VAD), conversational turn management, dynamic LLM prompt orchestration, and low-latency voice synthesis powered by specialized models like eleven_flash_v2_5.

Beyond audio streaming, the runtime supports multimodal interactions. Voice agents can reference structured knowledge bases, execute server-side webhook actions, and trigger client-side JavaScript functions on the user's active browser window. This enables developers to deploy agents that do not simply speak, but also drive user interfaces, fill out forms, and respond dynamically to customer actions.


Why Managed Voice Agents Matter Now

Real-time audio presents engineering constraints that differ drastically from text-based chat completions. In text interfaces, a two-second latency between prompt and token streaming feels acceptable to human users. In spoken conversation, however, conversational pauses exceeding 700 milliseconds feel awkward, disjointed, and unnatural.

Achieving natural cadence requires three simultaneous capabilities:

  1. Low Time-to-First-Audio (TTFA): Generating voice frames within 300 to 800 milliseconds from the moment a user finishes speaking.
  2. Instant Interruptibility: Halting playback immediately when the user speaks over the agent, clearing audio playback buffers and notifying the underlying language model to prune the interrupted response.
  3. Contextual Action Execution: Permitting the voice agent to query databases and alter frontend application views without stalling the audio stream.

Managed conversational runtimes eliminate the need to build custom client-side audio buffers, acoustic echo cancellation (AEC) filters, and complex interrupt-state handlers. Instead of wrestling with low-level audio engineering, frontend and full-stack teams can focus directly on application logic, user experience, and domain guardrails.


How ElevenLabs Conversational AI Works: Architecture and Pipeline

To make informed architectural choices, developers must understand how audio frames, text tokens, and metadata flow across the network during a live voice session.

Client App (Web Audio Context + @elevenlabs/react)
       ^                 |
       | Audio playback  | Mic input (WebSockets)
       v                 v
ElevenLabs Gateway (VAD + ASR + LLM + Flash TTS)
       |                 ^
       | Webhook calls   | Webhook responses
       v                 |
Backend Application API (Secure DB & Auth)

The End-to-End Cycle

  1. Audio Acquisition: The client application requests microphone access through the browser's navigator.mediaDevices.getUserMedia API. The audio stream is downsampled, encoded, and dispatched over an authenticated WebSocket connection.
  2. VAD and Speech Detection: As audio chunks arrive at the gateway, server-side VAD evaluates speech activity. The system differentiates between background noise, brief pauses, and completed sentences.
  3. Transcription & Prompt Assembly: Spoken words are converted into text tokens in real time. Once turn completion is detected, the transcript is merged with the agent's system instructions, conversation history, and any relevant snippets retrieved from attached knowledge bases.
  4. LLM Generation: The language model produces response tokens. If the agent determines that a tool call is required, it suspends text output and emits either a server webhook request or a client tool dispatch.
  5. Streaming Synthesis: Text tokens stream directly into the TTS engine (eleven_flash_v2_5), which begins returning raw audio frames before the language model has finished generating the full paragraph.
  6. Playback and Interruption Management: The client receives audio packets and plays them through the browser's Web Audio API. If the user begins speaking while playback is active, local audio is paused instantly, and an interruption signal resets the conversational buffer.

Architectural Comparison: Choosing Your Voice Stack

Voice architectures generally fall into three competing paradigms: managed voice platforms, native multimodal models, and modular telephony orchestrators.

Feature / Dimension ElevenLabs Conversational AI OpenAI Realtime API Modular Orchestrator (e.g., Vapi)
Primary Architecture Hosted runtime with integrated VAD, pluggable LLMs, and Flash TTS Native speech-to-speech foundation model (gpt-4o-realtime) Modular orchestrator stitching separate STT, LLM, and TTS providers
Voice Realism & Nuance Exceptional expressive range, emotion control, and extensive voice library High naturalness, but restricted to built-in synthetic voices Variable; depends entirely on selected third-party TTS engine
Synthesis Latency Approximately 75ms for eleven_flash_v2_5 synthesis engine Low latency via direct audio-in/audio-out token processing Cumulative sum of discrete STT, LLM, and TTS network hops
Frontend SDK Support First-party React (@elevenlabs/react), React Native, Kotlin, and Swift WebSocket/WebRTC protocols and generic community wrappers Official Web, Flutter, React Native, and Python client libraries
Tool Execution Dual-tier: trusted server Webhooks and untrusted Client Tools Native function calling and Model Context Protocol (MCP) support Server webhooks and custom client-side function callbacks
Telephony Integration Built-in web widget with expanding carrier support Requires custom SIP/WebRTC bridging (e.g., Twilio integration) Deep out-of-the-box SIP trunking and phone number provisioning
Pricing Model Tiered plans from $6/month (includes minutes; $0.08/min platform overage) Token-metered (~$0.06/min audio input + ~$0.24/min audio output = ~$0.30/min total) Platform fee ($0.05/min) plus pass-through STT, LLM, and TTS provider costs

Developers seeking an in-depth review of native multimodal options can inspect the OpenAI Realtime API Guide. Teams prioritizing complex phone PBX routing and multi-vendor voice fallbacks can explore the Vapi Documentation. For applications where user-facing brand identity, vocal nuance, and rapid web embedding are paramount, ElevenLabs provides the most cohesive developer workflow.


ElevenLabs Conversational AI Pros and Cons

Choosing a managed voice agent platform involves balancing vocal realism and rapid development against custom telephony requirements and infrastructure control.

Category Pros (Advantages) Cons (Trade-offs & Limitations)
Audio Quality & Latency • Exceptional emotional range, natural cadence, and vast voice library.
• Ultra-low synthesis latency (~75ms via eleven_flash_v2_5).
• Turnkey full-duplex VAD and instant interruptibility.
• Not a native speech-to-speech foundation model; audio is serialized through internal STT/TTS stages.
• Cannot directly reason on non-verbal acoustic cues (e.g., whispered distress).
Developer Experience • Dedicated frontend SDKs (@elevenlabs/react, React Native, Swift, Kotlin).
• Dual-tier tool support: secure server Webhooks and reactive Client Tools.
• Ephemeral signed URLs avoid leaking credentials.
• Requires custom server endpoint to mint signed WebSocket URLs for production security.
• Client tools run in browser context and cannot handle privileged mutations.
Cost & Concurrency • Predictable bundled minutes on paid tiers with transparent $0.08/min overage.
• Up to 16.7% discount (2 months free) on annual billing plans.
• Lower tiers enforce strict concurrency limits (6 on Starter, 10 on Creator).
• Burst calls exceeding baseline concurrency incur a 2x rate ($0.16/min).
• Custom LLMs and telephony carrier costs are billed separately.
Deployment & Telephony • Embeddable web widget and rapid client integration.
• Turnkey cloud infrastructure requires zero WebRTC/SIP server maintenance.
• Telephony features are developing; lacks built-in advanced SIP trunking and PBX routing found in Vapi/Retell.
• Cloud-only service; cannot run in air-gapped on-premises setups.

How to Build a Voice Agent with React: Step-by-Step Implementation

The following implementation walkthrough builds a production-ready voice assistant embedded within a React application. It uses a Next.js server route to mint secure signed URLs, invokes the official @elevenlabs/react SDK, and registers a client tool that manipulates application state.

Step 1: Scaffolding and Secure Authentication

Never embed your private API key (xi-api-key) inside frontend client bundles. A public client-side key can be extracted by any user, leading to unauthorized usage and account exhaustion. Instead, follow the security pattern outlined in the ElevenLabs Signed URL Guide: create a server-side endpoint that requests a temporary signed WebSocket URL on behalf of authenticated users.

Install the necessary dependencies in your project:

npm install @elevenlabs/react

Next, create an API route in your backend or Next.js App Router to fetch the signed URL:

// app/api/voice-token/route.ts
// (Unrun code snippet; verified against official documentation)

import { NextResponse } from "next/server";

export async function GET() {
  const agentId = process.env.ELEVENLABS_AGENT_ID;
  const apiKey = process.env.ELEVENLABS_API_KEY;

  if (!agentId || !apiKey) {
    return NextResponse.json({ error: "Missing ElevenLabs credentials" }, { status: 500 });
  }

  try {
    const response = await fetch(
      `https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id=${agentId}&environment=production`,
      {
        method: "GET",
        headers: { "xi-api-key": apiKey },
        cache: "no-store",
      }
    );

    if (!response.ok) throw new Error(`Signed URL error: ${response.statusText}`);
    const data = await response.json();
    return NextResponse.json({ signedUrl: data.signed_url });
  } catch (error) {
    return NextResponse.json({ error: "Token generation failed" }, { status: 500 });
  }
}

Step 2: Requesting Audio Permissions Gracefully

Before initiating a WebSocket handshake, modern browsers require explicit microphone authorization within a secure HTTPS origin or localhost, as specified by MDN Web Docs on getUserMedia. Calling getUserMedia prior to starting the session avoids unhandled promise rejections and gives users clear visual prompts.

// lib/audio-permissions.ts
// (Unrun code snippet; verified against official documentation)

export async function checkMicrophoneAccess(): Promise<void> {
  if (typeof window === "undefined" || !navigator.mediaDevices?.getUserMedia) {
    throw new Error("Audio capture not supported in this environment.");
  }
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    stream.getTracks().forEach((track) => track.stop());
  } catch (err: unknown) {
    if (err instanceof Error && err.name === "NotAllowedError") {
      throw new Error("Microphone permission denied.");
    }
    throw new Error("Unable to access recording hardware.");
  }
}

Step 3: Integrating the React Conversational UI

The package @elevenlabs/react on npm exports both an all-in-one hook (useConversation) and granular hooks (useConversationControls, useConversationStatus, useConversationMode). In production components, granular hooks prevent unnecessary component re-renders during high-frequency audio volume updates.

Here is a focused, modular voice control component:

// components/VoiceAssistant.tsx
// (Unrun code snippet; verified against official documentation)

"use client";

import React, { useState, useCallback } from "react";
import {
  ConversationProvider,
  useConversationControls,
  useConversationStatus,
  useConversationMode,
} from "@elevenlabs/react";
import { checkMicrophoneAccess } from "@/lib/audio-permissions";

export function VoiceAssistantRoot() {
  return (
    <ConversationProvider>
      <VoiceAssistantUI />
    </ConversationProvider>
  );
}

function VoiceAssistantUI() {
  const { startSession, endSession } = useConversationControls();
  const { status } = useConversationStatus(); // "disconnected" | "connecting" | "connected"
  const { mode } = useConversationMode(); // "speaking" | "listening"
  const [activeTab, setActiveTab] = useState<string>("overview");

  const handleStart = useCallback(async () => {
    try {
      await checkMicrophoneAccess();
      const res = await fetch("/api/voice-token");
      const { signedUrl } = await res.json();

      await startSession({
        signedUrl,
        clientTools: {
          updateNavigationTab: ({ tabName }: { tabName: string }): string => {
            setActiveTab(tabName);
            return `Active view switched to ${tabName}`;
          },
        },
      });
    } catch (err) {
      console.error("Session initialization failed:", err);
    }
  }, [startSession]);

  return (
    <div style={{ padding: 24, border: "1px solid #e5e7eb", borderRadius: 12 }}>
      <h3>Voice Assistant</h3>
      <p>Status: {status} | Mode: {mode}</p>
      <p>Active View: <code>{activeTab}</code></p>
      {status !== "connected" ? (
        <button onClick={handleStart} disabled={status === "connecting"}>
          {status === "connecting" ? "Connecting..." : "Start Talking"}
        </button>
      ) : (
        <button onClick={() => endSession()}>End Session</button>
      )}
    </div>
  );
}

Step 4: Configuring Client Tools vs Webhook Tools

As detailed in the ElevenLabs Custom Tools Documentation, tools expand an agent from a passive speech pipeline into an active participant in your workflow. However, developers must rigorously respect the trust boundary between client tools and server webhook tools:

  • Client Tools (Low Trust): These execute inside the user's browser runtime. They are ideal for triggering modal dialogs, updating tabs, scrolling down a page, or highlighting items. Because end users have full access to DevTools and can inspect, mock, or rewrite JavaScript execution, you must never trust a client tool to execute privileged mutations or security-critical confirmations.
  • Webhook Tools (High Trust): These execute server-to-server. When an agent invokes a webhook tool, ElevenLabs' cloud servers dispatch an authenticated HTTP POST request to your backend API. Use webhook tools for database lookups, payment processing, sending transactional emails, or booking reservations.

If you are launching a voice-first application and need a polished, conversion-ready presentation site, explore the AI SaaS Landing Template to quickly deploy your frontend marketing pages.


ElevenLabs Conversational AI Pricing, Plans, and Limits

Deploying voice agents to production exposes technical edge cases, concurrency boundaries, and cost structures that differ from traditional APIs.

(Pricing and plan specifications verified November 2026; subject to change)

1. Subscription Tiers and Monthly vs. Annual Billing

ElevenLabs Conversational AI (ElevenAgents) operates on a tiered subscription model with included monthly conversation minutes, with additional usage billed at a flat platform overage rate of $0.08 per platform minute.

Subscribers can choose between monthly and annual billing. Selecting annual billing provides an effective 16.7% discount (equivalent to 2 months free per year, paying for 10 months upfront):

  • Free: $0/month (15 minutes included, 4 concurrent calls)
  • Starter: $6/month billed monthly, or ~$5/month billed annually ($60/year) (75 minutes included, 6 concurrent calls)
  • Creator: $22/month billed monthly, or ~$18.33/month billed annually ($220/year) (275 minutes included, 10 concurrent calls)
  • Pro: $99/month billed monthly, or ~$82.50/month billed annually ($990/year) (1,238 minutes included, 20 concurrent calls)
  • Scale: $299/month billed monthly, or ~$249.17/month billed annually ($2,990/year) (3,738 minutes included, 30 concurrent calls)
  • Business: $990/month billed monthly, or ~$825/month billed annually ($9,900/year) (12,375 minutes included, 40 concurrent calls)
  • Enterprise: Custom minute packages, dedicated enterprise concurrency limits, and tailored SLAs

These platform fees cover ElevenLabs' managed turn-taking, speech recognition, and low-latency voice synthesis. If you configure custom underlying LLMs (such as third-party OpenAI or Anthropic models via your own API keys) or route calls through external telephony providers like Twilio, those provider token and carrier costs are billed separately by their respective platforms.

2. Concurrency Caps and Burst Rate Pricing

Each subscription tier enforces a baseline concurrency limit:

  • Free: 4 concurrent sessions
  • Starter: 6 concurrent sessions
  • Creator: 10 concurrent sessions
  • Pro: 20 concurrent sessions
  • Scale: 30 concurrent sessions
  • Business: 40 concurrent sessions

When your application encounters unexpected traffic surges, ElevenLabs' Burst Capacity allows active conversations to scale up to 3x your tier's baseline concurrency (capped at a ceiling of 300 concurrent calls for self-serve accounts).

  • Active calls within your plan's concurrency allowance consume standard bundled minutes or the baseline $0.08/min overage.
  • Additional simultaneous calls exceeding your baseline concurrency cap are billed at a $0.16 per minute burst rate (2x the standard platform rate).
  • Excess burst calls are processed with deprioritized speech queues, which may introduce minor latency during peak intervals. Once the 3x burst cap (or 300 concurrent call limit) is reached, subsequent incoming sessions are rejected or held in queue if queueing is enabled.

3. Choosing the Right Plan: Workload-to-Plan Decision Guide

To match your expected call volume and concurrency profile to the most cost-effective tier, use this decision framework:

Project Stage & Workload Recommended Tier Included Minutes & Concurrency Key Fit & Decision Factors
Prototyping & Local Development Free ($0/mo) 15 mins / 4 concurrent Test local components, evaluate eleven_flash_v2_5 latency, and build proof-of-concept client tools without cost.
MVP Testing & Beta Feedback Starter ($6/mo) 75 mins / 6 concurrent Validate end-to-end user flows, test signed URL backend minting, and demo to early stakeholders.
Early Commercial Traction Creator ($22/mo) 275 mins / 10 concurrent Support small production apps with ~4.5 hours of conversation monthly and low simultaneous peak usage.
Active Production Scaling Pro ($99/mo) 1,238 mins / 20 concurrent Suitable for growing applications (~20 hours of talk time/month). Higher concurrency (20 sessions) minimizes $0.16/min burst charges.
High-Volume Commercial Apps Scale ($299/mo) 3,738 mins / 30 concurrent Built for sustained traffic (~62 hours of monthly conversation) requiring reliable concurrency for customer support or sales workflows.
Enterprise Contact Centers Business / Enterprise ($990+/mo) 12,375+ mins / 40+ concurrent Essential for high-throughput environments requiring custom volume discounts, 40+ concurrent lines, and enterprise SLAs.

Decision Rule: If your monthly overage on Starter consistently exceeds $16 (200 extra minutes), upgrading to Creator ($22/month) immediately reduces effective per-minute costs while expanding concurrency from 6 to 10 lines. Similarly, upgrading to Pro when exceeding Creator minutes prevents costly burst pricing during peak business hours.

4. Browser Media Autoplay Policies

Modern desktop and mobile browsers aggressively block programmatic audio playback unless initiated by a direct user gesture (such as an explicit button click). Attempting to call startSession() inside an automatic useEffect or on page load will trigger AudioContext suspension. Always bind session initialization directly to user-initiated clicks.

5. Network Stability and Reconnection

WebSockets require stable bidirectional transport. When users switch networks (for example, transitioning from Wi-Fi to cellular data), the TCP connection terminates abruptly. The SDK emits an onDisconnect or onError callback. Production implementations must inform the user and provide a clear reconnect button rather than silently hanging in a "connected" state.


Who Should Skip ElevenLabs Conversational AI? (Best Alternatives)

While ElevenLabs delivers exceptional voice realism and clean developer ergonomics, it is not the ideal solution for every voice engineering team.

  1. Complex Telephony and Call Center Infrastructure: If your primary roadmap involves replacing legacy PBX systems, managing complex SIP trunk handoffs, configuring IVR trees, or dynamically routing inbound telephone calls across dozens of carrier lines, dedicated telephony orchestrators like Vapi or Retell AI provide far deeper native telephony tooling.
  2. Strict On-Premises or Air-Gapped Environments: Organizations bound by HIPAA, financial data sovereignty, or defense compliance that mandate completely local, air-gapped model execution cannot rely on cloud-hosted WebSocket endpoints. These teams should build self-hosted pipelines utilizing open-weight models (such as Whisper for STT and Kokoro or Piper for TTS).
  3. Purely Speech-to-Speech Acoustic Reasoning: If your application requires analyzing emotional nuances in user vocal tones (such as detecting whispered distress or subtle vocal inflections) and feeding those acoustic features directly into unified multimodal reasoning without text serialization, native speech-to-speech models like the OpenAI Realtime API offer an architectural alternative.

Getting Started: Next Steps with ElevenLabs Conversational AI

  1. Scaffold an Agent: Navigate to the ElevenLabs dashboard, create an agent, select a low-latency voice model (eleven_flash_v2_5), and define your system prompt instructions.
  2. Secure Your Backend: Deploy a server endpoint that securely queries the /v1/convai/conversation/get-signed-url endpoint using your private API key.
  3. Embed the Frontend SDK: Install @elevenlabs/react in your client project and build a test interface using ConversationProvider and useConversationControls.
  4. Register Custom Tools: Map safe UI interactions to client tools, while delegating all database modifications to authenticated webhook tools.
  5. Test Permission Failures: Deliberately deny microphone permissions in your test browser to verify that your UI handles hardware rejections gracefully.

Worth a look: ElevenLabs provides industry-leading expressive voices and turnkey conversational infrastructure for developers building in-app voice agents, though teams requiring native SIP trunking or ultra-custom multi-engine routing may prefer modular voice orchestrators.

Bekzod Erkinov

Bekzod Erkinov

Author

Founder of NextGenBeing. Software engineer working with Laravel, Python, and cloud infrastructure. Writes about patterns that actually hold up in production. Based in Tashkent, Uzbekistan.

Free guide

Get the AI-Assisted Developer's Field Guide

The workflow, prompts, and tools I use to ship faster with AI — free when you subscribe. Plus new deep-dives in your inbox. No spam, unsubscribe anytime.

Comments (0)

Please log in to leave a comment.

Log In

Related Articles

Don't miss the next deep dive

Get one well-researched tutorial in your inbox each week. No spam, unsubscribe anytime.