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

adapter.ts

714 lines21.0 KB

1import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
2import { buildSessionUpdate } from './session-update'
3import type {
4 AnyClientTool,
5 AudioVisualization,
6 RealtimeAdapter,
7 RealtimeConnection,
8 RealtimeEvent,
9 RealtimeEventHandler,
10 RealtimeMessage,
11 RealtimeMode,
12 RealtimeSessionConfig,
13 RealtimeToken,
14} from '@tanstack/ai'
15import type { InternalLogger } from '@tanstack/ai/adapter-internals'
16import type { OpenAIRealtimeOptions } from './types'
17​
18const OPENAI_REALTIME_URL = 'https://api.openai.com/v1/realtime'
19​
20/**
21 * Creates an OpenAI realtime adapter for client-side use.
22 *
23 * Uses WebRTC for browser connections (default) or WebSocket for Node.js.
24 *
25 * @param options - Optional configuration
26 * @returns A RealtimeAdapter for use with RealtimeClient
27 *
28 * @example
29 * ```typescript
30 * import { RealtimeClient } from '@tanstack/ai-client'
31 * import { openaiRealtime } from '@tanstack/ai-openai'
32 *
33 * const client = new RealtimeClient({
34 * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
35 * adapter: openaiRealtime(),
36 * })
37 * ```
38 */
39export function openaiRealtime(
40 options: OpenAIRealtimeOptions = {},
41): RealtimeAdapter {
42 const connectionMode = options.connectionMode ?? 'webrtc'
43 const logger = resolveDebugOption(options.debug)
44​
45 return {
46 provider: 'openai',
47​
48 async connect(
49 token: RealtimeToken,
50 _clientTools?: ReadonlyArray<AnyClientTool>,
51 ): Promise<RealtimeConnection> {
52 const model = token.config.model ?? 'gpt-realtime-2.1'
53 logger.request(`activity=realtime provider=openai model=${model}`, {
54 provider: 'openai',
55 model,
56 })
57​
58 if (connectionMode === 'webrtc') {
59 return createWebRTCConnection(token, logger)
60 }
61 const error = new Error('WebSocket connection mode not yet implemented')
62 logger.errors('openai.realtime fatal', {
63 error,
64 source: 'openai.realtime',
65 })
66 throw error
67 },
68 }
70​
71/**
72 * Creates a WebRTC connection to OpenAI's realtime API
73 */
74async function createWebRTCConnection(
75 token: RealtimeToken,
76 logger: InternalLogger,
77): Promise<RealtimeConnection> {
78 const eventHandlers = new Map<RealtimeEvent, Set<RealtimeEventHandler<any>>>()
79​
80 // WebRTC peer connection
81 const pc = new RTCPeerConnection()
82​
83 // Audio context for visualization
84 let audioContext: AudioContext | null = null
85 let inputAnalyser: AnalyserNode | null = null
86 let outputAnalyser: AnalyserNode | null = null
87 let inputSource: MediaStreamAudioSourceNode | null = null
88 let outputSource: MediaStreamAudioSourceNode | null = null
89 let localStream: MediaStream | null = null
90​
91 // Audio element for playback (more reliable than AudioContext.destination)
92 let audioElement: HTMLAudioElement | null = null
93​
94 // Data channel for events (assigned at construction below; nulled out by teardown)
95 let dataChannel: RTCDataChannel | null = null
96​
97 // Current state
98 let currentMode: RealtimeMode = 'idle'
99 let currentMessageId: string | null = null
100​
101 // Empty arrays for when visualization isn't available
102 // frequencyBinCount = fftSize / 2 = 1024
103 const emptyFrequencyData = new Uint8Array(1024)
104 const emptyTimeDomainData = new Uint8Array(2048).fill(128) // 128 is silence
105​
106 // Helper to emit events (defined early so it can be used during setup)
107 function emit<TEvent extends RealtimeEvent>(
108 event: TEvent,
109 payload: Parameters<RealtimeEventHandler<TEvent>>[0],
110 ) {
111 const handlers = eventHandlers.get(event)
112 if (handlers) {
113 for (const handler of handlers) {
114 handler(payload)
115 }
116 }
117 }
118​
119 // Set up data channel for bidirectional communication. Captured into a const
120 // so closures see a non-nullable reference (teardown re-points the outer
121 // `dataChannel` to null, but in-flight closures still need to close their
122 // own channel).
123 const channel = pc.createDataChannel('oai-events')
124 dataChannel = channel
125​
126 // Promise that resolves when the data channel is open and ready
127 const dataChannelReady = new Promise<void>((resolve) => {
128 channel.onopen = () => {
129 flushPendingEvents()
130 emit('status_change', { status: 'connected' })
131 resolve()
132 }
133 })
134​
135 channel.onmessage = (event) => {
136 try {
137 const message = JSON.parse(event.data)
138 logger.provider(
139 `provider=openai direction=in type=${(message as { type?: string }).type ?? '<unknown>'}`,
140 { frame: message },
141 )
142 handleServerEvent(message)
143 } catch (e) {
144 logger.errors('openai.realtime fatal', {
145 error: e,
146 source: 'openai.realtime',
147 })
148 }
149 }
150​
151 channel.onerror = (error) => {
152 logger.errors('openai.realtime fatal', {
153 error,
154 source: 'openai.realtime',
155 })
156 emit('error', { error: new Error(`Data channel error: ${error}`) })
157 }
158​
159 // Handle incoming audio track
160 pc.ontrack = (event) => {
161 if (event.track.kind === 'audio' && event.streams[0]) {
162 setupOutputAudioAnalysis(event.streams[0])
163 }
164 }
165​
166 // IMPORTANT: Request microphone access and add audio track BEFORE creating offer
167 // OpenAI's Realtime API requires an audio track in the SDP offer
168 try {
169 localStream = await navigator.mediaDevices.getUserMedia({
170 audio: {
171 echoCancellation: true,
172 noiseSuppression: true,
173 sampleRate: 24000,
174 },
175 })
176​
177 // Add audio track to peer connection
178 for (const track of localStream.getAudioTracks()) {
179 pc.addTrack(track, localStream)
180 }
181 } catch (error) {
182 throw new Error(
183 `Microphone access required for realtime voice: ${error instanceof Error ? error.message : error}`,
184 )
185 }
186​
187 // Create and set local description (now includes audio track)
188 const offer = await pc.createOffer()
189 await pc.setLocalDescription(offer)
190​
191 // Send SDP to OpenAI's GA `/calls` endpoint and get the answer. The model
192 // is bound to the ephemeral token (minted via `/v1/realtime/client_secrets`),
193 // so it must NOT be passed as a query param — GA rejects `?model=` with a
194 // 400. `offer.sdp` is `string | undefined` per the WebRTC type definitions;
195 // coerce to `null`, which `RequestInit.body` accepts.
196 const sdpResponse = await fetch(`${OPENAI_REALTIME_URL}/calls`, {
197 method: 'POST',
198 headers: {
199 Authorization: `Bearer ${token.token}`,
200 'Content-Type': 'application/sdp',
201 },
202 body: offer.sdp ?? null,
203 })
204​
205 if (!sdpResponse.ok) {
206 const errorText = await sdpResponse.text()
207 const error = new Error(
208 `Failed to establish WebRTC connection: ${sdpResponse.status} - ${errorText}`,
209 )
210 logger.errors('openai.realtime fatal', {
211 error,
212 source: 'openai.realtime',
213 })
214 throw error
215 }
216​
217 const answerSdp = await sdpResponse.text()
218 await pc.setRemoteDescription({ type: 'answer', sdp: answerSdp })
219​
220 // Set up input audio analysis now that we have the stream
221 setupInputAudioAnalysis(localStream)
222​
223 // Handle server events
224 function handleServerEvent(event: Record<string, unknown>) {
225 const type = event.type as string
226​
227 switch (type) {
228 case 'session.created':
229 case 'session.updated':
230 // Session ready
231 break
232​
233 case 'input_audio_buffer.speech_started':
234 currentMode = 'listening'
235 emit('mode_change', { mode: 'listening' })
236 break
237​
238 case 'input_audio_buffer.speech_stopped':
239 currentMode = 'thinking'
240 emit('mode_change', { mode: 'thinking' })
241 break
242​
243 case 'input_audio_buffer.committed':
244 // Audio buffer committed for processing
245 break
246​
247 case 'conversation.item.input_audio_transcription.completed': {
248 const transcript = event.transcript as string
249 emit('transcript', { role: 'user', transcript, isFinal: true })
250 break
251 }
252​
253 case 'response.created':
254 currentMode = 'thinking'
255 emit('mode_change', { mode: 'thinking' })
256 break
257​
258 case 'response.output_item.added': {
259 const item = event.item as Record<string, unknown>
260 if (item.type === 'message') {
261 currentMessageId = item.id as string
262 }
263 break
264 }
265​
266 case 'response.output_audio_transcript.delta': {
267 const delta = event.delta as string
268 emit('transcript', {
269 role: 'assistant',
270 transcript: delta,
271 isFinal: false,
272 })
273 break
274 }
275​
276 case 'response.output_audio_transcript.done': {
277 const transcript = event.transcript as string
278 emit('transcript', { role: 'assistant', transcript, isFinal: true })
279 break
280 }
281​
282 case 'response.output_text.delta': {
283 const delta = event.delta as string
284 emit('transcript', {
285 role: 'assistant',
286 transcript: delta,
287 isFinal: false,
288 })
289 break
290 }
291​
292 case 'response.output_text.done': {
293 const text = event.text as string
294 emit('transcript', {
295 role: 'assistant',
296 transcript: text,
297 isFinal: true,
298 })
299 break
300 }
301​
302 case 'response.output_audio.delta':
303 if (currentMode !== 'speaking') {
304 currentMode = 'speaking'
305 emit('mode_change', { mode: 'speaking' })
306 }
307 break
308​
309 case 'response.output_audio.done':
310 break
311​
312 case 'response.function_call_arguments.done': {
313 // Realtime payloads include both call_id and item_id; some sessions omit one.
314 const callId = (event['call_id'] ?? event['item_id']) as
315 | string
316 | undefined
317 const name = event['name'] as string
318 const args = event['arguments'] as string
319 if (!callId) {
320 logger.errors(
321 'openai.realtime function_call_arguments.done missing ids',
322 {
323 event,
324 source: 'openai.realtime',
325 },
326 )
327 break
328 }
329 try {
330 const input = JSON.parse(args)
331 emit('tool_call', { toolCallId: callId, toolName: name, input })
332 } catch {
333 emit('tool_call', {
334 toolCallId: callId,
335 toolName: name,
336 input: args,
337 })
338 }
339 break
340 }
341​
342 case 'response.done': {
343 const response = event.response as Record<string, unknown>
344 const output = response.output as
345 | Array<Record<string, unknown>>
346 | undefined
347​
348 currentMode = 'listening'
349 emit('mode_change', { mode: 'listening' })
350​
351 // Emit message complete if we have a current message
352 if (currentMessageId) {
353 const message: RealtimeMessage = {
354 id: currentMessageId,
355 role: 'assistant',
356 timestamp: Date.now(),
357 parts: [],
358 }
359​
360 // Extract content from output items
361 for (const item of output || []) {
362 if (item.type === 'message' && item.content) {
363 const content = item.content as Array<Record<string, unknown>>
364 for (const part of content) {
365 // GA renamed assistant content types: `audio` -> `output_audio`,
366 // `text` -> `output_text`
367 if (part.type === 'output_audio' && part.transcript) {
368 message.parts.push({
369 type: 'audio',
370 transcript: part.transcript as string,
371 })
372 } else if (part.type === 'output_text' && part.text) {
373 message.parts.push({
374 type: 'text',
375 content: part.text as string,
376 })
377 }
378 }
379 }
380 }
381​
382 emit('message_complete', { message })
383 currentMessageId = null
384 }
385 break
386 }
387​
388 case 'conversation.item.truncated':
389 emit(
390 'interrupted',
391 currentMessageId ? { messageId: currentMessageId } : {},
392 )
393 break
394​
395 case 'error': {
396 const error = event.error as Record<string, unknown>
397 emit('error', {
398 error: new Error((error.message as string) || 'Unknown error'),
399 })
400 break
401 }
402 }
403 }
404​
405 // Set up audio analysis for output
406 function setupOutputAudioAnalysis(stream: MediaStream) {
407 // Create audio element for playback - this is the standard way to play WebRTC audio
408 audioElement = new Audio()
409 audioElement.srcObject = stream
410 audioElement.autoplay = true
411 // Some browsers require this for autoplay
412 audioElement.play().catch((e) => {
413 logger.errors('openai.realtime audio autoplay failed', {
414 error: e,
415 source: 'openai.realtime',
416 })
417 })
418​
419 // Set up AudioContext for visualization only (not playback)
420 if (!audioContext) {
421 audioContext = new AudioContext()
422 }
423​
424 // Resume AudioContext if suspended (browsers require user interaction)
425 if (audioContext.state === 'suspended') {
426 audioContext.resume().catch(() => {
427 // Ignore - visualization just won't work
428 })
429 }
430​
431 outputAnalyser = audioContext.createAnalyser()
432 outputAnalyser.fftSize = 2048 // Larger size for more accurate level detection
433 outputAnalyser.smoothingTimeConstant = 0.3
434​
435 outputSource = audioContext.createMediaStreamSource(stream)
436 outputSource.connect(outputAnalyser)
437 // Don't connect to destination - the Audio element handles playback
438 }
439​
440 // Set up audio analysis for input
441 function setupInputAudioAnalysis(stream: MediaStream) {
442 if (!audioContext) {
443 audioContext = new AudioContext()
444 }
445​
446 // Resume AudioContext if suspended (browsers require user interaction)
447 if (audioContext.state === 'suspended') {
448 audioContext.resume().catch(() => {
449 // Ignore - visualization just won't work
450 })
451 }
452​
453 inputAnalyser = audioContext.createAnalyser()
454 inputAnalyser.fftSize = 2048 // Larger size for more accurate level detection
455 inputAnalyser.smoothingTimeConstant = 0.3
456​
457 inputSource = audioContext.createMediaStreamSource(stream)
458 inputSource.connect(inputAnalyser)
459 }
460​
461 // Queue for events sent before the data channel is open
462 const pendingEvents: Array<Record<string, unknown>> = []
463​
464 // Send event to server (queues if data channel not yet open)
465 function sendEvent(event: Record<string, unknown>) {
466 if (dataChannel?.readyState === 'open') {
467 logger.provider(
468 `provider=openai direction=out type=${(event.type as string | undefined) ?? '<unknown>'}`,
469 { frame: event },
470 )
471 dataChannel.send(JSON.stringify(event))
472 } else {
473 pendingEvents.push(event)
474 }
475 }
476​
477 // Flush any queued events (called when data channel opens)
478 function flushPendingEvents() {
479 for (const event of pendingEvents) {
480 logger.provider(
481 `provider=openai direction=out type=${(event.type as string | undefined) ?? '<unknown>'}`,
482 { frame: event },
483 )
484 channel.send(JSON.stringify(event))
485 }
486 pendingEvents.length = 0
487 }
488​
489 // Connection implementation
490 const connection: RealtimeConnection = {
491 async disconnect() {
492 if (localStream) {
493 for (const track of localStream.getTracks()) {
494 track.stop()
495 }
496 localStream = null
497 }
498​
499 if (audioElement) {
500 audioElement.pause()
501 audioElement.srcObject = null
502 audioElement = null
503 }
504​
505 if (dataChannel) {
506 dataChannel.close()
507 dataChannel = null
508 }
509​
510 pc.close()
511​
512 if (audioContext) {
513 await audioContext.close()
514 audioContext = null
515 }
516​
517 emit('status_change', { status: 'idle' })
518 },
519​
520 async startAudioCapture() {
521 // Audio capture is established during connection setup
522 // This method enables the tracks and signals listening mode
523 if (localStream) {
524 for (const track of localStream.getAudioTracks()) {
525 track.enabled = true
526 }
527 }
528 currentMode = 'listening'
529 emit('mode_change', { mode: 'listening' })
530 },
531​
532 stopAudioCapture() {
533 // Disable tracks rather than stopping them to allow re-enabling
534 if (localStream) {
535 for (const track of localStream.getAudioTracks()) {
536 track.enabled = false
537 }
538 }
539 currentMode = 'idle'
540 emit('mode_change', { mode: 'idle' })
541 },
542​
543 sendText(text: string) {
544 sendEvent({
545 type: 'conversation.item.create',
546 item: {
547 type: 'message',
548 role: 'user',
549 content: [{ type: 'input_text', text }],
550 },
551 })
552 sendEvent({
553 type: 'response.create',
554 })
555 },
556​
557 sendImage(imageData: string, mimeType: string) {
558 // Determine if imageData is a URL or base64 data
559 const isUrl =
560 imageData.startsWith('http://') || imageData.startsWith('https://')
561 const imageContent = isUrl
562 ? { type: 'input_image', image_url: imageData }
563 : {
564 type: 'input_image',
565 image_url: `data:${mimeType};base64,${imageData}`,
566 }
567​
568 sendEvent({
569 type: 'conversation.item.create',
570 item: {
571 type: 'message',
572 role: 'user',
573 content: [imageContent],
574 },
575 })
576 sendEvent({
577 type: 'response.create',
578 })
579 },
580​
581 sendToolResult(callId: string, result: string) {
582 sendEvent({
583 type: 'conversation.item.create',
584 item: {
585 type: 'function_call_output',
586 call_id: callId,
587 output: result,
588 },
589 })
590 sendEvent({ type: 'response.create' })
591 },
592​
593 updateSession(config: Partial<RealtimeSessionConfig>) {
594 if (config.temperature !== undefined) {
595 // The GA API removed `temperature` from session config; sending it
596 // would get the whole update rejected with `unknown_parameter`.
597 logger.provider(
598 'provider=openai direction=out type=session.update dropped `temperature` (removed in the GA realtime API)',
599 { frame: { temperature: config.temperature } },
600 )
601 }
602​
603 sendEvent({
604 type: 'session.update',
605 session: buildSessionUpdate(config),
606 })
607 },
608​
609 interrupt() {
610 sendEvent({ type: 'response.cancel' })
611 currentMode = 'listening'
612 emit('mode_change', { mode: 'listening' })
613 emit(
614 'interrupted',
615 currentMessageId ? { messageId: currentMessageId } : {},
616 )
617 },
618​
619 on<TEvent extends RealtimeEvent>(
620 event: TEvent,
621 handler: RealtimeEventHandler<TEvent>,
622 ): () => void {
623 let handlers = eventHandlers.get(event)
624 if (!handlers) {
625 handlers = new Set()
626 eventHandlers.set(event, handlers)
627 }
628 handlers.add(handler)
629​
630 return () => {
631 eventHandlers.get(event)?.delete(handler)
632 }
633 },
634​
635 getAudioVisualization(): AudioVisualization {
636 // Helper to calculate audio level from time domain data
637 // Uses peak amplitude which is more responsive for voice audio meters
638 function calculateLevel(analyser: AnalyserNode): number {
639 const data = new Uint8Array(analyser.fftSize)
640 analyser.getByteTimeDomainData(data)
641​
642 // Find peak deviation from center (128 is silence)
643 // This is more responsive than RMS for voice level meters
644 let maxDeviation = 0
645 for (const sample of data) {
646 const deviation = Math.abs(sample - 128)
647 if (deviation > maxDeviation) {
648 maxDeviation = deviation
649 }
650 }
651​
652 // Normalize to 0-1 range (max deviation is 128)
653 // Scale by 1.5x so that ~66% amplitude reads as full scale
654 // This provides good visual feedback without pegging too early
655 const normalized = maxDeviation / 128
656 return Math.min(1, normalized * 1.5)
657 }
658​
659 return {
660 get inputLevel() {
661 if (!inputAnalyser) return 0
662 return calculateLevel(inputAnalyser)
663 },
664​
665 get outputLevel() {
666 if (!outputAnalyser) return 0
667 return calculateLevel(outputAnalyser)
668 },
669​
670 getInputFrequencyData() {
671 if (!inputAnalyser) return emptyFrequencyData
672 const data = new Uint8Array(inputAnalyser.frequencyBinCount)
673 inputAnalyser.getByteFrequencyData(data)
674 return data
675 },
676​
677 getOutputFrequencyData() {
678 if (!outputAnalyser) return emptyFrequencyData
679 const data = new Uint8Array(outputAnalyser.frequencyBinCount)
680 outputAnalyser.getByteFrequencyData(data)
681 return data
682 },
683​
684 getInputTimeDomainData() {
685 if (!inputAnalyser) return emptyTimeDomainData
686 const data = new Uint8Array(inputAnalyser.fftSize)
687 inputAnalyser.getByteTimeDomainData(data)
688 return data
689 },
690​
691 getOutputTimeDomainData() {
692 if (!outputAnalyser) return emptyTimeDomainData
693 const data = new Uint8Array(outputAnalyser.fftSize)
694 outputAnalyser.getByteTimeDomainData(data)
695 return data
696 },
697​
698 get inputSampleRate() {
699 return 24000
700 },
701​
702 get outputSampleRate() {
703 return 24000
704 },
705 }
706 },
707 }
708​
709 // Wait for the data channel to be open before returning the connection.
710 // This ensures session.update (tools, instructions, etc.) can be sent immediately.
711 await dataChannelReady
712​
713 return connection