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

use-generation.ts

325 lines11.6 KB

1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import {
4 batch,
5 createEffect,
6 createSignal,
7 onCleanup,
8 onMount,
9 untrack,
10} from 'solid-js'
11import type { StreamChunk } from '@tanstack/ai'
12import type {
13 AIDevtoolsDisplayOptions,
14 ConnectConnectionAdapter,
15 GenerationClientOptions,
16 GenerationClientState,
17 GenerationFetcher,
18 GenerationPersistenceOptions,
19 GenerationRestoredResult,
20 InferGenerationOutputFromReturn,
21} from '@tanstack/ai-client'
22import type { ByokClient } from '@tanstack/ai-client/byok'
23import type { ProviderId } from '@tanstack/ai/byok'
24import type { Accessor } from 'solid-js'
25​
26/**
27 * Options for the useGeneration hook.
28 *
29 * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).
30 *
31 * @template TInput - The input type for the generation request
32 * @template TResult - The result type returned by the generation
33 * @template TOutput - The transformed output type (defaults to TResult)
34 */
35export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
36 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
37 connection?: ConnectConnectionAdapter
38 /** Direct async function for one-shot generation (no streaming protocol needed) */
39 fetcher?: GenerationFetcher<TInput, TResult>
40 /** Additional body parameters to send with connect-based adapter requests */
41 body?: Record<string, any>
42 /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */
43 byok?: ByokClient
44 /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */
45 byokProvider?: () => ProviderId | undefined
46 /** Display options for TanStack AI Devtools. */
47 devtools?: AIDevtoolsDisplayOptions
48 /**
49 * How this generation persists across reloads.
50 * - Omit / `false`: ephemeral, in-memory only.
51 * - `true`: server-driven — on mount the client hydrates the last generation
52 * for its `threadId` from the server (needs a connection with a
53 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
54 */
55 persistence?: boolean
56 /**
57 * The **scope** this generation belongs to: a stable, app-chosen name for the
58 * slot successive runs fill — not a link to a chat conversation.
59 *
60 * The hook starts empty and produces many runs over its life; each gets its
61 * own `runId`, but all belong to one scope. Persistence keys on this, so
62 * derive it from your own domain and keep it identical across reloads (e.g.
63 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
64 * id on the wire, which the protocol requires.
65 *
66 * **Required whenever `persistence` is set** — an app that cannot name the
67 * scope has nothing to restore to. Optional for ephemeral generations. If
68 * omitted, the client mints a wire id after mount.
69 */
70 threadId?: string
71 /**
72 * Server-driven hydration handler for `persistence: true` when the
73 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
74 * `rpcStream()` adapter built without handlers) — typically a one-line
75 * server-function call. The connection's own handler takes precedence.
76 */
77 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
78 /**
79 * Re-attach handler that replays a run still generating to completion on
80 * mount, when the connection doesn't carry one. Without it, a restored
81 * `running` snapshot surfaces as an (interrupted) error. The connection's
82 * own handler takes precedence.
83 */
84 joinRun?: ConnectConnectionAdapter['joinRun']
85 /**
86 * Callback when a result is received. Can optionally return a transformed value.
87 *
88 * - Return a non-null value to transform and store it as the result
89 * - Return `null` to keep the previous result unchanged
90 * - Return nothing (`void`) to store the raw result as-is
91 */
92 onResult?: (result: TResult) => TOutput | null | void
93 /** Callback when an error occurs */
94 onError?: (error: Error) => void
95 /** Callback when progress is reported (0-100) */
96 onProgress?: (progress: number, message?: string) => void
97 /** Callback for each stream chunk (connect-based adapter mode only) */
98 onChunk?: (chunk: StreamChunk) => void
99 /**
100 * @internal Rebuild a typed result from a restored snapshot, injected by each
101 * specialized hook (image / speech / audio / transcription / summarize).
102 * Forwarded to the client so a server-hydrate restore repaints `result`.
103 */
104 reconstructResult?: (restored: GenerationRestoredResult) => TResult | null
106​
107/**
108 * Return type for the useGeneration hook.
109 *
110 * @template TOutput - The output type (possibly transformed from the raw result)
111 * @template TInput - The input type accepted by `generate` (defaults to any object)
112 */
113export interface UseGenerationReturn<
114 TOutput,
115 TInput extends Record<string, any> = Record<string, any>,
116> {
117 /** Trigger a generation request */
118 generate: (input: TInput) => Promise<void>
119 /** The generation result, or null if not yet generated */
120 result: Accessor<TOutput | null>
121 /** Whether a generation is currently in progress */
122 isLoading: Accessor<boolean>
123 /** Current error, if any */
124 error: Accessor<Error | undefined>
125 /** Current state of the generation client */
126 status: Accessor<GenerationClientState>
127 /** Abort the current generation */
128 stop: () => void
129 /** Clear result, error, and return to idle */
130 reset: () => void
131 /**
132 * The id of the generation job currently running, or `null` when nothing is in
133 * flight. Each call to `generate` is one job with its own id. Pass it to your
134 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
135 * local stream, it does not stop work already running on the provider.
136 */
137 runId: Accessor<string | null>
139​
140/**
141 * Generic Solid hook for one-shot generation tasks.
142 *
143 * This is the base hook used by `useGenerateImage`, `useGenerateSpeech`,
144 * `useTranscription`, and `useSummarize`. You can also use it directly
145 * for custom generation types.
146 *
147 * @template TInput - The input type for the generation request
148 * @template TResult - The result type returned by the generation
149 * @template TOutput - The transformed output type (defaults to TResult)
150 *
151 * @example
152 * ```tsx
153 * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
154 * connection: fetchServerSentEvents('/api/generate/custom'),
155 * })
156 *
157 * await generate({ prompt: 'Hello' })
158 * ```
159 */
160// `TTransformed` infers from the `onResult` return position (a covariant
161// inference site that works even for an optional nested property), which types
162// the callback parameter as `TResult` and narrows `result`. Inferring the
163// whole callback as a defaulted type parameter instead collapses to the
164// default, leaving the parameter `any` — a hard error under `strict`. See
165// issue #848.
166export function useGeneration<
167 TInput extends Record<string, any>,
168 TResult,
169 TTransformed = void,
170>(
171 options: Omit<
172 UseGenerationOptions<TInput, TResult>,
173 'onResult' | 'persistence' | 'threadId'
174 > & {
175 onResult?: (result: TResult) => TTransformed
176 } & GenerationPersistenceOptions,
177): UseGenerationReturn<
178 InferGenerationOutputFromReturn<TResult, TTransformed>,
179 TInput
180> {
181 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
182​
183 const [result, setResult] = createSignal<TOutput | null>(null)
184 const [isLoading, setIsLoading] = createSignal(false)
185 const [error, setError] = createSignal<Error | undefined>(undefined)
186 const [status, setStatus] = createSignal<GenerationClientState>('idle')
187 const [runId, setRunId] = createSignal<string | null>(null)
188 let disposed = false
189​
190 // Built once. `untrack` keeps the option reads below from subscribing
191 // construction to `options.persistence` / `options.devtools` /
192 // `options.body`: a re-run would build a second client
193 // and orphan the first (only the live one is disposed on cleanup). Later
194 // `options.body` changes are pushed through `updateOptions` instead.
195 const client = untrack((): GenerationClient<TInput, TResult, TOutput> => {
196 // Conditional spread on `body`: `GenerationClientOptions.body` is a
197 // strict optional (`body?: Record<string, any>`) and EOPT forbids
198 // assigning the source `T | undefined` directly.
199 const clientOptions: Omit<
200 GenerationClientOptions<TInput, TResult, TOutput>,
201 'persistence' | 'threadId'
202 > = {
203 body: options.body,
204 ...(options.hydrateGeneration !== undefined && {
205 hydrateGeneration: options.hydrateGeneration,
206 }),
207 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
208 ...(options.byok !== undefined && { byok: options.byok }),
209 byokProvider: () => options.byokProvider?.(),
210 ...(options.reconstructResult
211 ? { reconstructResult: options.reconstructResult }
212 : {}),
213 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
214 devtools: {
215 ...options.devtools,
216 framework: 'solid',
217 hookName: 'useGeneration',
218 },
219 // The transform's raw return type (`TTransformed`) and the stored output
220 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
221 // the cast bridges the relationship that the conditional type hides.
222 onResult: ((r: TResult) => options.onResult?.(r)) as (
223 result: TResult,
224 ) => TOutput | null | void,
225 onError: (e: Error) => {
226 if (!disposed) options.onError?.(e)
227 },
228 onProgress: (p: number, m?: string) => {
229 if (!disposed) options.onProgress?.(p, m)
230 },
231 onChunk: (c: StreamChunk) => {
232 if (!disposed) options.onChunk?.(c)
233 },
234 }
235​
236 const persistenceProps =
237 typeof options.threadId === 'string' && options.persistence
238 ? {
239 persistence: options.persistence,
240 threadId: options.threadId,
241 }
242 : {
243 ...(options.threadId !== undefined && {
244 threadId: options.threadId,
245 }),
246 }
247​
248 if (options.connection) {
249 return new GenerationClient<TInput, TResult, TOutput>({
250 ...clientOptions,
251 ...persistenceProps,
252 connection: options.connection,
253 })
254 }
255​
256 if (options.fetcher) {
257 return new GenerationClient<TInput, TResult, TOutput>({
258 ...clientOptions,
259 ...persistenceProps,
260 fetcher: options.fetcher,
261 })
262 }
263​
264 throw new Error(
265 'useGeneration requires either a connection or fetcher option',
266 )
267 })
268​
269 const applySnapshot = () => {
270 const next = client.getSnapshot()
271 // One batch, so effects never see half of a snapshot.
272 batch(() => {
273 setResult(() => next.result)
274 setIsLoading(next.isLoading)
275 setError(next.error)
276 setStatus(next.status)
277 setRunId(next.runId)
278 })
279 }
280 applySnapshot()
281 onCleanup(client.subscribe(applySnapshot))
282​
283 // Sync body changes without recreating client
284 createEffect(() => {
285 const currentBody = options.body
286 client.updateOptions({
287 ...(currentBody !== undefined && { body: currentBody }),
288 })
289 })
290​
291 // Mount devtools only. Generation runs are never auto-started on mount — a
292 // persisted snapshot is hydrated for display, never replayed.
293 onMount(() => {
294 client.mountDevtools()
295 })
296​
297 // Cleanup on unmount: stop any in-flight requests and unregister devtools
298 onCleanup(() => {
299 disposed = true
300 client.dispose()
301 })
302​
303 const generate = async (input: TInput) => {
304 await client.generate(input)
305 }
306​
307 const stop = () => {
308 client.stop()
309 }
310​
311 const reset = () => {
312 client.reset()
313 }
314​
315 return {
316 generate,
317 result,
318 isLoading,
319 error,
320 status,
321 stop,
322 reset,
323 runId,
324 }