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

api.video-understanding.ts

108 lines3.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { chat, toServerSentEventsResponse } from '@tanstack/ai'
3import { geminiText, geminiVideoPart } from '@tanstack/ai-gemini'
4import type {
5 GeminiUploadedFile,
6 GeminiVideoMetadata,
7} from '@tanstack/ai-gemini'
8import type { ContentPart, ModelMessage } from '@tanstack/ai'
9​
10// Agentic understanding routes through the Interactions API; single-pass
11// understanding uses generateContent. Both run on the same GA flash model.
12const AGENTIC_MODEL = 'gemini-3.7-flash'
13const SINGLE_PASS_MODEL = 'gemini-3.7-flash'
14​
15const SYSTEM_PROMPT =
16 'You are a helpful assistant that answers questions about the video the user ' +
17 'has shared. Be concise and specific, and cite timestamps when relevant.'
18​
19/** Extract plain text from a wire message (string content or text parts). */
20function messageText(msg: any): string {
21 if (typeof msg?.content === 'string') return msg.content
22 const parts = Array.isArray(msg?.content)
23 ? msg.content
24 : Array.isArray(msg?.parts)
25 ? msg.parts
26 : []
27 return parts
28 .filter((p: any) => p?.type === 'text' && p.content)
29 .map((p: any) => p.content)
30 .join('\n')
32​
33/**
34 * Rebuild the conversation for the adapter, attaching the uploaded video to the
35 * first user turn so it stays in context for every turn (the full history is
36 * re-sent each request).
37 */
38function buildMessages(
39 wireMessages: Array<any>,
40 video: GeminiUploadedFile | undefined,
41 videoMetadata: GeminiVideoMetadata,
42): Array<ModelMessage> {
43 let videoAttached = false
44 return wireMessages.map((msg): ModelMessage => {
45 const role: ModelMessage['role'] =
46 msg.role === 'assistant' ? 'assistant' : 'user'
47 const text = messageText(msg)
48​
49 if (role === 'user' && video && !videoAttached) {
50 videoAttached = true
51 const content: Array<ContentPart> = [
52 geminiVideoPart(video, videoMetadata),
53 { type: 'text', content: text },
54 ]
55 return { role, content }
56 }
57 return { role, content: text }
58 })
60​
61export const Route = createFileRoute('/api/video-understanding')({
62 server: {
63 handlers: {
64 POST: async ({ request }) => {
65 const abortController = new AbortController()
66 const body = await request.json()
67 const data = body.data || {}
68 const mode: 'agentic' | 'single-pass' =
69 data.mode === 'agentic' ? 'agentic' : 'single-pass'
70 const video: GeminiUploadedFile | undefined = data.video
71​
72 try {
73 const videoMetadata: GeminiVideoMetadata =
74 mode === 'agentic' ? { processing: 'agentic' } : { fps: 1 }
75​
76 const messages = buildMessages(
77 body.messages ?? [],
78 video,
79 videoMetadata,
80 )
81​
82 const model = mode === 'agentic' ? AGENTIC_MODEL : SINGLE_PASS_MODEL
83 console.log(
84 `>> video-understanding chat mode=${mode} model=${model} hasVideo=${Boolean(video)}`,
85 )
86​
87 const stream = chat({
88 adapter: geminiText(model),
89 systemPrompts: [SYSTEM_PROMPT],
90 messages,
91 abortController,
92 })
93​
94 return toServerSentEventsResponse(stream, { abortController })
95 } catch (error: any) {
96 console.error(
97 '[API Route] video-understanding error:',
98 error?.message,
99 )
100 return new Response(
101 JSON.stringify({ error: error?.message ?? 'Unknown error' }),
102 { status: 500, headers: { 'Content-Type': 'application/json' } },
103 )
104 }
105 },
106 },
107 },
108})