Presentiamo Eleven v4Scopri Eleven v4, il nostro modello più espressivo di sempre.

Vai al contenuto

Aggiungi un Agente Voce di Babbo Natale alla tua app React in pochi minuti

Pubblicato

AscoltaAscolta questo articolo

Durante queste feste, aggiungi Babbo Natale alla tua app.

Con Agents Platform di ElevenLabs e l'SDK @elevenlabs/react, puoi integrare un agente vocale di Babbo Natale nella tua app React in pochi minuti. In questa guida:

  1. Crea un agente di Babbo Natale nella dashboard di ElevenLabs
  2. Collegalo a un componente React con WebRTC
  3. Aggiungi un semplice pulsante “Chiama Babbo Natale”

1. Registrati e apri Agents Platform

  1. Registrati / accedi a ElevenLabs.
  2. Nella barra laterale sinistra, apri il selettore della piattaforma in alto.
  3. Scegli Agents Platform.

Vedrai una barra laterale con Agenti, Knowledge Base, Strumenti e Voci nella sezione “Crea”.

2. Crea il tuo agente di Babbo Natale

Ora creeremo un agente che si comporta come Babbo Natale e parla con la sua voce.

  1. Nella barra laterale, fai clic su Agenti.
  2. Fai clic su + Nuovo agente.
  3. Scegli Agente vuoto per iniziare da zero.

Assegnagli il nome: Santa.

Prompt di sistema

Nel campo Prompt di sistema, incolla quanto segue:

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.

Primo messaggio

Imposta Primo messaggio su:

Ho, ho, ho! Buon Natale, amico mio. Dimmi, come ti chiami?

È ciò che gli utenti sentiranno all'inizio della chiamata.

Voce

Nella sezione Voce:

  • Scegli “Jerry B. – Babbo Natale”
  • ID della voce: MDLAMJ0jxkpYkjXbmG4t

Ora Babbo Natale suonerà davvero come Babbo Natale.

Sicurezza

Per questo esempio, lo lasceremo aperto:

  • In Sicurezza, assicurati che Abilita autenticazione sia disattivato.

Per la tua prima demo, puoi tranquillamente lasciare Abilita autenticazione disattivato, così chiunque potrà connettersi all'agente senza restrizioni. Questo rende l'onboarding più rapido ed è ideale per prototipi veloci, progetti di hackathon o presentazioni interne.

Tuttavia, per qualsiasi applicazione in produzione o accessibile dall'esterno, non dovresti mai lasciare aperto il tuo agente. Usa invece il Token Endpoint di ElevenLabs per generare token di accesso con ambito definito e di breve durata per ogni sessione utente. In questo modo mantieni il pieno controllo su chi può connettersi, sulla durata dell'accesso e sulle azioni che l'utente può eseguire. Abilitare l'autenticazione protegge il tuo agente da chiamate non autorizzate, abusi o utilizzi oltre i limiti previsti — ed è fortemente consigliato prima della pubblicazione.

3. Recupera l'ID dell'agente

In alto nella pagina dell'agente, vedrai un campo ID dell'agente.

Prendi nota di questo valore — lo inseriremo in un componente React in un passaggio successivo:

agentId: "<AGENT_ID>"

4. Installa l'SDK React

Nel tuo progetto React / Next.js, installa l'SDK React di ElevenLabs:

npm install @elevenlabs/react

A questo punto, possiamo usare l'hook useConversation per avviare e terminare le chiamate vocali.

5. Aggiungi il pulsante "Chiama Babbo Natale"

Crea un nuovo componente, ad esempio CallSantaButton.tsx, e incolla questo codice:

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

Ora sostituisci "<AGENT_ID>" con l'ID dell'agente effettivo che hai copiato dalla dashboard.

Poi visualizza il pulsante in un punto della tua UI, ad esempio:

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. Provalo

Apri l'app nel browser e fai clic su Avvia chiamata:

  1. Il browser ti chiederà l'autorizzazione per il microfono.
  2. Viene avviata una sessione WebRTC con il tuo agente di Babbo Natale.
  3. Sentirai:

    “Ho, ho, ho! Buon Natale, amico mio. Dimmi, come ti chiami?”

Da lì, Babbo Natale ti chiederà il tuo nome, la lista dei desideri e cosa hai fatto quest'anno per restare nella Lista dei Buoni.

Prossimi passi

Una volta che le basi funzionano, puoi:

  • Proteggere Babbo Natale con l'autenticazione usando le impostazioni di sicurezza dell'agente
  • Cambiare lingua passando la lingua dell'utente e lasciando che il prompt la gestisca
  • Personalizzare la UI con pulsanti personalizzati, animazioni o una schermata completa “Chiama Babbo Natale”

Ma l'integrazione essenziale è semplicemente:

  • Un agente nella Agents Platform
  • Un agentId
  • Un hook useConversation e un pulsante

È tutto ciò che ti serve per portare la magia conversazionale di Babbo Natale in tempo reale nella tua app React.

Articoli simili

Crea con l'audio IA della massima qualità