mcpField
E
elevenlabs-agents

elevenlabs-agents

github.com/jackspaceAgent 工作流1641 次安装12 周前更新
代码仓库

关于 elevenlabs-agents

ElevenLabs Agents Platform 面向构建生产级语音对话 Agent 的开发者,协调语音识别、LLM、语音合成和对话轮次控制。平台提供可视化工作流、SDK、CLI、测试与分析功能,并支持接入 MCP 服务。

主要功能

  1. 01协调语音识别、LLM 与语音合成
  2. 02配置可视化分支对话工作流
  3. 03通过 SDK 和 CLI 创建与管理 Agent
  4. 04使用动态变量实现个性化对话
  5. 05运行自动测试并分析对话

适用场景

  1. 01构建语音客服 Agent
  2. 02为网站或移动应用添加语音聊天
  3. 03通过 CLI 管理版本化的 Agent 配置
  4. 04为 Agent 接入 MCP 服务

MCP 相关

支持将 MCP 服务集成到语音 Agent。README 未说明其 MCP 客户端连接或管理方式。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jackspace/claudeskillz --skill elevenlabs-agents

安装后在 Claude Code 中输入/elevenlabs-agents确认已加载。

附带文件README.mdSKILL.json

详细介绍

ElevenLabs Agents Platform

概述

ElevenLabs Agents Platform 是用于构建可投入生产的对话式 AI 语音 Agent 的全面解决方案。该平台协调四个核心组件:

  1. ASR(自动语音识别) - 将语音转换为文本(支持 32+ 种语言,延迟低于 1 秒)
  2. LLM(大语言模型) - 推理和生成回复(GPT、Claude、Gemini、自定义模型)
  3. TTS(文本转语音) - 将文本转换为语音(5000+ 种声音,31 种语言,低延迟)
  4. 轮次交替模型 - 用于处理对话时机和打断的专有模型
🚨 软件包更新(2025 年 11 月)

ElevenLabs 于 2025 年 8 月迁移到了新的带作用域软件包:

已弃用(请勿使用):

  • @11labs/react → 已弃用
  • @11labs/client → 已弃用

当前软件包:

npm install @elevenlabs/[email protected]        # React SDK
npm install @elevenlabs/[email protected]       # JavaScript SDK
npm install @elevenlabs/[email protected] # React Native SDK
npm install @elevenlabs/[email protected] # Base SDK
npm install -g @elevenlabs/[email protected]  # CLI

如果已安装旧版软件包,请先卸载:

npm uninstall @11labs/react @11labs/client
何时使用此技能

在以下情况下使用此技能:

  • 构建支持语音的客户支持 Agent
  • 创建交互式语音应答(IVR)系统
  • 开发对话式 AI 应用
  • 集成电话服务(Twilio、SIP 中继)
  • 在 Web/移动应用中实现语音聊天
  • 通过 CLI 配置 Agent(“Agent 即代码”)
  • 为 Agent 设置 RAG/知识库
  • 集成 MCP(Model Context Protocol)服务
  • 构建符合 HIPAA/GDPR 的语音系统
  • 通过缓存策略优化 LLM 成本
平台功能

设计和配置:

  • 使用可视化构建器创建多步骤工作流
  • 系统提示词工程(6 组件框架)
  • 5000+ 种声音,支持 31 种语言
  • 发音词典(IPA/CMU 格式)
  • 语速控制(0.7x-1.2x)
  • RAG 驱动的知识库
  • 动态变量和个性化

连接和部署:

  • React SDK(@elevenlabs/react)
  • JavaScript SDK(@elevenlabs/client)
  • React Native SDK(@elevenlabs/react-native)
  • Swift SDK(iOS/macOS)
  • 可嵌入小组件
  • 电话服务集成(Twilio、SIP)
  • Scribe(实时语音转文本)- Beta 版

运行和优化:

  • 自动化测试(场景、工具调用、负载)
  • 对话分析和评估
  • 分析仪表板(解决率、情绪、合规性)
  • 隐私控制(GDPR、HIPAA、SOC 2)
  • 成本优化(LLM 缓存、模型切换、突发定价)
  • 用于“Agent 即代码”工作流的 CLI

1. 快速入门(3 种集成路径)

路径 A:React SDK(嵌入式语音聊天)

用于在 React 应用中构建语音聊天界面。

安装:

npm install @elevenlabs/react zod

基本示例:

import { useConversation } from '@elevenlabs/react';
import { z } from 'zod';

export default function VoiceChat() {
  const { startConversation, stopConversation, status } = useConversation({
    // Public agent (no API key needed)
    agentId: 'your-agent-id',

    // OR private agent (requires API key)
    apiKey: process.env.NEXT_PUBLIC_ELEVENLABS_API_KEY,

    // OR signed URL (server-generated, most secure)
    signedUrl: '/api/elevenlabs/auth',

    // Client-side tools (browser functions)
    clientTools: {
      updateCart: {
        description: "Update the shopping cart",
        parameters: z.object({
          item: z.string(),
          quantity: z.number()
        }),
        handler: async ({ item, quantity }) => {
          console.log('Updating cart:', item, quantity);
          return { success: true };
        }
      }
    },

    // Event handlers
    onConnect: () => console.log('Connected'),
    onDisconnect: () => console.log('Disconnected'),
    onEvent: (event) => {
      switch (event.type) {
        case 'transcript':
          console.log('User said:', event.data.text);
          break;
        case 'agent_response':
          console.log('Agent replied:', event.data.text);
          break;
      }
    },

    // Regional compliance (GDPR, data residency)
    serverLocation: 'us' // 'us' | 'global' | 'eu-residency' | 'in-residency'
  });

  return (
    <div>
      <button onClick={startConversation}>Start Conversation</button>
      <button onClick={stopConversation}>Stop</button>
      <p>Status: {status}</p>
    </div>
  );
}
路径 B:CLI(“Agent 即代码”)

用于通过代码管理 Agent,并使用版本控制和 CI/CD。

安装:

npm install -g @elevenlabs/agents-cli
# or
pnpm install -g @elevenlabs/agents-cli

工作流:

# 1. Authenticate
elevenlabs auth login

# 2. Initialize project (creates agents.json, tools.json, tests.json)
elevenlabs agents init

# 3. Create agent from template
elevenlabs agents add "Support Agent" --template customer-service

# 4. Configure in agent_configs/support-agent.json

# 5. Push to platform
elevenlabs agents push --env dev

# 6. Test
elevenlabs agents test "Support Agent"

# 7. Deploy to production
elevenlabs agents push --env prod

创建的项目结构:

your_project/
├── agents.json              # Agent registry
├── tools.json               # Tool configurations
├── tests.json               # Test configurations
├── agent_configs/           # Individual agent files
├── tool_configs/            # Tool configuration files
└── test_configs/            # Test configuration files
路径 C:API(以编程方式管理 Agent)

用于动态创建 Agent(多租户、SaaS 平台)。

安装:

npm install elevenlabs

示例:

import { ElevenLabsClient } from 'elevenlabs';

const client = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY
});

// Create agent
const agent = await client.agents.create({
  name: 'Support Bot',
  conversation_config: {
    agent: {
      prompt: {
        prompt: "You are a helpful customer support agent.",
        llm: "gpt-4o",
        temperature: 0.7
      },
      first_message: "Hello! How can I help you today?",
      language: "en"
    },
    tts: {
      model_id: "eleven_turbo_v2_5",
      voice_id: "your-voice-id"
    }
  }
});

