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

use-transcription.ts

169 lines6.4 KB

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