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

create-summarize.ts

96 lines2.7 KB

1import { createGeneration } from './create-generation.ts'
2import { reconstructSummarizeResult } from '@tanstack/ai-client'
3import type { Handle } from 'remix/ui'
4import type { SummarizationResult } from '@tanstack/ai'
5import type {
6 GenerationPersistenceOptions,
7 SummarizeGenerateInput,
8} from '@tanstack/ai-client'
9import type {
10 CreateGenerationOptions,
11 CreateGenerationReturn,
12} from './create-generation.ts'
13​
14/**
15 * Options for the createSummarize 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 SummarizationResult)
20 */
21export type CreateSummarizeOptions<TOutput = SummarizationResult> = Omit<
22 CreateGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>,
23 'onResult' | 'reconstructResult'
24> & {
25 onResult?: (result: SummarizationResult) => TOutput | null | void
27​
28/**
29 * Return type for the createSummarize helper.
30 *
31 * @template TOutput - The output type (after optional transform)
32 */
33export type CreateSummarizeReturn<TOutput = SummarizationResult> =
34 CreateGenerationReturn<TOutput, SummarizeGenerateInput>
35​
36/**
37 * Creates a text summarization 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 { createSummarize } from '@tanstack/ai-remix'
45 * import { fetchServerSentEvents } from '@tanstack/ai-client'
46 * import type { Handle } from 'remix/ui'
47 *
48 * function Summarizer(handle: Handle) {
49 * const summarizer = createSummarize(handle, {
50 * connection: fetchServerSentEvents('/api/summarize'),
51 * })
52 *
53 * return () => (
54 * <div>
55 * <button
56 * onClick={() =>
57 * summarizer.generate({
58 * text: 'Long article text...',
59 * style: 'bullet-points',
60 * maxLength: 200,
61 * })
62 * }
63 * >
64 * Summarize
65 * </button>
66 * {summarizer.isLoading ? <p>Summarizing...</p> : null}
67 * {summarizer.result ? <p>{summarizer.result.summary}</p> : null}
68 * </div>
69 * )
70 * }
71 * ```
72 */
73export function createSummarize<TTransformed = void>(
74 handle: Pick<Handle, 'id' | 'update' | 'signal'>,
75 options: Omit<
76 CreateSummarizeOptions,
77 'onResult' | 'persistence' | 'threadId'
78 > & {
79 onResult?: (result: SummarizationResult) => TTransformed
80 } & GenerationPersistenceOptions,
81) {
82 const devtools = {
83 ...options.devtools,
84 hookName: 'createSummarize',
85 outputKind: 'text' as const,
86 }
87 return createGeneration<
88 SummarizeGenerateInput,
89 SummarizationResult,
90 TTransformed
91 >(handle, {
92 ...options,
93 devtools,
94 reconstructResult: reconstructSummarizeResult,
95 })