
Elevenlabs Agents
- 1.5k installs
- 946 repo stars
- Updated July 2, 2026
- jezweb/claude-skills
A skill for creating, configuring, integrating, testing, and deploying ElevenLabs conversational AI voice agents with custom tools and RAG-based knowledge bases.
About
ElevenLabs Agent Builder enables developers to create production-ready conversational AI voice agents through dashboard configuration or CLI (Agents as Code). Developers use this when building phone systems, receptionists, or customer support agents that need voice interaction, tool integration, and knowledge base retrieval. Key workflows include: creating agents via dashboard or CLI with voice/LLM selection, authoring system prompts using a 6-component framework (personality, environment, tone, goal, guardrails, tools), integrating client-side or server-side tools, uploading document knowledge bases, embedding SDKs (React, React Native, Swift, JavaScript), testing via CLI or API simulation, and deploying across dev/staging/prod environments using multi-stage deployment commands.
- CLI-first agent management (elevenlabs agents init/push/test) with Agents as Code templates (default, customer-service,
- 6-component system prompt framework (personality, environment, tone, goal, guardrails, tools) for consistent agent behav
- Client and server-side tool support: browser-based tools (cart updates, navigation) via handler functions and webhook-ba
- MCP tool integration via custom JSON-RPC server (protocol 2024-11-05) returning plain JSON responses, not SSE
- Multi-environment deployment (dev/staging/prod) with dry-run preview, versioning, A/B testing, and post-call webhooks wi
Elevenlabs Agents by the numbers
- 1,504 all-time installs (skills.sh)
- +23 installs in the week ending Jul 29, 2026 (Skillselion tracking)
- Ranked #787 of 16,565 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 31, 2026 (Skillselion catalog sync)
elevenlabs-agents capabilities & compatibility
- Capabilities
- create agents via dashboard or cli with template · configure voice, llm, system prompt, and first m · define and integrate client side tools (handler · define and integrate server side tools (webhooks · upload and manage knowledge bases for rag · embed react, react native, swift, or javascript · test agents via cli, test scenarios, or api simu · deploy to multiple environments with versioning
- Works with
- openai · anthropic
- Use cases
- orchestration
- Platforms
- macOS · Windows · Linux · WSL
- Runs
- Hosted SaaS
- Pricing
- Bring your own API key
What elevenlabs-agents says it does
Build a production-ready conversational AI voice agent. Produces a configured agent with tools, knowledge base, and SDK integration.
npx skills add https://github.com/jezweb/claude-skills --skill elevenlabs-agentsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.5k |
|---|---|
| repo stars | ★ 946 |
| Security audit | 2 / 3 scanners passed |
| Last updated | July 2, 2026 |
| Repository | jezweb/claude-skills ↗ |
What it does
Build and deploy conversational AI voice agents with custom tools and knowledge bases on the ElevenLabs platform.
Who is it for?
Building customer support agents, AI receptionists, phone systems, multi-language conversational interfaces, and voice-first applications requiring tool integration and RAG.
Skip if: Text-only chatbots without voice, simple FAQ bots without tools, real-time transcription services, audio processing without conversation logic.
When should I use this skill?
User mentions ElevenLabs, building a voice agent, AI phone system, AI receptionist, conversational AI, or troubleshooting @11labs packages, webhook errors, CSP violations, localhost allowlist, or tool parsing errors.
What you get
Deployed voice agent handling customer interactions with tool calls, knowledge base lookups, multi-turn conversations, and post-call analysis via webhooks.
- Configured agent (via dashboard or CLI)
- System prompt with personality/tone/guardrails
- Tool definitions (client-side handlers or webhook specs)
By the numbers
- 5000+ voices available for selection or cloning
- 6-component system prompt framework (personality, environment, tone, goal, guardrails, tools)
- Up to 90% cost savings with LLM caching
Files
ElevenLabs Agent Builder
Build a production-ready conversational AI voice agent. Produces a configured agent with tools, knowledge base, and SDK integration.
Packages
npm install @elevenlabs/react # React SDK
npm install @elevenlabs/client # JavaScript SDK (browser + server)
npm install @elevenlabs/react-native # React Native SDK
npm install @elevenlabs/elevenlabs-js # Full API (server only)
npm install -g @elevenlabs/agents-cli # CLI ("Agents as Code")DEPRECATED: @11labs/react, @11labs/client -- uninstall if present.
Server-only warning: @elevenlabs/elevenlabs-js uses Node.js child_process and won't work in browsers. Use @elevenlabs/client for browser environments, or create a proxy server.
Workflow
Step 1: Create Agent via Dashboard or CLI
Dashboard: https://elevenlabs.io/app/conversational-ai -> Create Agent
CLI (Agents as Code):
elevenlabs agents init
elevenlabs agents add "Support Bot" --template customer-service
# Edit agent_configs/support-bot.json
elevenlabs agents push --env devTemplates: default, minimal, voice-only, text-only, customer-service, assistant.
Configure:
- Voice -- Choose from 5000+ voices or clone
- LLM -- GPT, Claude, Gemini, or custom
- System prompt -- Use the 6-component framework below
- First message -- What the agent says when conversation starts
Step 2: Write the System Prompt
Use the 6-component framework for effective agent prompts:
1. Personality -- who the agent is:
You are [NAME], a [ROLE] at [COMPANY].
You have [EXPERIENCE]. Your traits: [LIST TRAITS].2. Environment -- communication context:
You're communicating via [phone/chat/video].
Consider [environmental factors]. Adapt to [context].3. Tone -- speech patterns and formality:
Tone: Professional yet warm. Use contractions for natural speech.
Avoid jargon. Keep responses to 2-3 sentences. Ask one question at a time.4. Goal -- objectives and success criteria:
Primary Goal: Resolve customer issues on the first call.
Success: Customer verbally confirms issue is resolved.5. Guardrails -- boundaries and ethics:
Never: provide medical/legal/financial advice, share confidential info.
Always: verify identity before account access, document interactions.
Escalation: customer requests manager, issue beyond knowledge base.6. Tools -- available functions and when to use them:
1. lookup_order(order_id) -- Use when customer mentions an order.
2. transfer_to_supervisor() -- Use when issue requires manager approval.
Always explain what you're doing before calling a tool.Step 3: Add Tools
Client-side tools (run in browser):
const clientTools = {
updateCart: {
description: "Add or remove items from the shopping cart",
parameters: z.object({
action: z.enum(['add', 'remove']),
item: z.string(),
quantity: z.number().min(1)
}),
handler: async ({ action, item, quantity }) => {
const cart = getCart();
action === 'add' ? cart.add(item, quantity) : cart.remove(item, quantity);
return { success: true, total: cart.total, items: cart.items.length };
}
},
navigate: {
description: "Navigate user to a different page",
parameters: z.object({ url: z.string().url() }),
handler: async ({ url }) => { window.location.href = url; return { success: true }; }
}
};Server-side tools (webhooks):
{
"name": "get_weather",
"description": "Fetch current weather for a city",
"url": "https://api.weather.com/v1/current",
"method": "GET",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "City name" }
},
"required": ["city"]
},
"headers": {
"Authorization": "Bearer {{secret__weather_api_key}}"
}
}Use {{secret__key_name}} for API keys in webhook headers -- never hardcode.
MCP Tools -- CRITICAL COMPATIBILITY NOTE:
ElevenLabs labels their MCP integration as "Streamable HTTP" but does NOT support the actual MCP 2025-03-26 Streamable HTTP spec (SSE responses). ElevenLabs expects:
- Plain JSON responses (
application/json), NOT SSE (text/event-stream) - Protocol version
2024-11-05, NOT2025-03-26 - Simple JSON-RPC over HTTP with direct JSON responses
What does NOT work:
- Official MCP SDK's
createMcpHandler(returns SSE) - Cloudflare Agents SDK
McpServer.serve()(returns SSE) - Any server returning
Content-Type: text/event-stream
Working MCP server pattern for ElevenLabs:
import { Hono } from 'hono';
import { cors } from 'hono/cors';
const tools = [{
name: "my_tool",
description: "Tool description",
inputSchema: {
type: "object",
properties: { param1: { type: "string", description: "Description" } },
required: ["param1"]
}
}];
async function handleMCPRequest(request, env) {
const { id, method, params } = request;
switch (method) {
case 'initialize':
return {
jsonrpc: '2.0', id,
result: {
protocolVersion: '2024-11-05', // MUST be 2024-11-05
serverInfo: { name: 'my-mcp', version: '1.0.0' },
capabilities: { tools: {} }
}
};
case 'tools/list':
return { jsonrpc: '2.0', id, result: { tools } };
case 'tools/call':
const result = await handleTool(params.name, params.arguments, env);
return { jsonrpc: '2.0', id, result };
default:
return { jsonrpc: '2.0', id, error: { code: -32601, message: `Unknown: ${method}` } };
}
}
const app = new Hono();
app.use('/*', cors({ origin: '*', allowMethods: ['GET', 'POST', 'OPTIONS'] }));
app.post('/mcp', async (c) => {
const body = await c.req.json();
return c.json(await handleMCPRequest(body, c.env)); // Plain JSON, NOT SSE
});
export default app;Step 4: Add Knowledge Base (RAG)
Upload documents for the agent to reference:
- PDFs, text files, web URLs
- Configure via dashboard: Agent -> Knowledge Base -> Upload
- Or via API:
POST /v1/convai/knowledge-base/upload(multipart/form-data) - Agent automatically searches knowledge base during conversation
Step 5: Integrate SDK
React -- copy and customise assets/react-sdk-boilerplate.tsx:
import { useConversation } from '@elevenlabs/react';
const { startConversation, stopConversation, status } = useConversation({
agentId: 'your-agent-id',
signedUrl: '/api/elevenlabs/auth',
clientTools,
dynamicVariables: {
user_name: 'John',
account_type: 'premium',
},
onEvent: (event) => { /* transcript, agent_response, tool_call */ },
});System prompt references dynamic variables as {{user_name}}.
React Native -- see assets/react-native-boilerplate.tsx Widget embed -- see assets/widget-embed-template.html Swift -- see assets/swift-sdk-boilerplate.swift
Step 6: Test
CLI testing:
# Run all tests for an agent
elevenlabs agents test "Support Agent"
# Add a test scenario
elevenlabs tests add "Refund Request" --template basic-llmTest configuration:
{
"name": "Refund Request Test",
"scenario": "Customer requests refund for defective product",
"user_input": "I want a refund for order #12345. The product arrived broken.",
"success_criteria": [
"Agent acknowledges the issue empathetically",
"Agent asks for or uses provided order number",
"Agent verifies order details",
"Agent provides clear next steps or refund timeline"
],
"evaluation_type": "llm"
}Tool call testing:
{
"name": "Order Lookup Test",
"scenario": "Customer asks about order status",
"user_input": "What's the status of order ORD-12345?",
"expected_tool_call": {
"tool_name": "lookup_order",
"parameters": { "order_id": "ORD-12345" }
}
}API simulation:
const simulation = await client.agents.simulate({
agent_id: 'agent_123',
scenario: 'Customer requests refund',
user_messages: [
"I want a refund for order #12345",
"It arrived broken",
"Yes, process the refund"
],
success_criteria: [
"Agent shows empathy",
"Agent verifies order",
"Agent provides timeline"
]
});
console.log('Passed:', simulation.passed);CI/CD integration:
name: Test Agent
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm install -g @elevenlabs/cli
- run: elevenlabs tests push
env:
ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY }}
- run: elevenlabs agents test "Support Agent"
env:
ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY }}Step 7: Deploy
# Dry run first (always)
elevenlabs agents push --env prod --dry-run
# Deploy to production
elevenlabs agents push --env prodMulti-environment workflow:
elevenlabs agents push --env dev # Development
elevenlabs agents push --env staging # Staging
elevenlabs agents test "Agent Name" # Test in staging
elevenlabs agents push --env prod # Production---
Critical Patterns
Signed URLs (Security)
Never expose API keys in client code. Use a server endpoint:
app.get('/api/elevenlabs/auth', async (req, res) => {
const response = await fetch(
'https://api.elevenlabs.io/v1/convai/conversation/get-signed-url',
{
headers: { 'xi-api-key': process.env.ELEVENLABS_API_KEY },
body: JSON.stringify({ agent_id: 'your-agent-id' }),
method: 'POST'
}
);
const { signed_url } = await response.json();
res.json({ signed_url });
});Agent Versioning (A/B Testing)
Dashboard: Agent -> Versions -> Create Branch. Compare metrics, promote winner.
Post-Call Webhook
{
"type": "post_call_transcription",
"data": {
"conversation_id": "conv_xyz789",
"transcript": "...",
"duration_seconds": 120,
"analysis": { "sentiment": "positive", "resolution": true }
}
}Verify with HMAC SHA-256:
const hmac = crypto.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(JSON.stringify(request.body)).digest('hex');
if (signature !== hmac) { /* reject */ }---
Cost Optimisation
Model lineups and pricing rot fast — check the live list in the ElevenLabs dashboard (Agent → LLM dropdown) or docs before picking, and don't hardcode a model id you haven't verified this session. The durable picks: a current cheap-fast model for most agents (upgrade only where quality demands it), a long-context model when the knowledge base is large.
Key savings:
- LLM caching: up to 90% on repeated prompts (enable in config)
- Prompt length: 150 tokens > 500 tokens for same instructions
- RAG over context: use knowledge base instead of stuffing system prompt
- Duration limits: set
max_duration_secondsto prevent runaway conversations - Turn mode: "patient" mode = fewer LLM calls = lower cost
---
CLI Quick Reference
elevenlabs auth login # Authenticate
elevenlabs agents init # Init project
elevenlabs agents add "Name" --template default # Add agent
elevenlabs agents push --env dev # Deploy to dev
elevenlabs agents push --env prod --dry-run # Preview prod deploy
elevenlabs agents push --env prod # Deploy to prod
elevenlabs agents pull # Pull from platform
elevenlabs agents test "Name" # Run tests
elevenlabs agents list # List agents
elevenlabs agents status # Check sync status
elevenlabs agents widget "Name" # Generate widget
elevenlabs tools add-webhook "Name" --config-path tool.json # Add tool
elevenlabs tests add "Name" --template basic-llm # Add testEnvironment: ELEVENLABS_API_KEY for CI/CD.
---
Optional References
For specialised use cases, see:
references/api-reference.md-- full REST API for programmatic agent managementreferences/compliance-guide.md-- GDPR, HIPAA, PCI DSS, data residencyreferences/workflow-examples.md-- multi-agent routing, escalation, multi-language
---
Asset Files
assets/react-sdk-boilerplate.tsx-- React integration templateassets/react-native-boilerplate.tsx-- React Native templateassets/swift-sdk-boilerplate.swift-- Swift/iOS templateassets/javascript-sdk-boilerplate.js-- Vanilla JS templateassets/widget-embed-template.html-- Embeddable widgetassets/system-prompt-template.md-- System prompt guideassets/agent-config-schema.json-- Config schema referenceassets/ci-cd-example.yml-- CI/CD pipeline template
{
"name": "Support Agent",
"conversation_config": {
"agent": {
"prompt": {
"prompt": "You are a helpful customer support agent...",
"llm": "gpt-4o-mini",
"temperature": 0.7,
"max_tokens": 500,
"tool_ids": ["tool_123"],
"knowledge_base": ["doc_456"],
"custom_llm": {
"endpoint": "https://api.openai.com/v1/chat/completions",
"api_key": "{{secret__openai_api_key}}",
"model": "gpt-4"
}
},
"first_message": "Hello! How can I help you today?",
"language": "en"
},
"tts": {
"model_id": "eleven_turbo_v2_5",
"voice_id": "your_voice_id",
"stability": 0.5,
"similarity_boost": 0.75,
"speed": 1.0,
"output_format": "pcm_22050"
},
"asr": {
"quality": "high",
"provider": "deepgram",
"keywords": ["product_name", "company_name"]
},
"turn": {
"mode": "normal",
"turn_timeout": 5000
},
"conversation": {
"max_duration_seconds": 600
},
"language_presets": [
{
"language": "en",
"voice_id": "en_voice_id",
"first_message": "Hello! How can I help you?"
},
{
"language": "es",
"voice_id": "es_voice_id",
"first_message": "¡Hola! ¿Cómo puedo ayudarte?"
}
]
},
"workflow": {
"nodes": [
{
"id": "node_1",
"type": "subagent",
"config": {
"system_prompt": "You are now handling technical support...",
"turn_eagerness": "patient",
"voice_id": "tech_voice_id"
}
},
{
"id": "node_2",
"type": "tool",
"tool_name": "transfer_to_human"
}
],
"edges": [
{
"from": "node_1",
"to": "node_2",
"condition": "user_requests_escalation"
}
]
},
"platform_settings": {
"widget": {
"theme": {
"primaryColor": "#3B82F6",
"backgroundColor": "#1F2937",
"textColor": "#F9FAFB"
},
"position": "bottom-right"
},
"authentication": {
"type": "signed_url",
"session_duration": 3600
},
"privacy": {
"transcripts": {
"retention_days": 730
},
"audio": {
"retention_days": 2190
},
"zero_retention": false
}
},
"webhooks": {
"post_call": {
"url": "https://api.example.com/webhook",
"headers": {
"Authorization": "Bearer {{secret__webhook_auth_token}}"
}
}
},
"tags": ["customer-support", "production"]
}
name: Deploy ElevenLabs Agent
on:
push:
branches: [main]
paths:
- 'agent_configs/**'
- 'tool_configs/**'
- 'test_configs/**'
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install ElevenLabs CLI
run: npm install -g @elevenlabs/cli
- name: Dry Run (Preview Changes)
run: elevenlabs agents push --env staging --dry-run
env:
ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY_STAGING }}
- name: Push to Staging
if: github.event_name == 'pull_request'
run: elevenlabs agents push --env staging
env:
ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY_STAGING }}
- name: Run Tests
if: github.event_name == 'pull_request'
run: |
elevenlabs tests push --env staging
elevenlabs agents test "Support Agent"
env:
ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY_STAGING }}
deploy:
runs-on: ubuntu-latest
needs: test
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install ElevenLabs CLI
run: npm install -g @elevenlabs/cli
- name: Deploy to Production
run: elevenlabs agents push --env prod
env:
ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY_PROD }}
- name: Verify Deployment
run: elevenlabs agents status
env:
ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY_PROD }}
- name: Notify on Success
if: success()
run: echo "✅ Agent deployed to production successfully"
- name: Notify on Failure
if: failure()
run: echo "❌ Deployment failed"
import { Conversation } from '@elevenlabs/client';
// Configuration
const AGENT_ID = 'your-agent-id';
const API_KEY = process.env.ELEVENLABS_API_KEY; // Server-side only, never expose in browser
// Initialize conversation
const conversation = new Conversation({
agentId: AGENT_ID,
// Authentication (choose one)
// Option 1: API key (for private agents)
apiKey: API_KEY,
// Option 2: Signed URL (most secure)
// signedUrl: 'https://api.elevenlabs.io/v1/convai/auth/...',
// Client tools (browser-side functions)
clientTools: {
updateCart: {
description: "Update shopping cart",
parameters: {
type: "object",
properties: {
item: { type: "string" },
quantity: { type: "number" }
},
required: ["item", "quantity"]
},
handler: async ({ item, quantity }) => {
console.log('Cart updated:', item, quantity);
// Your cart logic here
return { success: true };
}
}
},
// Event handlers
onConnect: () => {
console.log('Connected to agent');
updateStatus('connected');
clearTranscript();
},
onDisconnect: () => {
console.log('Disconnected from agent');
updateStatus('disconnected');
},
onEvent: (event) => {
switch (event.type) {
case 'transcript':
addToTranscript('user', event.data.text);
break;
case 'agent_response':
addToTranscript('agent', event.data.text);
break;
case 'tool_call':
console.log('Tool called:', event.data.tool_name);
break;
case 'error':
console.error('Agent error:', event.data);
showError(event.data.message);
break;
}
},
onError: (error) => {
console.error('Connection error:', error);
showError(error.message);
},
// Regional compliance
serverLocation: 'us' // 'us' | 'global' | 'eu-residency' | 'in-residency'
});
// UI Helpers
function updateStatus(status) {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.textContent = `Status: ${status}`;
}
}
function addToTranscript(role, text) {
const transcriptEl = document.getElementById('transcript');
if (transcriptEl) {
const messageEl = document.createElement('div');
messageEl.className = `message ${role}`;
messageEl.innerHTML = `
<strong>${role === 'user' ? 'You' : 'Agent'}:</strong>
<p>${text}</p>
`;
transcriptEl.appendChild(messageEl);
transcriptEl.scrollTop = transcriptEl.scrollHeight;
}
}
function clearTranscript() {
const transcriptEl = document.getElementById('transcript');
if (transcriptEl) {
transcriptEl.innerHTML = '';
}
}
function showError(message) {
const errorEl = document.getElementById('error');
if (errorEl) {
errorEl.textContent = `Error: ${message}`;
errorEl.style.display = 'block';
}
}
function hideError() {
const errorEl = document.getElementById('error');
if (errorEl) {
errorEl.style.display = 'none';
}
}
// Button event listeners
document.getElementById('start-btn')?.addEventListener('click', async () => {
try {
hideError();
await conversation.start();
} catch (error) {
console.error('Failed to start conversation:', error);
showError(error.message);
}
});
document.getElementById('stop-btn')?.addEventListener('click', async () => {
try {
await conversation.stop();
} catch (error) {
console.error('Failed to stop conversation:', error);
showError(error.message);
}
});
// HTML Template
/*
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ElevenLabs Voice Agent</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
}
button {
padding: 10px 20px;
margin: 5px;
cursor: pointer;
}
#status {
margin: 10px 0;
padding: 10px;
background: #f0f0f0;
border-radius: 4px;
}
#error {
display: none;
margin: 10px 0;
padding: 10px;
background: #ffebee;
color: #c62828;
border-radius: 4px;
}
#transcript {
margin-top: 20px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
max-height: 400px;
overflow-y: auto;
}
.message {
margin: 10px 0;
padding: 10px;
border-radius: 4px;
}
.message.user {
background: #e3f2fd;
}
.message.agent {
background: #f5f5f5;
}
</style>
</head>
<body>
<h1>ElevenLabs Voice Agent</h1>
<div>
<button id="start-btn">Start Conversation</button>
<button id="stop-btn">Stop</button>
</div>
<div id="status">Status: disconnected</div>
<div id="error"></div>
<div id="transcript"></div>
<script type="module" src="./app.js"></script>
</body>
</html>
*/
import { useConversation } from '@elevenlabs/react-native';
import { View, Button, Text, ScrollView } from 'react-native';
import { z } from 'zod';
import { useState } from 'react';
export default function VoiceAgent() {
const [transcript, setTranscript] = useState<Array<{ role: string; text: string }>>([]);
const { startConversation, stopConversation, status } = useConversation({
agentId: process.env.EXPO_PUBLIC_ELEVENLABS_AGENT_ID!,
// Use signed URL (most secure)
signedUrl: async () => {
const response = await fetch('https://your-api.com/elevenlabs/auth');
const { signedUrl } = await response.json();
return signedUrl;
},
clientTools: {
updateProfile: {
description: "Update user profile",
parameters: z.object({
name: z.string()
}),
handler: async ({ name }) => {
console.log('Updating profile:', name);
return { success: true };
}
}
},
onEvent: (event) => {
if (event.type === 'transcript') {
setTranscript(prev => [...prev, { role: 'user', text: event.data.text }]);
} else if (event.type === 'agent_response') {
setTranscript(prev => [...prev, { role: 'agent', text: event.data.text }]);
}
}
});
return (
<View style={{ padding: 20 }}>
<Text style={{ fontSize: 24, fontWeight: 'bold', marginBottom: 20 }}>Voice Agent</Text>
<View style={{ flexDirection: 'row', gap: 10, marginBottom: 20 }}>
<Button title="Start" onPress={startConversation} disabled={status === 'connected'} />
<Button title="Stop" onPress={stopConversation} disabled={status !== 'connected'} />
</View>
<Text>Status: {status}</Text>
<ScrollView style={{ marginTop: 20, maxHeight: 400 }}>
{transcript.map((msg, i) => (
<View key={i} style={{ padding: 10, marginBottom: 10, backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#f5f5f5' }}>
<Text style={{ fontWeight: 'bold' }}>{msg.role === 'user' ? 'You' : 'Agent'}</Text>
<Text>{msg.text}</Text>
</View>
))}
</ScrollView>
</View>
);
}
import { useConversation } from '@elevenlabs/react';
import { z } from 'zod';
import { useState } from 'react';
export default function VoiceAgent() {
const [transcript, setTranscript] = useState<Array<{ role: 'user' | 'agent'; text: string }>>([]);
const [error, setError] = useState<string | null>(null);
const {
startConversation,
stopConversation,
status,
isSpeaking
} = useConversation({
// Agent Configuration
agentId: process.env.NEXT_PUBLIC_ELEVENLABS_AGENT_ID!,
// Authentication (choose one)
// Option 1: API key (for private agents, less secure)
// apiKey: process.env.NEXT_PUBLIC_ELEVENLABS_API_KEY,
// Option 2: Signed URL (most secure, recommended for production)
signedUrl: async () => {
const response = await fetch('/api/elevenlabs/auth');
const { signedUrl } = await response.json();
return signedUrl;
},
// Client-side tools (browser functions)
clientTools: {
updateCart: {
description: "Update the shopping cart with items",
parameters: z.object({
item: z.string().describe("The item name"),
quantity: z.number().describe("Quantity to add"),
action: z.enum(['add', 'remove']).describe("Add or remove item")
}),
handler: async ({ item, quantity, action }) => {
console.log(`${action} ${quantity}x ${item}`);
// Your cart logic here
return { success: true, total: 99.99 };
}
},
navigate: {
description: "Navigate to a different page",
parameters: z.object({
url: z.string().url().describe("The URL to navigate to")
}),
handler: async ({ url }) => {
window.location.href = url;
return { success: true };
}
}
},
// Event handlers
onConnect: () => {
console.log('Connected to agent');
setTranscript([]);
setError(null);
},
onDisconnect: () => {
console.log('Disconnected from agent');
},
onEvent: (event) => {
switch (event.type) {
case 'transcript':
setTranscript(prev => [
...prev,
{ role: 'user', text: event.data.text }
]);
break;
case 'agent_response':
setTranscript(prev => [
...prev,
{ role: 'agent', text: event.data.text }
]);
break;
case 'tool_call':
console.log('Tool called:', event.data.tool_name, event.data.parameters);
break;
case 'error':
console.error('Agent error:', event.data);
setError(event.data.message);
break;
}
},
onError: (error) => {
console.error('Connection error:', error);
setError(error.message);
},
// Regional compliance (for GDPR)
serverLocation: 'us' // 'us' | 'global' | 'eu-residency' | 'in-residency'
});
return (
<div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
<h1 className="text-2xl font-bold mb-4">Voice Agent</h1>
{/* Controls */}
<div className="flex gap-2 mb-4">
<button
onClick={startConversation}
disabled={status === 'connected'}
className="px-4 py-2 bg-blue-500 text-white rounded disabled:bg-gray-300"
>
Start Conversation
</button>
<button
onClick={stopConversation}
disabled={status !== 'connected'}
className="px-4 py-2 bg-red-500 text-white rounded disabled:bg-gray-300"
>
Stop
</button>
</div>
{/* Status */}
<div className="mb-4 p-2 bg-gray-100 rounded">
<p>Status: <span className="font-semibold">{status}</span></p>
{isSpeaking && <p className="text-blue-600">Agent is speaking...</p>}
</div>
{/* Error */}
{error && (
<div className="mb-4 p-2 bg-red-100 border border-red-400 text-red-700 rounded">
Error: {error}
</div>
)}
{/* Transcript */}
<div className="flex-1 overflow-y-auto border rounded p-4 space-y-2">
<h2 className="font-semibold mb-2">Transcript</h2>
{transcript.length === 0 ? (
<p className="text-gray-500">No conversation yet. Click "Start Conversation" to begin.</p>
) : (
transcript.map((message, i) => (
<div
key={i}
className={`p-2 rounded ${
message.role === 'user'
? 'bg-blue-100 ml-8'
: 'bg-gray-100 mr-8'
}`}
>
<p className="text-xs font-semibold mb-1">
{message.role === 'user' ? 'You' : 'Agent'}
</p>
<p>{message.text}</p>
</div>
))
)}
</div>
</div>
);
}
{
"agent_id": "YOUR_AGENT_ID",
"scenario": "Book an appointment for tomorrow at 2pm",
"max_turns": 10,
"expected_outcomes": [
"Agent confirms the appointment time",
"Agent asks for the customer's name",
"Agent provides a confirmation number"
]
}
import SwiftUI
import ElevenLabs
struct VoiceAgentView: View {
@State private var isConnected = false
@State private var transcript: [(role: String, text: String)] = []
private let agentID = "your-agent-id"
private let apiKey = "your-api-key" // Use environment variable in production
var body: some View {
VStack {
Text("Voice Agent")
.font(.largeTitle)
.padding()
HStack {
Button("Start Conversation") {
startConversation()
}
.disabled(isConnected)
Button("Stop") {
stopConversation()
}
.disabled(!isConnected)
}
.padding()
Text("Status: \(isConnected ? "Connected" : "Disconnected")")
.padding()
ScrollView {
ForEach(transcript.indices, id: \.self) { index in
let message = transcript[index]
HStack {
VStack(alignment: .leading) {
Text(message.role == "user" ? "You" : "Agent")
.font(.caption)
.fontWeight(.bold)
Text(message.text)
}
.padding()
.background(message.role == "user" ? Color.blue.opacity(0.1) : Color.gray.opacity(0.1))
.cornerRadius(8)
Spacer()
}
.padding(.horizontal)
}
}
}
}
private func startConversation() {
// Initialize ElevenLabs conversation
// Implementation would use the ElevenLabs Swift SDK
isConnected = true
}
private func stopConversation() {
isConnected = false
}
}
#Preview {
VoiceAgentView()
}
// Note: This is a placeholder. Full Swift SDK documentation available at:
// https://github.com/elevenlabs/elevenlabs-swift-sdk
System Prompt Template
Use this template to create structured, effective agent prompts.
---
Personality
You are [NAME], a [ROLE/PROFESSION] at [COMPANY].
You have [YEARS] years of experience [DOING WHAT].
Your key traits: [LIST 3-5 PERSONALITY TRAITS].Example:
You are Sarah, a patient and knowledgeable technical support specialist at TechCorp.
You have 7 years of experience helping customers troubleshoot software issues.
Your key traits: patient, empathetic, detail-oriented, solution-focused, friendly.---
Environment
You're communicating via [CHANNEL: phone/chat/video].
Context: [ENVIRONMENTAL FACTORS].
Communication style: [GUIDELINES].Example:
You're speaking with customers over the phone.
Context: Background noise and poor connections are common.
Communication style: Speak clearly, use short sentences, pause occasionally for emphasis.---
Tone
Formality: [PROFESSIONAL/CASUAL/FORMAL].
Language: [CONTRACTIONS/JARGON GUIDELINES].
Verbosity: [SENTENCE/RESPONSE LENGTH].
Emotional Expression: [HOW TO EXPRESS EMPATHY/ENTHUSIASM].Example:
Formality: Professional yet warm and approachable.
Language: Use contractions for natural conversation. Avoid jargon unless customer uses it first.
Verbosity: 2-3 sentences per response. Ask one question at a time.
Emotional Expression: Show empathy with phrases like "I understand how frustrating that must be."---
Goal
Primary Goal: [MAIN OBJECTIVE]
Secondary Goals:
- [SUPPORTING OBJECTIVE 1]
- [SUPPORTING OBJECTIVE 2]
- [SUPPORTING OBJECTIVE 3]
Success Criteria:
- [MEASURABLE OUTCOME 1]
- [MEASURABLE OUTCOME 2]Example:
Primary Goal: Resolve customer technical issues on the first call.
Secondary Goals:
- Verify customer identity securely
- Document issue details accurately
- Provide proactive tips to prevent future issues
Success Criteria:
- Customer verbally confirms issue is resolved
- Issue documented in CRM
- Customer satisfaction ≥ 4/5---
Guardrails
Never:
- [PROHIBITED ACTION 1]
- [PROHIBITED ACTION 2]
- [PROHIBITED ACTION 3]
Always:
- [REQUIRED ACTION 1]
- [REQUIRED ACTION 2]
Escalate When:
- [ESCALATION TRIGGER 1]
- [ESCALATION TRIGGER 2]Example:
Never:
- Provide medical, legal, or financial advice
- Share confidential company information
- Make promises about refunds without verification
- Continue if customer becomes abusive
Always:
- Verify customer identity before accessing account details
- Document all interactions
- Offer alternative solutions if first approach fails
Escalate When:
- Customer requests manager
- Issue requires account credit/refund approval
- Technical issue beyond knowledge base
- Customer exhibits abusive behavior---
Tools
Available Tools:
1. tool_name(param1, param2)
Purpose: [WHAT IT DOES]
Use When: [TRIGGER CONDITION]
Example: [SAMPLE USAGE]
2. ...
Guidelines:
- Always explain to customer before calling tool
- Wait for tool response before continuing
- If tool fails, offer alternativeExample:
Available Tools:
1. lookup_order(order_id: string)
Purpose: Fetch order details from database
Use When: Customer mentions order number or asks about order status
Example: "Let me look that up for you. [Call lookup_order('ORD-12345')]"
2. send_password_reset(email: string)
Purpose: Trigger password reset email
Use When: Customer can't access account and identity verified
Example: "I'll send a password reset email. [Call send_password_reset('user@example.com')]"
3. transfer_to_supervisor()
Purpose: Escalate to human agent
Use When: Issue requires manager approval or customer explicitly requests
Example: "Let me connect you with a supervisor. [Call transfer_to_supervisor()]"
Guidelines:
- Always explain what you're doing before calling tool
- Wait for tool response before continuing conversation
- If tool fails, acknowledge and offer alternative solution---
Complete Prompt
Combine all sections into your final system prompt:
Personality:
You are [NAME], a [ROLE] at [COMPANY]. You have [EXPERIENCE]. Your traits: [TRAITS].
Environment:
You're communicating via [CHANNEL]. [CONTEXT]. [COMMUNICATION STYLE].
Tone:
[FORMALITY]. [LANGUAGE]. [VERBOSITY]. [EMOTIONAL EXPRESSION].
Goal:
Primary: [PRIMARY GOAL]
Secondary: [SECONDARY GOALS]
Success: [SUCCESS CRITERIA]
Guardrails:
Never: [PROHIBITIONS]
Always: [REQUIREMENTS]
Escalate: [TRIGGERS]
Tools:
[TOOL DESCRIPTIONS WITH EXAMPLES]---
Testing Your Prompt
1. Create test scenarios covering common use cases 2. Run conversations and analyze transcripts 3. Check for:
- Tone consistency
- Goal achievement
- Guardrail adherence
- Tool usage accuracy
4. Iterate based on findings 5. Monitor analytics dashboard for real performance
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ElevenLabs Voice Agent Widget</title>
</head>
<body>
<h1>Welcome to Our Support</h1>
<p>Need help? Click the voice assistant button in the bottom-right corner!</p>
<!-- ElevenLabs Widget -->
<script src="https://elevenlabs.io/convai-widget/index.js"></script>
<script>
ElevenLabsWidget.init({
// Required: Your agent ID
agentId: 'your-agent-id',
// Optional: Theming
theme: {
primaryColor: '#3B82F6', // Blue
backgroundColor: '#1F2937', // Dark gray
textColor: '#F9FAFB', // Light gray
accentColor: '#10B981' // Green
},
// Optional: Position
position: 'bottom-right', // or 'bottom-left'
// Optional: Custom branding
branding: {
logo: 'https://example.com/logo.png',
name: 'Support Assistant',
tagline: 'How can I help you today?'
},
// Optional: Customize button
button: {
size: 'medium', // 'small' | 'medium' | 'large'
icon: 'microphone', // 'microphone' | 'chat' | 'phone'
text: 'Talk to us' // Optional button label
},
// Optional: Auto-open widget
autoOpen: false,
autoOpenDelay: 3000, // milliseconds
// Optional: Welcome message
welcomeMessage: {
enabled: true,
message: "Hi! I'm here to help. Click to start a voice conversation."
},
// Optional: Callbacks
onOpen: () => {
console.log('Widget opened');
},
onClose: () => {
console.log('Widget closed');
},
onConversationStart: () => {
console.log('Conversation started');
},
onConversationEnd: () => {
console.log('Conversation ended');
}
});
</script>
<!-- Optional: Custom styling -->
<style>
/* Override widget styles if needed */
.elevenlabs-widget {
/* Custom styles */
}
</style>
</body>
</html>
ElevenLabs Agents API Reference
Base URL
https://api.elevenlabs.io/v1/convaiAuthentication
All requests require an API key in the header:
curl -H "xi-api-key: YOUR_API_KEY" https://api.elevenlabs.io/v1/convai/agents---
Agents
Create Agent
Endpoint: POST /agents/create
Request Body:
{
"name": "Support Agent",
"conversation_config": {
"agent": {
"prompt": {
"prompt": "You are a helpful support agent.",
"llm": "<verify current model id in dashboard>",
"temperature": 0.7,
"max_tokens": 500,
"tool_ids": ["tool_123"],
"knowledge_base": ["doc_456"]
},
"first_message": "Hello! How can I help?",
"language": "en"
},
"tts": {
"model_id": "eleven_turbo_v2_5",
"voice_id": "voice_abc123",
"stability": 0.5,
"similarity_boost": 0.75,
"speed": 1.0
},
"asr": {
"quality": "high",
"provider": "deepgram"
},
"turn": {
"mode": "normal"
}
}
}Response:
{
"agent_id": "agent_abc123",
"name": "Support Agent",
"created_at": "2025-11-03T12:00:00Z"
}Update Agent
Endpoint: PATCH /agents/:agent_id
Request Body: Same as Create Agent
Get Agent
Endpoint: GET /agents/:agent_id
Response:
{
"agent_id": "agent_abc123",
"name": "Support Agent",
"conversation_config": { ... },
"created_at": "2025-11-03T12:00:00Z",
"updated_at": "2025-11-03T14:00:00Z"
}List Agents
Endpoint: GET /agents
Response:
{
"agents": [
{
"agent_id": "agent_abc123",
"name": "Support Agent",
"created_at": "2025-11-03T12:00:00Z"
}
]
}Delete Agent
Endpoint: DELETE /agents/:agent_id
Response:
{
"success": true
}---
Conversations
Create Conversation
Endpoint: POST /conversations/create
Request Body:
{
"agent_id": "agent_abc123",
"dynamic_variables": {
"user_name": "John",
"account_tier": "premium"
},
"overrides": {
"agent": {
"prompt": {
"prompt": "Custom prompt override"
}
}
}
}Response:
{
"conversation_id": "conv_xyz789",
"signed_url": "wss://api.elevenlabs.io/v1/convai/...",
"created_at": "2025-11-03T12:00:00Z"
}Get Conversation
Endpoint: GET /conversations/:conversation_id
Response:
{
"conversation_id": "conv_xyz789",
"agent_id": "agent_abc123",
"transcript": "...",
"duration_seconds": 120,
"status": "completed",
"created_at": "2025-11-03T12:00:00Z",
"ended_at": "2025-11-03T12:02:00Z"
}---
Knowledge Base
Upload Document
Endpoint: POST /knowledge-base/upload
Request Body (multipart/form-data):
file: <binary>
name: "Support Documentation"Response:
{
"document_id": "doc_456",
"name": "Support Documentation",
"status": "processing"
}Compute RAG Index
Endpoint: POST /knowledge-base/:document_id/rag-index
Request Body:
{
"embedding_model": "e5_mistral_7b"
}Response:
{
"document_id": "doc_456",
"status": "computing"
}Get RAG Index Status
Endpoint: GET /knowledge-base/:document_id/rag-index
Response:
{
"document_id": "doc_456",
"status": "ready",
"embedding_model": "e5_mistral_7b",
"created_at": "2025-11-03T12:00:00Z"
}---
Tools
Create Webhook Tool
Endpoint: POST /tools/webhook
Request Body:
{
"name": "get_weather",
"description": "Fetch current weather for a city",
"url": "https://api.weather.com/v1/current",
"method": "GET",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
}
},
"required": ["city"]
},
"headers": {
"Authorization": "Bearer {{secret__weather_api_key}}"
}
}Response:
{
"tool_id": "tool_123",
"name": "get_weather",
"created_at": "2025-11-03T12:00:00Z"
}---
Testing
Simulate Conversation
Endpoint: POST /agents/:agent_id/simulate
Request Body:
{
"scenario": "Customer requests refund",
"user_messages": [
"I want a refund for order #12345",
"I ordered it last week"
],
"success_criteria": [
"Agent acknowledges request",
"Agent provides timeline"
]
}Response:
{
"simulation_id": "sim_123",
"passed": true,
"transcript": "...",
"evaluation": {
"criteria_met": 2,
"criteria_total": 2,
"details": [
{
"criterion": "Agent acknowledges request",
"passed": true
},
{
"criterion": "Agent provides timeline",
"passed": true
}
]
}
}---
Error Codes
| Code | Meaning | Solution |
|---|---|---|
| 400 | Bad Request | Check request body format |
| 401 | Unauthorized | Verify API key is correct |
| 403 | Forbidden | Check agent visibility settings |
| 404 | Not Found | Verify resource ID exists |
| 429 | Rate Limited | Implement backoff strategy |
| 500 | Server Error | Retry with exponential backoff |
---
Rate Limits
- Standard Tier: 100 requests/minute
- Pro Tier: 500 requests/minute
- Enterprise Tier: Custom limits
Rate Limit Headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1730640000---
Pagination
Query Parameters:
?page=1&per_page=50Response Headers:
X-Total-Count: 250
X-Page: 1
X-Per-Page: 50---
Webhook Events
Post-Call Webhook
Event Type: post_call_transcription
Payload:
{
"type": "post_call_transcription",
"data": {
"conversation_id": "conv_xyz789",
"agent_id": "agent_abc123",
"transcript": "...",
"duration_seconds": 120,
"analysis": {
"sentiment": "positive",
"resolution": true,
"extracted_data": {}
}
},
"event_timestamp": "2025-11-03T12:02:00Z"
}Verification (HMAC SHA-256):
import crypto from 'crypto';
const signature = request.headers['elevenlabs-signature'];
const payload = JSON.stringify(request.body);
const hmac = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(payload)
.digest('hex');
if (signature !== hmac) {
// Invalid signature
}---
SDK vs API
| Feature | SDK | API |
|---|---|---|
| WebSocket Connection | ✅ | ❌ |
| Client Tools | ✅ | ❌ |
| Real-time Events | ✅ | ❌ |
| Agent Management | ❌ | ✅ |
| Tool Management | ❌ | ✅ |
| Knowledge Base | ❌ | ✅ |
Recommendation: Use SDK for conversations, API for agent management.
Privacy & Compliance Guide
GDPR Compliance
Data Retention
Default: 2 years (730 days)
{
"privacy": {
"transcripts": {
"retention_days": 730
},
"audio": {
"retention_days": 730
}
}
}Right to Be Forgotten
Enable data deletion requests:
await client.conversations.delete(conversation_id);Data Residency
const { startConversation } = useConversation({
serverLocation: 'eu-residency' // GDPR-compliant EU data centers
});User Consent
Inform users before recording:
{
"first_message": "This call will be recorded for quality and training purposes. Do you consent?"
}---
HIPAA Compliance
Data Retention
Minimum: 6 years (2190 days)
{
"privacy": {
"transcripts": {
"retention_days": 2190
},
"audio": {
"retention_days": 2190
}
}
}Encryption
- In Transit: TLS 1.3 (automatic)
- At Rest: AES-256 (automatic)
Business Associate Agreement (BAA)
Contact ElevenLabs for HIPAA BAA.
PHI Handling
Never:
- Store PHI in dynamic variables
- Log PHI in tool parameters
- Send PHI to third-party tools without BAA
Always:
- Use secure authentication
- Verify patient identity
- Document access logs
---
SOC 2 Compliance
Security Controls
✅ Encryption in transit and at rest (automatic) ✅ Access controls (API key management) ✅ Audit logs (conversation history) ✅ Incident response (automatic backups)
Best Practices
{
"authentication": {
"type": "signed_url", // Most secure
"session_duration": 3600 // 1 hour max
}
}---
Regional Compliance
US Residency
serverLocation: 'us'EU Residency (GDPR)
serverLocation: 'eu-residency'India Residency
serverLocation: 'in-residency'---
Zero Retention Mode
Maximum Privacy: Immediately delete all data after conversation ends.
{
"privacy": {
"zero_retention": true
}
}Limitations:
- No conversation history
- No analytics
- No post-call webhooks
- No MCP tool integrations
---
PCI DSS (Payment Card Industry)
Never:
❌ Store credit card numbers in conversation logs ❌ Send credit card data to LLM ❌ Log CVV or PIN numbers
Always:
✅ Use PCI-compliant payment processors (Stripe, PayPal) ✅ Tokenize payment data ✅ Use DTMF keypad for card entry (telephony)
Example: Secure Payment Collection
{
"system_tools": [
{
"name": "dtmf_playpad",
"description": "Display keypad for secure card entry"
}
]
}---
Compliance Checklist
GDPR
- [ ] Data retention ≤ 2 years (or justify longer)
- [ ] EU data residency enabled
- [ ] User consent obtained before recording
- [ ] Data deletion process implemented
- [ ] Privacy policy updated
HIPAA
- [ ] Data retention ≥ 6 years
- [ ] BAA signed with ElevenLabs
- [ ] Encryption enabled (automatic)
- [ ] Access logs maintained
- [ ] Staff trained on PHI handling
SOC 2
- [ ] API key security (never expose in client)
- [ ] Use signed URLs for authentication
- [ ] Monitor access logs
- [ ] Incident response plan documented
PCI DSS
- [ ] Never log card data
- [ ] Use tokenization for payments
- [ ] DTMF keypad for card entry
- [ ] PCI-compliant payment processor
---
Monitoring & Auditing
Access Logs
const logs = await client.conversations.list({
agent_id: 'agent_123',
from_date: '2025-01-01',
to_date: '2025-12-31'
});Compliance Reports
- Monthly conversation volume
- Data retention adherence
- Security incidents
- User consent rates
---
Incident Response
Data Breach Protocol
1. Identify affected conversations 2. Notify ElevenLabs immediately 3. Delete compromised data 4. Notify affected users (GDPR requirement) 5. Document incident 6. Review security controls
Contact
security@elevenlabs.io
Workflow Examples
Customer Support Routing
Scenario: Route calls to specialized agents based on customer needs.
{
"workflow": {
"nodes": [
{
"id": "initial_routing",
"type": "subagent",
"config": {
"system_prompt": "Ask customer: Are you calling about billing, technical support, or sales?",
"turn_eagerness": "patient"
}
},
{
"id": "billing_agent",
"type": "subagent",
"config": {
"system_prompt": "You are a billing specialist. Help with invoices, payments, and account charges.",
"voice_id": "billing_voice_id"
}
},
{
"id": "technical_agent",
"type": "subagent",
"config": {
"system_prompt": "You are a technical support specialist. Troubleshoot product issues.",
"voice_id": "tech_voice_id"
}
},
{
"id": "sales_agent",
"type": "subagent",
"config": {
"system_prompt": "You are a sales representative. Help customers choose products.",
"voice_id": "sales_voice_id"
}
}
],
"edges": [
{ "from": "initial_routing", "to": "billing_agent", "condition": "user_mentions_billing" },
{ "from": "initial_routing", "to": "technical_agent", "condition": "user_mentions_technical" },
{ "from": "initial_routing", "to": "sales_agent", "condition": "user_mentions_sales" }
]
}
}Escalation Workflow
Scenario: Attempt self-service resolution, then escalate to human if needed.
{
"workflow": {
"nodes": [
{
"id": "self_service",
"type": "subagent",
"config": {
"system_prompt": "Try to resolve issue using knowledge base and tools. If issue can't be resolved, offer human transfer.",
"knowledge_base": ["faq_doc_id"],
"tool_ids": ["lookup_order", "check_status"]
}
},
{
"id": "human_transfer",
"type": "tool",
"tool_name": "transfer_to_human"
}
],
"edges": [
{ "from": "self_service", "to": "human_transfer", "condition": "user_requests_human_or_issue_unresolved" }
]
}
}Multi-Language Support
Scenario: Detect language and route to appropriate voice/agent.
{
"workflow": {
"nodes": [
{
"id": "language_detection",
"type": "subagent",
"config": {
"system_prompt": "Greet customer and detect language.",
"language": "auto"
}
},
{
"id": "english_agent",
"type": "subagent",
"config": {
"language": "en",
"voice_id": "en_voice_id",
"first_message": "Hello! How can I help you today?"
}
},
{
"id": "spanish_agent",
"type": "subagent",
"config": {
"language": "es",
"voice_id": "es_voice_id",
"first_message": "¡Hola! ¿Cómo puedo ayudarte hoy?"
}
}
],
"edges": [
{ "from": "language_detection", "to": "english_agent", "condition": "detected_language_en" },
{ "from": "language_detection", "to": "spanish_agent", "condition": "detected_language_es" }
]
}
}Best Practices
1. Keep workflows simple - Max 5-7 nodes for maintainability 2. Test all paths - Ensure every edge condition works 3. Add fallbacks - Always have a default path 4. Monitor transitions - Track which paths users take most 5. Avoid loops - Workflows can get stuck in infinite loops
Related skills
How it compares
Use when you need ElevenLabs voice plus LLM agent JSON scaffolding rather than generic chatbot prompt writing alone.
FAQ
What packages should I use for ElevenLabs agent integration?
@elevenlabs/react for React apps, @elevenlabs/react-native for mobile, @elevenlabs/client for browser/server JavaScript, @elevenlabs/elevenlabs-js for server-only (uses Node.js child_process). Avoid deprecated @11labs/* packages.
How do I secure API keys for webhook tools and signed URLs?
Use {{secret__key_name}} placeholders in webhook headers (never hardcode). For signed URLs, implement a server endpoint that calls POST /v1/convai/conversation/get-signed-url with your API key and returns the signed_url to the client.
Why doesn't my MCP tool work with ElevenLabs agents?
ElevenLabs uses protocol 2024-11-05 and expects plain JSON responses, NOT SSE (text/event-stream). Avoid createMcpHandler or McpServer.serve(). Use a custom JSON-RPC handler returning application/json with tools/call method.
Is Elevenlabs Agents safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.