console.log('Agent created:', agent.agent_id);

2. Agent 配置

系统提示词架构(6 个组件)

ElevenLabs 建议使用 6 个组件来组织 Agent 提示词:

1. 个性

定义 Agent 的身份、角色和性格特征。

示例:

You are Alex, a friendly and knowledgeable customer support specialist at TechCorp.
You have 5 years of experience helping customers solve technical issues.
You're patient, empathetic, and always maintain a positive attitude.
2. 环境

描述沟通场景(电话、Web 聊天、视频通话)。

示例:

You're speaking with customers over the phone. Communication is voice-only.
Customers may have background noise or poor connection quality.
Speak clearly and occasionally use thoughtful pauses for emphasis.
3. 语气

指定正式程度、说话方式、幽默感和详略程度。

示例:

Tone: Professional yet warm. Use contractions ("I'm" instead of "I am") to sound natural.
Avoid jargon unless the customer uses it first. Keep responses concise (2-3 sentences max).
Use encouraging phrases like "I'll be happy to help with that" and "Let's get this sorted for you."
4. 目标

定义目标和成功标准。

示例:

Primary Goal: Resolve customer technical issues on the first call.
Secondary Goals:
- Verify customer identity securely
- Document issue details accurately
- Offer proactive solutions
- End calls with confirmation that the issue is resolved

Success Criteria: Customer verbally confirms their issue is resolved.
5. 护栏

设定边界、禁止讨论的话题和道德约束。

示例:

Guardrails:
- Never provide medical, legal, or financial advice
- Do not share confidential company information
- If asked about competitors, politely redirect to TechCorp's offerings
- Escalate to a human supervisor if customer becomes abusive
- Never make promises about refunds or credits without verification
6. 工具

描述可用的外部功能及其使用时机。

示例:

Available Tools:
1. lookup_order(order_id) - Fetch order details from database. Use when customer mentions an order number.
2. transfer_to_supervisor() - Escalate to human agent. Use when issue requires manager approval.
3. send_password_reset(email) - Trigger password reset email. Use when customer can't access account.

Always explain to the customer what you're doing before calling a tool.

完整模板:

{
  "agent": {
    "prompt": {
      "prompt": "Personality:\nYou are Alex, a friendly customer support specialist.\n\nEnvironment:\nYou're speaking with customers over the phone.\n\nTone:\nProfessional yet warm. Keep responses concise.\n\nGoal:\nResolve technical issues on the first call.\n\nGuardrails:\n- Never provide medical/legal/financial advice\n- Escalate abusive customers\n\nTools:\n- lookup_order(order_id) - Fetch order details\n- transfer_to_supervisor() - Escalate to human",
      "llm": "gpt-4o",
      "temperature": 0.7,
      "max_tokens": 500
    }
  }
}
轮流发言模式

控制 Agent 何时打断用户,或等待用户说完。

3 种模式:

模式行为适用场景
Eager快速回应,在最早的时机插话快节奏支持、快速下单
Normal保持平衡,在自然的对话间隙回应常规客户服务(默认)
Patient等待更久,允许用户详细作答信息收集、心理咨询、辅导

配置:

{
  "conversation_config": {
    "turn": {
      "mode": "patient" // "eager" | "normal" | "patient"
    }
  }
}

适用场景:

  • Eager:快餐点餐、快速常见问题解答、紧急通知
  • Normal:常规支持、产品咨询、预约
  • Patient:填写详细表单、情绪支持、教育辅导

注意事项:

  • Eager 模式可能让部分用户觉得被打断
  • 在快节奏场景中,Patient 模式可能显得缓慢
  • 可在工作流中动态调整,以适应不同情境
工作流(可视化构建器)

创建包含子 Agent 节点和条件路由的分支对话流程。

节点类型:

  1. 子 Agent 节点 - 覆盖基础 Agent 配置(更改提示词、语音、轮流发言设置)
  2. 工具节点 - 确保工具执行(不同于子 Agent 中的工具)

配置:

{
  "workflow": {
    "nodes": [
      {
        "id": "node_1",
        "type": "subagent",
        "config": {
          "system_prompt": "You are now a technical support specialist. Ask detailed diagnostic questions.",
          "turn_eagerness": "patient",
          "voice_id": "tech_support_voice_id"
        }
      },
      {
        "id": "node_2",
        "type": "tool",
        "tool_name": "transfer_to_human"
      }
    ],
    "edges": [
      {
        "from": "node_1",
        "to": "node_2",
        "condition": "user_requests_escalation"
      }
    ]
  }
}

适用场景:

  • 多部门路由(销售 → 支持 → 账单)
  • 决策树(“按 1 转销售,按 2 转支持”)
  • 角色扮演场景(客户与 Agent 的不同声音)
  • 升级处理路径(机器人 → 转接人工)

注意事项:

  • 工作流中的每次节点转换都会增加约 100–200 毫秒延迟
  • 工具节点可确保工具执行(子 Agent 可能会跳过工具)
  • 如果未正确测试,边可能会造成无限循环
动态变量与个性化

使用 {{var_name}} 语法,将运行时数据注入提示词、首条消息和工具参数。

系统变量(自动可用):

{{system__agent_id}}         // Current agent ID
{{system__conversation_id}}  // Conversation ID
{{system__caller_id}}        // Phone number (telephony only)
{{system__called_number}}    // Called number (telephony only)
{{system__call_duration_secs}} // Call duration
{{system__time_utc}}         // Current UTC time
{{system__call_sid}}         // Twilio call SID (Twilio only)

自定义变量:

// Provide when starting conversation
const conversation = await client.conversations.create({
  agent_id: "agent_123",
  dynamic_variables: {
    user_name: "John",
    account_tier: "premium",
    order_id: "ORD-12345"
  }
});

机密变量(用于 API 密钥):

{{secret__stripe_api_key}}
{{secret__database_password}}

重要提示:机密变量仅用于请求头,不会发送给大模型提供商。

在提示词中的用法:

{
  "agent": {
    "prompt": {
      "prompt": "You are helping {{user_name}}, a {{account_tier}} customer."
    },
    "first_message": "Hello {{user_name}}! I see you're calling about order {{order_id}}."
  }
}

注意:缺少变量会导致“Missing required dynamic variables”错误。启动对话时,务必提供所有引用的变量。

身份验证模式

选项 1:公开 Agent(无 API 密钥)

const { startConversation } = useConversation({
  agentId: 'your-public-agent-id' // Anyone can use
});

选项 2:使用 API 密钥的私有 Agent

const { startConversation } = useConversation({
  agentId: 'your-private-agent-id',
  apiKey: process.env.NEXT_PUBLIC_ELEVENLABS_API_KEY
});

⚠️ 警告:切勿在客户端代码中暴露 API 密钥。请改用签名 URL。

选项 3:签名 URL(生产环境推荐)

// Server-side (Next.js API route)
import { ElevenLabsClient } from 'elevenlabs';

export async function POST(req: Request) {
  const client = new ElevenLabsClient({
    apiKey: process.env.ELEVENLABS_API_KEY // Server-side only
  });

  const signedUrl = await client.convai.getSignedUrl({
    agent_id: 'your-agent-id'
  });

  return Response.json({ signedUrl });
}

// Client-side
const { startConversation } = useConversation({
  agentId: 'your-agent-id',
  signedUrl: await fetch('/api/elevenlabs/auth').then(r => r.json()).then(d => d.signedUrl)
});

3. 语音与语言功能

