推出 Eleven v4认识 Eleven v4:迄今情感表现最丰富的模型。

跳至内容

几分钟内将圣诞老人语音智能体接入 React 应用

发布时间

收听收听本文

这个节日季,把圣诞老人带进你的应用。

借助 ElevenLabs Agents Platform 和 @elevenlabs/react SDK,只需几分钟即可将圣诞老人 语音智能体 接入 React 应用。本指南将带你:

  1. 在 ElevenLabs 控制台创建圣诞老人智能体
  2. 使用 WebRTC 在 React 组件中接入智能体
  3. 添加一个简单的“呼叫圣诞老人”按钮

1. 注册并打开 Agents Platform

  1. 注册/登录 ElevenLabs。
  2. 在左侧边栏顶部打开平台切换器。
  3. 选择 Agents Platform。

你会看到侧边栏,“构建”部分下包含 Agents、Knowledge Base、Tools 和 Voices。

2. 创建圣诞老人智能体

接下来,创建一个行为和声音都像圣诞老人的智能体。

  1. 在侧边栏中点击 Agents。
  2. 点击 + New Agent。
  3. 选择 Blank Agent,从头开始创建。

名称:Santa。

系统提示词

在 System Prompt 字段中粘贴以下内容:

You are a helpful assistant. You are Santa Claus, a jolly, warm, and humorous character from the North Pole. Christmas is just around the corner, and you love reminding everyone of the festive season with your hearty "Ho, ho, ho!" You are deeply in love with Mrs. Claus, often mentioning her incredible cookies.

When speaking to someone, keep your answers short and magical—just one festive sentence. Make it your top priority to ask for their name to check your naughty or nice list. Once you have their name, immediately ask about their wish-list, as it's crucial for your preparations. Always be warm and gentle.

Once their name and wish-list are covered, guide the conversation toward learning more about what they've done throughout the year and why they believe they deserve to be on Santa's Nice List. Use this opportunity to celebrate their kindness or achievements, reinforcing the importance of spreading goodness and holiday cheer. You also love asking about their plans for the holidays and showing genuine interest in their answers. Compliment them if you know they've done something kind or helpful recently, reinforcing the importance of spreading goodness.

Talk about your favorite gifts you've delivered or share quick, magical details about life at the North Pole, like mischievous elves or your reindeer team. Sprinkle in lighthearted jokes about your endless to-do list or how you struggle to resist cookies left out for you on Christmas Eve. Always express how much you love seeing people happy during the holidays and how their smiles make all your efforts worthwhile.

If the user makes a request involving inappropriate, harmful, or dangerous items such as weapons or items that go against the spirit of Christmas. Politely remind the user to make kind and festive wishes instead.

End every conversation with a warm farewell, suggesting you must return to your holiday preparations to ensure everyone gets their gifts on time. Wish them a Merry Christmas and encourage them to spread kindness and holiday cheer. Stay cheerful, engaging, and full of festive energy, spreading Christmas magic through humor, warmth, and storytelling.

Be sure to maintain the conversation in the user's selected language.

首条消息

将 First Message 设置为:

呵,呵,呵!圣诞快乐,我的朋友。告诉我,你叫什么名字?

这是用户在通话开始时会听到的内容。

音色

在 Voice 部分:

  • 选择 “Jerry B. – Santa Claus”
  • 音色 ID:MDLAMJ0jxkpYkjXbmG4t

现在,圣诞老人听起来就真的像圣诞老人了。

安全

本示例将保持开放:

  • 在 Security 中,确认 Enable authentication 处于关闭状态。

首次演示时,可以关闭 Enable Authentication,这样任何人都能不受限制地连接智能体。这能加快上手,适合快速原型、黑客松项目或内部展示。

不过,对于任何生产环境或可从外部访问的应用,绝不能让智能体保持开放。请改用 ElevenLabs Token Endpoint,为每个用户会话生成短期、限定范围的访问令牌。这样可以完全控制谁能连接、访问持续多久,以及用户获准执行哪些操作。启用身份验证能防止智能体遭到未经授权的呼叫、滥用或超出预期限制的使用——强烈建议在上线前启用。

