Cogitator
Voice

Realtime Mode

Native speech-to-speech with RealtimeSession — connect to OpenAI Realtime API or Gemini Live API for low-latency voice conversations with tool calling support.

Overview

Realtime mode bypasses the STT -> Agent -> TTS pipeline entirely. Instead, the LLM directly processes incoming audio and generates audio responses. This results in lower latency and more natural prosody, since the model controls the voice output directly.

RealtimeSession is a unified interface over two provider-specific adapters:

  • OpenAI Realtime API (GA) — WebSocket connection to gpt-realtime-2.1-mini with server-side VAD, input transcription and tool calling
  • Gemini Live API — WebSocket connection to gemini-3.8-live with native audio, input/output transcription and tool calling

RealtimeSession

The main class for realtime voice interaction. It wraps the provider-specific adapter and exposes a consistent event-based API.

import { RealtimeSession } from '@cogitator-ai/voice';

const session = new RealtimeSession({
  provider: 'openai',
  apiKey: process.env.OPENAI_API_KEY!,
  model: 'gpt-realtime-2.1-mini',
  voice: 'marin',
  instructions: 'You are a helpful assistant.',
});

Connecting

await session.connect();

Opens a WebSocket connection to the provider. For OpenAI, this sends a GA session.update (type: 'realtime', audio formats, voice, transcription, instructions, tools). For Gemini, this sends a setup message with model config, transcription and tools and resolves on setupComplete. A failed connection rejects without emitting error.

Audio and text sent before connect() resolves are queued (audio capped at 1MB) and flushed in order once the session is ready.

Sending Audio

session.pushAudio(pcm16Chunk);

Send PCM16 mono frames — 24kHz for OpenAI, 16kHz for Gemini. Both providers handle VAD server-side — they detect when the user starts and stops speaking. Model audio is always PCM16 24kHz.

Sending Text

session.sendText('Hello!');

Send a text message instead of audio. The model responds with audio.

Interruption

session.interrupt();

Cancel the current response. For OpenAI, sends response.cancel (only while a response is active). Gemini barge-in is driven by user audio, so interrupt() drops the remaining model audio of the current turn locally; when Gemini detects the user talking over the model it reports interrupted and the session emits speech_start.

Closing

session.close();

Closes the WebSocket connection and drops queued input; a closed session cannot reconnect. session.provider and session.isConnected report its state. The provider adapters (OpenAIRealtimeAdapter, GeminiRealtimeAdapter) are exported for direct use.

Events

session.on('connected', () => {
  console.log('WebSocket connected');
});

session.on('audio', (chunk: Buffer) => {
  playAudio(chunk);
});

session.on('transcript', (text: string, role: 'user' | 'assistant') => {
  console.log(`${role}: ${text}`);
});

session.on('speech_start', () => {
  console.log('Server VAD: speech detected');
});

session.on('tool_call', (name: string, args: unknown) => {
  console.log(`Tool called: ${name}`, args);
});

session.on('error', (error: Error) => {
  console.error('Realtime error:', error);
});
EventPayloadDescription
connected—Session ready (OpenAI socket open / Gemini setupComplete)
disconnected(code, reason)Connection closed after it was established
audio(chunk: Buffer)Audio response chunk from the model (PCM16 24kHz)
transcript(text, role)Full transcription of a user or assistant turn
speech_start—Server-side VAD detected speech / user barged in
tool_call(name, args)Model invoked a tool
turn_end—Model finished its turn
error(error: Error)Connection or processing error

OpenAI Realtime API

Default model: gpt-realtime-2.1-mini (also gpt-realtime-2.1). Connects via WebSocket to wss://api.openai.com/v1/realtime using the GA interface (the beta OpenAI-Beta: realtime=v1 interface was shut down in May 2026).

const session = new RealtimeSession({
  provider: 'openai',
  apiKey: process.env.OPENAI_API_KEY!,
  model: 'gpt-realtime-2.1-mini',
  voice: 'marin',
  instructions: 'You are a friendly assistant who speaks concisely.',
  tools: [
    {
      name: 'get_weather',
      description: 'Get current weather for a city',
      parameters: {
        type: 'object',
        properties: { city: { type: 'string' } },
        required: ['city'],
      },
      execute: async (args) => {
        const { city } = args as { city: string };
        return { temperature: 72, unit: 'F', city };
      },
    },
  ],
});

await session.connect();
session.pushAudio(pcm16Chunk);

OpenAI Features

  • Server-side VAD — OpenAI handles turn detection, emits speech_start events
  • Tool calling — all function calls of a completed response are executed, their outputs sent back, then a single follow-up response is requested; unknown tools and invalid arguments are answered with an error output
  • Transcription — user speech transcripts (gpt-live-transcribe) and the model's audio transcripts via the transcript event
  • Audio format — PCM16 24kHz input and output

OpenAI Voices

