@tanstack/ai-react 0.6.2 → 0.6.4

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.
@@ -0,0 +1,206 @@
1
+ import { VideoGenerationClient } 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
+ GenerationClientState,
7
+ GenerationFetcher,
8
+ InferGenerationOutput,
9
+ VideoGenerateInput,
10
+ VideoGenerateResult,
11
+ VideoStatusInfo,
12
+ } from '@tanstack/ai-client'
13
+
14
+ /**
15
+ * Options for the useGenerateVideo hook.
16
+ */
17
+ export interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
18
+ /** Connection adapter for streaming transport (server handles polling) */
19
+ connection?: ConnectionAdapter
20
+ /** Direct async function that returns a completed video result */
21
+ fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>
22
+ /** Unique identifier for this generation instance */
23
+ id?: string
24
+ /** Additional body parameters to send with ConnectionAdapter requests */
25
+ body?: Record<string, any>
26
+ /**
27
+ * Callback when video generation completes. Can optionally return a transformed value.
28
+ *
29
+ * - Return a non-null value to transform and store it as the result
30
+ * - Return `null` to keep the previous result unchanged
31
+ * - Return nothing (`void`) to store the raw result as-is
32
+ */
33
+ onResult?: (result: VideoGenerateResult) => TOutput | null | void
34
+ /** Callback when an error occurs */
35
+ onError?: (error: Error) => void
36
+ /** Callback when progress is reported (0-100) */
37
+ onProgress?: (progress: number, message?: string) => void
38
+ /** Callback when a video job is created */
39
+ onJobCreated?: (jobId: string) => void
40
+ /** Callback on each status update */
41
+ onStatusUpdate?: (status: VideoStatusInfo) => void
42
+ /** Callback for each stream chunk (ConnectionAdapter mode only) */
43
+ onChunk?: (chunk: StreamChunk) => void
44
+ }
45
+
46
+ /**
47
+ * Return type for the useGenerateVideo hook.
48
+ *
49
+ * @template TOutput - The output type (after optional transform)
50
+ */
51
+ export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
52
+ /** Trigger video generation */
53
+ generate: (input: VideoGenerateInput) => Promise<void>
54
+ /** The final video result (with URL), or null */
55
+ result: TOutput | null
56
+ /** The current job ID, or null */
57
+ jobId: string | null
58
+ /** Current video generation status info, or null */
59
+ videoStatus: VideoStatusInfo | null
60
+ /** Whether generation/polling is in progress */
61
+ isLoading: boolean
62
+ /** Current error, if any */
63
+ error: Error | undefined
64
+ /** Current state of the generation */
65
+ status: GenerationClientState
66
+ /** Abort the current generation/polling */
67
+ stop: () => void
68
+ /** Clear all state and return to idle */
69
+ reset: () => void
70
+ }
71
+
72
+ /**
73
+ * React hook for generating videos using AI models.
74
+ *
75
+ * Video generation is asynchronous: a job is created, then polled for status
76
+ * until completion. This hook handles the full lifecycle.
77
+ *
78
+ * @example
79
+ * ```tsx
80
+ * import { useGenerateVideo } from '@tanstack/ai-react'
81
+ * import { fetchServerSentEvents } from '@tanstack/ai-client'
82
+ *
83
+ * function VideoGenerator() {
84
+ * const { generate, result, videoStatus, isLoading } = useGenerateVideo({
85
+ * connection: fetchServerSentEvents('/api/generate/video'),
86
+ * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),
87
+ * })
88
+ *
89
+ * return (
90
+ * <div>
91
+ * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>
92
+ * Generate Video
93
+ * </button>
94
+ * {isLoading && videoStatus && (
95
+ * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>
96
+ * )}
97
+ * {result && <video src={result.url} controls />}
98
+ * </div>
99
+ * )
100
+ * }
101
+ * ```
102
+ */
103
+ export function useGenerateVideo<
104
+ TOnResult extends ((result: VideoGenerateResult) => any) | undefined =
105
+ undefined,
106
+ >(
107
+ options: Omit<UseGenerateVideoOptions, 'onResult'> & {
108
+ onResult?: TOnResult
109
+ },
110
+ ): UseGenerateVideoReturn<
111
+ InferGenerationOutput<VideoGenerateResult, TOnResult>
112
+ > {
113
+ type TOutput = InferGenerationOutput<VideoGenerateResult, TOnResult>
114
+ const hookId = useId()
115
+ const clientId = options.id || hookId
116
+
117
+ const [result, setResult] = useState<TOutput | null>(null)
118
+ const [jobId, setJobId] = useState<string | null>(null)
119
+ const [videoStatus, setVideoStatus] = useState<VideoStatusInfo | null>(null)
120
+ const [isLoading, setIsLoading] = useState(false)
121
+ const [error, setError] = useState<Error | undefined>(undefined)
122
+ const [status, setStatus] = useState<GenerationClientState>('idle')
123
+
124
+ const optionsRef = useRef(options)
125
+ optionsRef.current = options
126
+
127
+ const client = useMemo(() => {
128
+ const opts = optionsRef.current
129
+
130
+ const baseOptions = {
131
+ id: clientId,
132
+ body: opts.body,
133
+ onResult: (r: VideoGenerateResult) => optionsRef.current.onResult?.(r),
134
+ onError: (e: Error) => optionsRef.current.onError?.(e),
135
+ onProgress: (p: number, m?: string) =>
136
+ optionsRef.current.onProgress?.(p, m),
137
+ onChunk: (c: StreamChunk) => optionsRef.current.onChunk?.(c),
138
+ onJobCreated: (id: string) => optionsRef.current.onJobCreated?.(id),
139
+ onStatusUpdate: (s: VideoStatusInfo) =>
140
+ optionsRef.current.onStatusUpdate?.(s),
141
+ onResultChange: setResult,
142
+ onLoadingChange: setIsLoading,
143
+ onErrorChange: setError,
144
+ onStatusChange: setStatus,
145
+ onJobIdChange: setJobId,
146
+ onVideoStatusChange: setVideoStatus,
147
+ }
148
+
149
+ if (opts.connection) {
150
+ return new VideoGenerationClient<TOutput>({
151
+ ...baseOptions,
152
+ connection: opts.connection,
153
+ })
154
+ }
155
+
156
+ if (opts.fetcher) {
157
+ return new VideoGenerationClient<TOutput>({
158
+ ...baseOptions,
159
+ fetcher: opts.fetcher,
160
+ })
161
+ }
162
+
163
+ throw new Error(
164
+ 'useGenerateVideo requires either a connection or fetcher option',
165
+ )
166
+ }, [clientId])
167
+
168
+ // Sync body changes without recreating client
169
+ useEffect(() => {
170
+ client.updateOptions({ body: options.body })
171
+ }, [client, options.body])
172
+
173
+ // Cleanup on unmount
174
+ useEffect(() => {
175
+ return () => {
176
+ client.stop()
177
+ }
178
+ }, [client])
179
+
180
+ const generate = useCallback(
181
+ async (input: VideoGenerateInput) => {
182
+ await client.generate(input)
183
+ },
184
+ [client],
185
+ )
186
+
187
+ const stop = useCallback(() => {
188
+ client.stop()
189
+ }, [client])
190
+
191
+ const reset = useCallback(() => {
192
+ client.reset()
193
+ }, [client])
194
+
195
+ return {
196
+ generate,
197
+ result,
198
+ jobId,
199
+ videoStatus,
200
+ isLoading,
201
+ error,
202
+ status,
203
+ stop,
204
+ reset,
205
+ }
206
+ }
@@ -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,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
+ }