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

use-summarize.ts

168 lines6.2 KB

1import { useGenerationWithDevtoolsIdentity } from './use-generation'
2import { reconstructSummarizeResult } from '@tanstack/ai-client'
3import type { StreamChunk, SummarizationResult } from '@tanstack/ai'
4import type {
5 AIDevtoolsDisplayOptions,
6 ConnectConnectionAdapter,
7 GenerationClientState,
8 GenerationFetcher,
9 GenerationPersistenceOptions,
10 InferGenerationOutputFromReturn,
11 SummarizeGenerateInput,
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 useSummarize hook.
18 *
19 * @template TOutput - The output type after optional transform (defaults to SummarizationResult)
20 */
21export interface UseSummarizeOptions<TOutput = SummarizationResult> {
22 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
23 connection?: ConnectConnectionAdapter
24 /** Direct async function for summarization */
25 fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>
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 summarization is complete. 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: SummarizationResult) => 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 useSummarize hook.
89 *
90 * @template TOutput - The output type (after optional transform)
91 */
92export interface UseSummarizeReturn<TOutput = SummarizationResult> {
93 /** Trigger summarization */
94 generate: (input: SummarizeGenerateInput) => Promise<void>
95 /** The summarization result, or null */
96 result: TOutput | null
97 /** Whether summarization 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 summarization */
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 summarizing text using AI models.
118 *
119 * @example
120 * ```tsx
121 * import { useSummarize } from '@tanstack/ai-react'
122 * import { fetchServerSentEvents } from '@tanstack/ai-client'
123 *
124 * function Summarizer() {
125 * const { generate, result, isLoading } = useSummarize({
126 * connection: fetchServerSentEvents('/api/summarize'),
127 * })
128 *
129 * return (
130 * <div>
131 * <button onClick={() => generate({
132 * text: 'Long article text...',
133 * style: 'bullet-points',
134 * maxLength: 200,
135 * })}>
136 * Summarize
137 * </button>
138 * {isLoading && <p>Summarizing...</p>}
139 * {result && <p>{result.summary}</p>}
140 * </div>
141 * )
142 * }
143 * ```
144 */
145export function useSummarize<TTransformed = void>(
146 options: Omit<
147 UseSummarizeOptions,
148 'onResult' | 'persistence' | 'threadId'
149 > & {
150 onResult?: (result: SummarizationResult) => TTransformed
151 } & GenerationPersistenceOptions,
152): UseSummarizeReturn<
153 InferGenerationOutputFromReturn<SummarizationResult, TTransformed>
154> {
155 const generation = useGenerationWithDevtoolsIdentity<
156 SummarizeGenerateInput,
157 SummarizationResult,
158 TTransformed
159 >(
160 { ...options, reconstructResult: reconstructSummarizeResult },
161 {
162 hookName: 'useSummarize',
163 outputKind: 'text',
164 },
165 )
166​
167 return generation