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

use-generation.tsrx

229 lines7.6 KB

1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'octane'
4import type { StreamChunk } from '@tanstack/ai'
5import type {
6 AIDevtoolsDisplayOptions,
7 ConnectConnectionAdapter,
8 GenerationClientOptions,
9 GenerationClientState,
10 GenerationFetcher,
11 InferGenerationOutputFromReturn,
12} from '@tanstack/ai-client'
13​
14/**
15 * Options for the useGeneration hook.
16 *
17 * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).
18 *
19 * @template TInput - The input type for the generation request
20 * @template TResult - The result type returned by the generation
21 * @template TOutput - The output type after optional transform (defaults to TResult)
22 */
23export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
24 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
25 connection?: ConnectConnectionAdapter
26 /** Direct async function for one-shot generation (no streaming protocol needed) */
27 fetcher?: GenerationFetcher<TInput, TResult>
28 /** Unique identifier for this generation instance */
29 id?: string
30 /** Additional body parameters to send with connect-based adapter requests */
31 body?: Record<string, any>
32 /** Display options for TanStack AI Devtools. */
33 devtools?: AIDevtoolsDisplayOptions
34 /**
35 * Callback when a result is received. Can optionally return a transformed value.
36 *
37 * - Return a non-null value to transform and store it as the result
38 * - Return `null` to keep the previous result unchanged
39 * - Return nothing (`void`) to store the raw result as-is
40 */
41 onResult?: (result: TResult) => TOutput | null | void
42 /** Callback when an error occurs */
43 onError?: (error: Error) => void
44 /** Callback when progress is reported (0-100) */
45 onProgress?: (progress: number, message?: string) => void
46 /** Callback for each stream chunk (connect-based adapter mode only) */
47 onChunk?: (chunk: StreamChunk) => void
49​
50/**
51 * Return type for the useGeneration hook.
52 *
53 * @template TInput - The input type accepted by `generate`
54 * @template TOutput - The output type (after optional transform)
55 */
56export interface UseGenerationReturn<TInput, TOutput> {
57 /**
58 * Trigger a generation request.
59 *
60 * Typed as `TInput` rather than `Record<string, any>` so required and narrow
61 * input fields are actually checked at the call site. (Upstream
62 * `@tanstack/ai-react` widens this; see status.json.)
63 */
64 generate: (input: TInput) => Promise<void>
65 /** The generation result, or null if not yet generated */
66 result: TOutput | null
67 /** Whether a generation is currently in progress */
68 isLoading: boolean
69 /** Current error, if any */
70 error: Error | undefined
71 /** Current state of the generation client */
72 status: GenerationClientState
73 /** Abort the current generation */
74 stop: () => void
75 /** Clear result, error, and return to idle */
76 reset: () => void
78​
79/**
80 * Generic Octane hook for one-shot generation tasks.
81 *
82 * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
83 * `useTranscription`, and `useSummarize`. You can also use it directly
84 * for custom generation types.
85 *
86 * @template TInput - The input type for the generation request
87 * @template TResult - The result type returned by the generation
88 *
89 * @example
90 * ```tsx
91 * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
92 * connection: fetchServerSentEvents('/api/generate/custom'),
93 * })
94 *
95 * await generate({ prompt: 'Hello' })
96 * ```
97 */
98// `TTransformed` infers from the `onResult` return position (a covariant
99// inference site that works even for an optional nested property), which types
100// the callback parameter as `TResult` and narrows `result`. Inferring the
101// whole callback as a defaulted type parameter instead collapses to the
102// default, leaving the parameter `any` — a hard error under `strict`. See
103// issue #848.
104export function useGeneration<
105 TInput extends Record<string, any>,
106 TResult,
107 TTransformed = void,
108>(
109 options: Omit<UseGenerationOptions<TInput, TResult>, 'onResult'> & {
110 onResult?: (result: TResult) => TTransformed
111 },
112): UseGenerationReturn<
113 TInput,
114 InferGenerationOutputFromReturn<TResult, TTransformed>
115> {
116 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
117 const hookId = useId()
118 const clientId = options.id || hookId
119​
120 const [result, setResult] = useState<TOutput | null>(null)
121 const [isLoading, setIsLoading] = useState(false)
122 const [error, setError] = useState<Error | undefined>(undefined)
123 const [status, setStatus] = useState<GenerationClientState>('idle')
124​
125 const optionsRef = useRef(options)
126 optionsRef.current = options
127​
128 const client = useMemo(() => {
129 const opts = optionsRef.current
130​
131 // Conditional spread for `body` (strict-optional in target;
132 // local source is `Record<string, any> | undefined`). Callbacks
133 // wrap optional ones in non-returning bodies so `?.()`'s
134 // implicit `undefined` doesn't pollute the function return type.
135 const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
136 id: clientId,
137 body: opts.body,
138 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
139 devtools: {
140 ...opts.devtools,
141 // OCTANE DIVERGENCE: identify this binding as Octane (not 'react') in TanStack AI Devtools.
142 // The spread comes first so a caller-supplied `devtools.framework` can't
143 // silently misidentify the binding — `useGeneration` is public API, and
144 // the sibling hooks (useChat, useGenerateVideo) already order it this way.
145 framework: 'octane',
146 hookName: 'useGeneration',
147 },
148 // The transform's raw return type (`TTransformed`) and the stored output
149 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
150 // the cast bridges the relationship that the conditional type hides.
151 onResult: ((r: TResult) => optionsRef.current.onResult?.(r)) as (
152 result: TResult,
153 ) => TOutput | null | void,
154 onError: (e: Error) => {
155 optionsRef.current.onError?.(e)
156 },
157 onProgress: (p: number, m?: string) => {
158 optionsRef.current.onProgress?.(p, m)
159 },
160 onChunk: (c: StreamChunk) => {
161 optionsRef.current.onChunk?.(c)
162 },
163 onResultChange: setResult,
164 onLoadingChange: setIsLoading,
165 onErrorChange: setError,
166 onStatusChange: setStatus,
167 }
168​
169 if (opts.connection) {
170 return new GenerationClient<TInput, TResult, TOutput>({
171 ...clientOptions,
172 connection: opts.connection,
173 })
174 }
175​
176 if (opts.fetcher) {
177 return new GenerationClient<TInput, TResult, TOutput>({
178 ...clientOptions,
179 fetcher: opts.fetcher,
180 })
181 }
182​
183 throw new Error(
184 'useGeneration requires either a connection or fetcher option',
185 )
186 }, [clientId])
187​
188 // Sync body changes without recreating client
189 useEffect(() => {
190 // Conditional spread: target uses strict-optional `body?: T`.
191 client.updateOptions({
192 ...(options.body !== undefined && { body: options.body }),
193 })
194 }, [client, options.body])
195​
196 // Cleanup on unmount
197 useEffect(() => {
198 client.mountDevtools()
199​
200 return () => {
201 client.dispose()
202 }
203 }, [client])
204​
205 const generate = useCallback(
206 async (input: TInput) => {
207 await client.generate(input)
208 },
209 [client],
210 )
211​
212 const stop = useCallback(() => {
213 client.stop()
214 }, [client])
215​
216 const reset = useCallback(() => {
217 client.reset()
218 }, [client])
219​
220 return {
221 generate,
222 result,
223 isLoading,
224 error,
225 status,
226 stop,
227 reset,
228 }