Persistence (Advanced)
- Generations
- Realtime Voice Chat
- GPT-Live VoiceUpdated
- Text-to-Speech
- Transcription
- Transcription: Advanced
- Voice Creation
- Audio Recording
- Audio Generation
- Image Generation
- Image Generation: Advanced
- Video Generation
- Video Generation: Advanced
- Live Generation
- World Generation
- Motion Generation
- 3D Model Generation
- 3D Model Generation: Advanced
- Generation Hooks
- Build your first harness
- Host options
- Send and show media
- Connect clients
- Write a client in any language
- Access and tenants
- Run in the terminal
- Deploy a harness
- Send inputs safely
- Run a tool without a model
- Durable sessions
- Run background work on workers
- List, rename, and fork sessions
- Lifecycle and retention
- Run side effects once
- Wait for a person
- Build on the session log
- Control how a turn ends
- Store settings per thread
- Compact a long session
- Fork and reset a thread
- One log for a session tree
- Write a plugin
- Track usage and cost
- Ask before risky tool calls
- Give your agent coding tools
- Sandbox and extend the coding tools
- Run the coding tools for many threads
- Undo a turn
- Build a coding agent
- Delegate to coding agents
- Switch between agent profiles
- Auth and connectors
- Share a thread between people
- Connect model providers
- Sign in with a ChatGPT or SuperGrok plan
- Build your own UI
- Code mode in a harness
- Work until a goal is met
- Run agents from a harness
- Hand off a conversation
- Add skills
- Use MCP servers
- Give your agent a computer
- Use from any MCP client
- Use a harness from an editor (ACP)
- Overview
- Quick Start
- Providers
- Harnesses
- Harness Auth
- Workspace
- Tools
- Policy
- Lifecycle & Snapshots
- Portable Snapshots
- Keep Files After Reload
- Save a Named Version
- Branch From a Version
- Send a Frozen File
- Let the Agent Save and Fork
- Pick Which Files to Keep
- What a Snapshot Stores
- Checkpoint at Any Time
- Store Checkpoints
- Instance Durability
- Durable Runs
- Events
Sandboxes (Advanced)
- Runtime Context
- Bring Your Own Key
- Keep Keys on the Server
- Debug Logging
- Multimodal Content
- Files API
- Per-Model Type Safety
- Runtime Adapter Switching
- Tree-Shaking
- Extend Adapter
- Extend Adapter: Advanced
- Typed Pre-Configured Options
- Test with a Fake Model
- Prompt Caching
- Mid-Conversation Changes
- Approval Flow Processing
GPT-Live Voice
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.
Quick setup#
This builds a GPT-Live voice chat in React. It takes about 5 minutes.
- Install the packages:
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-openai- Put your key in .env on the server:
OPENAI_API_KEY=sk-...- Add a POST route at /api/live-session that relays the session:
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)
}- Connect from a component:
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.
How it works#
The connection has three steps:
- The browser makes a WebRTC offer. createSession sends the offer and the hook config to your route.
- Your route calls realtimeSession(). openaiLiveSession() sends the offer to OpenAI with your API key and gets the answer.
- The browser gets the answer and connects straight to OpenAI. The audio does not go through your server.
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.
Server options#
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.
Tools#
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.
- Set delegation on the server:
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)
}- Pass the .client() tools to the hook in your chat component:
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.
- To change the delegation settings while connected, call updateSession from the same useRealtimeChat call. The Use metric units button above does this. updateSession changes these delegation fields:
- instructions: the instructions for the delegated model.
- toolChoice: how the delegated model picks tools.
- parallelToolCalls: lets the delegated model call more than one tool in one turn.
- maxOutputTokens: the output limit for the delegated model (16 or more).
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.
Differences from other realtime models#
GPT-Live does not support these hook functions:
- sendText() and sendImage(): the client adds a local message. GPT-Live does not send it. The adapter reports an error.
- updateSession(): the open session changes only providerOptions.delegation. It does not change delegation.model. The client stores instructions and voice. The next connect() sends them.
These functions work in a different way:
- interrupt(): it changes only the local state. The model hears the user and stops by itself.
- messages: a message is complete when the other person starts to talk.
- onUsage: the token counts are 0. billed holds the audio seconds.
You now have a full-duplex voice chat. The user can talk over the model, and the model can call your tools.
Other frameworks#
Each framework takes the same createSession option:
- Octane: useRealtimeChat from @tanstack/ai-octane.
- Remix: createRealtimeChat(handle, options) from @tanstack/ai-remix. See the Remix API.
- Preact, Solid, Vue, Svelte, and Angular: RealtimeClient from your framework package, for example @tanstack/ai-vue.
- Plain TypeScript: RealtimeClient from @tanstack/ai-client.
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.
Build a relay adapter#
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.
- On the server, write a RealtimeSessionAdapter. It gets the browser offer and returns the provider answer:
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.