多语音支持

在单次对话中动态切换不同语音。

适用场景:

  • 多角色讲故事(每个角色使用不同语音)
  • 语言辅导(每种语言使用母语者的语音)
  • 角色扮演场景(客户与 Agent)
  • 情绪化 Agent(根据不同情绪使用不同语音)

配置:

{
  "agent": {
    "prompt": {
      "prompt": "When speaking as the customer, use voice_id 'customer_voice_abc123'. When speaking as the agent, use voice_id 'agent_voice_def456'."
    }
  }
}

注意事项:

  • 每次切换语音都会增加约 200 毫秒延迟
  • 需要仔细设计提示词,才能正确触发切换
  • 并非所有语音都同样适合所有角色
发音词典

自定义 Agent 对特定单词或短语的发音方式。

支持的格式:

  • IPA(国际音标)
  • CMU(卡内基梅隆大学发音词典)
  • 单词替换(在 TTS 前替换单词)

配置:

{
  "pronunciation_dictionary": [
    {
      "word": "ElevenLabs",
      "pronunciation": "ɪˈlɛvənlæbz",
      "format": "ipa"
    },
    {
      "word": "API",
      "pronunciation": "ey-pee-ay",
      "format": "cmu"
    },
    {
      "word": "AI",
      "substitution": "artificial intelligence"
    }
  ]
}

适用场景:

  • 品牌名称(例如,“IKEA” → “ee-KAY-uh”)
  • 首字母缩略词(例如,“API” → “A-P-I”或“ay-pee-eye”)
  • 术语
  • 故事中的角色名称

注意:只有 Turbo v2/v2.5 模型支持基于音素的发音。其他模型会静默跳过音素条目,但仍会处理单词替换。

语速控制

动态调整说话速度(0.7x - 1.2x)。

配置:

{
  "voice_settings": {
    "speed": 1.0 // 0.7 = slow, 1.0 = normal, 1.2 = fast
  }
}

使用场景:

  • 慢速(0.7x-0.9x):无障碍场景、儿童、非母语使用者
  • 正常(1.0x):大多数场景的默认设置
  • 快速(1.1x-1.2x):紧急通知、高级用户

最佳实践:

  • 使用 0.9x-1.1x,调整后听起来更自然
  • 极端数值(低于 0.7 或高于 1.2)会降低质量
  • 语速可按 Agent 调整,而非按单次发言调整
语音设计

使用 ElevenLabs Voice Design 工具创建自定义语音。

工作流:

  1. 前往 Voice Library → Create Voice
  2. 使用 Voice Design(文本转语音)或 Voice Cloning(样本音频)
  3. 使用示例文本测试语音
  4. 将语音保存到库中
  5. 在 Agent 配置中使用 voice_id

语音克隆最佳实践:

  • 使用干净的音频样本(无背景噪声、音乐或爆音)
  • 保持麦克风距离一致
  • 避免音量过大或过小(耳语或喊叫)
  • 建议使用 1-2 分钟的音频

注意事项:将针对英语训练的语音用于非英语语言会导致发音问题。务必使用与语言匹配的语音。

语言配置

支持 32 种以上语言,并能自动检测语言及在对话中切换语言。

配置:

{
  "agent": {
    "language": "en" // ISO 639-1 code
  }
}

多语言预设(每种语言使用不同语音):

{
  "conversation_config": {
    "language_presets": [
      {
        "language": "en",
        "voice_id": "en_voice_id",
        "first_message": "Hello! How can I help you today?"
      },
      {
        "language": "es",
        "voice_id": "es_voice_id",
        "first_message": "¡Hola! ¿Cómo puedo ayudarte hoy?"
      },
      {
        "language": "fr",
        "voice_id": "fr_voice_id",
        "first_message": "Bonjour! Comment puis-je vous aider aujourd'hui?"
      }
    ]
  }
}

自动语言检测:Agent 会检测用户的语言并自动切换。

支持的语言:英语、西班牙语、法语、德语、意大利语、葡萄牙语、荷兰语、波兰语、阿拉伯语、中文、日语、韩语、印地语,以及其他 18 种以上语言。


4. 知识库与 RAG

RAG(检索增强生成)

让 Agent 能够访问大型知识库,而无需将整份文档加载到上下文中。

工作原理:

  1. 将文档(PDF、TXT、DOCX)上传到知识库
  2. ElevenLabs 会自动计算向量嵌入
  3. 对话期间,根据语义相似度检索相关片段
  4. 大模型使用检索到的上下文生成回复

配置:

{
  "agent": {
    "prompt": {
      "knowledge_base": ["doc_id_1", "doc_id_2"]
    }
  }
}

通过 API 上传文档:

import { ElevenLabsClient } from 'elevenlabs';

const client = new ElevenLabsClient({ apiKey: process.env.ELEVENLABS_API_KEY });

// Upload document
const doc = await client.knowledgeBase.upload({
  file: fs.createReadStream('support_docs.pdf'),
  name: 'Support Documentation'
});

// Compute RAG index
await client.knowledgeBase.computeRagIndex({
  document_id: doc.id,
  embedding_model: 'e5_mistral_7b' // or 'multilingual_e5_large'
});

检索配置:

{
  "knowledge_base_config": {
    "max_chunks": 5,              // Number of chunks to retrieve
    "vector_distance_threshold": 0.8  // Similarity threshold
  }
}

使用场景:

  • 产品文档 Agent
  • 客户支持(常见问题、帮助中心)
  • 教育辅导 Agent(教科书、课堂笔记)
  • 医疗助手(医疗指南)

注意事项:

  • RAG 每次查询会增加约 500ms 的延迟
  • 片段越多,成本越高,但上下文也更充分
  • 向量距离越大,上下文越多,但相关性可能越低
  • 文档必须先建立索引才能使用(大型文档可能需要几分钟)

5. 工具(4 种类型)

ElevenLabs 支持 4 种不同的工具类型,每种都有不同的执行模式。

A. 客户端工具

在客户端(浏览器或移动应用)上执行操作。

使用场景:

  • 更新 UI 元素(购物车、通知)
  • 触发导航(将用户重定向到页面)
  • 访问本地存储
  • 控制媒体播放

React 示例:

import { useConversation } from '@elevenlabs/react';
import { z } from 'zod';

const { startConversation } = useConversation({
  clientTools: {
    updateCart: {
      description: "Update the shopping cart with new items",
      parameters: z.object({
        item: z.string().describe("The item name"),
        quantity: z.number().describe("Quantity to add")
      }),
      handler: async ({ item, quantity }) => {
        // Client-side logic
        const cart = getCart();
        cart.add(item, quantity);
        updateUI(cart);
        return { success: true, total: cart.total };
      }
    },
    navigate: {
      description: "Navigate to a different page",
      parameters: z.object({
        url: z.string().describe("The URL to navigate to")
      }),
      handler: async ({ url }) => {
        window.location.href = url;
        return { success: true };
      }
    }
  }
});

注意事项:

  • 工具名称区分大小写
  • 必须返回值(Agent 会读取返回值)
  • 处理函数可以是异步函数
B. 服务端工具(Webhook)

通过 ElevenLabs 服务端向外部 API 发出 HTTP 请求。

使用场景:

  • 获取实时数据(天气、股价)
  • 更新 CRM 系统(Salesforce、HubSpot)
  • 处理付款(Stripe、PayPal)
  • 发送邮件/短信(SendGrid、Twilio)

通过 CLI 配置:

