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

use-generation.ts

299 lines11.1 KB

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