Open History to see the last commit
1import { RealtimeClient } from '@tanstack/ai-client'
2import type {
3 RealtimeMessage,
4 RealtimeMode,
5 RealtimeSessionConfig,
6 RealtimeStatus,
7} from '@tanstack/ai'
8import type { Handle } from 'remix/ui'
9import type { CreateRealtimeChatOptions } from './realtime-types.ts'
10
11const emptyFrequencyData = new Uint8Array(128)
12const emptyTimeDomainData = new Uint8Array(128).fill(128)
13
14/**
15 * Remix helper for realtime voice conversations.
16 *
17 * Call from component setup with Handle. State fields are getters so the
18 * render function reads the current value after `handle.update()`.
19 *
20 * @param handle - Remix Handle from setup. Used to re-render and to clean up
21 * when the component disconnects.
22 * @param options - Adapter, token loader, and optional session/callback config.
23 *
24 * @example
25 * ```typescript
26 * import { createRealtimeChat } from '@tanstack/ai-remix'
27 * import { openaiRealtime } from '@tanstack/ai-openai'
28 * import type { Handle } from 'remix/ui'
29 *
30 * function VoiceChat(handle: Handle) {
31 * const chat = createRealtimeChat(handle, {
32 * getToken: () => fetch('/api/realtime-token').then((r) => r.json()),
33 * adapter: openaiRealtime(),
34 * })
35 *
36 * return () => (
37 * <div>
38 * <p>Status: {chat.status}</p>
39 * <button on={{ click: chat.status === 'idle' ? chat.connect : chat.disconnect }}>
40 * {chat.status === 'idle' ? 'Start' : 'Stop'}
41 * </button>
42 * </div>
43 * )
44 * }
45 * ```
46 */
47export function createRealtimeChat(
48 handle: Handle,
49 options: CreateRealtimeChatOptions,
50) {
51 let status: RealtimeStatus = 'idle'
52 let mode: RealtimeMode = 'idle'
53 let messages: Array<RealtimeMessage> = []
54 let pendingUserTranscript: string | null = null
55 let pendingAssistantTranscript: string | null = null
56 let error: Error | null = null
57 let animationFrame: number | null = null
58
59 function notify() {
60 if (!handle.signal.aborted) {
61 void handle.update()
62 }
63 }
64
65 function stopLevelLoop() {
66 if (animationFrame === null) return
67 cancelAnimationFrame(animationFrame)
68 animationFrame = null
69 }
70
71 function startLevelLoop() {
72 if (animationFrame !== null) return
73 function tick() {
74 animationFrame = requestAnimationFrame(tick)
75 notify()
76 }
77 animationFrame = requestAnimationFrame(tick)
78 }
79
80 // Each optional source field is spread conditionally because the
81 // `RealtimeClientOptions` target declares strict optionals
82 // (`field?: T`) and `exactOptionalPropertyTypes` rejects passing
83 // `undefined` for absent values.
84 const client = new RealtimeClient({
85 getToken: () => options.getToken(),
86 adapter: {
87 get provider() {
88 return options.adapter.provider
89 },
90 connect(token, tools) {
91 return options.adapter.connect(token, tools)
92 },
93 },
94 ...(options.tools !== undefined && { tools: options.tools }),
95 ...(options.instructions !== undefined && {
96 instructions: options.instructions,
97 }),
98 ...(options.voice !== undefined && { voice: options.voice }),
99 ...(options.autoPlayback !== undefined && {
100 autoPlayback: options.autoPlayback,
101 }),
102 ...(options.autoCapture !== undefined && {
103 autoCapture: options.autoCapture,
104 }),
105 ...(options.vadMode !== undefined && { vadMode: options.vadMode }),
106 ...(options.outputModalities !== undefined && {
107 outputModalities: options.outputModalities,
108 }),
109 ...(options.temperature !== undefined && {
110 temperature: options.temperature,
111 }),
112 ...(options.maxOutputTokens !== undefined && {
113 maxOutputTokens: options.maxOutputTokens,
114 }),
115 ...(options.semanticEagerness !== undefined && {
116 semanticEagerness: options.semanticEagerness,
117 }),
118 onStatusChange: (newStatus) => {
119 status = newStatus
120 if (newStatus === 'connected') {
121 startLevelLoop()
122 } else {
123 stopLevelLoop()
124 }
125 notify()
126 options.onStatusChange?.(newStatus)
127 },
128 onModeChange: (newMode) => {
129 mode = newMode
130 notify()
131 options.onModeChange?.(newMode)
132 },
133 onMessage: (message) => {
134 messages = [...messages, message]
135 notify()
136 options.onMessage?.(message)
137 },
138 onUsage: (usage) => {
139 options.onUsage?.(usage)
140 },
141 onGoAway: (timeLeft) => {
142 options.onGoAway?.(timeLeft)
143 },
144 onError: (err) => {
145 error = err
146 notify()
147 options.onError?.(err)
148 },
149 onConnect: () => {
150 error = null
151 notify()
152 options.onConnect?.()
153 },
154 onDisconnect: () => {
155 options.onDisconnect?.()
156 },
157 onInterrupted: () => {
158 pendingAssistantTranscript = null
159 notify()
160 options.onInterrupted?.()
161 },
162 })
163
164 client.onStateChange((state) => {
165 pendingUserTranscript = state.pendingUserTranscript
166 pendingAssistantTranscript = state.pendingAssistantTranscript
167 notify()
168 })
169
170 handle.signal.addEventListener('abort', () => {
171 stopLevelLoop()
172 client.destroy()
173 })
174
175 return {
176 get status() {
177 return status
178 },
179 get error() {
180 return error
181 },
182 connect: async () => {
183 error = null
184 messages = []
185 pendingUserTranscript = null
186 pendingAssistantTranscript = null
187 notify()
188 await client.connect()
189 },
190 disconnect: () => client.disconnect(),
191
192 get mode() {
193 return mode
194 },
195 get messages() {
196 return messages
197 },
198 get pendingUserTranscript() {
199 return pendingUserTranscript
200 },
201 get pendingAssistantTranscript() {
202 return pendingAssistantTranscript
203 },
204
205 startListening: () => {
206 client.startListening()
207 },
208 stopListening: () => {
209 client.stopListening()
210 },
211 interrupt: () => {
212 client.interrupt()
213 },
214
215 sendText: (text: string) => {
216 client.sendText(text)
217 },
218
219 sendImage: (imageData: string, mimeType: string) => {
220 client.sendImage(imageData, mimeType)
221 },
222
223 get inputLevel() {
224 return client.audio?.inputLevel ?? 0
225 },
226 get outputLevel() {
227 return client.audio?.outputLevel ?? 0
228 },
229 getInputFrequencyData: () =>
230 client.audio?.getInputFrequencyData() ?? emptyFrequencyData,
231 getOutputFrequencyData: () =>
232 client.audio?.getOutputFrequencyData() ?? emptyFrequencyData,
233 getInputTimeDomainData: () =>
234 client.audio?.getInputTimeDomainData() ?? emptyTimeDomainData,
235 getOutputTimeDomainData: () =>
236 client.audio?.getOutputTimeDomainData() ?? emptyTimeDomainData,
237
238 updateSession: (config: RealtimeSessionConfig) => {
239 client.updateSession(config)
240 },
241 }
242}