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

create-generate-image.ts

89 lines2.7 KB

1import { createGeneration } from './create-generation.ts'
2import { reconstructImageResult } from '@tanstack/ai-client'
3import type { Handle } from 'remix/ui'
4import type { ImageGenerationResult } from '@tanstack/ai'
5import type { ImageGenerateInput } from '@tanstack/ai-client'
6import type {
7 CreateGenerationOptions,
8 CreateGenerationReturn,
9} from './create-generation.ts'
10​
11/**
12 * Options for the createGenerateImage helper.
13 *
14 * Handle is the first argument of the helper. It is not part of this type.
15 *
16 * @template TOutput - The output type after optional transform (defaults to ImageGenerationResult)
17 */
18export type CreateGenerateImageOptions<TOutput = ImageGenerationResult> = Omit<
19 CreateGenerationOptions<ImageGenerateInput, ImageGenerationResult, TOutput>,
20 'onResult' | 'reconstructResult'
21> & {
22 onResult?: (result: ImageGenerationResult) => TOutput | null | void
24​
25/**
26 * Return type for the createGenerateImage helper.
27 *
28 * @template TOutput - The output type (after optional transform)
29 */
30export type CreateGenerateImageReturn<TOutput = ImageGenerationResult> =
31 CreateGenerationReturn<TOutput, ImageGenerateInput>
32​
33/**
34 * Creates an image generation helper for Remix setup.
35 *
36 * Supports two transport modes:
37 * - **ConnectConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom)
38 * - **Fetcher** — Direct async function call
39 *
40 * Call this in a Remix component setup function. Pass the component Handle as
41 * the first argument.
42 *
43 * @example
44 * ```tsx
45 * import { createGenerateImage } from '@tanstack/ai-remix'
46 * import { fetchServerSentEvents } from '@tanstack/ai-client'
47 * import type { Handle } from 'remix/ui'
48 *
49 * function ImageGenerator(handle: Handle) {
50 * const image = createGenerateImage(handle, {
51 * threadId: 'hero-image',
52 * connection: fetchServerSentEvents('/api/generate/image'),
53 * })
54 *
55 * return () => (
56 * <div>
57 * <button onClick={() => image.generate({ prompt: 'A sunset over mountains' })}>
58 * Generate
59 * </button>
60 * {image.isLoading ? <p>Generating...</p> : null}
61 * {image.result?.images.map((img) => (
62 * <img src={img.url || `data:image/png;base64,${img.b64Json}`} />
63 * ))}
64 * </div>
65 * )
66 * }
67 * ```
68 */
69export function createGenerateImage<TTransformed = void>(
70 handle: Pick<Handle, 'update' | 'signal'>,
71 options: Omit<CreateGenerateImageOptions, 'onResult'> & {
72 onResult?: (result: ImageGenerationResult) => TTransformed
73 },
74) {
75 const devtools = {
76 ...options.devtools,
77 hookName: 'createGenerateImage',
78 outputKind: 'image' as const,
79 }
80 return createGeneration<
81 ImageGenerateInput,
82 ImageGenerationResult,
83 TTransformed
84 >(handle, {
85 ...options,
86 devtools,
87 reconstructResult: reconstructImageResult,
88 })