跳到内容

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

用 ElevenLabs 在 React 应用中构建实时圣诞老人 AI 语音智能体。按照本快速指南,结合 WebRTC 和 ElevenLabs Agents Platform,打造节日氛围浓厚、可互动的语音体验。

Agent Snippet

这个假期,把圣诞老人带进应用。

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

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

1. 注册并打开 Agents Platform

  1. 注册 / 登录 ElevenLabs。
  2. 在左侧边栏,打开 平台切换器(顶部)。
  3. 选择 智能体平台.

你会看到侧边栏,包含 智能体, 知识库, 工具音色(在“构建”分区下)。

2. 创建圣诞老人智能体

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

  1. 在侧边栏点击 智能体.
  2. 点击 + 新建智能体.
  3. 选择 空白智能体,从零开始。

命名为:Santa。

系统提示词

系统提示词 字段粘贴以下内容:

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.

首条消息

首条消息 设置为:

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

用户开始通话时会听到这句话。

音色

音色 部分:

  • 选择 “Jerry B. – 圣诞老人”
  • 音色 ID:MDLAMJ0jxkpYkjXbmG4t

现在圣诞老人会真正听起来像圣诞老人了。

安全

本示例保持开放:

  • 安全 下,确保 启用身份验证关闭.

首次演示时,保持 启用身份验证 关闭即可,任何人都能无门槛接入智能体。这样上手更快,适合原型、黑客松或内部演示。

但对于任何生产环境或对外应用,绝不能让智能体保持开放。应使用 ElevenLabs 令牌端点 为每个用户会话生成短时限、限定权限的访问令牌。这样可完全控制谁能接入、访问时长及可执行操作。启用身份验证可防止未授权访问、滥用或超出预期范围的使用——上线前强烈建议开启。

3. 获取智能体 ID

在智能体页面顶部可看到 智能体 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>" 为刚才从控制台复制的实际智能体 ID。

然后在界面合适位置渲染该按钮,例如:

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. 试用效果

在浏览器中打开并点击 开始通话:

  1. 浏览器会请求 麦克风权限.
  2. 将与圣诞老人智能体建立 WebRTC 会话。
  3. 你会听到:

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

接下来,圣诞老人会询问姓名、心愿单,以及今年做了哪些好事。

下一步可以做什么

基础功能跑通后,你可以:

  • 用身份验证限制访问(通过智能体安全设置)
  • 切换语言(传递用户语言,让提示词自动适配)
  • 自定义界面(自定义按钮、动画或完整“呼叫圣诞老人”界面)

但核心集成其实只需:

  • Agents Platform 中一个智能体智能体平台
  • 一个 agentId
  • 一个 useConversation hook 和一个按钮

这样就能把实时对话的圣诞老人体验带进 React 应用了。

查看更多 ElevenLabs 团队的文章

用高质量 AI 音频创作