ElevenLabs Integration Guide

Technology: eleven-labs · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/eleven-labs

Insight:

ElevenLabs is the voice layer: TTS (Eleven v4 is the new flagship), Scribe v2 speech-to-text, Voice Design / cloning, and ElevenAgents for full voice + chat agents on web, phone and WhatsApp. For Kenya-targeted work the big change is that Swahili TTS lives only in Eleven v4 / v3 — not Multilingual v2 or Flash — and Scribe v2 transcribes Swahili in its "High accuracy" tier. API usage is now billed in USD per 1K characters / per hour / per agent minute. Keep keys server-side, mint short-lived tokens for browsers, and verify every webhook.

███████╗██╗     ███████╗██╗   ██╗███████╗███╗   ██╗██╗      █████╗ ██████╗ ███████╗
██╔════╝██║     ██╔════╝██║   ██║██╔════╝████╗  ██║██║     ██╔══██╗██╔══██╗██╔════╝
█████╗  ██║     █████╗  ██║   ██║█████╗  ██╔██╗ ██║██║     ███████║██████╔╝███████╗
██╔══╝  ██║     ██╔══╝  ╚██╗ ██╔╝██╔══╝  ██║╚██╗██║██║     ██╔══██║██╔══██╗╚════██║
███████╗███████╗███████╗ ╚████╔╝ ███████╗██║ ╚████║███████╗██║  ██║██████╔╝███████║
╚══════╝╚══════╝╚══════╝  ╚═══╝  ╚══════╝╚═╝  ╚═══╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚══════╝

ElevenLabs Integration Guide

Focus: Text-to-speech (Eleven v4), speech-to-text (Scribe v2), voices and Voice Design, ElevenAgents (voice + chat agents with tools, knowledge base, phone and WhatsApp), the official MCP server, webhooks, and pricing — via the TypeScript SDK and Claude Code tooling.

Overview

ElevenLabs now ships as three product lines that share one API key and one account:

Line What it covers Pricing page
ElevenAPI TTS, Text to Dialogue, STT (Scribe), Voice Design/cloning, dubbing, voice changer/isolator, sound effects, music https://elevenlabs.io/pricing/api
ElevenAgents (formerly "Conversational AI" / "Agents Platform") Voice + text agents: LLM, tools, knowledge base/RAG, web widget, SDKs, telephony, WhatsApp, tests, analytics https://elevenlabs.io/pricing/agents
ElevenCreative Studio apps (dashboard), credit-based plans https://elevenlabs.io/pricing

