Presentamos Eleven v4Conoce Eleven v4, nuestro modelo más expresivo hasta la fecha.

Ir al contenido

Añade un agente de voz de Papá Noel a tu app React en minutos

Publicado

EscucharEscucha este artículo

Estas fiestas, añade a Papá Noel a tu app.

Con la Plataforma de Agentes de ElevenLabs y el SDK @elevenlabs/react, puedes incorporar un agente de voz de Papá Noel a tu app de React en solo unos minutos. En esta guía aprenderás a:

  1. Crear un agente de Papá Noel en el panel de control de ElevenLabs
  2. Conectarlo en un componente de React con WebRTC
  3. Añadir un sencillo botón «Llamar a Papá Noel»

1. Regístrate y abre la Plataforma de Agentes

  1. Regístrate o inicia sesión en ElevenLabs.
  2. En la barra lateral izquierda, abre el selector de plataforma de la parte superior.
  3. Selecciona Plataforma de Agentes.

Deberías ver una barra lateral con Agentes, Base de conocimiento, Herramientas y Voces en la sección «Crear».

2. Crea tu agente de Papá Noel

Ahora crearemos un agente que se comporte como Papá Noel y hable con una voz de Papá Noel.

  1. En la barra lateral, haz clic en Agentes.
  2. Haz clic en + Nuevo agente.
  3. Selecciona Agente en blanco para empezar desde cero.

Llámalo: Santa.

Prompt del sistema

En el campo Prompt del sistema, pega lo siguiente:

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.

Primer mensaje

Establece Primer mensaje como:

¡Jo, jo, jo! Feliz Navidad, amigo mío. Dime, ¿cómo te llamas?

Esto es lo que oirán usuarios cuando empiece la llamada.

Voz

En la sección Voz:

  • Selecciona «Jerry B. – Santa Claus»
  • ID de voz: MDLAMJ0jxkpYkjXbmG4t

Ahora Papá Noel sonará de verdad como Papá Noel.

Seguridad

Para este ejemplo, lo dejaremos abierto:

  • En Seguridad, asegúrate de que Activar autenticación esté desactivada.

Para tu primera demo, puedes dejar Activar autenticación desactivada para que cualquiera pueda conectarse al agente sin restricciones. Así, la incorporación es más rápida y resulta ideal para prototipos rápidos, proyectos de hackathon o presentaciones internas.

Sin embargo, para cualquier aplicación de producción o accesible externamente, nunca debes dejar abierto tu agente. En su lugar, utiliza el endpoint de token de ElevenLabs para generar tokens de acceso de corta duración y alcance limitado para cada sesión de usuario. Así mantendrás un control total sobre quién puede conectarse, cuánto dura el acceso y qué acciones puede realizar el usuario. Activar la autenticación protege tu agente frente a llamadas no autorizadas, abusos o usos fuera de los límites previstos, y es muy recomendable antes de lanzar la aplicación.

3. Obtén el ID de tu agente

En la parte superior de la página del agente, verás un campo ID de agente.

Anota este valor; lo pegaremos en nuestro componente de React en un paso posterior:

agentId: "<AGENT_ID>"

4. Instala el SDK de React

En tu proyecto de React / Next.js, instala el SDK de React de ElevenLabs:

npm install @elevenlabs/react

Con esto listo, podemos usar el hook useConversation para iniciar y finalizar llamadas de voz.

5. Añade el botón «Llamar a Papá Noel»

Crea un componente nuevo, por ejemplo, CallSantaButton.tsx, y pega este código:

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

Ahora sustituye "<AGENT_ID>" por el ID de agente real que copiaste del panel de control.

Después, muestra el botón en algún lugar de tu interfaz, por ejemplo:

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. Pruébalo

Ábrelo en tu navegador y haz clic en Iniciar llamada:

  1. Tu navegador solicitará permiso para usar el micrófono.
  2. Se iniciará una sesión de WebRTC con tu agente de Papá Noel.
  3. Oirás:

    «¡Jo, jo, jo! Feliz Navidad, amigo mío. Dime, ¿cómo te llamas?»

A partir de ahí, Papá Noel te preguntará tu nombre, tu lista de deseos y qué has hecho este año para seguir en la lista de niños buenos.

Siguientes pasos

Cuando tengas lo básico funcionando, puedes:

  • Proteger a Papá Noel con autenticación mediante los ajustes de seguridad del agente
  • Cambiar de idioma pasando la configuración regional del usuario y dejando que el prompt se encargue
  • Personalizar la interfaz con botones personalizados, animaciones o una pantalla completa para «Llamar a Papá Noel»

Pero la integración principal solo requiere:

  • Un agente en la Plataforma de Agentes
  • Un agentId
  • Un hook useConversation y un botón

Eso es todo lo que necesitas para llevar la magia conversacional de Papá Noel en tiempo real a tu app de React.

Artículos relacionados

Crea con el audio IA de la más alta calidad