@tanstack/ai-react 0.6.3 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/esm/index.d.ts +15 -1
  2. package/dist/esm/index.js +15 -1
  3. package/dist/esm/index.js.map +1 -1
  4. package/dist/esm/realtime-types.d.ts +109 -0
  5. package/dist/esm/use-generate-image.d.ts +87 -0
  6. package/dist/esm/use-generate-image.js +17 -0
  7. package/dist/esm/use-generate-image.js.map +1 -0
  8. package/dist/esm/use-generate-speech.d.ts +81 -0
  9. package/dist/esm/use-generate-speech.js +17 -0
  10. package/dist/esm/use-generate-speech.js.map +1 -0
  11. package/dist/esm/use-generate-video.d.ts +92 -0
  12. package/dist/esm/use-generate-video.js +83 -0
  13. package/dist/esm/use-generate-video.js.map +1 -0
  14. package/dist/esm/use-generation.d.ts +78 -0
  15. package/dist/esm/use-generation.js +75 -0
  16. package/dist/esm/use-generation.js.map +1 -0
  17. package/dist/esm/use-realtime-chat.d.ts +42 -0
  18. package/dist/esm/use-realtime-chat.js +174 -0
  19. package/dist/esm/use-realtime-chat.js.map +1 -0
  20. package/dist/esm/use-summarize.d.ts +84 -0
  21. package/dist/esm/use-summarize.js +19 -0
  22. package/dist/esm/use-summarize.js.map +1 -0
  23. package/dist/esm/use-transcription.d.ts +89 -0
  24. package/dist/esm/use-transcription.js +19 -0
  25. package/dist/esm/use-transcription.js.map +1 -0
  26. package/package.json +4 -4
  27. package/src/index.ts +47 -0
  28. package/src/realtime-types.ts +143 -0
  29. package/src/use-generate-image.ts +117 -0
  30. package/src/use-generate-speech.ts +108 -0
  31. package/src/use-generate-video.ts +206 -0
  32. package/src/use-generation.ts +180 -0
  33. package/src/use-realtime-chat.ts +277 -0
  34. package/src/use-summarize.ts +114 -0
  35. package/src/use-transcription.ts +121 -0
