Skip to content

OpenAI Realtime API in TypeScript, with examples

Use the OpenAI Realtime API from TypeScript with openai() from VoiceAI SDK: open a session, let the model answer by voice, put your own agent in the loop, and answer phone calls.

The OpenAI Realtime API is a speech-to-speech API: one WebSocket connection takes the caller's audio in and sends the model's spoken answer back, with no separate speech-to-text and text-to-speech steps. In TypeScript, openai() from VoiceAI SDK opens one Realtime connection per session and gives it the same converse, speak, transcribe and connect calls as every other provider. You don't need an OpenAI package.

The examples are written against the planned 1.0 API of VoiceAI SDK, which is in developer preview, and were not run against a live OpenAI account. What the provider supports comes from the OpenAI Realtime provider page. Pricing, response times and model behavior are set by OpenAI and depend on the provider, so this post doesn't quote them.

Realtime and a pipeline at a glance

openai()A pipeline, such as { stt: deepgram(), tts: cartesia({ voice }) }
Provider connectionsOne Realtime WebSocketOne per provider, plus your model
Who writes the replyThe Realtime model from instructions, or your handlerYour handler
Barge-inThe API's server-side voice activity detectionWhen both halves stream
Word timingsNoDepends on the speech-to-text provider
Speaker labelsNo; diarization fails with unsupportedDepends on the speech-to-text provider
pause() and resume()Fail with unsupportedDepends on the provider
CredentialsOPENAI_API_KEYOne key per provider

Pick Realtime when you want one connection and the model's own voice. Pick a pipeline when you need word timings, speaker labels, a specific voice, or a model from another vendor writing the text.

Open a Realtime session

Set OPENAI_API_KEY on your server. doctor confirms the SDK can see it, and the CLI can transcribe a file through Realtime before you write code:

npm install voiceai-sdk
npx voiceai-sdk doctor
npx voiceai-sdk transcribe question.wav --provider openai
import { readFile } from "node:fs/promises";
import { createSession } from "voiceai-sdk";
import { openai } from "voiceai-sdk/openai";

await using session = await createSession(openai());

const heard = await session.transcribe(await readFile("question.wav"));
console.log(heard.ok ? heard.text : heard.reason);

const reply = await session.speak("Thanks for calling. How can I help?");
console.log(`${reply.durationMs} ms of audio`);

transcribe returns what was said, using the input transcription model, and speak returns audio you can await or iterate. await using closes the Realtime connection when the block ends, even if the code throws. openai() also takes model, instructions and transcriptionModel; the provider page lists their defaults.

Let the model answer on its own

Call converse() without a handler and the Realtime model holds the conversation itself, following instructions. This server takes audio from any client that streams raw PCM over a WebSocket:

import { createSession } from "voiceai-sdk";
import { openai } from "voiceai-sdk/openai";
import { webSocketAudio } from "voiceai-sdk/ws";

const instructions =
  "You take table bookings for a small restaurant. Ask for the date, the time and the party size. Keep answers short.";

Bun.serve({
  port: 3000,
  fetch: (req, server) => (server.upgrade(req) ? undefined : new Response("upgrade required", { status: 426 })),
  websocket: {
    async open(ws) {
      await using session = await createSession(openai({ instructions }), {
        sampleRate: 24000,
        encoding: "pcm16",
      });
      session.connect(webSocketAudio(ws));
      await session.converse();
    },
  },
});

The provider page lists sampleRate: 24000 for pcm16, so the client streams 24 kHz audio. When the caller talks over a reply, the API's server-side voice activity detection notices, the SDK truncates the response, and the session emits interrupt. When the socket closes, converse resolves and the session closes.

Put your own agent in the loop

Pass a handler to converse and the SDK turns off the model's automatic responses. It creates each response from the text your handler returns, and instructions is ignored. Use this when the reply needs your own tools, your own data, or a different model.

import { streamText } from "ai";

// Inside open(ws), after session.connect(...)
await session.converse((text, ctx) => {
  const result = streamText({
    model: "openai/gpt-5",
    system: "You take table bookings for a small restaurant. Answer in one or two short sentences.",
    messages: [...ctx.history, { role: "user", content: text }],
    abortSignal: ctx.signal,
  });
  return result.textStream;
});

The Realtime connection still does the listening and the speaking. Your handler only decides the words. ctx.signal aborts when the caller interrupts, so the model call stops along with the audio.

Answer phone calls

Phone audio from Twilio is 8 kHz mu-law. The provider page notes that the SDK converts telephony audio for openai(), so you open the session in the call's format and connect the media stream:

import { createSession } from "voiceai-sdk";
import { openai } from "voiceai-sdk/openai";
import { twilioMediaStream } from "voiceai-sdk/twilio";

// Inside the open(ws) handler for Twilio's media stream
await using session = await createSession(openai({ instructions }), {
  encoding: "mulaw",
  sampleRate: 8000,
});
session.connect(twilioMediaStream(ws));

await session.say`Thanks for calling. How can I help?`;
await session.converse();

The webhook, the TwiML and the security checks are in Build a Twilio voice agent in TypeScript.

Reach the Realtime socket directly

session.native is the Realtime WebSocket. You can send any client event the API accepts, for example to change the instructions partway through a session:

import { createSession } from "voiceai-sdk";
import { openai } from "voiceai-sdk/openai";

await using session = await createSession(openai());

session.native.send(
  JSON.stringify({ type: "session.update", session: { instructions: "From now on, answer in French." } }),
);

Native calls skip the SDK's checks and don't carry over to other providers. Keep them to what the session API doesn't cover. See Native API.

Common questions

Do I need the openai npm package? No. openai() talks to the Realtime WebSocket directly. You need OPENAI_API_KEY on the server. If you build your agent with @openai/agents, install that separately.

Can I call the Realtime API from the browser with this SDK? No. The session reads your key, so it runs on the server. The browser streams microphone audio to your server, and webSocketAudio(ws) connects it to the session.

Does Realtime give word timings or speaker labels? Not through openai(). wordTimings is false and diarization fails with unsupported. If you need them, use a pipeline with a speech-to-text provider that has them.

How do I track usage? session.usage() returns audioInMs, audioOutMs and characters. Read it in a close handler to log each session. What that usage costs depends on the provider.

Next steps

  • OpenAI Realtime: options, capabilities and limitations of openai().
  • How it works: how a speech-to-speech provider differs from a pipeline.
  • OpenAI Agents: give an Agents SDK agent voice tools on the same session.

More guides on the VoiceAI SDK blog, or start with the quickstart.