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

use-generate-image.ts

135 lines4.3 KB

1import { useGeneration } from './use-generation'
2import { reconstructImageResult } from '@tanstack/ai-client'
3import type {
4 UseGenerationOptions,
5 UseGenerationReturn,
6} from './use-generation'
7import type { ImageGenerationResult, StreamChunk } from '@tanstack/ai'
8import type {
9 AIDevtoolsDisplayOptions,
10 ConnectConnectionAdapter,
11 GenerationClientState,
12 GenerationFetcher,
13 ImageGenerateInput,
14 InferGenerationOutputFromReturn,
15} from '@tanstack/ai-client'
16import type { Accessor } from 'solid-js'
17​
18/**
19 * Options for the useGenerateImage hook.
20 *
21 * @template TOutput - The transformed output type (defaults to ImageGenerationResult)
22 */
23export interface UseGenerateImageOptions<
24 TOutput = ImageGenerationResult,
25> extends Pick<
26 UseGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,
27 | 'persistence'
28 | 'threadId'
29 | 'hydrateGeneration'
30 | 'joinRun'
31 | 'byok'
32 | 'byokProvider'
33> {
34 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
35 connection?: ConnectConnectionAdapter
36 /** Direct async function for image generation */
37 fetcher?: GenerationFetcher<ImageGenerateInput, ImageGenerationResult>
38 /** Additional body parameters to send with connect-based adapter requests */
39 body?: Record<string, any>
40 /** Display options for TanStack AI Devtools. */
41 devtools?: AIDevtoolsDisplayOptions
42 /**
43 * Callback when images are generated. Can optionally return a transformed value.
44 *
45 * - Return a non-null value to transform and store it as the result
46 * - Return `null` to keep the previous result unchanged
47 * - Return nothing (`void`) to store the raw result as-is
48 */
49 onResult?: (result: ImageGenerationResult) => TOutput | null | void
50 /** Callback when an error occurs */
51 onError?: (error: Error) => void
52 /** Callback when progress is reported (0-100) */
53 onProgress?: (progress: number, message?: string) => void
54 /** Callback for each stream chunk (connect-based adapter mode only) */
55 onChunk?: (chunk: StreamChunk) => void
57​
58/**
59 * Return type for the useGenerateImage hook.
60 *
61 * @template TOutput - The transformed output type (defaults to ImageGenerationResult)
62 */
63export interface UseGenerateImageReturn<
64 TOutput = ImageGenerationResult,
65> extends Omit<UseGenerationReturn<TOutput>, 'generate'> {
66 /** Trigger image generation */
67 generate: (input: ImageGenerateInput) => Promise<void>
68 /** The generation result containing images, or null */
69 result: Accessor<TOutput | null>
70 /** Whether generation is in progress */
71 isLoading: Accessor<boolean>
72 /** Current error, if any */
73 error: Accessor<Error | undefined>
74 /** Current state of the generation */
75 status: Accessor<GenerationClientState>
77​
78/**
79 * Solid hook for generating images using AI models.
80 *
81 * Supports two transport modes:
82 * - **ConnectConnectionAdapter** -- Streaming transport (SSE, HTTP stream, custom)
83 * - **Fetcher** -- Direct async function call
84 *
85 * @example
86 * ```tsx
87 * import { useGenerateImage } from '@tanstack/ai-solid'
88 * import { fetchServerSentEvents } from '@tanstack/ai-client'
89 *
90 * function ImageGenerator() {
91 * const { generate, result, isLoading, error, reset } = useGenerateImage({
92 * threadId: 'hero-image',
93 * connection: fetchServerSentEvents('/api/generate/image'),
94 * })
95 *
96 * return (
97 * <div>
98 * <button onClick={() => generate({ prompt: 'A sunset over mountains' })}>
99 * Generate
100 * </button>
101 * {isLoading() && <p>Generating...</p>}
102 * {error() && <p>Error: {error()!.message}</p>}
103 * {result()?.images.map((img, i) => (
104 * <img src={img.url || `data:image/png;base64,${img.b64Json}`} />
105 * ))}
106 * </div>
107 * )
108 * }
109 * ```
110 */
111export function useGenerateImage<TTransformed = void>(
112 options: Omit<UseGenerateImageOptions, 'onResult'> & {
113 onResult?: (result: ImageGenerationResult) => TTransformed
114 },
115): UseGenerateImageReturn<
116 InferGenerationOutputFromReturn<ImageGenerationResult, TTransformed>
117> {
118 const devtools = {
119 ...options.devtools,
120 framework: 'solid',
121 hookName: 'useGenerateImage',
122 outputKind: 'image' as const,
123 }
124 const generation = useGeneration<
125 ImageGenerateInput,
126 ImageGenerationResult,
127 TTransformed
128 >({
129 ...options,
130 devtools,
131 reconstructResult: reconstructImageResult,
132 })
133​
134 return generation