elevenlabs tools add-webhook "Get Weather" --config-path tool_configs/get-weather.json

tool_configs/get-weather.json:

{
  "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": "The city name (e.g., 'London', 'New York')"
      }
    },
    "required": ["city"]
  },
  "headers": {
    "Authorization": "Bearer {{secret__weather_api_key}}"
  }
}

工具中的动态变量:

{
  "url": "https://api.crm.com/customers/{{user_id}}",
  "headers": {
    "X-API-Key": "{{secret__crm_api_key}}"
  }
}

注意事项:

  • 密钥变量仅能用于请求头(不能用于 URL 或请求体)
  • Schema 描述会指导大模型何时使用工具
C. MCP 工具(Model Context Protocol)

连接到外部 MCP 服务,以标准化方式访问工具。

使用场景:

  • 访问数据库(PostgreSQL、MongoDB)
  • 查询知识库(Pinecone、Weaviate)
  • 与 IDE 集成(VS Code、Cursor)
  • 连接数据源(Google Drive、Notion)

配置:

  1. 在控制面板中导航到 MCP 服务集成
  2. 点击“Add Custom MCP Server”
  3. 配置:
    • 名称:服务标识符
    • 服务 URL:SSE 或 HTTP 端点
    • 密钥令牌:可选的身份验证标头
  4. 测试连接并发现工具
  5. 添加到 Agent(公开或私有)

审批模式:

  • 始终询问:最高安全性,每次调用工具都需要权限
  • 精细控制:按工具设置审批选项
  • 无需审批:自动执行所有工具

注意事项:

  • 仅支持 SSE 和 HTTP 可流式传输协议
  • MCP 服务必须可公开访问或受身份验证保护
  • Zero Retention Mode 下不可用
  • 与 HIPAA 合规要求不兼容

示例:在 Claude Desktop 中使用 ElevenLabs MCP 服务:

{
  "mcpServers": {
    "ElevenLabs": {
      "command": "uvx",
      "args": ["elevenlabs-mcp"],
      "env": {
        "ELEVENLABS_API_KEY": "<your-key>",
        "ELEVENLABS_MCP_OUTPUT_MODE": "files"
      }
    }
  }
}
D. 系统工具

无需外部调用即可修改对话的内部状态。

使用场景:

  • 更新对话上下文
  • 在工作流节点之间切换
  • 在对话过程中修改 Agent 行为
  • 跟踪对话状态

内置系统工具:

  • end_call - 结束对话
  • detect_language - 检测用户的语言
  • transfer_agent - 切换到其他 Agent/工作流节点
  • transfer_to_number - 转接到外部电话号码(仅限电话服务)
  • dtmf_playpad - 显示 DTMF 键盘(仅限电话服务)
  • voicemail_detection - 检测语音信箱(仅限电话服务)

配置:

{
  "system_tools": [
    {
      "name": "update_conversation_state",
      "description": "Update the conversation context with new information",
      "parameters": {
        "key": { "type": "string" },
        "value": { "type": "string" }
      }
    }
  ]
}

注意事项:

  • 系统工具不会触发外部 API
  • 更改是临时的(对话结束后会丢失)
  • 适用于工作流和状态管理

6. SDK 集成

React SDK(@elevenlabs/react)

安装:

npm install @elevenlabs/react zod

完整示例:

import { useConversation } from '@elevenlabs/react';
import { z } from 'zod';
import { useState } from 'react';

export default function VoiceAgent() {
  const [transcript, setTranscript] = useState<string[]>([]);

  const {
    startConversation,
    stopConversation,
    status,
    isSpeaking
  } = useConversation({
    agentId: 'your-agent-id',

    // Authentication (choose one)
    apiKey: process.env.NEXT_PUBLIC_ELEVENLABS_API_KEY,

    // Client tools
    clientTools: {
      updateCart: {
        description: "Update shopping cart",
        parameters: z.object({
          item: z.string(),
          quantity: z.number()
        }),
        handler: async ({ item, quantity }) => {
          console.log('Cart updated:', item, quantity);
          return { success: true };
        }
      }
    },

    // Events
    onConnect: () => {
      console.log('Connected to agent');
      setTranscript([]);
    },
    onDisconnect: () => console.log('Disconnected'),
    onEvent: (event) => {
      if (event.type === 'transcript') {
        setTranscript(prev => [...prev, `User: ${event.data.text}`]);
      } else if (event.type === 'agent_response') {
        setTranscript(prev => [...prev, `Agent: ${event.data.text}`]);
      }
    },
    onError: (error) => console.error('Error:', error),

    // Regional compliance
    serverLocation: 'us'
  });

  return (
    <div>
      <div>
        <button onClick={startConversation} disabled={status === 'connected'}>
          Start Conversation
        </button>
        <button onClick={stopConversation} disabled={status !== 'connected'}>
          Stop
        </button>
      </div>

      <div>Status: {status}</div>
      <div>{isSpeaking && 'Agent is speaking...'}</div>

      <div>
        <h3>Transcript</h3>
        {transcript.map((line, i) => (
          <p key={i}>{line}</p>
        ))}
      </div>
    </div>
  );
}
JavaScript SDK(@elevenlabs/client)

适用于原生 JavaScript 项目(不使用 React)。

安装:

npm install @elevenlabs/client

示例:

import { Conversation } from '@elevenlabs/client';

const conversation = new Conversation({
  agentId: 'your-agent-id',
  apiKey: process.env.ELEVENLABS_API_KEY,

  onConnect: () => console.log('Connected'),
  onDisconnect: () => console.log('Disconnected'),

  onEvent: (event) => {
    switch (event.type) {
      case 'transcript':
        document.getElementById('user-text').textContent = event.data.text;
        break;
      case 'agent_response':
        document.getElementById('agent-text').textContent = event.data.text;
        break;
    }
  }
});

// Start conversation
document.getElementById('start-btn').addEventListener('click', async () => {
  await conversation.start();
});

// Stop conversation
document.getElementById('stop-btn').addEventListener('click', async () => {
  await conversation.stop();
});
连接类型:WebRTC 与 WebSocket

ElevenLabs SDK 支持两种特性各异的连接类型。

对比表:

特性WebSocketWebRTC
身份验证signedUrlconversationToken
音频格式可配置PCM_48000(硬编码)
采样率可配置(16k、24k、48k)48000(硬编码)
延迟标准更低
设备切换灵活受限(格式锁定)
最适合通用场景,灵活性高对低延迟有要求的场景

WebSocket 配置(默认):

import { useConversation } from '@elevenlabs/react';

const { startConversation } = useConversation({
  agentId: 'your-agent-id',

  // WebSocket uses signed URL
  signedUrl: async () => {
    const response = await fetch('/api/elevenlabs/auth');
    const { signedUrl } = await response.json();
    return signedUrl;
  },

  // Connection type (optional, defaults to 'websocket')
  connectionType: 'websocket',

  // Audio config (flexible)
  audioConfig: {
    sampleRate: 24000, // 16000, 24000, or 48000
    format: 'PCM_24000'
  }
});

WebRTC 配置:

const { startConversation } = useConversation({
  agentId: 'your-agent-id',

  // WebRTC uses conversation token (different auth flow)
  conversationToken: async () => {
    const response = await fetch('/api/elevenlabs/token');
    const { token } = await response.json();
    return token;
  },

  // Connection type
  connectionType: 'webrtc',

  // Audio format is HARDCODED to PCM_48000 (not configurable)
  // audioConfig ignored for WebRTC
});

