Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

realtime-client.ts

601 lines17.4 KB

1import { convertSchemaToJsonSchema } from '@tanstack/ai/client'
2import type {
3 AnyClientTool,
4 AudioVisualization,
5 RealtimeMessage,
6 RealtimeMode,
7 RealtimeSessionConfig,
8 RealtimeStatus,
9 RealtimeToken,
10} from '@tanstack/ai/client'
11import type {
12 RealtimeClientOptions,
13 RealtimeClientState,
14 RealtimeConnection,
15 RealtimeStateChangeCallback,
16} from './realtime-types'
17​
18// Token refresh buffer - refresh 1 minute before expiry
19const TOKEN_REFRESH_BUFFER_MS = 60_000
20​
21/**
22 * Client for managing realtime voice conversations.
23 *
24 * Handles connection lifecycle, audio I/O, message state,
25 * and tool execution for realtime voice-to-voice AI interactions.
26 *
27 * @example
28 * ```typescript
29 * import { RealtimeClient } from '@tanstack/ai-client'
30 * import { openaiRealtime } from '@tanstack/ai-openai'
31 *
32 * const client = new RealtimeClient({
33 * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
34 * adapter: openaiRealtime(),
35 * tools: [myTool.client(handler)],
36 * onMessage: (msg) => console.log('Message:', msg),
37 * })
38 *
39 * await client.connect()
40 * ```
41 */
42export class RealtimeClient {
43 private readonly options: RealtimeClientOptions
44 private connection: RealtimeConnection | null = null
45 private token: RealtimeToken | null = null
46 private tokenRefreshTimeout: ReturnType<typeof setTimeout> | null = null
47 private readonly clientTools: Map<string, AnyClientTool>
48 private readonly stateChangeCallbacks: Set<RealtimeStateChangeCallback> =
49 new Set()
50 private unsubscribers: Array<() => void> = []
51​
52 private state: RealtimeClientState = {
53 status: 'idle',
54 mode: 'idle',
55 messages: [],
56 pendingUserTranscript: null,
57 pendingAssistantTranscript: null,
58 error: null,
59 }
60​
61 constructor(options: RealtimeClientOptions) {
62 this.options = {
63 autoPlayback: true,
64 autoCapture: true,
65 vadMode: 'server',
66 ...options,
67 }
68​
69 // Build client tools map
70 this.clientTools = new Map()
71 if (options.tools) {
72 for (const tool of options.tools) {
73 this.clientTools.set(tool.name, tool)
74 }
75 }
76 }
77​
78 // ============================================================================
79 // Connection Lifecycle
80 // ============================================================================
81​
82 /**
83 * Connect to the realtime session.
84 * Fetches a token and establishes the connection.
85 */
86 async connect(): Promise<void> {
87 if (this.state.status === 'connected') {
88 return
89 }
90​
91 this.updateState({ status: 'connecting', error: null })
92​
93 try {
94 // Fetch token from server
95 this.token = await this.options.getToken()
96​
97 // Schedule token refresh
98 this.scheduleTokenRefresh()
99​
100 // Connect via adapter (pass tools for providers like ElevenLabs that need them at connect time)
101 const toolsList =
102 this.clientTools.size > 0
103 ? Array.from(this.clientTools.values())
104 : undefined
105​
106 this.connection = await this.options.adapter.connect(
107 this.token,
108 toolsList,
109 )
110​
111 // Subscribe to connection events
112 this.subscribeToConnectionEvents()
113​
114 // Auto-configure session with client-provided settings
115 this.applySessionConfig()
116​
117 // Start audio capture if configured
118 if (this.options.autoCapture) {
119 await this.connection.startAudioCapture()
120 }
121​
122 this.updateState({ status: 'connected', mode: 'listening' })
123 this.options.onConnect?.()
124 } catch (error) {
125 const err = error instanceof Error ? error : new Error(String(error))
126 this.updateState({ status: 'error', error: err })
127 this.options.onError?.(err)
128 throw err
129 }
130 }
131​
132 /**
133 * Disconnect from the realtime session.
134 */
135 async disconnect(): Promise<void> {
136 if (this.tokenRefreshTimeout) {
137 clearTimeout(this.tokenRefreshTimeout)
138 this.tokenRefreshTimeout = null
139 }
140​
141 // Unsubscribe from all events
142 for (const unsub of this.unsubscribers) {
143 unsub()
144 }
145 this.unsubscribers = []
146​
147 if (this.connection) {
148 await this.connection.disconnect()
149 this.connection = null
150 }
151​
152 this.token = null
153 this.updateState({
154 status: 'idle',
155 mode: 'idle',
156 pendingUserTranscript: null,
157 pendingAssistantTranscript: null,
158 })
159 this.options.onDisconnect?.()
160 }
161​
162 // ============================================================================
163 // Voice Control
164 // ============================================================================
165​
166 /**
167 * Start listening for voice input.
168 * Only needed when vadMode is 'manual'.
169 */
170 startListening(): void {
171 if (!this.connection || this.state.status !== 'connected') {
172 return
173 }
174 void this.connection.startAudioCapture()
175 this.updateState({ mode: 'listening' })
176 }
177​
178 /**
179 * Stop listening for voice input.
180 * Only needed when vadMode is 'manual'.
181 */
182 stopListening(): void {
183 if (!this.connection) {
184 return
185 }
186 this.connection.stopAudioCapture()
187 this.updateState({ mode: 'idle' })
188 }
189​
190 /**
191 * Interrupt the current assistant response.
192 */
193 interrupt(): void {
194 if (!this.connection) {
195 return
196 }
197 this.connection.interrupt()
198 }
199​
200 // ============================================================================
201 // Text Input
202 // ============================================================================
203​
204 /**
205 * Send a text message instead of voice.
206 */
207 sendText(text: string): void {
208 if (!this.connection || this.state.status !== 'connected') {
209 return
210 }
211​
212 // Add user message
213 const userMessage: RealtimeMessage = {
214 id: this.generateId(),
215 role: 'user',
216 timestamp: Date.now(),
217 parts: [{ type: 'text', content: text }],
218 }
219 this.addMessage(userMessage)
220​
221 // Send to provider
222 this.connection.sendText(text)
223 }
224​
225 /**
226 * Send an image to the conversation.
227 * @param imageData - Base64-encoded image data or a URL
228 * @param mimeType - MIME type of the image (e.g., 'image/png', 'image/jpeg')
229 */
230 sendImage(imageData: string, mimeType: string): void {
231 if (!this.connection || this.state.status !== 'connected') {
232 return
233 }
234​
235 // Add user message with image part
236 const userMessage: RealtimeMessage = {
237 id: this.generateId(),
238 role: 'user',
239 timestamp: Date.now(),
240 parts: [{ type: 'image', data: imageData, mimeType }],
241 }
242 this.addMessage(userMessage)
243​
244 // Send to provider
245 this.connection.sendImage(imageData, mimeType)
246 }
247​
248 // ============================================================================
249 // State Access
250 // ============================================================================
251​
252 /** Get current connection status */
253 get status(): RealtimeStatus {
254 return this.state.status
255 }
256​
257 /** Get current mode */
258 get mode(): RealtimeMode {
259 return this.state.mode
260 }
261​
262 /** Get conversation messages */
263 get messages(): Array<RealtimeMessage> {
264 return this.state.messages
265 }
266​
267 /** Get current error, if any */
268 get error(): Error | null {
269 return this.state.error
270 }
271​
272 /** Get pending user transcript (while user is speaking) */
273 get pendingUserTranscript(): string | null {
274 return this.state.pendingUserTranscript
275 }
276​
277 /** Get pending assistant transcript (while assistant is speaking) */
278 get pendingAssistantTranscript(): string | null {
279 return this.state.pendingAssistantTranscript
280 }
281​
282 /** Get audio visualization data */
283 get audio(): AudioVisualization | null {
284 return this.connection?.getAudioVisualization() ?? null
285 }
286​
287 /**
288 * Update the session configuration.
289 * This applies changes to the active connection and persists them for future reconnections.
290 */
291 updateSession(config: Partial<RealtimeSessionConfig>): void {
292 // Persist type-compatible fields so future (re)connections use the updated
293 // config. `tools` is intentionally excluded: a session's tool configs are
294 // serialized descriptors, whereas `options.tools` holds executable client
295 // tools tracked separately via `clientTools`.
296 const o = this.options
297 if (config.instructions !== undefined) o.instructions = config.instructions
298 if (config.voice !== undefined) o.voice = config.voice
299 if (config.vadMode !== undefined) o.vadMode = config.vadMode
300 if (config.outputModalities !== undefined) {
301 o.outputModalities = config.outputModalities
302 }
303 if (config.temperature !== undefined) o.temperature = config.temperature
304 if (config.maxOutputTokens !== undefined) {
305 o.maxOutputTokens = config.maxOutputTokens
306 }
307 if (config.semanticEagerness !== undefined) {
308 o.semanticEagerness = config.semanticEagerness
309 }
310 if (config.providerOptions !== undefined) {
311 o.providerOptions = config.providerOptions
312 }
313​
314 if (this.connection) {
315 this.applySessionConfig()
316 }
317 }
318​
319 // ============================================================================
320 // State Subscription
321 // ============================================================================
322​
323 /**
324 * Subscribe to state changes.
325 * @returns Unsubscribe function
326 */
327 onStateChange(callback: RealtimeStateChangeCallback): () => void {
328 this.stateChangeCallbacks.add(callback)
329 return () => {
330 this.stateChangeCallbacks.delete(callback)
331 }
332 }
333​
334 // ============================================================================
335 // Cleanup
336 // ============================================================================
337​
338 /**
339 * Clean up resources.
340 * Call this when disposing of the client.
341 */
342 destroy(): void {
343 void this.disconnect()
344 this.stateChangeCallbacks.clear()
345 }
346​
347 // ============================================================================
348 // Private Methods
349 // ============================================================================
350​
351 private updateState(updates: Partial<RealtimeClientState>): void {
352 this.state = { ...this.state, ...updates }
353​
354 // Notify callbacks
355 for (const callback of this.stateChangeCallbacks) {
356 callback(this.state)
357 }
358​
359 // Notify specific callbacks
360 if ('status' in updates && updates.status !== undefined) {
361 this.options.onStatusChange?.(updates.status)
362 }
363 if ('mode' in updates && updates.mode !== undefined) {
364 this.options.onModeChange?.(updates.mode)
365 }
366 }
367​
368 private addMessage(message: RealtimeMessage): void {
369 this.updateState({
370 messages: [...this.state.messages, message],
371 })
372 this.options.onMessage?.(message)
373 }
374​
375 private scheduleTokenRefresh(): void {
376 if (!this.token) return
377​
378 const timeUntilExpiry = this.token.expiresAt - Date.now()
379 const refreshIn = Math.max(0, timeUntilExpiry - TOKEN_REFRESH_BUFFER_MS)
380​
381 this.tokenRefreshTimeout = setTimeout(() => {
382 void this.refreshToken()
383 }, refreshIn)
384 }
385​
386 private async refreshToken(): Promise<void> {
387 try {
388 this.token = await this.options.getToken()
389 this.scheduleTokenRefresh()
390 this.connection?.updateToken?.(this.token)
391 // Note: Some providers may require reconnection with new token
392 // This is handled by the adapter implementation
393 } catch (error) {
394 const err = error instanceof Error ? error : new Error(String(error))
395 this.updateState({ error: err })
396 this.options.onError?.(err)
397 }
398 }
399​
400 private subscribeToConnectionEvents(): void {
401 if (!this.connection) return
402​
403 // Status changes
404 this.unsubscribers.push(
405 this.connection.on('status_change', ({ status }) => {
406 this.updateState({ status })
407 }),
408 )
409​
410 // Mode changes
411 this.unsubscribers.push(
412 this.connection.on('mode_change', ({ mode }) => {
413 this.updateState({ mode })
414 }),
415 )
416​
417 // Transcripts (streaming)
418 // User transcripts are added as messages when final (no separate message_complete for user input)
419 // Assistant transcripts are streamed, final message comes via message_complete
420 this.unsubscribers.push(
421 this.connection.on('transcript', ({ role, transcript, isFinal }) => {
422 if (role === 'user') {
423 this.updateState({
424 pendingUserTranscript: isFinal ? null : transcript,
425 })
426 // Add user message when transcript is finalized
427 if (isFinal && transcript) {
428 this.addMessage({
429 id: this.generateId(),
430 role: 'user',
431 timestamp: Date.now(),
432 parts: [{ type: 'audio', transcript, durationMs: 0 }],
433 })
434 }
435 } else {
436 // Assistant transcripts - just update pending, message_complete handles final
437 this.updateState({
438 pendingAssistantTranscript: isFinal ? null : transcript,
439 })
440 }
441 }),
442 )
443​
444 // Tool calls
445 this.unsubscribers.push(
446 this.connection.on('tool_call', ({ toolCallId, toolName, input }) => {
447 if (!toolCallId) {
448 console.error(
449 '[RealtimeClient] tool_call missing toolCallId',
450 toolName,
451 )
452 return
453 }
454 const tool = this.clientTools.get(toolName)
455 const execute = tool?.execute
456 if (execute) {
457 void (async () => {
458 try {
459 const output = await execute(input)
460 this.connection?.sendToolResult(
461 toolCallId,
462 typeof output === 'string' ? output : JSON.stringify(output),
463 )
464 } catch (error) {
465 const errMsg =
466 error instanceof Error ? error.message : String(error)
467 this.connection?.sendToolResult(
468 toolCallId,
469 JSON.stringify({ error: errMsg }),
470 )
471 }
472 })()
473 } else {
474 this.connection?.sendToolResult(
475 toolCallId,
476 JSON.stringify({
477 error: `Unknown or non-executable tool: ${String(toolName)}`,
478 }),
479 )
480 }
481 }),
482 )
483​
484 // Message complete
485 this.unsubscribers.push(
486 this.connection.on('message_complete', ({ message }) => {
487 // Replace pending message with final version if needed
488 const existingIndex = this.state.messages.findIndex(
489 (m) => m.id === message.id,
490 )
491 if (existingIndex >= 0) {
492 const newMessages = [...this.state.messages]
493 newMessages[existingIndex] = message
494 this.updateState({ messages: newMessages })
495 } else {
496 this.addMessage(message)
497 }
498 }),
499 )
500​
501 // Interruption
502 this.unsubscribers.push(
503 this.connection.on('interrupted', ({ messageId }) => {
504 if (messageId) {
505 const newMessages = this.state.messages.map((m) =>
506 m.id === messageId ? { ...m, interrupted: true } : m,
507 )
508 this.updateState({ messages: newMessages })
509 }
510 this.updateState({
511 mode: 'listening',
512 pendingAssistantTranscript: null,
513 })
514 this.options.onInterrupted?.()
515 }),
516 )
517​
518 // Errors
519 this.unsubscribers.push(
520 this.connection.on('error', ({ error }) => {
521 this.updateState({ error })
522 this.options.onError?.(error)
523 }),
524 )
525​
526 this.unsubscribers.push(
527 this.connection.on('go_away', ({ timeLeft }) => {
528 this.options.onGoAway?.(timeLeft)
529 }),
530 )
531​
532 this.unsubscribers.push(
533 this.connection.on('usage', (usage) => {
534 this.options.onUsage?.(usage)
535 }),
536 )
537 }
538​
539 private applySessionConfig(): void {
540 if (!this.connection) return
541​
542 const {
543 instructions,
544 voice,
545 vadMode,
546 tools,
547 outputModalities,
548 temperature,
549 maxOutputTokens,
550 semanticEagerness,
551 } = this.options
552 const hasConfig =
553 instructions ||
554 voice ||
555 vadMode ||
556 (tools && tools.length > 0) ||
557 outputModalities ||
558 temperature !== undefined ||
559 maxOutputTokens !== undefined ||
560 semanticEagerness
561 if (!hasConfig) return
562​
563 // `RealtimeToolConfig.inputSchema`/`outputSchema` are `Record<string, any>`
564 // (no `undefined` under `exactOptionalPropertyTypes`). Conditionally spread
565 // each so we don't pass `undefined` when the tool has no such schema.
566 const toolsConfig = tools
567 ? Array.from(this.clientTools.values()).map((t) => {
568 const inputSchema = t.inputSchema
569 ? convertSchemaToJsonSchema(t.inputSchema)
570 : undefined
571 const outputSchema = t.outputSchema
572 ? convertSchemaToJsonSchema(t.outputSchema)
573 : undefined
574 return {
575 name: t.name,
576 description: t.description,
577 ...(inputSchema ? { inputSchema } : {}),
578 ...(outputSchema ? { outputSchema } : {}),
579 }
580 })
581 : undefined
582​
583 // `RealtimeSessionConfig` declares each field as `field?: T` (no
584 // `undefined`). Spread each one conditionally so we don't violate
585 // `exactOptionalPropertyTypes` when the source is `T | undefined`.
586 this.connection.updateSession({
587 ...(instructions !== undefined ? { instructions } : {}),
588 ...(voice !== undefined ? { voice } : {}),
589 ...(vadMode !== undefined ? { vadMode } : {}),
590 ...(toolsConfig !== undefined ? { tools: toolsConfig } : {}),
591 ...(outputModalities !== undefined ? { outputModalities } : {}),
592 ...(temperature !== undefined ? { temperature } : {}),
593 ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
594 ...(semanticEagerness !== undefined ? { semanticEagerness } : {}),
595 })
596 }
597​
598 private generateId(): string {
599 return `msg-${Date.now()}-${Math.random().toString(36).substring(7)}`
600 }