mcpField
E
elevenlabs-agents

elevenlabs-agents

github.com/jezwebAgent 工作流1.1k1.7k 次安装3 周前更新
代码仓库

关于 elevenlabs-agents

此 Skill 指导使用 ElevenLabs Agent Builder 创建和部署对话式语音 AI Agent,适用于构建客户支持等语音交互应用的开发者。内容涵盖工具、知识库、SDK 集成、测试及多环境部署,并说明 ElevenLabs MCP 集成的兼容限制。

主要功能

  1. 01通过 Dashboard 或 CLI 配置 Agent
  2. 02设置语音、LLM 与系统提示词
  3. 03添加客户端工具和 Webhook 工具
  4. 04上传文档构建知识库
  5. 05使用 CLI 测试与部署 Agent

适用场景

  1. 01创建客户服务语音 Agent
  2. 02将订单查询等工具接入对话
  3. 03让 Agent 在交谈中检索上传文档
  4. 04在部署前测试 Agent 的回复和工具调用

MCP 相关

说明 ElevenLabs 如何接入 MCP 工具,并列出其 Streamable HTTP 实现与实际 MCP 规范的兼容限制,包括要求 JSON 响应及特定协议版本。

安装

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

$npx skills add https://github.com/jezweb/claude-skills --skill elevenlabs-agents

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

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
agent-config-schema.json
ci-cd-example.yml
javascript-sdk-boilerplate.js
react-native-boilerplate.tsx
react-sdk-boilerplate.tsx
simulation-template.json
swift-sdk-boilerplate.swift
system-prompt-template.md
widget-embed-template.html
references/
api-reference.md
compliance-guide.md
workflow-examples.md

详细介绍

ElevenLabs Agent Builder

构建可用于生产环境的对话式 AI 语音 Agent。生成配置好的 Agent,包含工具、知识库和 SDK 集成。

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")

已弃用: @11labs/react、@11labs/client——如果已安装,请卸载。

仅限服务端的警告: @elevenlabs/elevenlabs-js 使用 Node.js child_process,无法在浏览器中运行。在浏览器环境中使用 @elevenlabs/client,或创建代理服务器。

工作流

第 1 步:通过控制面板或 CLI 创建 Agent

控制面板: https://elevenlabs.io/app/conversational-ai -> 创建 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 dev

模板:default、minimal、voice-only、text-only、customer-service、assistant。

配置:

  • Voice —— 从 5000 多种语音中选择,或克隆语音
  • LLM —— GPT、Claude、Gemini 或自定义模型
  • System prompt —— 使用下方的 6 部分框架
  • First message —— 对话开始时 Agent 说的话
第 2 步:编写 System prompt

使用 6 部分框架编写有效的 Agent 提示词:

1. Personality —— Agent 的身份:

You are [NAME], a [ROLE] at [COMPANY].
You have [EXPERIENCE]. Your traits: [LIST TRAITS].

2. Environment —— 沟通情境:

You're communicating via [phone/chat/video].
Consider [environmental factors]. Adapt to [context].

3. Tone —— 说话方式和正式程度:

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 —— 目标和成功标准:

Primary Goal: Resolve customer issues on the first call.
Success: Customer verbally confirms issue is resolved.

5. Guardrails —— 边界和道德规范:

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 —— 可用函数及其使用时机:

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.
第 3 步:添加工具

客户端工具(在浏览器中运行):

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 }; }
  }
};

服务端工具(webhook):

{
  "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}}"
  }
}

在 webhook 标头中使用 {{secret__key_name}} 存放 API 密钥——切勿硬编码。

MCP 工具——关键兼容性说明:

ElevenLabs 将其 MCP 集成标记为“Streamable HTTP”,但不支持实际的 MCP 2025-03-26 Streamable HTTP 规范(SSE 响应)。ElevenLabs 要求:

  • 纯 JSON 响应(application/json),而非 SSE(text/event-stream)
  • 协议版本为 2024-11-05,而非 2025-03-26
  • 通过 HTTP 进行简单的 JSON-RPC 通信,并直接返回 JSON 响应