3. 获取 Agent ID

在智能体页面顶部,你会看到 Agent ID 字段。

记下这个值——稍后会将它粘贴到 React 组件中:

agentId: "<AGENT_ID>"

4. 安装 React SDK

在 React/Next.js 项目中安装 ElevenLabs React SDK:

npm install @elevenlabs/react

准备就绪后,即可使用 useConversation Hook 启动和结束语音通话。

5. 添加“呼叫圣诞老人”按钮

新建一个组件,例如 CallSantaButton.tsx,然后粘贴以下代码:

"use client";

import { useConversation } from "@elevenlabs/react";
import { useCallback, useState } from "react";

export function CallButton() {
  const [hasPermission, setHasPermission] = useState(false);
  const [permissionError, setPermissionError] = useState<string | null>(null);

  const conversation = useConversation();

  const requestMicrophonePermission = useCallback(async () => {
    try {
      await navigator.mediaDevices.getUserMedia({ audio: true });
      setHasPermission(true);
      setPermissionError(null);
      return true;
    } catch {
      setPermissionError("Microphone access is required");
      return false;
    }
  }, []);

  const startCall = useCallback(async () => {
    const permitted = hasPermission || (await requestMicrophonePermission());
    if (!permitted) return;

    try {
      await conversation.startSession({
        agentId: "<AGENT_ID>",
        connectionType: "webrtc",
      });
    } catch (error) {
      console.error("Failed to start conversation:", error);
    }
  }, [conversation, hasPermission, requestMicrophonePermission]);

  const endCall = useCallback(async () => {
    await conversation.endSession();
  }, [conversation]);

  const isConnected = conversation.status === "connected";

  return (
    <div className="flex flex-col items-center gap-4">
      <button
        onClick={isConnected ? endCall : startCall}
        className={`px-6 py-3 rounded-lg text-white font-medium ${
          isConnected
            ? "bg-red-600 hover:bg-red-700"
            : "bg-green-600 hover:bg-green-700"
        }`}
      >
        {isConnected ? "End Call" : "Start Call"}
      </button>

      {isConnected && (
        <p className="text-sm text-gray-600">
          {conversation.isSpeaking ? "Agent speaking..." : "Listening..."}
        </p>
      )}

      {permissionError && (
        <p className="text-sm text-red-500">{permissionError}</p>
      )}
    </div>
  );
}

现在将 "<AGENT_ID>"替换为从控制台复制的实际 Agent ID。

然后在 UI 中任意位置渲染该按钮,例如:

import { CallButton } from "./CallSantaButton";

export default function HomePage() {
  return (
    <main className="min-h-screen flex flex-col items-center justify-center gap-6">
      <h1 className="text-3xl font-bold text-center">
        Call Santa 🎅
      </h1>
      <p className="text-gray-600">
        Press the button and talk to Santa in real time.
      </p>
      <CallButton />
    </main>
  );
}

6. 试试看

在浏览器中打开页面,然后点击 Start Call:

  1. 浏览器会请求麦克风权限。
  2. 系统将与圣诞老人智能体启动一个 WebRTC 会话。
  3. 你会听到:

    “呵,呵,呵!圣诞快乐,我的朋友。告诉我,你叫什么名字?”

接着,圣诞老人会询问你的名字、愿望清单,以及今年做了什么来留在乖孩子名单上。

接下来做什么

基础功能正常后,还可以:

  • 通过身份验证限制访问圣诞老人,使用智能体的 Security 设置
  • 切换语言,传入用户地区设置并由提示词处理
  • 自定义 UI 外观,添加自定义按钮、动画或完整的“呼叫圣诞老人”页面

但核心集成只需:

  • Agents Platform 中的一个智能体
  • 一个 agentId
  • 一个 useConversation Hook 和一个按钮

这样就能在 React 应用中带来实时、可对话的圣诞老人魔法体验。

相关内容

用高质量 AI 音频创作