Realtime Voice Agent

advanced15 minrealtime-voice-agent.ts

The same WebSocket server, but backed by a realtime model with server-side tools.

What it shows

  • Run VoiceAgent in realtime mode on Gemini Live
  • Give the model the agent's own tools through createCogitatorRunner, approval included
  • Talk to it from a WebSocket client

The code

realtime-voice-agent.ts
import { Agent, Cogitator, tool } from '@cogitator-ai/core';
import { createCogitatorRunner, VoiceAgent } from '@cogitator-ai/voice';
import { WebSocket } from 'ws';
import { z } from 'zod';

const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');

const openingHours = tool({
  name: 'get_opening_hours',
  description: 'Opening hours of the office for a given weekday',
  parameters: z.object({ day: z.string().describe('Weekday name') }),
  execute: async ({ day }) => ({
    day,
    open: '09:00',
    close: day.toLowerCase() === 'friday' ? '15:00' : '18:00',
  }),
});

const bookRoom = tool({
  name: 'book_meeting_room',
  description: 'Book the meeting room for a weekday',
  parameters: z.object({ day: z.string().describe('Weekday name') }),
  requiresApproval: true,
  execute: async ({ day }) => ({ booked: day }),
});

const cogitator = new Cogitator();
const concierge = new Agent({
  name: 'concierge',
  instructions: 'You are a concise voice concierge. Use tools when they help.',
  tools: [openingHours, bookRoom],
});
const voiceAgent = new VoiceAgent({
  mode: 'realtime',
  agent: createCogitatorRunner(cogitator, concierge),
  realtimeProvider: 'gemini',
  realtimeApiKey: apiKey,
  voice: 'Puck',
  agentTools: {
    onApproval: async (request) => {
      console.log(`Approving ${request.toolName}(${JSON.stringify(request.arguments)})`);
      return { approved: true };
    },
  },
});
voiceAgent.on('error', (error) => console.error(error.message));
await voiceAgent.listen(0);

const client = new WebSocket(`ws://localhost:${voiceAgent.port}/voice`);
let audioBytes = 0;
const answered = new Promise<void>((resolve) => {
  client.on('message', (data, isBinary) => {
    if (isBinary) {
      audioBytes += (data as Buffer).length;
      return;
    }
    const event = JSON.parse(data.toString()) as { type: string; text?: string; role?: string };
    if (event.type === 'transcript') console.log(`[${event.role}] ${event.text}`);
    if (event.type === 'turn_end' && audioBytes > 0) resolve();
  });
});
await new Promise<void>((resolve) => client.once('open', () => resolve()));

client.send(
  JSON.stringify({
    type: 'text',
    text: 'When does the office close on Friday? Book the meeting room for that day too.',
  })
);
await Promise.race([answered, new Promise((resolve) => setTimeout(resolve, 30_000))]);
console.log(`Received ${audioBytes} bytes of PCM16 24kHz audio`);

client.close();
await voiceAgent.close();
await cogitator.close();

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/voice ws zod
EnvironmentGOOGLE_API_KEY
run · bash
GOOGLE_API_KEY=your-key npx tsx realtime-voice-agent.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/voice/04-realtime-voice-agent.ts

Learn more