后端令牌端点:

// WebSocket signed URL (GET /v1/convai/conversation/get-signed-url)
app.get('/api/elevenlabs/auth', async (req, res) => {
  const response = await fetch(
    `https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id=${AGENT_ID}`,
    { headers: { 'xi-api-key': ELEVENLABS_API_KEY } }
  );
  const { signed_url } = await response.json();
  res.json({ signedUrl: signed_url });
});

// WebRTC conversation token (GET /v1/convai/conversation/token)
app.get('/api/elevenlabs/token', async (req, res) => {
  const response = await fetch(
    `https://api.elevenlabs.io/v1/convai/conversation/token?agent_id=${AGENT_ID}`,
    { headers: { 'xi-api-key': ELEVENLABS_API_KEY } }
  );
  const { conversation_token } = await response.json();
  res.json({ token: conversation_token });
});

适用场景:

使用 WebSocket 的情况使用 WebRTC 的情况
需要灵活的音频格式需要尽可能低的延迟
经常在音频设备之间切换音频格式可以锁定为 48 kHz
可以接受标准延迟构建实时应用
需要最大程度地控制配置性能至关重要

注意事项:

  • WebRTC 将 PCM_48000 硬编码,无法更改格式
  • WebRTC 中的设备切换受固定格式限制
  • 身份验证方法不同(signedUrl 与 conversationToken)
  • WebRTC 的性能可能更好,但灵活性较低
React Native SDK(Expo)

安装:

npx expo install @elevenlabs/react-native @livekit/react-native @livekit/react-native-webrtc livekit-client

要求:

  • Expo SDK 47+
  • iOS 14.0+ / macOS 11.0+
  • 需要自定义开发构建(不支持 Expo Go)

示例:

import { useConversation } from '@elevenlabs/react-native';
import { View, Button, Text } from 'react-native';
import { z } from 'zod';

export default function App() {
  const { startConversation, stopConversation, status } = useConversation({
    agentId: 'your-agent-id',
    signedUrl: 'https://api.elevenlabs.io/v1/convai/auth/...',

    clientTools: {
      updateProfile: {
        description: "Update user profile",
        parameters: z.object({
          name: z.string()
        }),
        handler: async ({ name }) => {
          console.log('Updating profile:', name);
          return { success: true };
        }
      }
    }
  });

  return (
    <View style={{ padding: 20 }}>
      <Button title="Start" onPress={startConversation} />
      <Button title="Stop" onPress={stopConversation} />
      <Text>Status: {status}</Text>
    </View>
  );
}

注意事项:

  • 需要自定义开发构建(不支持 Expo Go)
  • 仅限 iOS/macOS(可通过 Kotlin SDK 支持 Android,但尚未正式发布)
Swift SDK(iOS/macOS)

安装(Swift Package Manager):

dependencies: [
  .package(url: "https://github.com/elevenlabs/elevenlabs-swift-sdk", from: "1.0.0")
]

要求:

  • iOS 14.0+ / macOS 11.0+
  • Swift 5.9+

使用场景:

  • 原生 iOS 应用
  • macOS 应用
  • watchOS(有限制)
Widget(可嵌入式 Web 组件)

安装: 从控制面板复制嵌入代码,或使用此模板:

<script src="https://elevenlabs.io/convai-widget/index.js"></script>
<script>
  ElevenLabsWidget.init({
    agentId: 'your-agent-id',

    // Theming
    theme: {
      primaryColor: '#3B82F6',
      backgroundColor: '#1F2937',
      textColor: '#F9FAFB'
    },

    // Position
    position: 'bottom-right', // 'bottom-left' | 'bottom-right'

    // Custom branding
    branding: {
      logo: 'https://example.com/logo.png',
      name: 'Support Agent'
    }
  });
</script>

使用场景:

  • 客户支持聊天气泡
  • 网站助手
  • 线索收集表单
Scribe(实时语音转文本)

状态:封闭测试版(需联系销售) 发布:2025

Scribe 是 ElevenLabs 的实时语音转文本服务,可实现低延迟转录。

功能:

  • 麦克风流式传输(实时转录)
  • 预录制音频文件转录
  • 部分(中间)和最终转录文本
  • 词级时间戳
  • 语音活动检测(VAD)
  • 手动和自动提交策略
  • 语言检测
  • PCM_16000 和 PCM_24000 音频格式

身份验证: 使用一次性令牌(而非 API 密钥):

// Fetch token from backend
const response = await fetch('/api/scribe/token');
const { token } = await response.json();

// Backend endpoint
const token = await client.scribe.getToken();
return { token };

React Hook(useScribe):

import { useScribe } from '@elevenlabs/react';

export default function Transcription() {
  const {
    connect,
    disconnect,
    startRecording,
    stopRecording,
    status,
    transcript,
    partialTranscript
  } = useScribe({
    token: async () => {
      const response = await fetch('/api/scribe/token');
      const { token } = await response.json();
      return token;
    },

    // Commit strategy
    commitStrategy: 'vad', // 'vad' (automatic) or 'manual'

    // Audio format
    sampleRate: 16000, // 16000 or 24000

    // Events
    onConnect: () => console.log('Connected to Scribe'),
    onDisconnect: () => console.log('Disconnected'),

    onPartialTranscript: (text) => {
      console.log('Interim:', text);
    },

    onFinalTranscript: (text, timestamps) => {
      console.log('Final:', text);
      console.log('Timestamps:', timestamps); // Word-level timing
    },

    onError: (error) => console.error('Error:', error)
  });

  return (
    <div>
      <button onClick={connect}>Connect</button>
      <button onClick={startRecording}>Start Recording</button>
      <button onClick={stopRecording}>Stop Recording</button>
      <button onClick={disconnect}>Disconnect</button>

      <p>Status: {status}</p>
      <p>Partial: {partialTranscript}</p>
      <p>Final: {transcript}</p>
    </div>
  );
}

JavaScript SDK(Scribe.connect):

import { Scribe } from '@elevenlabs/client';

const connection = await Scribe.connect({
  token: 'your-single-use-token',

  sampleRate: 16000,
  commitStrategy: 'vad',

  onPartialTranscript: (text) => {
    document.getElementById('interim').textContent = text;
  },

  onFinalTranscript: (text, timestamps) => {
    const finalDiv = document.getElementById('final');
    finalDiv.textContent += text + ' ';

    // timestamps: [{ word: 'hello', start: 0.5, end: 0.8 }, ...]
  },

  onError: (error) => {
    console.error('Scribe error:', error);
  }
});

// Start recording from microphone
await connection.startRecording();

// Stop recording
await connection.stopRecording();

// Manual commit (if commitStrategy: 'manual')
await connection.commit();

// Disconnect
await connection.disconnect();

转录预录制文件:

import { Scribe } from '@elevenlabs/client';

const connection = await Scribe.connect({ token });

// Send audio buffer
const audioBuffer = fs.readFileSync('recording.pcm');
await connection.sendAudioData(audioBuffer);

// Manually commit to get final transcript
await connection.commit();

// Wait for final transcript event

事件类型:

  • SESSION_STARTED:连接已建立
  • PARTIAL_TRANSCRIPT:中间转录(未缓冲)
  • FINAL_TRANSCRIPT:完整句子/短语
  • FINAL_TRANSCRIPT_WITH_TIMESTAMPS:最终文本 + 词级时间信息
  • ERROR:转录错误
  • AUTH_ERROR:身份验证失败
  • OPEN:WebSocket 已打开
  • CLOSE:WebSocket 已关闭

