返回內容列表

Call Santa Claus

Build a Santa video call with Agora Conversational AI and LiveAvatar.

Web / TypeScript進階zicojiao
Call Santa Claus title beside a real-device Santa video call showing a timer, camera toggle, mute and hang-up controls

實踐教程

本教程目錄

文檔語言:English · 暫無所選語言,當前展示作者提供的可用版本。

Build a Santa video call with Agora Conversational AI and LiveAvatar

English · 简体中文

Christmas is coming. Build a Santa calling app for your own children, so they can share their Christmas wishes and hear Santa reply.

This recipe uses Agora Conversational AI for real-time conversation and LiveAvatar to bring Santa on screen. Follow the implementation from creating an agent to playing its media and ending the session safely.

Try Call Santa Claus · Get the source code · Account setup and installation

Santa video call on a phone with mute and hang-up controls

1. Define what a successful call means

The caller can tell Santa a Christmas wish, hear a short reply, interrupt, and say goodbye. Video adds a moving Santa, not a second independent conversation. The local camera preview is optional and never published.

Follow this guide after setting up the repository. You need an Agora project with Conversational AI access; the checked-in voice configuration also needs an ElevenLabs key. Video additionally needs a LiveAvatar key, an accessible real-time avatar and credits. The README covers those accounts and commands; this guide focuses on implementation. Examples follow the locked agora-agents 2.9.0 API in this repository.

Checkpoint: first run voice locally with your own credentials. Treat a visible page, successful API response, audible reply and decoded video frame as four separate observations.

2. Separate session control from real-time media

正在加載圖示…

圖示源碼
sequenceDiagram
  participant B as Browser
  participant W as Worker / Family
  participant A as Agora Conversational AI
  participant V as LiveAvatar
  B->>W: Start call
  W->>W: Validate input and reserve quota
  W->>A: Create agent session
  W-->>B: Channel, caller UID, short-lived token, media UID
  B->>A: Microphone over Agora RTC
  A-->>B: Voice reply over Agora RTC
  opt Video mode
    A->>V: Synthesized speech
    V-->>B: Avatar audio/video over Agora RTC
  end
  B->>W: Heartbeat / hangup
  W->>A: Stop agent and settle minutes

The browser owns permission and playback. The Worker creates the Agora session. A Cloudflare Durable Object owns the app's minutes and active-call record. Media travels through Agora RTC; it does not pass through a React API handler.

In api.ts, a signed HttpOnly cookie selects a browser's Family object, and POST requests must have the expected origin. In family.ts, the start operation validates input, checks remaining time, and reserves browser/network quota before creating an agent. A serial queue prevents two starts from racing in the same object without holding Cloudflare's initialization lock over slow provider calls.

Why: a UI button cannot enforce one active session or settle usage when a tab disappears. Those decisions need a server owner. The cookie is a browser identity, not a recoverable account or strong protection against a determined attacker.

Checkpoint: issue two start requests for the same browser. The second must not create a second active agent. Cancel during setup and check that any completed session is stopped.

3. Compose the agent, then start one session

agora.ts creates an AgoraClient using the App ID and App Certificate, then an Agent with its greeting, character instructions and turn-detection configuration. The chain attaches managed speech recognition and language-model providers; tts.ts supplies the configured voice.

The important transition is from an agent configuration to one running session. This excerpt is taken from startAgent; its variables are defined earlier in that function:

ts
const configured = input.mode === "video"
    ? agent.withTts(elevenLabsTts(env, input.character)).withAvatar(santaAvatar(env))
    : agent.withTts(characterTts(env, input.character));
  const session = configured.createSession({
    channel,
    agentUid: AGENT_UID,
    remoteUids: [uid],
    idleTimeout: 25,
    expiresIn: ExpiresIn.hours(1),
    debug: false,
  });
  const agentId = await session.start();

remoteUids identifies the caller the agent should hear. AGENT_UID is the agent's control identity. In video mode, the avatar publishes media under a different UID. After session.start(), the server generates a caller RTC/RTM token scoped to that channel; the App Certificate and provider keys never go to the browser. If token creation fails after startup, the code stops the newly created agent.

The one-hour session credential expiry is not the app's call duration. Family enforces maxSeconds; demo-policy.json supplies the example video budget.

Checkpoint: inspect a start response: it should contain channel/UID/token/session data, not provider keys. Then hang up and confirm the corresponding agent stops. Never paste those temporary tokens into logs or screenshots.

4. Make character behavior server configuration

character-conversation.ts provides a minimal Christmas role example and per-character server overrides for instructions and greetings. The default asks for a friendly, brief conversation; it is not the production-tuned script.

Define your own character with server-only SANTA_SYSTEM_PROMPT and SANTA_GREETING, using MRS_* / COMET_* for the other characters. See the configuration guide. Keep tuned prompts out of browser code, test snapshots and public repositories.

Optional names and wishes are appended as JSON context, not new instructions, and internal profile IDs are omitted. Basic boundaries remain: no real gift promises, contact-detail requests or claims to see the camera. A prompt cannot guarantee every model response.

Checkpoint: check the default role, server overrides, language selection and input-data separation. Then test your own character behavior with real speech.

5. Coordinate pauses, ringback and interruption

This focused example shows how agora.ts applies optional settings; the complete agent also enables its media and messaging features:

ts
const settings = agentSettings(env);
const agent = new Agent({
  client: agora(env),
  instructions,
  greeting,
  ...settings.history,
  ...settings.turns,
});

agent-settings.ts adds VAD/generation settings only when the operator supplies valid values. Empty values leave SDK/provider defaults in place; production tuning is not embedded. Shorter silence or interruption windows can improve responsiveness but can also increase accidental interruptions, so validate on your own devices and network.

VoiceCall.tsx subscribes to the toolkit's transcript and interruption events. Transcripts stay internal: they help identify a finished user turn, ignore an interrupted reply, and coordinate a goodbye. No transcript panel is rendered. The conversation watchdog distinguishes missing first audio, blocked playback and a delayed reply.

Ringback starts from the user's call action. Remote speech activity stops it; teardown and playback-blocked recovery also stop it. A remote audio track can exist before any audible greeting, so “track published” must not be treated as proof that the caller heard Santa.

Checkpoint: check silence before the greeting, microphone denial, autoplay blocking, speaking over Santa and a pause mid-sentence. Confirm the ringback does not continue over Santa's reply or after closing the call.

6. Add an avatar without mixing up media identities

avatar.ts returns this adapter after checking configuration:

ts
return new LiveAvatarAvatar({
    apiKey: env.LIVEAVATAR_API_KEY!, avatarId: env.SANTA_AVATAR_ID!,
    agoraUid: AVATAR_UID, quality: "high", activityIdleTimeout: VIDEO_MAX_SECONDS,
    // The SDK mints the avatar's separate RTC token using the server certificate.
  });

The agent control UID is 123456; the avatar media UID is 123457. The server returns the selected mediaUid to the browser. The media subscription guard in VoiceCall.tsx is:

ts
if (String(user.uid) !== mediaUid || disposed || finished || (type !== 'audio' && type !== 'video')) return;
await rtc.subscribe(user, type);

In video mode, subscribe to the avatar's audio and video, while agent messages still belong to the agent control identity. Subscribing to both audio publishers can produce duplicate speech. The configured TTS supplies 24 kHz audio, and the SDK generates the avatar's separate Agora token from the server certificate.

The screen keeps its waiting portrait until first-frame-decoded. A track announcement alone is not a visible video frame. LocalCamera separately owns the optional local MediaStream: it is never published, and late permission results are stopped if the caller has already closed the view.

Checkpoint: check lip movement and one audible voice, then end the call while a camera permission prompt is still open. Granting permission afterward must not leave a camera running. A provider balance check is only a readiness hint; it does not reserve capacity.

7. End the call even if the browser disappears

正在加載圖示…

圖示源碼
stateDiagram-v2
  [*] --> Preparing
  Preparing --> Connecting: microphone granted / session reserved
  Preparing --> Ended: denied or cancelled
  Connecting --> Active: remote audio track subscribed
  Connecting --> Ended: startup deadline or failure
  Active --> Recovering: temporary connection loss
  Recovering --> Active: same session restored
  Recovering --> Ended: recovery deadline
  Active --> Ended: goodbye, hangup or time limit
  Ended --> [*]: stop agent and tracks / settle time

A normal hangup calls the server; heartbeats and Durable Object alarms cover lost tabs and connections. family.ts records an ending state, stops the Agora agent, settles quota, writes remaining minutes and removes the active session. Failed cleanup is retried by an alarm.

Billing uses a bounded duration in billing.ts:

ts
  if (connected === undefined) return 0;
  return Math.max(
    0,
    Math.min(
      maxSeconds,
      Math.ceil((Math.min(ended, lastSeen + 8000) - connected) / 1000),
    ),
  );

An unconnected call uses zero app minutes. Connected usage is bounded by the call limit and the last heartbeat plus an eight-second grace. In the current implementation, connection timing starts with remote audio subscription; first audible audio is detected separately to stop ringback and manage playback. App minutes are not a copy of provider billing, and this rule cannot guarantee zero provider charges during failed setup.

Checkpoint: hang up normally, close the tab, briefly go offline and exhaust the call duration. Check that the agent is eventually stopped and retries do not double-settle a session. A finite reconnect window should recover the same session, not silently buy another call.

8. Validate and build your own character experience

ScenarioWhat to observe
Voice conversationOne spoken wish receives one understandable reply.
InterruptionThe old answer stops and the next response follows the new input.
VideoA decoded moving frame and one audio stream; no duplicated speech.
Temporary disconnectBounded recovery or a clear end state, without an extra agent.
Permission/playback failureA relevant recovery action; no endlessly ringing screen.
Hangup/tab exitMicrophone, local camera and server session are cleaned up.
Exhausted quota/provider capacityA useful failure state without claiming connection success.

Automated tests cover state helpers, avatar serialization and other bounded behavior; they do not prove these live-media observations. Use the README's local and deployment steps and record which scenarios you actually tested on your own accounts and devices. This tutorial does not claim measured latency, guaranteed lip sync or physical-device coverage.

To build a different experience, change the character prompt first, then choose voices and an avatar you can use. Keep the same session ownership, media separation and cleanup boundaries. Get the full source code and adapt it for your friends or family.

References: Agora managed mode · LiveAvatar integration.