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

use-generate-audio.ts

169 lines6.5 KB

1import { useGenerationWithDevtoolsIdentity } from './use-generation'
2import { reconstructAudioResult } from '@tanstack/ai-client'
3import type { AudioGenerationResult, StreamChunk } from '@tanstack/ai'
4import type {
5 AIDevtoolsDisplayOptions,
6 AudioGenerateInput,
7 ConnectConnectionAdapter,
8 GenerationClientState,
9 GenerationFetcher,
10 GenerationPersistenceOptions,
11 InferGenerationOutputFromReturn,
12} from '@tanstack/ai-client'
13import type { ByokClient } from '@tanstack/ai-client/byok'
14import type { ProviderId } from '@tanstack/ai/byok'
15​
16/**
17 * Options for the useGenerateAudio hook.
18 *
19 * @template TOutput - The output type after optional transform (defaults to AudioGenerationResult)
20 */
21export interface UseGenerateAudioOptions<TOutput = AudioGenerationResult> {
22 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
23 connection?: ConnectConnectionAdapter
24 /** Direct async function for audio generation */
25 fetcher?: GenerationFetcher<AudioGenerateInput, AudioGenerationResult>
26 /** Additional body parameters to send with connect-based adapter requests */
27 body?: Record<string, any>
28 /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */
29 byok?: ByokClient
30 /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */
31 byokProvider?: () => ProviderId | undefined
32 /** Display options for TanStack AI Devtools. */
33 devtools?: AIDevtoolsDisplayOptions
34 /**
35 * How this generation persists across reloads.
36 * - Omit / `false`: ephemeral, in-memory only.
37 * - `true`: server-driven — on mount the client hydrates the last generation
38 * for its `threadId` from the server (needs a connection with a
39 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
40 */
41 persistence?: boolean
42 /**
43 * The **scope** this generation belongs to: a stable, app-chosen name for the
44 * slot successive runs fill — not a link to a chat conversation.
45 *
46 * The hook starts empty and produces many runs over its life; each gets its
47 * own `runId`, but all belong to one scope. Persistence keys on this, so
48 * derive it from your own domain and keep it identical across reloads (e.g.
49 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
50 * id on the wire, which the protocol requires.
51 *
52 * **Required whenever `persistence` is set** — an app that cannot name the
53 * scope has nothing to restore to. Optional for ephemeral generations. If
54 * omitted, the client mints a wire id after mount.
55 */
56 threadId?: string
57 /**
58 * Server-driven hydration handler for `persistence: true` when the
59 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
60 * `rpcStream()` adapter built without handlers) — typically a one-line
61 * server-function call. The connection's own handler takes precedence.
62 */
63 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
64 /**
65 * Re-attach handler that replays a run still generating to completion on
66 * mount, when the connection doesn't carry one. Without it, a restored
67 * `running` snapshot surfaces as an (interrupted) error. The connection's
68 * own handler takes precedence.
69 */
70 joinRun?: ConnectConnectionAdapter['joinRun']
71 /**
72 * Callback when audio is generated. Can optionally return a transformed value.
73 *
74 * - Return a non-null value to transform and store it as the result
75 * - Return `null` to keep the previous result unchanged
76 * - Return nothing (`void`) to store the raw result as-is
77 */
78 onResult?: (result: AudioGenerationResult) => TOutput | null | void
79 /** Callback when an error occurs */
80 onError?: (error: Error) => void
81 /** Callback when progress is reported (0-100) */
82 onProgress?: (progress: number, message?: string) => void
83 /** Callback for each stream chunk (connect-based adapter mode only) */
84 onChunk?: (chunk: StreamChunk) => void
86​
87/**
88 * Return type for the useGenerateAudio hook.
89 *
90 * @template TOutput - The output type (after optional transform)
91 */
92export interface UseGenerateAudioReturn<TOutput = AudioGenerationResult> {
93 /** Trigger audio generation */
94 generate: (input: AudioGenerateInput) => Promise<void>
95 /** The generation result containing audio, or null */
96 result: TOutput | null
97 /** Whether generation is in progress */
98 isLoading: boolean
99 /** Current error, if any */
100 error: Error | undefined
101 /** Current state of the generation */
102 status: GenerationClientState
103 /** Abort the current generation */
104 stop: () => void
105 /** Clear result, error, and return to idle */
106 reset: () => void
107 /**
108 * The id of the generation job currently running, or `null` when nothing is in
109 * flight. Each call to `generate` is one job with its own id. Pass it to your
110 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
111 * local stream, it does not stop work already running on the provider.
112 */
113 runId: string | null
115​
116/**
117 * React hook for generating audio (music, sound effects) using AI models.
118 *
119 * Supports two transport modes:
120 * - **ConnectConnectionAdapter** — Streaming transport (SSE, HTTP stream, custom)
121 * - **Fetcher** — Direct async function call
122 *
123 * @example
124 * ```tsx
125 * import { useGenerateAudio } from '@tanstack/ai-react'
126 * import { fetchServerSentEvents } from '@tanstack/ai-client'
127 *
128 * function AudioGenerator() {
129 * const { generate, result, isLoading, error, reset } = useGenerateAudio({
130 * connection: fetchServerSentEvents('/api/generate/audio'),
131 * })
132 *
133 * return (
134 * <div>
135 * <button onClick={() => generate({ prompt: 'An upbeat electronic track', duration: 10 })}>
136 * Generate
137 * </button>
138 * {isLoading && <p>Generating...</p>}
139 * {error && <p>Error: {error.message}</p>}
140 * {result?.audio.url && <audio src={result.audio.url} controls />}
141 * </div>
142 * )
143 * }
144 * ```
145 */
146export function useGenerateAudio<TTransformed = void>(
147 options: Omit<
148 UseGenerateAudioOptions,
149 'onResult' | 'persistence' | 'threadId'
150 > & {
151 onResult?: (result: AudioGenerationResult) => TTransformed
152 } & GenerationPersistenceOptions,
153): UseGenerateAudioReturn<
154 InferGenerationOutputFromReturn<AudioGenerationResult, TTransformed>
155> {
156 const generation = useGenerationWithDevtoolsIdentity<
157 AudioGenerateInput,
158 AudioGenerationResult,
159 TTransformed
160 >(
161 { ...options, reconstructResult: reconstructAudioResult },
162 {
163 hookName: 'useGenerateAudio',
164 outputKind: 'audio',
165 },
166 )
167​
168 return generation