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

use-generate-speech.ts

128 lines3.9 KB

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