alloy, ash, ballad, coral, echo, sage, shimmer, verse, marin (default), cedar

Gemini Live API

Default model: gemini-3.8-live (also gemini-3.1-flash-live-preview). Connects via WebSocket to the Gemini Developer API BidiGenerateContent endpoint, authenticating with the x-goog-api-key header.

const session = new RealtimeSession({
  provider: 'gemini',
  apiKey: process.env.GOOGLE_API_KEY!,
  model: 'gemini-3.8-live',
  voice: 'Puck',
  instructions: 'You are a helpful assistant.',
  tools: [
    {
      name: 'search',
      description: 'Search the web',
      parameters: {
        type: 'object',
        properties: { query: { type: 'string' } },
      },
      execute: async (args) => {
        const { query } = args as { query: string };
        return { results: [`Result for: ${query}`] };
      },
    },
  ],
});

await session.connect();
session.pushAudio(pcm16Chunk);

Gemini Features

  • Native audio generation — model generates audio directly
  • Transcription — input and output audio transcription is enabled; streamed fragments are emitted as one transcript per turn (user first, then assistant). Model "thought" parts are never emitted
  • Tool calling — function declarations sent during setup, structured results ({ result } / { error }) returned via toolResponse
  • Tool call cancellation - when the user talks over a turn with a pending call, Gemini cancels it with toolCallCancellation: its signal aborts and it gets no answer. The 2.5 native audio models do this. On the 3.x Live models a call blocks the turn and is never cancelled: the model answers what the user says next while the call keeps running, and its answer is sent when it is ready
  • Audio format — PCM16 16kHz input (realtimeInput.audio), PCM16 24kHz output

Gemini Voices

Puck, Charon, Kore, Fenrir, Aoede

Provider Comparison

FeatureOpenAI RealtimeGemini Live
Default modelgpt-realtime-2.1-minigemini-3.8-live
Server-side VADYesYes
Tool callingYesYes
User transcriptsYesYes
Text inputYesYes
Interruptionresponse.cancelLocal audio drop; server interrupted on barge-in
Input audioPCM16 24kHzPCM16 16kHz
Output audioPCM16 24kHzPCM16 24kHz
Default voicemarinPuck

Realtime with VoiceAgent

Use VoiceAgent to expose a realtime session over WebSocket transport:

import { VoiceAgent, createCogitatorRunner } from '@cogitator-ai/voice';

const voiceAgent = new VoiceAgent({
  agent: createCogitatorRunner(cogitator, agent),
  mode: 'realtime',
  realtimeProvider: 'openai',
  realtimeApiKey: process.env.OPENAI_API_KEY!,
  realtimeModel: 'gpt-realtime-2.1-mini',
  voice: 'marin',
  agentTools: {
    onApproval: async (request) => ({ approved: await askOperator(request) }),
  },
});

await voiceAgent.listen(8080);

Each WebSocket client gets its own RealtimeSession. The session instructions come from instructions or, if unset, from agent.instructions, and tools are executed server-side. The model talks to the user directly - agent.run() is not called in realtime mode, so the Cogitator agent's memory is not used.

Without tools, the model gets the agent's own tools from agent.realtimeTools(). This is on by default: a realtime VoiceAgent built with createCogitatorRunner() exposes the agent's tools to the model, and agentTools: false keeps it without tools. A createCogitatorRunner() runner builds them with createRealtimeTools and the agent, so every call goes through cogitator.invokeTool with the gates a text run of the agent applies: schema validation, approvals, the guardrails (built with the agent's model unless guardrails.model is set, as for a text run), the agent's wrapToolCall middleware after the Cogitator's, the sandbox and tool.timeout. The tools see the agent's id and the session's thread (voice:<sessionId>, or the runner's threadId resolver).

What differs from a text run:

  • a tool with requiresApproval runs only when agentTools.onApproval or guardrails.onToolApproval approves the call, otherwise it is refused and the model reads that it needs approval
  • a realtime session sets no maxIterations: the model may call tools as often as it likes
  • a runtime without invokeTool (a custom CogitatorLike) gets no tools from the bridge

agentTools takes the options of createRealtimeTools: onApproval(request, context) gets the call's agentId, threadId and userId in the request and its sessionId and callId in the context, and userId is a string or a function of the call's context. Explicit tools always win, and tools: [] gives the model none.

Audio from the client is forwarded to the realtime API, and audio/transcript/speech_start/turn_end events are forwarded back. Clients can send { type: 'text', text } and { type: 'interrupt' } control messages. If the provider connection fails or drops, the client is closed with code 1011.

RealtimeSessionConfig