以下方案不起作用:

  • 官方 MCP SDK 的 createMcpHandler(返回 SSE)
  • Cloudflare Agents SDK 的 McpServer.serve()(返回 SSE)
  • 任何返回 Content-Type: text/event-stream 的服务端

适用于 ElevenLabs 的 MCP 服务模式:

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;
第 4 步:添加知识库(RAG)

上传供 Agent 参考的文档:

  • PDF、文本文件、网页 URL
  • 通过控制面板配置:Agent -> 知识库 -> 上传
  • 或通过 API:POST /v1/convai/knowledge-base/upload(multipart/form-data)
  • Agent 会在对话过程中自动搜索知识库
第 5 步:集成 SDK

React —— 复制并自定义 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 使用 {{user_name}} 引用动态变量。

React Native —— 参见 assets/react-native-boilerplate.tsx 嵌入 Widget —— 参见 assets/widget-embed-template.html Swift —— 参见 assets/swift-sdk-boilerplate.swift

第 6 步:测试

CLI 测试:

# Run all tests for an agent
elevenlabs agents test "Support Agent"

# Add a test scenario
elevenlabs tests add "Refund Request" --template basic-llm

测试配置:

{
  "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"
}

工具调用测试:

{
  "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 模拟:

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 集成:

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 }}
第 7 步:部署
# Dry run first (always)
elevenlabs agents push --env prod --dry-run

# Deploy to production
elevenlabs agents push --env prod

多环境工作流:

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

关键模式

签名 URL(安全)

切勿在客户端代码中暴露 API 密钥。请使用服务端端点:

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 版本管理(A/B 测试)

控制面板:Agent -> 版本 -> 创建分支。比较指标并提升表现更佳的版本。

通话后 Webhook
{
  "type": "post_call_transcription",
  "data": {
    "conversation_id": "conv_xyz789",
    "transcript": "...",
    "duration_seconds": 120,
    "analysis": { "sentiment": "positive", "resolution": true }
  }
}

使用 HMAC SHA-256 验证:

const hmac = crypto.createHmac('sha256', process.env.WEBHOOK_SECRET)
  .update(JSON.stringify(request.body)).digest('hex');
if (signature !== hmac) { /* reject */ }

成本优化

模型阵容和定价变化很快——选择模型前,请在 ElevenLabs 控制面板(Agent → LLM 下拉菜单)或文档中查看最新列表,不要对本次会话中尚未核实的模型 ID 进行硬编码。长期适用的选择:大多数 Agent 使用当前性价比高、速度快的模型(仅在质量要求需要时升级);知识库较大时使用长上下文模型。

节省成本的关键措施:

  • LLM 缓存:重复提示词最多可节省 90%(在配置中启用)
  • 提示词长度:相同指令用 150 个 token 优于 500 个 token
  • 基于 RAG 而非上下文填充:使用知识库,而不是把内容塞进系统提示词
  • 时长限制:设置 max_duration_seconds,防止对话失控
  • 轮次模式:“patient”模式 = 更少的 LLM 调用 = 更低的成本

CLI 快速参考

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 test

环境变量:CI/CD 需要 ELEVENLABS_API_KEY。


可选参考资料

针对特定用途,请参阅:

  • references/api-reference.md -- 用于以编程方式管理 Agent 的完整 REST API
  • references/compliance-guide.md -- GDPR、HIPAA、PCI DSS、数据驻留
  • references/workflow-examples.md -- 多 Agent 路由、升级处理、多语言

资源文件

  • assets/react-sdk-boilerplate.tsx -- React 集成模板
  • assets/react-native-boilerplate.tsx -- React Native 模板
  • assets/swift-sdk-boilerplate.swift -- Swift/iOS 模板
  • assets/javascript-sdk-boilerplate.js -- Vanilla JS 模板
  • assets/widget-embed-template.html -- 可嵌入式小组件
  • assets/system-prompt-template.md -- 系统提示词指南
  • assets/agent-config-schema.json -- 配置架构参考
  • assets/ci-cd-example.yml -- CI/CD 流水线模板

评论

支持 Markdown