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

use-generate-speech.ts

165 lines6.2 KB

1import { useGenerationWithDevtoolsIdentity } from './use-generation'
2import { reconstructSpeechResult } from '@tanstack/ai-client'
3import type { StreamChunk, TTSResult } from '@tanstack/ai'
4import type {
5 AIDevtoolsDisplayOptions,
6 ConnectConnectionAdapter,
7 GenerationClientState,
8 GenerationFetcher,
9 GenerationPersistenceOptions,
10 InferGenerationOutputFromReturn,
11 SpeechGenerateInput,
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 useGenerateSpeech hook.
18 *
19 * @template TOutput - The output type after optional transform (defaults to TTSResult)
20 */
21export interface UseGenerateSpeechOptions<TOutput = TTSResult> {
22 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
23 connection?: ConnectConnectionAdapter
24 /** Direct async function for speech generation */
25 fetcher?: GenerationFetcher<SpeechGenerateInput, TTSResult>
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 speech 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: TTSResult) => 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 useGenerateSpeech hook.
89 *
90 * @template TOutput - The output type (after optional transform)
91 */
92export interface UseGenerateSpeechReturn<TOutput = TTSResult> {
93 /** Trigger speech generation */
94 generate: (input: SpeechGenerateInput) => Promise<void>
95 /** The TTS result containing audio data, 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 speech (text-to-speech) using AI models.
118 *
119 * @example
120 * ```tsx
121 * import { useGenerateSpeech } from '@tanstack/ai-react'
122 * import { fetchServerSentEvents } from '@tanstack/ai-client'
123 *
124 * function SpeechGenerator() {
125 * const { generate, result, isLoading } = useGenerateSpeech({
126 * connection: fetchServerSentEvents('/api/generate/speech'),
127 * })
128 *
129 * return (
130 * <div>
131 * <button onClick={() => generate({ text: 'Hello world', voice: 'alloy' })}>
132 * Generate Speech
133 * </button>
134 * {result && (
135 * <audio src={`data:audio/${result.format};base64,${result.audio}`} controls />
136 * )}
137 * </div>
138 * )
139 * }
140 * ```
141 */
142export function useGenerateSpeech<TTransformed = void>(
143 options: Omit<
144 UseGenerateSpeechOptions,
145 'onResult' | 'persistence' | 'threadId'
146 > & {
147 onResult?: (result: TTSResult) => TTransformed
148 } & GenerationPersistenceOptions,
149): UseGenerateSpeechReturn<
150 InferGenerationOutputFromReturn<TTSResult, TTransformed>
151> {
152 const generation = useGenerationWithDevtoolsIdentity<
153 SpeechGenerateInput,
154 TTSResult,
155 TTransformed
156 >(
157 { ...options, reconstructResult: reconstructSpeechResult },
158 {
159 hookName: 'useGenerateSpeech',
160 outputKind: 'audio',
161 },
162 )
163​
164 return generation