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

api.summarize.ts

152 lines5.2 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { summarize } from '@tanstack/ai'
3import { anthropicSummarize } from '@tanstack/ai-anthropic'
4import { geminiSummarize } from '@tanstack/ai-gemini'
5import { grokSummarize } from '@tanstack/ai-grok'
6import { openaiSummarize } from '@tanstack/ai-openai'
7import { ollamaSummarize } from '@tanstack/ai-ollama'
8import { openRouterSummarize } from '@tanstack/ai-openrouter'
9import type { AnySummarizeAdapter } from '@tanstack/ai'
10​
11type Provider =
12 | 'openai'
13 | 'anthropic'
14 | 'gemini'
15 | 'ollama'
16 | 'grok'
17 | 'openrouter'
18​
19export const Route = createFileRoute('/api/summarize')({
20 server: {
21 handlers: {
22 POST: async ({ request }) => {
23 const body = await request.json()
24 const {
25 text,
26 maxLength = 100,
27 style = 'concise',
28 stream = false,
29 } = body
30 const data = body.forwardedProps || {}
31 const provider: Provider = data.provider || body.provider || 'openai'
32 // Don't set a global default - let each adapter use its own default model
33 const model: string | undefined = data.model || body.model
34​
35 try {
36 // Default models per provider
37 const defaultModels: Record<Provider, string> = {
38 anthropic: 'claude-sonnet-4-5',
39 gemini: 'gemini-2.5-flash',
40 grok: 'grok-build-0.1',
41 ollama: 'mistral:7b',
42 openai: 'gpt-4o-mini',
43 openrouter: 'openai/gpt-4o-mini',
44 }
45​
46 // Determine the actual model being used
47 const actualModel = model || defaultModels[provider]
48​
49 // Pre-define adapter factories per provider. The map is typed as the
50 // adapter union so each provider's summarize adapter unifies cleanly
51 // when handed to summarize() below.
52 const adapterConfig: Record<Provider, () => AnySummarizeAdapter> = {
53 anthropic: () => anthropicSummarize(actualModel as any),
54 gemini: () => geminiSummarize(actualModel as any),
55 grok: () => grokSummarize(actualModel as any),
56 ollama: () => ollamaSummarize(actualModel as any),
57 openai: () => openaiSummarize(actualModel as any),
58 openrouter: () => openRouterSummarize(actualModel as any),
59 }
60​
61 // Select the provider's summarize adapter
62 const adapter = adapterConfig[provider]()
63​
64 console.log(
65 `>> summarize with model: ${actualModel} on provider: ${provider} (stream: ${stream})`,
66 )
67​
68 if (stream) {
69 // Streaming mode
70 const encoder = new TextEncoder()
71 const readable = new ReadableStream({
72 async start(controller) {
73 try {
74 const streamResult = summarize({
75 threadId: 'panel-summarize',
76 adapter,
77 text,
78 maxLength,
79 style,
80 stream: true,
81 })
82​
83 for await (const chunk of streamResult) {
84 const data = JSON.stringify({
85 type: chunk.type,
86 delta: 'delta' in chunk ? chunk.delta : undefined,
87 content: 'content' in chunk ? chunk.content : undefined,
88 provider,
89 model: ('model' in chunk && chunk.model) || actualModel,
90 })
91 controller.enqueue(encoder.encode(`data: ${data}\n\n`))
92 }
93​
94 controller.enqueue(encoder.encode('data: [DONE]\n\n'))
95 controller.close()
96 } catch (error: any) {
97 const errorData = JSON.stringify({
98 type: 'error',
99 error: error.message || 'An error occurred',
100 })
101 controller.enqueue(encoder.encode(`data: ${errorData}\n\n`))
102 controller.close()
103 }
104 },
105 })
106​
107 return new Response(readable, {
108 status: 200,
109 headers: {
110 'Content-Type': 'text/event-stream',
111 'Cache-Control': 'no-cache',
112 Connection: 'keep-alive',
113 },
114 })
115 }
116​
117 // Non-streaming mode
118 const result = await summarize({
119 threadId: 'panel-summarize',
120 adapter,
121 text,
122 maxLength,
123 style,
124 })
125​
126 return new Response(
127 JSON.stringify({
128 summary: result.summary,
129 provider,
130 model: result.model || actualModel,
131 }),
132 {
133 status: 200,
134 headers: { 'Content-Type': 'application/json' },
135 },
136 )
137 } catch (error: any) {
138 console.error('[API Route] Error in summarize request:', error)
139 return new Response(
140 JSON.stringify({
141 error: error.message || 'An error occurred',
142 }),
143 {
144 status: 500,
145 headers: { 'Content-Type': 'application/json' },
146 },
147 )
148 }
149 },
150 },
151 },
152})