openaiLive() connects the browser to OpenAI gpt-live-1.1 for full-duplex voice. The user and the model can talk at the same time. GPT-Live has no browser token, so your server relays the connection with realtimeSession().
The hook is the same useRealtimeChat as in Realtime Voice Chat. You give it createSession in place of getToken.
This builds a GPT-Live voice chat in React. It takes about 5 minutes.
npm i @tanstack/ai @tanstack/ai-react @tanstack/ai-openaipnpm add @tanstack/ai @tanstack/ai-react @tanstack/ai-openaiyarn add @tanstack/ai @tanstack/ai-react @tanstack/ai-openaibun add @tanstack/ai @tanstack/ai-react @tanstack/ai-openaiOPENAI_API_KEY=sk-...import { realtimeSession } from '@tanstack/ai'
import { openaiLiveSession } from '@tanstack/ai-openai'
export async function POST(request: Request) {
const answer = await realtimeSession({
adapter: openaiLiveSession({ model: 'gpt-live-1.1' }),
request: await request.json(),
abortSignal: request.signal,
})
return Response.json(answer)
}import { useRealtimeChat } from '@tanstack/ai-react'
import { openaiLive } from '@tanstack/ai-openai'
import type { RealtimeSessionRequest } from '@tanstack/ai'
function createSession(
request: RealtimeSessionRequest,
abortSignal?: AbortSignal,
) {
return fetch('/api/live-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
signal: abortSignal,
}).then((r) => r.json())
}
export function LiveVoiceChat() {
const {
status,
mode,
messages,
connect,
disconnect,
pendingUserTranscript,
pendingAssistantTranscript,
} = useRealtimeChat({
createSession,
adapter: openaiLive(),
instructions: 'You are a helpful voice assistant. Keep answers short.',
voice: 'marin',
})
return (
<div>
<p>
Status: {status}. Mode: {mode}.
</p>
<button onClick={status === 'idle' ? connect : disconnect}>
{status === 'idle' ? 'Start conversation' : 'End conversation'}
</button>
{pendingUserTranscript && <p>You: {pendingUserTranscript}...</p>}
{pendingAssistantTranscript && <p>AI: {pendingAssistantTranscript}...</p>}
{messages.map((msg) => (
<div key={msg.id}>
<strong>{msg.role}:</strong>
{msg.parts.map((part, i) => (
<span key={i}>{part.type === 'audio' ? part.transcript : null}</span>
))}
</div>
))}
</div>
)
}Click Start conversation and allow the microphone. Talk to the model. It answers out loud, and you can talk over it at any time.
The connection has three steps:
realtimeSession() checks the request body before it calls the adapter. The body must have a non-empty sdp string and a config object. Other keys are dropped, so you can pass await request.json() directly.
The server options win over the browser config. Set them in openaiLiveSession():
import { openaiLiveSession } from '@tanstack/ai-openai'
const adapter = openaiLiveSession({
model: 'gpt-live-1.1',
instructions: 'You are a support agent for Acme. Keep answers short.',
voice: 'marin',
delegation: { model: 'gpt-6.1-terra' },
})| Option | Default | Description |
|---|---|---|
| model | 'gpt-live-1.1' | 'gpt-live-1' or 'gpt-live-1.1'. Server only. |
| instructions | the client value | Replaces the instructions from the hook. |
| voice | the client value | Replaces the voice from the hook. If neither sets it, OpenAI uses marin. |
| delegation | none | The Responses model that runs tools, and its settings. The server sets the start values. See Tools. |
| store | OpenAI default | Lets OpenAI store the session. |
| apiKey | OPENAI_API_KEY | The OpenAI API key. |
| baseURL | https://api.openai.com/v1 | The API base URL. |
The server reads only instructions, voice, and tools from the browser config. The other hook options, such as vadMode and temperature, have no effect on GPT-Live.
Voices: marin, quartz, ripple, vesper, willow, stone, gleam, meridian, bossa, tempo, beacon, delta, cinder, nuri, juni, flitz, brise, sillage, nira, harema, shida, noeul.
GPT-Live gives tool work to a Responses model. That model calls your client tools. The browser runs each tool and sends the result back. When the delegated response fails, or ends before it is complete, the adapter reports an error. It does not continue the turn.
import { realtimeSession } from '@tanstack/ai'
import { openaiLiveSession } from '@tanstack/ai-openai'
export async function POST(request: Request) {
const answer = await realtimeSession({
adapter: openaiLiveSession({
delegation: { model: 'gpt-6.1-terra' },
}),
request: await request.json(),
abortSignal: request.signal,
})
return Response.json(answer)
}import { toolDefinition } from '@tanstack/ai'
import { useRealtimeChat } from '@tanstack/ai-react'
import { openaiLive } from '@tanstack/ai-openai'
import { z } from 'zod'
import { createSession } from './create-session'
const getWeatherDef = toolDefinition({
name: 'getWeather',
description: 'Get weather for a location',
inputSchema: z.object({
location: z.string().meta({ description: 'City name' }),
}),
outputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
}),
})
const getWeather = getWeatherDef.client(async ({ location }) => {
const res = await fetch(`/api/weather?location=${location}`)
return res.json()
})
export function WeatherLiveChat() {
const { status, connect, disconnect, updateSession } = useRealtimeChat({
createSession,
adapter: openaiLive(),
tools: [getWeather],
})
function switchToMetric() {
updateSession({
providerOptions: {
delegation: {
instructions: 'Use metric units.',
maxOutputTokens: 500,
},
},
})
}
return (
<div>
<button onClick={status === 'idle' ? connect : disconnect}>
{status === 'idle' ? 'Start conversation' : 'End conversation'}
</button>
<button onClick={switchToMetric} disabled={status !== 'connected'}>
Use metric units
</button>
</div>
)
}If the browser sends tools and the server has no delegation, realtimeSession() rejects. No session starts.
updateSession does not change the delegation model. If you send delegation.model, the adapter drops it and logs an error.
The server sets the start values of delegation, which include the model. But the browser holds the data channel, so a user can change these values with a raw session.update event. Do not use the delegation model as a security limit or a cost limit. Set spend limits in your OpenAI project.
GPT-Live does not support these hook functions:
These functions work in a different way:
You now have a full-duplex voice chat. The user can talk over the model, and the model can call your tools.
Each framework takes the same createSession option:
A RealtimeClient with GPT-Live:
import { RealtimeClient } from '@tanstack/ai-vue'
import { openaiLive } from '@tanstack/ai-openai'
const client = new RealtimeClient({
adapter: openaiLive(),
createSession: (request, abortSignal) =>
fetch('/api/live-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
signal: abortSignal,
}).then((r) => r.json()),
instructions: 'You are a helpful voice assistant.',
onMessage: (message) => console.log(`${message.role}:`, message.parts),
onStatusChange: (status) => console.log('Status:', status),
})
await client.connect()
// When you are done:
await client.disconnect()
client.destroy()Use the server route from the quick setup for every framework.
A relay adapter connects to a provider through your server. Use one for a provider that has no browser token. It has a server half and a browser half.
import type { RealtimeSessionAdapter } from '@tanstack/ai'
export function myProviderSession(): RealtimeSessionAdapter {
const apiKey = process.env.MY_PROVIDER_API_KEY
return {
provider: 'my-provider',
async createSession(request, options) {
const response = await fetch('https://api.example.com/v1/sessions', {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/sdp',
},
body: request.sdp,
signal: options?.abortSignal ?? null,
})
if (!response.ok) {
throw new Error(`Session failed: ${response.status}`)
}
const sessionId = response.headers.get('x-session-id')
if (!sessionId) throw new Error('The response has no session id')
return {
provider: 'my-provider',
sessionId,
sdp: await response.text(),
config: request.config,
}
},
}
}Give it to realtimeSession() in your route, the same as openaiLiveSession().
In the browser, write a RealtimeRelayAdapter with kind: 'relay'. connect makes the offer and calls createSession:
import type { RealtimeRelayAdapter } from '@tanstack/ai'
import { createMyConnection } from './my-connection'
// Asks for the microphone. Stops the wait when `signal` aborts.
function getMicrophone(signal?: AbortSignal): Promise<MediaStream> {
return new Promise((resolve, reject) => {
signal?.throwIfAborted()
const onAbort = () => reject(signal?.reason)
signal?.addEventListener('abort', onAbort, { once: true })
navigator.mediaDevices
.getUserMedia({ audio: true })
.then((stream) => {
// The stream can come after the abort. Then nothing uses it.
if (signal && signal.aborted) {
stream.getTracks().forEach((track) => track.stop())
reject(signal.reason)
return
}
resolve(stream)
}, reject)
.finally(() => signal?.removeEventListener('abort', onAbort))
})
}
export function myProviderLive(): RealtimeRelayAdapter {
return {
provider: 'my-provider',
kind: 'relay',
async connect(createSession, clientTools, options) {
const peer = new RTCPeerConnection()
let mic: MediaStream | null = null
try {
const stream = await getMicrophone(options?.abortSignal)
mic = stream
stream.getTracks().forEach((track) => peer.addTrack(track, stream))
const events = peer.createDataChannel('events')
// The track event can fire before setRemoteDescription() returns.
const speaker = new Audio()
speaker.autoplay = true
peer.ontrack = (event) => {
// A provider can send a track with no stream.
speaker.srcObject = event.streams[0] ?? new MediaStream([event.track])
}
const offer = await peer.createOffer()
await peer.setLocalDescription(offer)
// Candidates arrive after setLocalDescription. Wait, then send that SDP.
if (peer.iceGatheringState !== 'complete') {
await new Promise<void>((resolve, reject) => {
const signal = options?.abortSignal
const timer = setTimeout(() => {
cleanup()
reject(new Error('ICE gathering timed out'))
}, 10_000)
const onChange = () => {
if (peer.iceGatheringState !== 'complete') return
cleanup()
resolve()
}
const onAbort = () => {
cleanup()
reject(signal?.reason)
}
function cleanup() {
clearTimeout(timer)
peer.removeEventListener('icegatheringstatechange', onChange)
signal?.removeEventListener('abort', onAbort)
}
if (signal?.aborted) return onAbort()
signal?.addEventListener('abort', onAbort, { once: true })
peer.addEventListener('icegatheringstatechange', onChange)
})
}
const sdp = peer.localDescription?.sdp
if (!sdp) throw new Error('The offer has no SDP')
options?.abortSignal?.throwIfAborted()
const answer = await createSession({ sdp })
await peer.setRemoteDescription({ type: 'answer', sdp: answer.sdp })
return createMyConnection({
peer,
mic: stream,
speaker,
events,
clientTools,
})
} catch (error) {
mic?.getTracks().forEach((track) => track.stop())
peer.close()
throw error
}
},
}
}Set peer.ontrack before setRemoteDescription(). The browser can fire the track event before that call returns, and a later handler misses the audio of the model.
If a step fails, for example createSession rejects, the catch stops each microphone track and closes the peer. Then it throws the error again.
If options?.abortSignal aborts while the browser asks for the microphone, getMicrophone rejects at once. If the stream comes after the abort, it stops the tracks.
The adapter can also read options?.autoCapture. If it is false, open the microphone on the first startAudioCapture(), not on connect. openaiLive() does this.
createMyConnection returns a RealtimeConnection. From then on, the connection owns the microphone and the peer. It maps the provider events to the realtime events, and it stops the microphone on disconnect(). For a full example, read the source of openaiLive() in @tanstack/ai-openai.
Pass the adapter to useRealtimeChat with createSession. The hook sees kind: 'relay' and sends the offer and the config through your route.