The SDK still namespaces agents under client.conversationalAi.* and the REST paths under /v1/convai/* — the rename is branding only.

flowchart LR
  A["App text"] -->|"textToSpeech / textToDialogue"| B["ElevenLabs API"]
  B --> C["Audio (mp3 / pcm / ulaw)"]
  E["User audio / voice note"] -->|"speechToText (scribe_v2)"| B
  B --> F["Transcript"]
  U["Caller / WhatsApp user / web widget"] <-->|"ElevenAgents<br/>ASR + LLM + TTS + turn-taking"| B
  B -->|"server tools"| T["Your HTTPS API"]
  B -->|"post-call webhook"| W["Your webhook route"]

Official Documentation

Resource URL
Docs home https://elevenlabs.io/docs/overview/intro
Models (IDs, languages, limits, concurrency) https://elevenlabs.io/docs/overview/models
API reference https://elevenlabs.io/docs/api-reference/introduction
ElevenAgents https://elevenlabs.io/docs/eleven-agents/overview
Hosted MCP https://elevenlabs.io/docs/eleven-agents/operate/hosted-mcp
Webhooks https://elevenlabs.io/docs/eleven-api/resources/webhooks
Changelog (weekly) https://elevenlabs.io/docs/changelog
Any docs page as Markdown append .md to the URL; full index at https://elevenlabs.io/docs/sitemap-en.xml

Versions (verified 2026-10-20)

Package Registry Version Notes
@elevenlabs/elevenlabs-js npm 2.73.0 Server SDK (Node ≥ 18). Bare elevenlabs npm pkg is deprecated.
@elevenlabs/react npm 1.18.0 Agent + Scribe hooks; re-exports @elevenlabs/client.
@elevenlabs/client npm 1.28.0 Framework-agnostic browser client (agents, Scribe realtime).
@elevenlabs/react-native npm 1.2.30 Mobile agents.
@elevenlabs/cli npm 1.6.1 elevenlabs CLI — agents-as-code (agents push/pull, tests, branches).
elevenlabs PyPI 2.73.1 Python SDK (Python ≥ 3.8).
elevenlabs-mcp PyPI 0.12.2 Local MCP server — repo archived 2026-08-20; prefer hosted MCP.

There is no @elevenlabs/elevenlabs-mcp npm package (404).


MCP Server Setup

The official server is remote at https://api.elevenlabs.io/v1/mcp and authenticates with OAuth (no API key in config). It is also listed in Claude's connector directory as ElevenLabs.

# Claude Code — streamable HTTP; completes OAuth on first connect
claude mcp add --transport http elevenlabs https://api.elevenlabs.io/v1/mcp
Region (isolated data residency workspace) MCP URL
Global (default) https://api.elevenlabs.io/v1/mcp
EU https://api.eu.residency.elevenlabs.io/v1/mcp
India https://api.in.residency.elevenlabs.io/v1/mcp
Singapore https://api.sg.residency.elevenlabs.io/v1/mcp

What it can do (per docs): create/update/duplicate/delete agents; read conversations and transcripts and search them; manage procedures, tools, MCP servers, knowledge-base documents; create/run tests; branches, drafts, deployments, merge proposals; triage tickets; estimate LLM cost; get widget config/link; and generate speech (returned as a short-lived download link). The claude.ai connector in this workspace also exposes creative_* tools (image/video/speech generation, voice design, transcription) — these spend credits.

Gotcha: updates made through the MCP server publish directly (to main or the targeted branch) — they are not staged as drafts. Keep "ask before running" on write tools in your client, and restrict who can connect.

Self-hosted (legacy)

uvx elevenlabs-mcp (PyPI elevenlabs-mcp, needs uv) still installs, but the GitHub repo was archived on 2026-08-20 and gets no updates. Only use it if you need offline creative tools without OAuth.

// .mcp.json — legacy local server
{
  "mcpServers": {
    "elevenlabs": {
      "command": "uvx",
      "args": ["elevenlabs-mcp"],
      "env": { "ELEVENLABS_API_KEY": "${ELEVENLABS_API_KEY}" }
    }
  }
}

SDK Setup

npm install @elevenlabs/elevenlabs-js@2.73.0        # server
npm install @elevenlabs/react@1.18.0                # browser agents / Scribe (optional)
pip install elevenlabs==2.73.1                      # Python
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";

// Server-only. Omitting apiKey reads ELEVENLABS_API_KEY from the environment.
const client = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
  timeoutInSeconds: 60,
  maxRetries: 2,
});
import os
from elevenlabs.client import ElevenLabs

client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])

SDK conventions: camelCase request fields in TS (modelId, outputFormat, voiceSettings.similarityBoost); response fields are camelCase too (voice.voiceId, cloned.voiceId, result.languageCode). TTS methods return a web ReadableStream<Uint8Array>.


Models (verified 2026-10-20)

Text to Speech

Model ID Use Languages Latency Char limit API price
eleven_v4 New flagship (GA 2026-09-28): most expressive, best cloning, audio tags 90+ incl. Swahili — 10,000 $0.08 / 1K chars
eleven_v4_turbo Realtime v4 — agents & interactive; ElevenAgents default TTS 90+ incl. Swahili ~100 ms — $0.04 / 1K chars
eleven_v3 Previous expressive gen; Text to Dialogue 70+ incl. Swahili — 5,000 $0.08 / 1K
eleven_v3_conversational Previous realtime expressive 70+ incl. Swahili ~280 ms — $0.04 / 1K
eleven_multilingual_v2 Stable long-form; API default model_id 29 (no Swahili) — 10,000 $0.08 / 1K
eleven_flash_v2_5 Cheapest/fastest bulk + realtime 32 (no Swahili) ~75 ms 40,000 $0.04 / 1K
eleven_flash_v2 English-only fast en ~75 ms 30,000 $0.04 / 1K

Deprecated: eleven_turbo_v2_5 → eleven_flash_v2_5; eleven_turbo_v2 → eleven_flash_v2; scribe_v1 → scribe_v2. optimize_streaming_latency is deprecated (no-op) — pick a faster model instead.

Eleven v4 notes: only Stability and Similarity settings (no Style/Speed sliders, no SSML); audio tags like [whispering], [laughing]; when the target language differs from the cloned voice's language, v4 speaks it with a native accent (a deliberate change — test before migrating dubbing/voice-agent flows).

Speech to Text

Model ID Use Price
scribe_v2 Batch STT, 90+ langs, diarization (32 speakers), keyterms (≤1000), entity detection/redaction, transcript editing $0.22 / hour
scribe_v2_realtime Streaming STT ~150 ms, VAD, manual commit $0.39 / hour
scribe_v2_medical Clinical batch STT (GA 2026-09-11), HIPAA-eligible with BAA (Enterprise) $0.22 / hour

Add-ons: keyterm prompting +$0.05/h (realtime +$0.08/h); transcript editing +$0.07/h (realtime +$0.12/h).

Other model IDs you may meet: eleven_ttv_v3 / eleven_multilingual_ttv_v2 (Voice Design), eleven_multilingual_sts_v2 (voice changer), eleven_text_to_sound_v2, music_v2_5.


Swahili / Kenya support status (codeAmani)

Capability Status (docs, 2026-10-20)
TTS eleven_v4, eleven_v4_turbo, eleven_v3, eleven_v3_conversational list Swahili (sw). eleven_multilingual_v2 and eleven_flash_v2_5 do not — the previous guide's "use multilingual_v2 for Swahili" advice was wrong.
STT Scribe v2 lists Swahili (swa) in the "High accuracy" tier (>5% to ≤10% WER). language_code accepts ISO 639-1 or 639-3. Leave it unset to auto-detect Sheng/English code-switching.
v4 also covers Amharic, Somali, Luganda, Hausa, Yoruba, Shona, Lingala, Wolof, Fula — useful for wider East/West African reach.
ElevenAgents Default TTS is now eleven_v4_turbo (Swahili-capable), but the agent language docs still describe a 31-language "Additional languages" list based on older models. Whether language: "sw" is accepted as an agent language is unverified — test in the dashboard before promising Swahili voice agents.
WhatsApp agents Inbound voice notes are transcribed and the agent can reply with voice notes "in any voice, any language".

codeAmani's Swahili-AI R&D report still gates any voice rollout on a TTS MOS eval (see research-and-development/). Candidates to benchmark now: eleven_v4 vs eleven_v3 (quality) and eleven_v4_turbo (agents). Text-first (WhatsApp + M-Pesa) remains Phase 1.


Core Patterns

Text-to-Speech (buffered and streaming)

const audio = await client.textToSpeech.convert("JBFqnCBsd6RMkjVDRZzb", {
  text: "Karibu! Hii ni sauti yako mpya kwenye codeAmani.",
  modelId: "eleven_v4", // Swahili-capable
  outputFormat: "mp3_44100_128",
  voiceSettings: { stability: 0.5, similarityBoost: 0.75 },
});
const bytes = Buffer.from(await new Response(audio).arrayBuffer());

JBFqnCBsd6RMkjVDRZzb is "George" (the voice the official quickstart uses) — not "Rachel" as the old guide said. Full routes: examples/tts.ts (buffered) and examples/stream.ts (textToSpeech.stream, piped straight into a Response).

Text to Dialogue (multi-speaker, Eleven v4)

client.textToDialogue.convert({ modelId: "eleven_v4", inputs: [{ text, voiceId }, …] }) — keep the sum of inputs[].text ≤ 2,000 chars per request. Realtime dialogue uses eleven_v4_turbo over the Text to Dialogue WebSocket (metered as sessions, closed after 20 s idle unless you send keep_alive). See examples/v4-dialogue-and-voice-design.mts.

Voices

// GET /v2/voices — paginated search (getAll() is legacy)
const { voices } = await client.voices.search({ search: "swahili", pageSize: 20 });
for (const voice of voices) {
  console.log(voice.voiceId, voice.name, voice.labels?.language ?? "multi");
}

Voice Design (describe → preview → save)

client.textToVoice.design({ modelId: "eleven_ttv_v3", voiceDescription, text }) returns previews[] (generatedVoiceId, audioBase64); save one with client.textToVoice.create({ voiceName, voiceDescription, generatedVoiceId }). Each saved voice uses a custom-voice slot (Free has 3 slots, Voice Design only). Docs warn Voice Design voices "may not be as performative" on Eleven v4.

Voice cloning (IVC)

import { createReadStream } from "node:fs";

const cloned = await client.voices.ivc.create({
  name: "codeAmani Brand Voice",
  files: [createReadStream("samples/sample-1.mp3"), createReadStream("samples/sample-2.mp3")],
});
const voiceId = cloned.voiceId; // persist in your DB
console.log(cloned.requiresVerification);

Cloning needs Starter or above. Eleven v4 reproduces the source including its flaws (noise, plosives, loudness) — 1–2 minutes of clean single-speaker audio, one speaking style. Professional Voice Clones (PVC) can be fine-tuned on v4 from My Voices.

Consent: only clone voices you have explicit, recorded permission for (ElevenLabs ToS; KDPA 2019 treats voice as personal/biometric data on Kenya-targeted projects).

Speech-to-Text (Scribe v2)

const transcription = await client.speechToText.convert({
  file: createReadStream("recording.mp3"),
  modelId: "scribe_v2",
  languageCode: "sw", // or omit to auto-detect
});
console.log(transcription.text);

Long files: pass sourceUrl + webhook: true (+ webhookMetadata) and receive the result on your webhook (examples/stt-voice-note.ts). Browsers: mint a single-use token (POST /v1/single-use-token/..., 15-min expiry) and use useScribe() from @elevenlabs/react for realtime.


ElevenAgents (voice + chat agents)

Architecture: fine-tuned ASR → your chosen LLM (or a custom LLM) → low-latency TTS → proprietary turn-taking model. Build in the dashboard, the visual Workflow builder, the CLI (@elevenlabs/cli, agents-as-code), the SDK, or the hosted MCP.

Build blocks

Block What it is
LLM conversationConfig.agent.prompt.llm — Claude (claude-haiku-4-5, claude-sonnet-4-6, claude-sonnet-5-5, claude-opus-5-5, …), GPT, Gemini, GLM, DeepSeek, Qwen, or customLlm. Billed separately per minute.
Tools Webhook (server) tools (call your HTTPS API), client tools (run in the browser/app), code tools (sandboxed JS on ElevenLabs), MCP tools (attach MCP servers), system tools (end call, language detection, transfer to agent/number, skip turn, keypad DTMF, voicemail detection, update state, flag for review).
Knowledge base Files (PDF, DOCX, TXT, MD, HTML, EPUB; ≤ 20 MB), URLs (with auto-sync), or text. Usage mode auto (RAG when enabled and indexed) or prompt (full text, ≤ ~300k chars). Folders always go through RAG.
Procedures GA 2026-08: task-specific instruction packs with a trigger, loaded on demand instead of bloating the system prompt.
Personalization Dynamic variables + per-conversation overrides; userId for user mapping.
Analysis Evaluation criteria, data collection, triage tickets, topics, tests, A/B experiments, alerting (PagerDuty, Slack, webhooks).

Create an agent with a KB document and a server tool from code: see examples/agent-setup.mts.

Channels

Channel How
Web widget <elevenlabs-convai agent-id="…"> embed, or ElevenLabs UI (shadcn components)
React / RN / iOS / Android / Flutter @elevenlabs/react (ConversationProvider + useConversationControls / useConversationStatus / useConversation), @elevenlabs/react-native, Swift, Kotlin, elevenlabs_agents (pub.dev)
Phone Native Twilio integration, SIP trunking, Vonage, Telnyx, Plivo, Exotel, Bandwidth, Sinch; Genesys / Five9 / Amazon Connect; Microsoft Teams. Batch outbound calls with Twilio answering-machine detection.
WhatsApp Import a WhatsApp Business account (Meta business portfolio + a number not used in the WhatsApp Business app elsewhere). Agent handles text, voice notes (transcribed; replies as voice notes by default), images, documents, location, contacts, interactive buttons/lists, inbound and outbound calls. Outbound starts from a Meta-approved template (conversationalAi.whatsapp.outboundMessage). Meta bills templates/calls separately. 15-min inactivity timeout per message conversation.

Private agents: the browser never sees your API key. Your server mints a conversation token (WebRTC, conversations.getWebrtcToken) or a signed URL (WebSocket, conversations.getSignedUrl) — examples/conversation-token-route.ts + examples/voice-agent-widget.tsx.

// WhatsApp outbound template (TS SDK)
await client.conversationalAi.whatsapp.outboundMessage({
  whatsappPhoneNumberId: "<phone-number-id>",
  whatsappUserId: "2547XXXXXXXX", // recipient, digits only
  templateName: "welcome",
  templateLanguageCode: "en",
  templateParams: [
    { type: "body", parameters: [{ type: "text", parameterName: "name", text: "Wanjiku" }] },
  ],
  agentId: "<agent-id>",
});

Overlap with codeAmani's WhatsApp apps: the six Kenyan WhatsApp + M-Pesa apps use the Meta Cloud API directly. A number can only be connected to one provider, so importing it into ElevenLabs means ElevenLabs owns that number's webhook. Turn off Enable messaging to let ElevenLabs handle only calls while your app handles text.


Webhooks

Configure workspace webhooks in Settings → Webhooks (admins only), then select them per product (agent post-call, STT, flows). Events:

Event When
post_call_transcription Agent conversation ended and analysis is done (transcript, analysis, metadata incl. cost)
post_call_audio Base64 MP3 of the full conversation (no transcript fields)
call_initiation_failure Outbound call failed to connect
answering_machine_detection Twilio AMD verdict (2026-09)
speech_to_text_transcription Async Scribe job finished (one doc sample says speech_to_text.completed — handle both)
voice_removal_notice / voice_removal_notice_withdrawn / voice_removed Shared library voice lifecycle
flows_generation / flows_template_run Image & video / template run done

Signature verification: header ElevenLabs-Signature: t=<unix>,v0=<hex> where v0 = HMAC_SHA256(secret, "${t}.${rawBody}"). The SDK rejects timestamps older than 30 minutes. Always verify the raw body:

const rawBody = await req.text();
const event = await client.webhooks.constructEvent(
  rawBody,
  req.headers.get("elevenlabs-signature") ?? "",
  process.env.ELEVENLABS_WEBHOOK_SECRET ?? "",
); // throws on missing/invalid signature → return 401

Python: client.webhooks.construct_event(rawBody=..., sig_header=..., secret=...) (returns a dict). Full route with dedupe: examples/webhook-route.ts.

Delivery rules: return 2xx fast. Retries are off by default; when enabled, up to 5 attempts (immediate, 30 s, 2 min, 8 min, 30 min, ±10% jitter) on 5xx/429/408/timeouts only — so make handlers idempotent (conversation_id / request_id + event_timestamp). Audio payloads > 50 MiB are not retried. Webhooks auto-disable after ≥ 10 consecutive failures with no success in 7 days. Optionally allowlist ElevenLabs' static egress IPs as a second layer.


Pricing (verified 2026-10-20 — re-check before quoting)

API usage is billed in USD, not credits (ElevenAPI page FAQ). Plans include an allowance; overage is billed at the per-unit rate.

Plan $/month Creative credits v4 TTS chars incl. Agent minutes incl. Agent concurrency
Free 0 10k 10,000 15 4
Starter 6 30k 75,000 75 6
Creator 22 (first month 11) 121k 275,000 275 10
Pro 99 600k 1,238,000 1,238 20
Scale 299 1.8M 3,738,000 3,738 30
Business 990 6M 12,375,000 12,375 40

Per-unit API rates: TTS $0.08 / 1K chars (v4, v3, Multilingual v2) or $0.04 (v4 Turbo, v3 Conversational, Flash); Scribe v2 $0.22/h, realtime $0.39/h; ElevenAgents $0.08/min extra minutes, $0.16/min burst (up to 3× concurrency), $0.003 per text message, LLM billed on top, telephony billed by your carrier; Voice Changer / Isolator / SFX $0.12/min; Music $0.15/min; Dubbing v1 $0.33/min, Dubbing v2 $2.20/min. Commercial use requires a paid plan. Startup grants: 12 months, 33M characters. Detail: reference/pricing-snapshot.md.


Environment Variables

Secrets (store in the vault / Vercel env, never in code):

ELEVENLABS_API_KEY=sk_...
ELEVENLABS_WEBHOOK_SECRET=your-webhook-hmac-secret

Non-secret settings:

Variable Example Purpose
ELEVENLABS_DEFAULT_VOICE_ID JBFqnCBsd6RMkjVDRZzb Default voice ("George")
ELEVENLABS_AGENT_ID agent_… Agent used by the token route
ELEVENLABS_TTS_MODEL eleven_v4 Override default TTS model

Restrict every API key in the dashboard: endpoint scope, a credit quota, and an IP allowlist (non-allowlisted IPs get 403). Use a separate key per app/environment.


Common Use Cases

Use Case Approach
Voice notifications / IVR prompts textToSpeech.convert → cache to R2 → play
Swahili audio content eleven_v4 (quality) after the MOS eval; eleven_v4_turbo for realtime
Transcribe WhatsApp voice notes speechToText.convert with scribe_v2 (auto-detect for Sheng)
Support voice agent on web ElevenAgents + @elevenlabs/react + conversation-token route
Phone agent ElevenAgents + Twilio native or SIP trunk; batch calls for outbound
WhatsApp voice/chat agent Import WABA into ElevenAgents; template-initiated outbound
Brand voice Voice Design (eleven_ttv_v3) or IVC/PVC with consent
Manage agents from Claude Hosted MCP https://api.elevenlabs.io/v1/mcp

Troubleshooting

Issue Fix
401 Unauthorized Key missing/revoked, or key scope lacks that endpoint
too_many_concurrent_requests Plan concurrency hit (e.g. Free 2 Multilingual / 4 Flash). Queue, use the TTS WebSocket (only generation time counts), or upgrade. Watch current-concurrent-requests / maximum-concurrent-requests headers.
Swahili sounds wrong / English accent You are on Multilingual v2 or Flash (no Swahili) — switch to eleven_v4 / eleven_v3
Numbers/phone numbers read oddly on Flash Flash disables normalization by default; normalize in your LLM or use Multilingual v2/v4 (apply_text_normalization: "on" for Flash is Enterprise-only)
Style/speed sliders ignored Eleven v4 only uses Stability + Similarity; SSML unsupported
Webhook signature fails You parsed JSON before verifying — pass the raw text body; check clock skew (30-min window)
WhatsApp agent never replies No agent assigned, Enable messaging off, or required dynamic variables missing
MCP change went live unexpectedly Hosted MCP publishes directly — use a branch or require approval

codeAmani notes

Official docs: