AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Deploying Real-Time Voice Agents with Uberduck Conversational AI and LiveKit Tokens

Kim Hyuk-chul · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

For game developers building conversational non-player characters (NPCs) and interactive media creators designing virtual companions, traditional Text-to-Speech (TTS) pipelines break player immersion. Standard RESTful HTTP endpoints (POST /v1/text-to-speech) operate in half-duplex request-response mode: the client records the user's speech, sends the audio or transcribed text over HTTP, waits for server-side generation, and streams back an audio file. This round-trip loop regularly accumulates 1.5 to 3 seconds of latency. In interactive gameplay or live installation environments, a 2-second pause makes conversation feel robotic, rigid, and disconnected.

To achieve sub-second, natural dialogue, developers must move from transactional HTTP calls to a full-duplex WebRTC streaming architecture. Uberduck addresses this engineering bottleneck by integrating directly with LiveKit WebRTC infrastructure through its POST /v1/conversational/token endpoint. Instead of handling fragmented speech-to-text (STT), large language model (LLM) reasoning, and speech synthesis as discrete network hops, developers can mint an authenticated LiveKit room token pre-configured with agent personas and synthetic voices, establishing bi-directional sub-second audio streams in engines like Unity or browser-based Web frontends.

At 365Finds, our assessment is straightforward: For interactive character dialogues and virtual companions, abandoning discrete REST TTS in favor of WebRTC-backed conversational tokens is an essential architectural upgrade. While Uberduck requires paid plans for commercial licensing and careful session-timeout management to avoid running up credit usage, its unified LiveKit token pipeline reduces integration overhead by at least half compared to assembling disparate voice, reasoning, and RTC components from scratch.


Architectural Comparison: REST TTS vs. Full-Duplex WebRTC

Understanding why traditional voice pipelines stutter requires examining the network transport differences:

Metric / DimensionTraditional REST TTS PipelineUberduck + LiveKit Conversational Pipeline
Transport ProtocolHTTP/1.1 or HTTP/2 (Unidirectional / Half-Duplex)WebRTC / WebSocket (Full-Duplex Bidirectional)
Typical Round-Trip Latency1,500 ms – 3,500 ms (Noticeable lag)400 ms – 800 ms (Sub-second, conversational)
Audio TransmissionChunked or complete audio file downloads (WAV/MP3)Low-latency Opus audio stream over RTP/WebRTC
Barge-in / InterruptionDifficult to handle; requires manual request cancellationNative support; player speech instantly triggers agent turn handling
Client OverheadContinuous polling, audio buffer decoding, and state syncingManaged event-driven connection via client SDK
Target Use CasesPre-rendered narration, offline dialogue generation, cutscenesReal-time NPC dialogue, dynamic virtual companions, interactive kiosks

The Secure Token Broker Architecture

A fundamental security requirement when integrating Uberduck into public game builds is credential protection. Game binaries (especially Unity IL2CPP or WebGL builds) can be decompiled or memory-inspected, meaning you must never hardcode your Uberduck API secret inside the client.

Instead, implement a lightweight backend broker (using Node.js, Python FastAPI, or Go) between your game client and Uberduck:

  1. Player Interaction: The player approaches an NPC in Unity or triggers a voice widget in a web browser.
  2. Session Request: The game client requests a voice session from your game server (GET /api/npc-session?characterId=blacksmith).
  3. Token Minting: Your backend calls Uberduck's POST https://api.uberduck.ai/v1/conversational/token with your Bearer API key, attaching the character's persona and voice settings.
  4. Credential Handoff: Uberduck returns a server_url, a room_name, and a short-lived signed JWT participant_token.
  5. Direct WebRTC Stream: Your server hands these credentials back to the client. The client connects directly to the LiveKit WebRTC server, establishing a real-time, bi-directional audio channel.

Step 1: Minting the Conversational Token via Uberduck API

The core endpoint for conversational AI sessions in the Uberduck API specification is POST /v1/conversational/token.

Endpoint Specification

Request Payload (ConversationalTokenRequest)

The endpoint accepts three core properties:

Here is an example backend implementation in Node.js (Express / Fetch) configuring an interactive RPG blacksmith NPC:

// server.js - Token Broker Service
import express from 'express';

const app = express();
app.use(express.json());

const UBERDUCK_API_KEY = process.env.UBERDUCK_API_KEY;

app.post('/api/create-npc-session', async (req, res) => {
  try {
    const { playerId, characterId, questStatus } = req.body;

    const agentPayload = {
      identity: `player_${playerId || 'guest'}`,
      metadata: {
        character_id: characterId || 'blacksmith_dorin',
        quest_status: questStatus || 'not_started'
      },
      agent_config: {
        json: {
          prompt: "You are Dorin, an experienced dwarven blacksmith in the town of Ironford. You speak with a gruff, warm tone, keep responses concise, and never break character. Advise travelers on forging and armor repairs.",
          voice: "dorin-custom-uuid-or-voice-id",
          model: "azure_neural"
        }
      }
    };

    const response = await fetch('https://api.uberduck.ai/v1/conversational/token', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${UBERDUCK_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(agentPayload)
    });

    if (!response.ok) {
      const errDetail = await response.text();
      return res.status(response.status).json({ error: 'Failed to mint token', details: errDetail });
    }

    const tokenData = await response.json();
    // Returns { server_url, room_name, participant_token }
    return res.json(tokenData);
  } catch (error) {
    console.error('Error minting conversational token:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

app.listen(3000, () => console.log('Broker running on port 3000'));

Response Payload (ConversationalTokenResponse)

When successful, Uberduck returns HTTP status 200 with the following structure:

{
  "server_url": "wss://livekit.uberduck.ai",
  "room_name": "room_conv_9a2f1b8c",
  "participant_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Step 2: Deploying to Unity (client-sdk-unity)

For game creators building in Unity (targeting Windows, macOS, Linux, iOS, or Android), the official client-sdk-unity package provides native WebRTC bindings.

Installation

In Unity (Unity 2022.3 LTS or Unity 6), open the Package Manager (Window > Package Manager), click + > Add package from git URL..., and enter:

https://github.com/livekit/client-sdk-unity.git

(Note: For browser WebGL builds, import https://github.com/livekit/client-sdk-unity-web.git instead.)

Connecting and Streaming Audio in C#

Create a script named NpcVoiceAgentController.cs and attach it to your NPC or game manager GameObject:

using System;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using LiveKit;

public class NpcVoiceAgentController : MonoBehaviour
{
    [Header("Backend Broker Settings")]
    [SerializeField] private string brokerEndpoint = "https://your-game-server.com/api/create-npc-session";
    [SerializeField] private string characterId = "blacksmith_dorin";

    [Header("Audio Output")]
    [SerializeField] private AudioSource npcAudioSource;

    private Room room;

    [Serializable]
    private class TokenBrokerResponse
    {
        public string server_url;
        public string room_name;
        public string participant_token;
    }

    public void StartConversation(string playerId)
    {
        StartCoroutine(RequestSessionAndConnect(playerId));
    }

    private IEnumerator RequestSessionAndConnect(string playerId)
    {
        // 1. Request LiveKit session token from secure backend broker
        string requestBody = $"{{\"playerId\":\"{playerId}\",\"characterId\":\"{characterId}\"}}";
        using (UnityWebRequest req = new UnityWebRequest(brokerEndpoint, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(requestBody);
            req.uploadHandler = new UploadHandlerRaw(bodyRaw);
            req.downloadHandler = new DownloadHandlerBuffer();
            req.SetRequestHeader("Content-Type", "application/json");

            yield return req.SendWebRequest();

            if (req.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"[VoiceAgent] Broker error: {req.error} - {req.downloadHandler.text}");
                yield break;
            }

            TokenBrokerResponse sessionData = JsonUtility.FromJson<TokenBrokerResponse>(req.downloadHandler.text);
            ConnectToLiveKitRoom(sessionData.server_url, sessionData.participant_token);
        }
    }

    private async void ConnectToLiveKitRoom(string serverUrl, string token)
    {
        try
        {
            room = new Room();

            // Handle incoming remote audio tracks from the Uberduck Voice Agent
            room.TrackSubscribed += OnTrackSubscribed;

            // Connect to LiveKit WebRTC room
            await room.Connect(serverUrl, token);
            Debug.Log("[VoiceAgent] Connected to LiveKit room successfully.");

            // Publish local player microphone track
            await room.LocalParticipant.PublishMicrophone();
            Debug.Log("[VoiceAgent] Player microphone published. Full-duplex conversation active.");
        }
        catch (Exception ex)
        {
            Debug.LogError($"[VoiceAgent] LiveKit connection failed: {ex.Message}");
        }
    }

    private void OnTrackSubscribed(RemoteTrack track, RemoteParticipant participant)
    {
        if (track.Kind == TrackKind.Audio)
        {
            Debug.Log("[VoiceAgent] Subscribed to agent audio track.");
            if (npcAudioSource != null && track is AudioTrack audioTrack)
            {
                // Stream agent voice directly through the NPC 3D AudioSource
                audioTrack.StartAudioRendering(npcAudioSource);
            }
        }
    }

    public async void EndConversation()
    {
        if (room != null)
        {
            await room.Disconnect();
            room = null;
            Debug.Log("[VoiceAgent] Disconnected from session.");
        }
    }

    private void OnDestroy()
    {
        EndConversation();
    }
}

Step 3: Deploying to Web and Interactive Media

For interactive web exhibits, virtual museums, or kiosk installations running in a browser, use the standard livekit-client NPM library:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Uberduck LiveKit Web Voice Agent</title>
</head>
<body>
  <button id="start-btn">Start Voice Chat</button>
  <button id="stop-btn" disabled>End Call</button>
  <div id="status">Status: Idle</div>
  <audio id="agent-audio" autoplay></audio>

  <script type="module">
    import { Room, RoomEvent, Track } from 'https://cdn.jsdelivr.net/npm/livekit-client/dist/livekit-client.esm.mjs';

    const startBtn = document.getElementById('start-btn');
    const stopBtn = document.getElementById('stop-btn');
    const statusDiv = document.getElementById('status');
    const audioElement = document.getElementById('agent-audio');

    let room = null;

    startBtn.addEventListener('click', async () => {
      statusDiv.textContent = 'Status: Minting token...';
      try {
        const res = await fetch('/api/create-npc-session', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ playerId: 'web_visitor_1', characterId: 'docent' })
        });
        const { server_url, participant_token } = await res.json();

        room = new Room();

        // Subscribe to audio rendered by the conversational agent
        room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
          if (track.kind === Track.Kind.Audio) {
            track.attach(audioElement);
          }
        });

        statusDiv.textContent = 'Status: Connecting to WebRTC...';
        await room.connect(server_url, participant_token);

        // Enable microphone
        await room.localParticipant.setMicrophoneEnabled(true);

        statusDiv.textContent = 'Status: Conversation Active (Speak into mic)';
        startBtn.disabled = true;
        stopBtn.disabled = false;
      } catch (err) {
        statusDiv.textContent = `Error: ${err.message}`;
      }
    });

    stopBtn.addEventListener('click', async () => {
      if (room) {
        await room.disconnect();
        room = null;
      }
      statusDiv.textContent = 'Status: Disconnected';
      startBtn.disabled = false;
      stopBtn.disabled = true;
    });
  </script>
</body>
</html>

365Finds Institutional Evaluation & Practical Trade-Offs

When deploying voice agents in commercial games or production installations, 365Finds highlights several operational considerations:

1. Unified WebRTC vs. DIY Pipeline (Why We Recommend Uberduck's Approach)

Building your own pipeline by daisy-chaining OpenAI Whisper (STT) + an LLM API + ElevenLabs (TTS) requires maintaining custom WebSockets, building client-side Voice Activity Detection (VAD), and resolving interruption handling. In contrast, Uberduck’s LiveKit token endpoint packages turn-detection, media routing, and voice synthesis into a single session credential. 365Finds prefers this integrated approach for indie teams and agile media studios because it cuts development and debugging overhead significantly.

2. Managing Billable Minutes and Inactivity Disconnects

LiveKit WebRTC connections persist in real time. If a player approaches an NPC, triggers a session, and walks away without ending the conversation, the WebRTC room and conversational agent remain active, consuming monthly API credits.

3. Voice Latency vs. Expressiveness

Uberduck supports standard and neural model engines (including Polly Neural, Azure Neural, and custom cloned voices). Cloned or highly emotive custom voices add approximately 100 to 200 ms of synthesis processing compared to streamlined stock neural voices.

4. Licensing and Commercial Rights

Uberduck's Free and Starter plans are restricted to non-commercial evaluation. Deploying NPCs in a commercial game or public commercial exhibition requires a Creator plan or above, which grants commercial licensing for generated voices and access to production API features.


References