FieldTypeRequiredDescription
provider'openai' | 'gemini'YesRealtime API provider
apiKeystringYesAPI key
modelstringNoModel override
instructionsstringNoSystem instructions
voicestringNoVoice name (default: marin for OpenAI, Puck for Gemini)
toolsArray<RealtimeTool>NoTools the model can invoke
sessionIdstringNoId handed to tools as context.sessionId (VoiceAgent sets the client id)
toolImagesbooleanNoSend images that tools return to the model (default false), see Tool Results
audioFormat'pcm' | 'pcmu'Nopcm (default) is PCM16 at the provider's rates, pcmu is G.711 μ-law 8kHz in both directions

VoiceAgentConfig takes toolImages too and passes it to every realtime session it opens.

With audioFormat: 'pcmu' the session takes and gives the audio of a phone call. OpenAI Realtime handles audio/pcmu natively, without transcoding. Gemini Live takes PCM16, so the adapter decodes the μ-law and resamples it to 16kHz with a band-limited filter, and resamples the model's 24kHz audio to 8kHz μ-law. A VoiceAgent serving a Twilio call sets it for you.

RealtimeTool

interface RealtimeTool {
  name: string;
  description: string;
  parameters: Record<string, unknown>;
  execute: (args: unknown, context: RealtimeToolContext) => Promise<unknown>;
  maxResultLength?: number; // characters of the result the model reads (default 100000)
}

interface RealtimeToolContext {
  callId: string; // the provider's id of the call
  signal: AbortSignal; // aborts when the session closes or drops, or Gemini cancels the call
  sessionId?: string; // RealtimeSessionConfig.sessionId
}

A call still running when the session closes or loses its connection has its signal aborted, and its answer is not sent.

Tool Results

A plain result reaches the model as a JSON string with OpenAI and as { result: value } in the function response with Gemini. A result made of parts, a toolContent() result or an object with a base64 image such as a browser screenshot, reaches the model as the text of its parts instead of a JSON string full of base64: text, JSON and text resources as they are, every image and file as a one-line description such as [image/png image, 182.4 KB]. The text is cut to the tool's maxResultLength (default 100 000 characters) the way a run cuts it, keeping the start and the end (see Result Size), and a plain result whose JSON is longer than that is cut the same way, sent to Gemini as the cut JSON text.

import { toolContent } from '@cogitator-ai/core';

const lookAtScreen: RealtimeTool = {
  name: 'look_at_screen',
  description: 'Take a screenshot of the shared screen',
  parameters: { type: 'object', properties: {} },
  execute: async () =>
    toolContent(
      { type: 'text', text: 'The shared screen right now' },
      { type: 'image', data: await captureScreen(), mediaType: 'image/png' }
    ),
};

const session = new RealtimeSession({
  provider: 'openai',
  apiKey: process.env.OPENAI_API_KEY!,
  model: 'gpt-realtime-2',
  tools: [lookAtScreen],
  toolImages: true,
});

With toolImages: true the model also gets the PNG, JPEG, GIF and WebP images themselves, for a model that takes images as input. Images in other formats stay described. OpenAI gets a user message with input_image parts right after the turn's tool outputs (gpt-realtime and gpt-realtime-2 take images), Gemini gets them as parts: [{ inlineData: { mimeType, data } }] of the function response (Gemini 3 models). Leave it off for models without image input, which then read only the descriptions.

Cogitator Tools

createRealtimeTools(cogitator, tools, options) turns Cogitator tools into realtime tools whose calls run through cogitator.invokeTool, the way an agent run executes them: the arguments checked against the tool's schema, approval asked for calls that need it, the guardrails applied, sandboxed tools run in the sandbox and tool.timeout kept. The call's signal cancels it.

import { Cogitator, tool } from '@cogitator-ai/core';
import { createRealtimeTools, RealtimeSession } from '@cogitator-ai/voice';
import { z } from 'zod';

const cogitator = new Cogitator();
const unlock = tool({
  name: 'unlock_door',
  description: 'Unlock the door of a room',
  parameters: z.object({ room: z.string() }),
  requiresApproval: true,
  execute: async ({ room }) => ({ unlocked: room }),
});

const session = new RealtimeSession({
  provider: 'gemini',
  apiKey: process.env.GOOGLE_API_KEY!,
  tools: createRealtimeTools(cogitator, [unlock], {
    onApproval: async (request) => ({ approved: await askOperator(request) }),
  }),
});

A call that needs approval (requiresApproval, or the guardrails) goes to onApproval, then to guardrails.onToolApproval. A call nobody approves does not run: the model gets the error Tool "unlock_door" needs approval, and nobody approved this call and can say so. A declined call reaches the model with its reason.

OptionDefaultDescription
onApproval-(request, context): decides calls that need approval, as RunOptions.onApproval in a run, with the call's session in context
agentIdagent.id, else 'voice'Agent id the tools see in their context
agent-The agent the tools belong to: its model builds the guardrails, its middleware wraps the calls
threadIdvoice:<sessionId>Thread id for the tools, computed from the call context
userId-The user the calls act for, a string or a function of the call's context

On this page