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

use-realtime-chat.ts

294 lines7.8 KB

1import { useCallback, useEffect, useRef, useState } from 'react'
2import { RealtimeClient } from '@tanstack/ai-client'
3import type {
4 RealtimeMessage,
5 RealtimeMode,
6 RealtimeSessionConfig,
7 RealtimeStatus,
8} from '@tanstack/ai'
9import type {
10 UseRealtimeChatOptions,
11 UseRealtimeChatReturn,
12} from './realtime-types'
13​
14// Empty frequency data for when client is not connected
15const emptyFrequencyData = new Uint8Array(128)
16const emptyTimeDomainData = new Uint8Array(128).fill(128)
17​
18/**
19 * React hook for realtime voice conversations.
20 *
21 * Provides a simple interface for voice-to-voice AI interactions
22 * with support for multiple providers (OpenAI, ElevenLabs, etc.).
23 *
24 * @param options - Configuration options including adapter and callbacks
25 * @returns Hook return value with state and control methods
26 *
27 * @example
28 * ```typescript
29 * import { useRealtimeChat } from '@tanstack/ai-react'
30 * import { openaiRealtime } from '@tanstack/ai-openai'
31 *
32 * function VoiceChat() {
33 * const {
34 * status,
35 * mode,
36 * messages,
37 * connect,
38 * disconnect,
39 * inputLevel,
40 * outputLevel,
41 * } = useRealtimeChat({
42 * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
43 * adapter: openaiRealtime(),
44 * })
45 *
46 * return (
47 * <div>
48 * <p>Status: {status}</p>
49 * <p>Mode: {mode}</p>
50 * <button onClick={status === 'idle' ? connect : disconnect}>
51 * {status === 'idle' ? 'Start' : 'Stop'}
52 * </button>
53 * </div>
54 * )
55 * }
56 * ```
57 */
58export function useRealtimeChat(
59 options: UseRealtimeChatOptions,
60): UseRealtimeChatReturn {
61 // State
62 const [status, setStatus] = useState<RealtimeStatus>('idle')
63 const [mode, setMode] = useState<RealtimeMode>('idle')
64 const [messages, setMessages] = useState<Array<RealtimeMessage>>([])
65 const [pendingUserTranscript, setPendingUserTranscript] = useState<
66 string | null
67 >(null)
68 const [pendingAssistantTranscript, setPendingAssistantTranscript] = useState<
69 string | null
70 >(null)
71 const [error, setError] = useState<Error | null>(null)
72 const [inputLevel, setInputLevel] = useState(0)
73 const [outputLevel, setOutputLevel] = useState(0)
74​
75 // Refs
76 const clientRef = useRef<RealtimeClient | null>(null)
77 const optionsRef = useRef(options)
78 optionsRef.current = options
79 const animationFrameRef = useRef<number | null>(null)
80​
81 // Create client instance - use ref to ensure we reuse the same instance
82 // This handles React StrictMode double-rendering
83 if (!clientRef.current) {
84 // Each optional source field is spread conditionally because the
85 // `RealtimeClientOptions` target declares strict optionals
86 // (`field?: T`) and `exactOptionalPropertyTypes` rejects passing
87 // `undefined` for absent values.
88 const initial = optionsRef.current
89 clientRef.current = new RealtimeClient({
90 getToken: initial.getToken,
91 adapter: initial.adapter,
92 ...(initial.tools !== undefined && { tools: initial.tools }),
93 ...(initial.instructions !== undefined && {
94 instructions: initial.instructions,
95 }),
96 ...(initial.voice !== undefined && { voice: initial.voice }),
97 ...(initial.autoPlayback !== undefined && {
98 autoPlayback: initial.autoPlayback,
99 }),
100 ...(initial.autoCapture !== undefined && {
101 autoCapture: initial.autoCapture,
102 }),
103 ...(initial.vadMode !== undefined && { vadMode: initial.vadMode }),
104 ...(initial.outputModalities !== undefined && {
105 outputModalities: initial.outputModalities,
106 }),
107 ...(initial.temperature !== undefined && {
108 temperature: initial.temperature,
109 }),
110 ...(initial.maxOutputTokens !== undefined && {
111 maxOutputTokens: initial.maxOutputTokens,
112 }),
113 ...(initial.semanticEagerness !== undefined && {
114 semanticEagerness: initial.semanticEagerness,
115 }),
116 onStatusChange: (newStatus) => {
117 setStatus(newStatus)
118 },
119 onModeChange: (newMode) => {
120 setMode(newMode)
121 optionsRef.current.onModeChange?.(newMode)
122 },
123 onMessage: (message) => {
124 setMessages((prev) => [...prev, message])
125 optionsRef.current.onMessage?.(message)
126 },
127 onUsage(usage) {
128 optionsRef.current.onUsage?.(usage)
129 },
130 onGoAway(timeLeft) {
131 optionsRef.current.onGoAway?.(timeLeft)
132 },
133 onError: (err) => {
134 setError(err)
135 optionsRef.current.onError?.(err)
136 },
137 onConnect: () => {
138 setError(null)
139 optionsRef.current.onConnect?.()
140 },
141 onDisconnect: () => {
142 optionsRef.current.onDisconnect?.()
143 },
144 onInterrupted: () => {
145 setPendingAssistantTranscript(null)
146 optionsRef.current.onInterrupted?.()
147 },
148 })
149​
150 // Subscribe to state changes for transcripts
151 clientRef.current.onStateChange((state) => {
152 setPendingUserTranscript(state.pendingUserTranscript)
153 setPendingAssistantTranscript(state.pendingAssistantTranscript)
154 })
155 }
156​
157 const client = clientRef.current
158​
159 // Audio level animation loop
160 useEffect(() => {
161 function updateLevels() {
162 if (clientRef.current?.audio) {
163 setInputLevel(clientRef.current.audio.inputLevel)
164 setOutputLevel(clientRef.current.audio.outputLevel)
165 }
166 animationFrameRef.current = requestAnimationFrame(updateLevels)
167 }
168​
169 if (status === 'connected') {
170 updateLevels()
171 }
172​
173 return () => {
174 if (animationFrameRef.current) {
175 cancelAnimationFrame(animationFrameRef.current)
176 animationFrameRef.current = null
177 }
178 }
179 }, [status])
180​
181 // Cleanup on unmount
182 useEffect(() => {
183 return () => {
184 clientRef.current?.destroy()
185 }
186 }, [])
187​
188 // Connection methods
189 const connect = useCallback(async () => {
190 setError(null)
191 setMessages([])
192 setPendingUserTranscript(null)
193 setPendingAssistantTranscript(null)
194 await client.connect()
195 }, [client])
196​
197 const disconnect = useCallback(async () => {
198 await client.disconnect()
199 }, [client])
200​
201 // Voice control methods
202 const startListening = useCallback(() => {
203 client.startListening()
204 }, [client])
205​
206 const stopListening = useCallback(() => {
207 client.stopListening()
208 }, [client])
209​
210 const interrupt = useCallback(() => {
211 client.interrupt()
212 }, [client])
213​
214 // Text input
215 const sendText = useCallback(
216 (text: string) => {
217 client.sendText(text)
218 },
219 [client],
220 )
221​
222 // Image input
223 const sendImage = useCallback(
224 (imageData: string, mimeType: string) => {
225 client.sendImage(imageData, mimeType)
226 },
227 [client],
228 )
229​
230 // Audio visualization
231 const getInputFrequencyData = useCallback(() => {
232 return (
233 clientRef.current?.audio?.getInputFrequencyData() ?? emptyFrequencyData
234 )
235 }, [])
236​
237 const getOutputFrequencyData = useCallback(() => {
238 return (
239 clientRef.current?.audio?.getOutputFrequencyData() ?? emptyFrequencyData
240 )
241 }, [])
242​
243 const getInputTimeDomainData = useCallback(() => {
244 return (
245 clientRef.current?.audio?.getInputTimeDomainData() ?? emptyTimeDomainData
246 )
247 }, [])
248​
249 const getOutputTimeDomainData = useCallback(() => {
250 return (
251 clientRef.current?.audio?.getOutputTimeDomainData() ?? emptyTimeDomainData
252 )
253 }, [])
254​
255 const updateSession = useCallback((config: RealtimeSessionConfig) => {
256 clientRef.current?.updateSession(config)
257 }, [])
258​
259 return {
260 // Connection state
261 status,
262 error,
263 connect,
264 disconnect,
265​
266 // Conversation state
267 mode,
268 messages,
269 pendingUserTranscript,
270 pendingAssistantTranscript,
271​
272 // Voice control
273 startListening,
274 stopListening,
275 interrupt,
276​
277 // Text input
278 sendText,
279​
280 // Image input
281 sendImage,
282​
283 // Audio visualization
284 inputLevel,
285 outputLevel,
286 getInputFrequencyData,
287 getOutputFrequencyData,
288 getInputTimeDomainData,
289 getOutputTimeDomainData,
290​
291 // Session control
292 updateSession,
293 }