提交策略:

策略说明适用场景
vad(自动)语音活动检测会在静音时自动提交实时转录
manual显式调用 connection.commit()预录制文件、受控提交

音频格式:

  • PCM_16000(16kHz,16 位 PCM)
  • PCM_24000(24kHz,16 位 PCM)

注意事项:

  • 令牌为一次性令牌(一次连接后即过期)
  • 封闭测试版 — 需联系销售
  • 自动检测语言(无法手动覆盖)
  • 暂不支持说话人分离

何时使用 Scribe:

  • 构建自定义转录界面
  • 实时字幕
  • 语音备忘录应用
  • 会议转录
  • 无障碍功能

何时不使用: 如果需要以下功能,请改用 Agents Platform:

  • 对话式 AI(大模型 + TTS)
  • 双向语音交互
  • Agent 回复

7. 测试与评估

场景测试(基于大模型的评估)

模拟完整对话,并根据成功标准进行评估。

通过 CLI 配置:

elevenlabs tests add "Refund Request Test" --template basic-llm

test_configs/refund-request-test.json:

{
  "name": "Refund Request Test",
  "scenario": "Customer requests refund for defective product",
  "user_input": "I want a refund for order #12345. The product was broken when it arrived.",
  "success_criteria": [
    "Agent acknowledges the request empathetically",
    "Agent asks for order number (which was already provided)",
    "Agent verifies order details",
    "Agent provides refund timeline or next steps"
  ],
  "evaluation_type": "llm"
}

运行测试:

elevenlabs agents test "Support Agent"
工具调用测试

验证 Agent 是否使用正确的参数正确调用工具。

配置:

{
  "name": "Account Balance Test",
  "scenario": "Customer requests account balance",
  "expected_tool_call": {
    "tool_name": "get_account_balance",
    "parameters": {
      "account_id": "ACC-12345"
    }
  }
}
负载测试

在高并发情况下测试 Agent 的承载能力。

配置:

# Spawn 100 users, 1 per second, test for 10 minutes
elevenlabs test load \
  --users 100 \
  --spawn-rate 1 \
  --duration 600

注意事项:

  • 负载测试会消耗真实 API 额度
  • 对预期流量高峰使用突发定价
  • 需要仔细规划,以避免触及速率限制
模拟 API(程序化测试)

API 端点:

POST /v1/convai/agents/:agent_id/simulate

示例:

const simulation = await client.agents.simulate({
  agent_id: 'agent_123',
  scenario: 'Customer requests refund',
  user_messages: [
    "I want a refund for order #12345",
    "I ordered it last week",
    "Yes, please process it"
  ],
  success_criteria: [
    "Agent acknowledges request",
    "Agent asks for order details",
    "Agent provides refund timeline"
  ]
});

console.log('Test passed:', simulation.passed);
console.log('Criteria met:', simulation.evaluation.criteria_met);

使用场景:

  • CI/CD 集成(部署前测试)
  • 回归测试
  • 负载测试准备

8. 分析与监控

对话分析

从对话转录文本中提取结构化数据。

功能:

成功评估(基于大模型)
{
  "evaluation_criteria": {
    "resolution": "Was the customer's issue resolved?",
    "sentiment": "Was the conversation tone positive?",
    "compliance": "Did the agent follow company policies?"
  }
}
数据收集
{
  "data_collection": {
    "fields": [
      { "name": "customer_name", "type": "string" },
      { "name": "issue_type", "type": "enum", "values": ["billing", "technical", "other"] },
      { "name": "satisfaction", "type": "number", "range": [1, 5] }
    ]
  }
}

访问方式:

  • 通过通话后 Webhook(实时)
  • 通过分析控制面板(批量)
  • 通过 API(按需)
分析控制面板

指标:

  • 问题解决率:已解决问题的百分比
  • CX 指标:情绪、满意度、CSAT
  • 合规性:政策遵循情况、护栏违规情况
  • 性能:响应时间、通话时长、并发数
  • 工具使用情况:工具调用频率、成功率
  • 大模型成本:跟踪每个 Agent/对话的成本

访问方式:控制面板 → 分析选项卡


9. 隐私与合规

数据保留

默认值:2 年(符合 GDPR)

配置:

{
  "privacy": {
    "transcripts": {
      "retention_days": 730  // 2 years (GDPR)
    },
    "audio": {
      "retention_days": 2190  // 6 years (HIPAA)
    }
  }
}

合规建议:

  • GDPR:与数据处理目的保持一致(通常为 1–2 年)
  • HIPAA:医疗记录至少保留 6 年
  • SOC 2:传输中和静态数据均加密(自动)
加密
  • 传输中:TLS 1.3
  • 静态数据:AES-256
  • 区域合规性:数据驻留(美国、欧盟、印度)

区域配置:

const { startConversation } = useConversation({
  serverLocation: 'eu-residency' // 'us' | 'global' | 'eu-residency' | 'in-residency'
});
零保留模式

如需最大程度保护隐私,请启用零保留,立即删除所有对话数据。

限制:

  • 无对话历史记录
  • 无分析数据
  • 无通话后 Webhook
  • 无 MCP 工具集成

10. 成本优化

LLM 缓存

通过缓存重复输入来降低成本。

工作原理:

  • 首次请求:全额费用(input_cache_write)
  • 后续请求:费用降低(input_cache_read)
  • TTL 到期后自动失效缓存

配置:

{
  "llm_config": {
    "caching": {
      "enabled": true,
      "ttl_seconds": 3600  // 1 hour
    }
  }
}

适用场景:

  • 重复的系统提示词
  • 大型知识库
  • 高频使用的工具定义

节省:缓存输入最多可节省 90% 的费用

模型切换

根据成本和性能需求切换模型。

可用模型:

  • GPT-4o(成本高,质量高)
  • GPT-4o-mini(成本中等,质量良好)
  • Claude Sonnet 4.5(成本高,推理能力最佳)
  • Gemini 2.5 Flash(成本低,速度快)

配置:

{
  "llm_config": {
    "model": "gpt-4o-mini"  // Swap anytime via dashboard or API
  }
}
突发定价

在需求高峰期临时超出并发限制。

工作原理:

  • 正常:订阅的并发限制(例如,同时通话 10 次)
  • 突发:最高可达限制的 3 倍(例如,同时通话 30 次)
  • 费用:突发通话按标准费率的 2 倍计费

配置:

{
  "call_limits": {
    "burst_pricing_enabled": true
  }
}

适用场景:

  • 黑色星期五的流量高峰
  • 产品发布
  • 季节性需求(节假日)

注意事项:

  • 突发通话费用为 2 倍(请做好规划)
  • 并非无限制(上限为 3 倍)

11. 高级功能

事件(WebSocket/SSE)

实时事件流,用于实时转录、Agent 响应和工具调用。

事件类型:

  • audio - 音频流分块
  • transcript - 实时转录
  • agent_response - Agent 的文本响应
  • tool_call - 工具执行状态
  • conversation_state - 状态更新

示例:

const { startConversation } = useConversation({
  onEvent: (event) => {
    switch (event.type) {
      case 'transcript':
        console.log('User said:', event.data.text);
        break;
      case 'agent_response':
        console.log('Agent replied:', event.data.text);
        break;
      case 'tool_call':
        console.log('Tool called:', event.data.tool_name);
        break;
    }
  }
});
自定义模型(自带 LLM)

使用自己的 OpenAI API 密钥或自定义 LLM 服务。

