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

create-summarize.ts

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