Open History to see the last commit
1import { createGeneration } from './create-generation.ts'
2import { reconstructSpeechResult } from '@tanstack/ai-client'
3import type { Handle } from 'remix/ui'
4import type { TTSResult } from '@tanstack/ai'
5import type {
6 GenerationPersistenceOptions,
7 SpeechGenerateInput,
8} from '@tanstack/ai-client'
9import type {
10 CreateGenerationOptions,
11 CreateGenerationReturn,
12} from './create-generation.ts'
13
14/**
15 * Options for the createGenerateSpeech helper.
16 *
17 * Handle is the first argument of the helper. It is not part of this type.
18 *
19 * @template TOutput - The output type after optional transform (defaults to TTSResult)
20 */
21export type CreateGenerateSpeechOptions<TOutput = TTSResult> = Omit<
22 CreateGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,
23 'onResult' | 'reconstructResult'
24> & {
25 onResult?: (result: TTSResult) => TOutput | null | void
26}
27
28/**
29 * Return type for the createGenerateSpeech helper.
30 *
31 * @template TOutput - The output type (after optional transform)
32 */
33export type CreateGenerateSpeechReturn<TOutput = TTSResult> =
34 CreateGenerationReturn<TOutput, SpeechGenerateInput>
35
36/**
37 * Creates a speech generation (text-to-speech) helper for Remix setup.
38 *
39 * Call this in a Remix component setup function. Pass the component Handle as
40 * the first argument.
41 *
42 * @example
43 * ```tsx
44 * import { createGenerateSpeech } from '@tanstack/ai-remix'
45 * import { fetchServerSentEvents } from '@tanstack/ai-client'
46 * import type { Handle } from 'remix/ui'
47 *
48 * function SpeechGenerator(handle: Handle) {
49 * const speech = createGenerateSpeech(handle, {
50 * connection: fetchServerSentEvents('/api/generate/speech'),
51 * })
52 *
53 * return () => (
54 * <div>
55 * <button
56 * onClick={() => speech.generate({ text: 'Hello world', voice: 'alloy' })}
57 * >
58 * Generate Speech
59 * </button>
60 * {speech.result ? (
61 * <audio
62 * src={`data:audio/${speech.result.format};base64,${speech.result.audio}`}
63 * controls
64 * />
65 * ) : null}
66 * </div>
67 * )
68 * }
69 * ```
70 */
71export function createGenerateSpeech<TTransformed = void>(
72 handle: Pick<Handle, 'id' | 'update' | 'signal'>,
73 options: Omit<
74 CreateGenerateSpeechOptions,
75 'onResult' | 'persistence' | 'threadId'
76 > & {
77 onResult?: (result: TTSResult) => TTransformed
78 } & GenerationPersistenceOptions,
79) {
80 const devtools = {
81 ...options.devtools,
82 hookName: 'createGenerateSpeech',
83 outputKind: 'audio' as const,
84 }
85 return createGeneration<SpeechGenerateInput, TTSResult, TTransformed>(
86 handle,
87 {
88 ...options,
89 devtools,
90 reconstructResult: reconstructSpeechResult,
91 },
92 )
93}