配置:

{
  "llm_config": {
    "custom": {
      "endpoint": "https://api.openai.com/v1/chat/completions",
      "api_key": "{{secret__openai_api_key}}",
      "model": "gpt-4"
    }
  }
}

适用场景:

  • 自定义微调模型
  • 私有 LLM 部署(Ollama、LocalAI)
  • 成本控制(使用自己的额度)
  • 合规要求(本地部署模型)

注意事项:

  • 端点必须与 OpenAI 兼容
  • 不正式支持与 OpenAI 不兼容的模型
通话后 Webhook

在通话结束且分析完成时接收通知。

配置:

{
  "webhooks": {
    "post_call": {
      "url": "https://api.example.com/webhook",
      "headers": {
        "Authorization": "Bearer {{secret__webhook_auth_token}}"
      }
    }
  }
}

载荷:

{
  "conversation_id": "conv_123",
  "agent_id": "agent_456",
  "transcript": "...",
  "duration_seconds": 120,
  "analysis": {
    "sentiment": "positive",
    "resolution": true,
    "extracted_data": {
      "customer_name": "John Doe",
      "issue_type": "billing"
    }
  }
}

安全性(HMAC 验证):

import crypto from 'crypto';

export async function POST(req: Request) {
  const signature = req.headers.get('elevenlabs-signature');
  const payload = await req.text();

  const hmac = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET!)
    .update(payload)
    .digest('hex');

  if (signature !== hmac) {
    return new Response('Invalid signature', { status: 401 });
  }

  // Process webhook
  const data = JSON.parse(payload);
  console.log('Conversation ended:', data.conversation_id);

  // MUST return 200
  return new Response('OK', { status: 200 });
}

注意事项:

  • 必须返回 200 状态码
  • 连续失败 10 次后自动禁用(距上次成功已超过 7 天)
  • 重试逻辑:采用指数退避,最多重试 3 次
聊天模式(纯文本)

关闭语音,使用纯文本对话。

配置:

{
  "conversation_config": {
    "chat_mode": true  // Disables audio input/output
  }
}

优势:

  • 响应更快(约节省 200 毫秒)
  • 成本更低(无需支付 ASR/TTS 费用)
  • 测试更简单(无需麦克风)

适用场景:

  • 不使用音频测试 Agent
  • 构建文本聊天界面
  • 无障碍访问(仅使用文本的用户)
电话集成

SIP 中继:

SIP Endpoint: sip-static.rtc.elevenlabs.io
TLS Transport: Recommended for production
SRTP Encryption: Supported

支持的服务提供商:Twilio、Vonage、RingCentral、Sinch、Infobip、Telnyx、Exotel、Plivo、Bandwidth

Twilio 原生集成:

{
  "telephony": {
    "provider": "twilio",
    "phone_number": "+1234567890",
    "account_sid": "{{secret__twilio_account_sid}}",
    "auth_token": "{{secret__twilio_auth_token}}"
  }
}

适用场景:

  • 客户支持热线
  • 预约安排
  • 订单状态查询
  • IVR 系统

12. CLI 和 DevOps(“Agent 即代码”)

安装与身份验证
# Install globally
npm install -g @elevenlabs/cli

# Authenticate
elevenlabs auth login

# Set residency (for GDPR compliance)
elevenlabs auth residency eu-residency  # or 'in-residency' | 'global'

# Check current user
elevenlabs auth whoami

环境变量(用于 CI/CD):

export ELEVENLABS_API_KEY=your-api-key
项目结构

初始化项目:

elevenlabs agents init

创建的目录结构:

your_project/
├── agents.json              # Agent registry
├── tools.json               # Tool configurations
├── tests.json               # Test configurations
├── agent_configs/           # Individual agent files (.json)
├── tool_configs/            # Tool configuration files
└── test_configs/            # Test configuration files
Agent 管理命令
# Create agent
elevenlabs agents add "Support Agent" --template customer-service

# Deploy to platform
elevenlabs agents push
elevenlabs agents push --agent "Support Agent"
elevenlabs agents push --env prod
elevenlabs agents push --dry-run  # Preview changes

# Import existing agents
elevenlabs agents pull

# List agents
elevenlabs agents list

# Check sync status
elevenlabs agents status

# Delete agent
elevenlabs agents delete <agent_id>
工具管理命令
# Create webhook tool
elevenlabs tools add-webhook "Get Weather" --config-path tool_configs/get-weather.json

# Create client tool
elevenlabs tools add-client "Update Cart" --config-path tool_configs/update-cart.json

# Deploy tools
elevenlabs tools push

# Import existing tools
elevenlabs tools pull

# Delete tools
elevenlabs tools delete <tool_id>
elevenlabs tools delete --all
测试命令
# Create test
elevenlabs tests add "Refund Test" --template basic-llm

# Deploy tests
elevenlabs tests push

# Import tests
elevenlabs tests pull

# Run test
elevenlabs agents test "Support Agent"
多环境部署

模式:

# Development
elevenlabs agents push --env dev

# Staging
elevenlabs agents push --env staging

# Production (with confirmation)
elevenlabs agents push --env prod --dry-run
# Review changes...
elevenlabs agents push --env prod

环境专属配置:

agent_configs/
├── support-bot.json          # Base config
├── support-bot.dev.json      # Dev overrides
├── support-bot.staging.json  # Staging overrides
└── support-bot.prod.json     # Prod overrides
CI/CD 集成

GitHub Actions 示例:

name: Deploy Agent
on:
  push:
    branches: [main]
    paths:
      - 'agent_configs/**'
      - 'tool_configs/**'

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install CLI
        run: npm install -g @elevenlabs/cli

      - name: Test Configs
        run: elevenlabs agents push --dry-run --env prod
        env:
          ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY_PROD }}

      - name: Deploy
        run: elevenlabs agents push --env prod
        env:
          ELEVENLABS_API_KEY: ${{ secrets.ELEVENLABS_API_KEY_PROD }}
版本控制最佳实践