@@ -0,0 +1,180 @@
1
+ import { GenerationClient } from '@tanstack/ai-client'
2
+ import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
3
+ import type { StreamChunk } from '@tanstack/ai'
4
+ import type {
5
+ ConnectionAdapter,
6
+ GenerationClientOptions,
7
+ GenerationClientState,
8
+ GenerationFetcher,
9
+ InferGenerationOutput,
10
+ } from '@tanstack/ai-client'
11
+
12
+ /**
13
+ * Options for the useGeneration hook.
14
+ *
15
+ * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).
16
+ *
17
+ * @template TInput - The input type for the generation request
18
+ * @template TResult - The result type returned by the generation
19
+ * @template TOutput - The output type after optional transform (defaults to TResult)
20
+ */
21
+ export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
22
+ /** Connection adapter for streaming transport (SSE, HTTP stream, custom) */
23
+ connection?: ConnectionAdapter
24
+ /** Direct async function for one-shot generation (no streaming protocol needed) */
25
+ fetcher?: GenerationFetcher<TInput, TResult>
26
+ /** Unique identifier for this generation instance */
27
+ id?: string
28
+ /** Additional body parameters to send with ConnectionAdapter requests */
29
+ body?: Record<string, any>
30
+ /**
31
+ * Callback when a result is received. Can optionally return a transformed value.
32
+ *
33
+ * - Return a non-null value to transform and store it as the result
34
+ * - Return `null` to keep the previous result unchanged
35
+ * - Return nothing (`void`) to store the raw result as-is
36
+ */
37
+ onResult?: (result: TResult) => TOutput | null | void
38
+ /** Callback when an error occurs */
39
+ onError?: (error: Error) => void
40
+ /** Callback when progress is reported (0-100) */
41
+ onProgress?: (progress: number, message?: string) => void
42
+ /** Callback for each stream chunk (ConnectionAdapter mode only) */
43
+ onChunk?: (chunk: StreamChunk) => void
44
+ }
45
+
46
+ /**
47
+ * Return type for the useGeneration hook.
48
+ *
49
+ * @template TOutput - The output type (after optional transform)
50
+ */
51
+ export interface UseGenerationReturn<TOutput> {
52
+ /** Trigger a generation request */
53
+ generate: (input: Record<string, any>) => Promise<void>
54
+ /** The generation result, or null if not yet generated */
55
+ result: TOutput | null
56
+ /** Whether a generation is currently in progress */
57
+ isLoading: boolean
58
+ /** Current error, if any */
59
+ error: Error | undefined
60
+ /** Current state of the generation client */
61
+ status: GenerationClientState
62
+ /** Abort the current generation */
63
+ stop: () => void
64
+ /** Clear result, error, and return to idle */
65
+ reset: () => void
66
+ }
67
+
68
+ /**
69
+ * Generic React hook for one-shot generation tasks.
70
+ *
71
+ * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
72
+ * `useTranscription`, and `useSummarize`. You can also use it directly
73
+ * for custom generation types.
74
+ *
75
+ * @template TInput - The input type for the generation request
76
+ * @template TResult - The result type returned by the generation
77
+ *
78
+ * @example
79
+ * ```tsx
80
+ * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
81
+ * connection: fetchServerSentEvents('/api/generate/custom'),
82
+ * })
83
+ *
84
+ * await generate({ prompt: 'Hello' })
85
+ * ```
86
+ */
87
+ export function useGeneration<
88
+ TInput extends Record<string, any>,
89
+ TResult,
90
+ TOnResult extends ((result: TResult) => any) | undefined = undefined,
91
+ >(
92
+ options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
93
+ onResult?: TOnResult
94
+ },
95
+ ): UseGenerationReturn<InferGenerationOutput<TResult, TOnResult>> {
96
+ type TOutput = InferGenerationOutput<TResult, TOnResult>
97
+ const hookId = useId()
98
+ const clientId = options.id || hookId
99
+
100
+ const [result, setResult] = useState<TOutput | null>(null)
101
+ const [isLoading, setIsLoading] = useState(false)
102
+ const [error, setError] = useState<Error | undefined>(undefined)
103
+ const [status, setStatus] = useState<GenerationClientState>('idle')
104
+
105
+ const optionsRef = useRef(options)
106
+ optionsRef.current = options
107
+
108
+ const client = useMemo(() => {
109
+ const opts = optionsRef.current
110
+
111
+ const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
112
+ id: clientId,
113
+ body: opts.body,
114
+ onResult: (r: TResult) => optionsRef.current.onResult?.(r),
115
+ onError: (e: Error) => optionsRef.current.onError?.(e),
116
+ onProgress: (p: number, m?: string) =>
117
+ optionsRef.current.onProgress?.(p, m),
118
+ onChunk: (c: StreamChunk) => optionsRef.current.onChunk?.(c),
119
+ onResultChange: setResult,
120
+ onLoadingChange: setIsLoading,
121
+ onErrorChange: setError,
122
+ onStatusChange: setStatus,
123
+ }
124
+
125
+ if (opts.connection) {
126
+ return new GenerationClient<TInput, TResult, TOutput>({
127
+ ...clientOptions,
128
+ connection: opts.connection,
129
+ })
130
+ }
131
+
132
+ if (opts.fetcher) {
133
+ return new GenerationClient<TInput, TResult, TOutput>({
134
+ ...clientOptions,
135
+ fetcher: opts.fetcher,
136
+ })
137
+ }
138
+
139
+ throw new Error(
140
+ 'useGeneration requires either a connection or fetcher option',
141
+ )
142
+ }, [clientId])
143
+
144
+ // Sync body changes without recreating client
145
+ useEffect(() => {
146
+ client.updateOptions({ body: options.body })
147
+ }, [client, options.body])
148
+
149
+ // Cleanup on unmount
150
+ useEffect(() => {
151
+ return () => {
152
+ client.stop()
153
+ }
154
+ }, [client])
155
+
156
+ const generate = useCallback(
157
+ async (input: TInput) => {
158
+ await client.generate(input)
159
+ },
160
+ [client],
161
+ )
162
+
163
+ const stop = useCallback(() => {
164
+ client.stop()
165
+ }, [client])
166
+
167
+ const reset = useCallback(() => {
168
+ client.reset()
169
+ }, [client])
170
+
171
+ return {
172
+ generate: generate as (input: Record<string, any>) => Promise<void>,
173
+ result,
174
+ isLoading,
175
+ error,
176
+ status,
177
+ stop,
178
+ reset,
179
+ }
180
+ }
@@ -0,0 +1,277 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { RealtimeClient } from '@tanstack/ai-client'
3
+ import type {
4
+ RealtimeMessage,
5
+ RealtimeMode,
6
+ RealtimeStatus,
7
+ } from '@tanstack/ai'
8
+ import type {
9
+ UseRealtimeChatOptions,
10
+ UseRealtimeChatReturn,
11
+ } from './realtime-types'
12
+
13
+ // Empty frequency data for when client is not connected
14
+ const emptyFrequencyData = new Uint8Array(128)
15
+ const emptyTimeDomainData = new Uint8Array(128).fill(128)
16
+
17
+ /**
18
+ * React hook for realtime voice conversations.
19
+ *
20
+ * Provides a simple interface for voice-to-voice AI interactions
21
+ * with support for multiple providers (OpenAI, ElevenLabs, etc.).
22
+ *
23
+ * @param options - Configuration options including adapter and callbacks
24
+ * @returns Hook return value with state and control methods
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * import { useRealtimeChat } from '@tanstack/ai-react'
29
+ * import { openaiRealtime } from '@tanstack/ai-openai'
30
+ *
31
+ * function VoiceChat() {
32
+ * const {
33
+ * status,
34
+ * mode,
35
+ * messages,
36
+ * connect,
37
+ * disconnect,
38
+ * inputLevel,
39
+ * outputLevel,
40
+ * } = useRealtimeChat({
41
+ * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
42
+ * adapter: openaiRealtime(),
43
+ * })
44
+ *
45
+ * return (
46
+ * <div>
47
+ * <p>Status: {status}</p>
48
+ * <p>Mode: {mode}</p>
49
+ * <button onClick={status === 'idle' ? connect : disconnect}>
50
+ * {status === 'idle' ? 'Start' : 'Stop'}
51
+ * </button>
52
+ * </div>
53
+ * )
54
+ * }
55
+ * ```
56
+ */
57
+ export function useRealtimeChat(
58
+ options: UseRealtimeChatOptions,
59
+ ): UseRealtimeChatReturn {
60
+ // State
61
+ const [status, setStatus] = useState<RealtimeStatus>('idle')
62
+ const [mode, setMode] = useState<RealtimeMode>('idle')
63
+ const [messages, setMessages] = useState<Array<RealtimeMessage>>([])
64
+ const [pendingUserTranscript, setPendingUserTranscript] = useState<
65
+ string | null
66
+ >(null)
67
+ const [pendingAssistantTranscript, setPendingAssistantTranscript] = useState<
68
+ string | null
69
+ >(null)
70
+ const [error, setError] = useState<Error | null>(null)
71
+ const [inputLevel, setInputLevel] = useState(0)
72
+ const [outputLevel, setOutputLevel] = useState(0)
73
+ const [vadMode, setVADModeState] = useState<'server' | 'semantic' | 'manual'>(
74
+ options.vadMode ?? 'server',
75
+ )
76
+
77
+ // Refs
78
+ const clientRef = useRef<RealtimeClient | null>(null)
79
+ const optionsRef = useRef(options)
80
+ optionsRef.current = options
81
+ const animationFrameRef = useRef<number | null>(null)
82
+
83
+ // Create client instance - use ref to ensure we reuse the same instance
84
+ // This handles React StrictMode double-rendering
85
+ if (!clientRef.current) {
86
+ clientRef.current = new RealtimeClient({
87
+ getToken: optionsRef.current.getToken,
88
+ adapter: optionsRef.current.adapter,
89
+ tools: optionsRef.current.tools,
90
+ instructions: optionsRef.current.instructions,
91
+ voice: optionsRef.current.voice,
92
+ autoPlayback: optionsRef.current.autoPlayback,
93
+ autoCapture: optionsRef.current.autoCapture,
94
+ vadMode: optionsRef.current.vadMode,
95
+ outputModalities: optionsRef.current.outputModalities,
96
+ temperature: optionsRef.current.temperature,
97
+ maxOutputTokens: optionsRef.current.maxOutputTokens,
98
+ semanticEagerness: optionsRef.current.semanticEagerness,
99
+ onStatusChange: (newStatus) => {
100
+ setStatus(newStatus)
101
+ },
102
+ onModeChange: (newMode) => {
103
+ setMode(newMode)
104
+ optionsRef.current.onModeChange?.(newMode)
105
+ },
106
+ onMessage: (message) => {
107
+ setMessages((prev) => [...prev, message])
108
+ optionsRef.current.onMessage?.(message)
109
+ },
110
+ onError: (err) => {
111
+ setError(err)
112
+ optionsRef.current.onError?.(err)
113
+ },
114
+ onConnect: () => {
115
+ setError(null)
116
+ optionsRef.current.onConnect?.()
117
+ },
118
+ onDisconnect: () => {
119
+ optionsRef.current.onDisconnect?.()
120
+ },
121
+ onInterrupted: () => {
122
+ setPendingAssistantTranscript(null)
123
+ optionsRef.current.onInterrupted?.()
124
+ },
125
+ })
126
+
127
+ // Subscribe to state changes for transcripts
128
+ clientRef.current.onStateChange((state) => {
129
+ setPendingUserTranscript(state.pendingUserTranscript)
130
+ setPendingAssistantTranscript(state.pendingAssistantTranscript)
131
+ })
132
+ }
133
+
134
+ const client = clientRef.current
135
+
136
+ // Audio level animation loop
137
+ useEffect(() => {
138
+ function updateLevels() {
139
+ if (clientRef.current?.audio) {
140
+ setInputLevel(clientRef.current.audio.inputLevel)
141
+ setOutputLevel(clientRef.current.audio.outputLevel)
142
+ }
143
+ animationFrameRef.current = requestAnimationFrame(updateLevels)
144
+ }
145
+
146
+ if (status === 'connected') {
147
+ updateLevels()
148
+ }
149
+
150
+ return () => {
151
+ if (animationFrameRef.current) {
152
+ cancelAnimationFrame(animationFrameRef.current)
153
+ animationFrameRef.current = null
154
+ }
155
+ }
156
+ }, [status])
157
+
158
+ // Cleanup on unmount
159
+ useEffect(() => {
160
+ return () => {
161
+ clientRef.current?.destroy()
162
+ }
163
+ }, [])
164
+
165
+ // Connection methods
166
+ const connect = useCallback(async () => {
167
+ setError(null)
168
+ setMessages([])
169
+ setPendingUserTranscript(null)
170
+ setPendingAssistantTranscript(null)
171
+ await client.connect()
172
+ }, [client])
173
+
174
+ const disconnect = useCallback(async () => {
175
+ await client.disconnect()
176
+ }, [client])
177
+
178
+ // Voice control methods
179
+ const startListening = useCallback(() => {
180
+ client.startListening()
181
+ }, [client])
182
+
183
+ const stopListening = useCallback(() => {
184
+ client.stopListening()
185
+ }, [client])
186
+
187
+ const interrupt = useCallback(() => {
188
+ client.interrupt()
189
+ }, [client])
190
+
191
+ // Text input
192
+ const sendText = useCallback(
193
+ (text: string) => {
194
+ client.sendText(text)
195
+ },
196
+ [client],
197
+ )
198
+
199
+ // Image input
200
+ const sendImage = useCallback(
201
+ (imageData: string, mimeType: string) => {
202
+ client.sendImage(imageData, mimeType)
203
+ },
204
+ [client],
205
+ )
206
+
207
+ // Audio visualization
208
+ const getInputFrequencyData = useCallback(() => {
209
+ return (
210
+ clientRef.current?.audio?.getInputFrequencyData() ?? emptyFrequencyData
211
+ )
212
+ }, [])
213
+
214
+ const getOutputFrequencyData = useCallback(() => {
215
+ return (
216
+ clientRef.current?.audio?.getOutputFrequencyData() ?? emptyFrequencyData
217
+ )
218
+ }, [])
219
+
220
+ const getInputTimeDomainData = useCallback(() => {
221
+ return (
222
+ clientRef.current?.audio?.getInputTimeDomainData() ?? emptyTimeDomainData
223
+ )
224
+ }, [])
225
+
226
+ const getOutputTimeDomainData = useCallback(() => {
227
+ return (
228
+ clientRef.current?.audio?.getOutputTimeDomainData() ?? emptyTimeDomainData
229
+ )
230
+ }, [])
231
+
232
+ // VAD mode control
233
+ const setVADMode = useCallback(
234
+ (newMode: 'server' | 'semantic' | 'manual') => {
235
+ setVADModeState(newMode)
236
+ // TODO: Update session config if connected
237
+ },
238
+ [],
239
+ )
240
+
241
+ return {
242
+ // Connection state
243
+ status,
244
+ error,
245
+ connect,
246
+ disconnect,
247
+
248
+ // Conversation state
249
+ mode,
250
+ messages,
251
+ pendingUserTranscript,
252
+ pendingAssistantTranscript,
253
+
254
+ // Voice control
255
+ startListening,
256
+ stopListening,
257
+ interrupt,
258
+
259
+ // Text input
260
+ sendText,
261
+
262
+ // Image input
263
+ sendImage,
264
+
265
+ // Audio visualization
266
+ inputLevel,
267
+ outputLevel,
268
+ getInputFrequencyData,
269
+ getOutputFrequencyData,
270
+ getInputTimeDomainData,
271
+ getOutputTimeDomainData,
272
+
273
+ // VAD control
274
+ vadMode,
275
+ setVADMode,
276
+ }
277
+ }
@@ -0,0 +1,114 @@
1
+ import { useGeneration } from './use-generation'
2
+ import type { StreamChunk, SummarizationResult } from '@tanstack/ai'
3
+ import type {
4
+ ConnectionAdapter,
5
+ GenerationClientState,
6
+ GenerationFetcher,
7
+ InferGenerationOutput,
8
+ SummarizeGenerateInput,
9
+ } from '@tanstack/ai-client'
10
+
11
+ /**
12
+ * Options for the useSummarize hook.
13
+ *
14
+ * @template TOutput - The output type after optional transform (defaults to SummarizationResult)
15
+ */
16
+ export interface UseSummarizeOptions<TOutput = SummarizationResult> {
17
+ /** Connection adapter for streaming transport (SSE, HTTP stream, custom) */
18
+ connection?: ConnectionAdapter
19
+ /** Direct async function for summarization */
20
+ fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>
21
+ /** Unique identifier for this generation instance */
22
+ id?: string
23
+ /** Additional body parameters to send with ConnectionAdapter requests */
24
+ body?: Record<string, any>
25
+ /**
26
+ * Callback when summarization is complete. Can optionally return a transformed value.
27
+ *
28
+ * - Return a non-null value to transform and store it as the result
29
+ * - Return `null` to keep the previous result unchanged
30
+ * - Return nothing (`void`) to store the raw result as-is
31
+ */
32
+ onResult?: (result: SummarizationResult) => TOutput | null | void
33
+ /** Callback when an error occurs */
34
+ onError?: (error: Error) => void
35
+ /** Callback when progress is reported (0-100) */
36
+ onProgress?: (progress: number, message?: string) => void
37
+ /** Callback for each stream chunk (ConnectionAdapter mode only) */
38
+ onChunk?: (chunk: StreamChunk) => void
39
+ }
40
+
41
+ /**
42
+ * Return type for the useSummarize hook.
43
+ *
44
+ * @template TOutput - The output type (after optional transform)
45
+ */
46
+ export interface UseSummarizeReturn<TOutput = SummarizationResult> {
47
+ /** Trigger summarization */
48
+ generate: (input: SummarizeGenerateInput) => Promise<void>
49
+ /** The summarization result, or null */
50
+ result: TOutput | null
51
+ /** Whether summarization is in progress */
52
+ isLoading: boolean
53
+ /** Current error, if any */
54
+ error: Error | undefined
55
+ /** Current state of the generation */
56
+ status: GenerationClientState
57
+ /** Abort the current summarization */
58
+ stop: () => void
59
+ /** Clear result, error, and return to idle */
60
+ reset: () => void
61
+ }
62
+
63
+ /**
64
+ * React hook for summarizing text using AI models.
65
+ *
66
+ * @example
67
+ * ```tsx
68
+ * import { useSummarize } from '@tanstack/ai-react'
69
+ * import { fetchServerSentEvents } from '@tanstack/ai-client'
70
+ *
71
+ * function Summarizer() {
72
+ * const { generate, result, isLoading } = useSummarize({
73
+ * connection: fetchServerSentEvents('/api/summarize'),
74
+ * })
75
+ *
76
+ * return (
77
+ * <div>
78
+ * <button onClick={() => generate({
79
+ * text: 'Long article text...',
80
+ * style: 'bullet-points',
81
+ * maxLength: 200,
82
+ * })}>
83
+ * Summarize
84
+ * </button>
85
+ * {isLoading && <p>Summarizing...</p>}
86
+ * {result && <p>{result.summary}</p>}
87
+ * </div>
88
+ * )
89
+ * }
90
+ * ```
91
+ */
92
+ export function useSummarize<
93
+ TOnResult extends ((result: SummarizationResult) => any) | undefined =
94
+ undefined,
95
+ >(
96
+ options: Omit<UseSummarizeOptions, 'onResult'> & {
97
+ onResult?: TOnResult
98
+ },
99
+ ): UseSummarizeReturn<InferGenerationOutput<SummarizationResult, TOnResult>> {
100
+ const { generate, result, isLoading, error, status, stop, reset } =
101
+ useGeneration<SummarizeGenerateInput, SummarizationResult, TOnResult>(
102
+ options,
103
+ )
104
+
105
+ return {
106
+ generate: generate as (input: SummarizeGenerateInput) => Promise<void>,
107
+ result,
108
+ isLoading,
109
+ error,
110
+ status,
111
+ stop,
112
+ reset,
113
+ }
114
+ }
@@ -0,0 +1,121 @@
1
+ import { useGeneration } from './use-generation'
2
+ import type { StreamChunk, TranscriptionResult } from '@tanstack/ai'
3
+ import type {
4
+ ConnectionAdapter,
5
+ GenerationClientState,
6
+ GenerationFetcher,
7
+ InferGenerationOutput,
8
+ TranscriptionGenerateInput,
9
+ } from '@tanstack/ai-client'
10
+
11
+ /**
12
+ * Options for the useTranscription hook.
13
+ *
14
+ * @template TOutput - The output type after optional transform (defaults to TranscriptionResult)
15
+ */
16
+ export interface UseTranscriptionOptions<TOutput = TranscriptionResult> {
17
+ /** Connection adapter for streaming transport (SSE, HTTP stream, custom) */
18
+ connection?: ConnectionAdapter
19
+ /** Direct async function for transcription */
20
+ fetcher?: GenerationFetcher<TranscriptionGenerateInput, TranscriptionResult>
21
+ /** Unique identifier for this generation instance */
22
+ id?: string
23
+ /** Additional body parameters to send with ConnectionAdapter requests */
24
+ body?: Record<string, any>
25
+ /**
26
+ * Callback when transcription is complete. Can optionally return a transformed value.
27
+ *
28
+ * - Return a non-null value to transform and store it as the result
29
+ * - Return `null` to keep the previous result unchanged
30
+ * - Return nothing (`void`) to store the raw result as-is
31
+ */
32
+ onResult?: (result: TranscriptionResult) => TOutput | null | void
33
+ /** Callback when an error occurs */
34
+ onError?: (error: Error) => void
35
+ /** Callback when progress is reported (0-100) */
36
+ onProgress?: (progress: number, message?: string) => void
37
+ /** Callback for each stream chunk (ConnectionAdapter mode only) */
38
+ onChunk?: (chunk: StreamChunk) => void
39
+ }
40
+
41
+ /**
42
+ * Return type for the useTranscription hook.
43
+ *
44
+ * @template TOutput - The output type (after optional transform)
45
+ */
46
+ export interface UseTranscriptionReturn<TOutput = TranscriptionResult> {
47
+ /** Trigger transcription */
48
+ generate: (input: TranscriptionGenerateInput) => Promise<void>
49
+ /** The transcription result, or null */
50
+ result: TOutput | null
51
+ /** Whether transcription is in progress */
52
+ isLoading: boolean
53
+ /** Current error, if any */
54
+ error: Error | undefined
55
+ /** Current state of the generation */
56
+ status: GenerationClientState
57
+ /** Abort the current transcription */
58
+ stop: () => void
59
+ /** Clear result, error, and return to idle */
60
+ reset: () => void
61
+ }
62
+
63
+ /**
64
+ * React hook for transcribing audio to text using AI models.
65
+ *
66
+ * @example
67
+ * ```tsx
68
+ * import { useTranscription } from '@tanstack/ai-react'
69
+ * import { fetchServerSentEvents } from '@tanstack/ai-client'
70
+ *
71
+ * function Transcriber() {
72
+ * const { generate, result, isLoading } = useTranscription({
73
+ * connection: fetchServerSentEvents('/api/transcribe'),
74
+ * })
75
+ *
76
+ * const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
77
+ * const file = e.target.files?.[0]
78
+ * if (file) {
79
+ * const reader = new FileReader()
80
+ * reader.onload = () => {
81
+ * generate({ audio: reader.result as string, language: 'en' })
82
+ * }
83
+ * reader.readAsDataURL(file)
84
+ * }
85
+ * }
86
+ *
87
+ * return (
88
+ * <div>
89
+ * <input type="file" accept="audio/*" onChange={handleFile} />
90
+ * {isLoading && <p>Transcribing...</p>}
91
+ * {result && <p>{result.text}</p>}
92
+ * </div>
93
+ * )
94
+ * }
95
+ * ```
96
+ */
97
+ export function useTranscription<
98
+ TOnResult extends ((result: TranscriptionResult) => any) | undefined =
99
+ undefined,
100
+ >(
101
+ options: Omit<UseTranscriptionOptions, 'onResult'> & {
102
+ onResult?: TOnResult
103
+ },
104
+ ): UseTranscriptionReturn<
105
+ InferGenerationOutput<TranscriptionResult, TOnResult>
106
+ > {
107
+ const { generate, result, isLoading, error, status, stop, reset } =
108
+ useGeneration<TranscriptionGenerateInput, TranscriptionResult, TOnResult>(
109
+ options,
110
+ )
111
+
112
+ return {
113
+ generate: generate as (input: TranscriptionGenerateInput) => Promise<void>,
114
+ result,
115
+ isLoading,
116
+ error,
117
+ status,
118
+ stop,
119
+ reset,
120
+ }
121
+ }