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

create-generate-speech.ts

88 lines2.6 KB

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