提交:

  • agent_configs/*.json
  • tool_configs/*.json
  • test_configs/*.json
  • agents.json、tools.json、tests.json

忽略:

# .gitignore
.env
.elevenlabs/
*.secret.json

13. 常见错误与解决方案

错误 1:缺少必需的动态变量

症状:“Missing required dynamic variables”错误,未生成转录文本

原因:提示词/消息中引用了动态变量,但在对话开始时未提供

解决方案:

const conversation = await client.conversations.create({
  agent_id: "agent_123",
  dynamic_variables: {
    user_name: "John",
    account_tier: "premium",
    // Provide ALL variables referenced in prompts
  }
});
错误 2:工具名称区分大小写

症状:工具未执行,Agent 提示“tool not found”

原因:配置中的工具名称与注册名称不匹配(区分大小写)

解决方案:

// agent_configs/bot.json
{
  "agent": {
    "prompt": {
      "tool_ids": ["orderLookup"]  // Must match exactly
    }
  }
}

// tool_configs/order-lookup.json
{
  "name": "orderLookup"  // Match case exactly
}
错误 3:Webhook 身份验证失败

症状:失败后 Webhook 自动停用

原因:

  • HMAC 签名验证不正确
  • 未返回 200 状态码
  • 连续失败 10 次以上

解决方案:

// Always verify HMAC signature
import crypto from 'crypto';

const signature = req.headers['elevenlabs-signature'];
const payload = JSON.stringify(req.body);

const hmac = crypto
  .createHmac('sha256', process.env.WEBHOOK_SECRET)
  .update(payload)
  .digest('hex');

if (signature !== hmac) {
  return res.status(401).json({ error: 'Invalid signature' });
}

// Process webhook
// ...

// MUST return 200
res.status(200).json({ success: true });
错误 4:语音一致性问题

症状:生成的音频音量/音调不一致

原因:

  • 语音克隆训练数据中存在背景噪声
  • 麦克风距离不一致
  • 样本中有耳语或喊叫

解决方案:

  • 使用干净的音频样本(无音乐、噪声、爆音)
  • 保持麦克风距离一致
  • 避免音量过大或过小
  • 部署前测试语音设置
错误 5:语音语言错误

症状:发音不可预测、口音异常

原因:非英语语音使用了基于英语训练的语音

解决方案:

{
  "language_presets": [
    {
      "language": "es",
      "voice_id": "spanish_trained_voice_id"  // Must be Spanish-trained
    }
  ]
}
错误 6:不支持受限 API 密钥(CLI)

症状:CLI 身份验证失败

原因:使用了受限 API 密钥(目前不支持)

解决方案:CLI 操作请使用不受限的 API 密钥

错误 7:Agent 配置推送冲突

症状:推送后更改未生效

原因:基于哈希的变更检测未检测到修改

解决方案:

# Force re-sync
elevenlabs agents init --override
elevenlabs agents pull  # Re-import from platform
# Make changes
elevenlabs agents push
错误 8:工具参数架构不匹配

症状:工具已调用,但参数为空或不正确

原因:架构定义与实际用法不匹配

解决方案:

// tool_configs/order-lookup.json
{
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "description": "The order ID to look up (format: ORD-12345)"  // Clear description
      }
    },
    "required": ["order_id"]
  }
}
错误 9:RAG 索引尚未就绪

症状:Agent 未使用知识库

原因:RAG 索引仍在计算中(大型文档可能需要几分钟)

解决方案:

// Check index status before using
const index = await client.knowledgeBase.getRagIndex({
  document_id: 'doc_123'
});

if (index.status !== 'ready') {
  console.log('Index still computing...');
}
错误 10:WebSocket 协议错误(1002)

症状:使用 WebSocket 连接时,偶尔出现“protocol error”

原因:网络不稳定或浏览器不兼容

解决方案:

  • 使用 WebRTC 替代 WebSocket(稳定性更高)
  • 实现重新连接逻辑
  • 检查浏览器兼容性
错误 11:生产环境中出现 401 Unauthorized

症状:本地运行正常,但在生产环境中失败

原因:Agent 可见性设置或 API 密钥配置有误

解决方案:

  • 检查 Agent 可见性(公开或私有)
  • 确认生产环境中已设置 API 密钥
  • 如果已启用,请检查允许列表配置
错误 12:允许列表连接错误

症状:“Host elevenlabs.io is not allowed to connect to this agent”

原因:Agent 启用了允许列表,但使用了共享链接

解决方案:

  • 为 Agent 配置正确的允许列表域名
  • 或在测试时禁用允许列表
错误 13:工作流陷入无限循环

症状:Agent 卡在工作流中,始终无法完成

原因:边缘条件导致循环

解决方案:

  • 添加最大迭代次数限制
  • 测试所有边缘路径
  • 添加明确的退出条件
错误 14:未启用突发定价

症状:流量激增时,通话被拒绝

原因:Agent 设置中未启用突发定价

解决方案:

{
  "call_limits": {
    "burst_pricing_enabled": true
  }
}
错误 15:MCP 服务超时

症状:MCP 工具无响应

原因:MCP 服务速度缓慢或无法访问

解决方案:

  • 检查 MCP 服务 URL 是否可访问
  • 确认传输类型(SSE 还是 HTTP)
  • 检查身份验证令牌
  • 监控 MCP 服务日志
错误 16:Android 上的首条消息被截断

症状:Agent 发出的首条消息在 Android 设备上被截断(在 iOS/网页上正常)

原因:连接后,Android 设备需要一些时间才能切换到正确的音频模式

解决方案:

import { useConversation } from '@elevenlabs/react';

const { startConversation } = useConversation({
  agentId: 'your-agent-id',

  // Add connection delay for Android
  connectionDelay: {
    android: 3_000,  // 3 seconds (default)
    ios: 0,          // No delay needed
    default: 0       // Other platforms
  },

  // Rest of config...
});

说明:

  • Android 需要 3 秒才能切换音频路由模式
  • 如果没有延迟,首个音频块会丢失
  • iOS 和网页不会遇到此问题
  • 如果 3 秒不够,请调整延迟

测试:

# Test on Android device
npm run android

# First message should now be complete
错误 17:CSP(内容安全策略)违规

症状:浏览器控制台中出现 “Refused to load the script because it violates the following Content Security Policy directive” 错误

原因:采用严格内容安全策略的应用不允许在 script-src 指令中使用 data: 或 blob: URL。ElevenLabs SDK 默认会将 Audio Worklets 作为 blob 加载。

解决方案 - 自托管 Worklet 文件:

步骤 1:将 worklet 文件复制到公共目录:

# Copy from node_modules
cp node_modules/@elevenlabs/client/dist/worklets/*.js public/elevenlabs/

步骤 2:配置 SDK 以使用自托管的 worklet:

import { useConversation } from '@elevenlabs/react';

const { startConversation } = useConversation({
  agentId: 'your-agent-id',

  // Point to self-hosted worklet files
  workletPaths: {
    'rawAudioProcessor': '/elevenlabs/rawAudioProcessor.worklet.js',
    'audioConcatProcessor': '/elevenlabs/audioConcatProcessor.worklet.js',
  },

  // Rest of config...
});

步骤 3:更新 CSP 标头,以允许自托管脚本:

# nginx example
add_header Content-Security-Policy "
  default-src 'self';
  script-src 'self' https://elevenlabs.io;
  connect-src 'self' https://api.elevenlabs.io wss://api.elevenlabs.io;
  worker-src 'self';
" always;

Worklet 文件位置:

node_modules/@elevenlabs/client/dist/worklets/
├── rawAudioProcessor.worklet.js
└── audioConcatProcessor.worklet.js

注意事项:

  • Worklet 文件必须从同一来源提供(CORS 限制)
  • 升级 @elevenlabs/client 时,请更新 worklet 文件
  • 路径必须完全一致(区分大小写)

适用场景:

  • 采用严格 CSP 的企业应用
  • 政府/金融应用
  • 需要通过安全审计的应用
  • 任何阻止 blob: URL 的应用

与现有技能集成

此技能可与以下技能很好地配合使用:

  • cloudflare-worker-base → 在 Cloudflare Workers 边缘网络上部署 Agent
  • cloudflare-workers-ai → 在 Agent 中将 Cloudflare LLM 用作自定义模型
  • cloudflare-durable-objects → 持久化对话状态和会话管理
  • cloudflare-kv → 缓存 Agent 配置和用户偏好设置
  • nextjs → 在 Next.js 应用中集成 React SDK
  • ai-sdk-core → 使用 Vercel AI SDK 提供程序,实现统一的 AI 接口
  • clerk-auth → 使用用户身份验证语音会话
  • hono-routing → 为 Webhook 和服务端工具配置 API 路由

其他资源

官方文档:

示例:

社区:


已通过生产环境测试:WordPress Auditor、客户支持 Agent 最后更新:2025-11-03 软件包版本:[email protected], @elevenlabs/[email protected]

评论

支持 Markdown