Open History to see the last commit
1import { FileState } from '@google/genai'
2import { createGeminiClient, getGeminiApiKeyFromEnv } from '../utils'
3import type { GeminiVideoMetadata } from '../message-types'
4import type { VideoPart } from '@tanstack/ai'
5
6/**
7 * A file uploaded to the Gemini Files API and ready to reference in a message.
8 */
9export interface GeminiUploadedFile {
10 /** Resource name, e.g. `"files/abc123"`. */
11 name: string
12 /** File URI to reference from message content (as a `url` source). */
13 uri: string
14 /** MIME type reported by the Files API. */
15 mimeType: string
16}
17
18/**
19 * Options for {@link uploadGeminiFile}.
20 */
21export interface GeminiUploadFileOptions {
22 /**
23 * API key. Falls back to `GOOGLE_API_KEY` / `GEMINI_API_KEY` from the
24 * environment when omitted.
25 */
26 apiKey?: string
27 /**
28 * MIME type of the file (e.g. `"video/mp4"`). Recommended so the Files API
29 * processes and serves the file with the correct type.
30 */
31 mimeType?: string
32 /** Poll interval while the file is `PROCESSING`, in ms. Default `5000`. */
33 pollIntervalMs?: number
34 /** Max time to wait for processing, in ms. Default `300000` (5 min). */
35 timeoutMs?: number
36}
37
38/**
39 * Upload a file via the Gemini Files API and wait until it is `ACTIVE`.
40 *
41 * Large media (notably video) must be uploaded rather than inlined as base64;
42 * the Files API processes uploads asynchronously. This wraps the upload +
43 * poll-until-ready loop and returns a reference you can drop into message
44 * content as a `url` source (see {@link geminiVideoPart}).
45 *
46 * @throws if the upload has no URI, or processing fails or times out.
47 */
48export async function uploadGeminiFile(
49 file: string | Blob,
50 options: GeminiUploadFileOptions = {},
51): Promise<GeminiUploadedFile> {
52 const {
53 apiKey = getGeminiApiKeyFromEnv(),
54 mimeType,
55 pollIntervalMs = 5000,
56 timeoutMs = 300_000,
57 } = options
58
59 const client = createGeminiClient({ apiKey })
60
61 let uploaded = await client.files.upload({
62 file,
63 ...(mimeType && { config: { mimeType } }),
64 })
65
66 const fileName = uploaded.name
67 if (!fileName) {
68 throw new Error('Gemini file upload did not return a file name.')
69 }
70
71 const deadline = Date.now() + timeoutMs
72 while (uploaded.state === FileState.PROCESSING) {
73 if (Date.now() > deadline) {
74 throw new Error(
75 `Gemini file processing timed out after ${timeoutMs}ms (${fileName}).`,
76 )
77 }
78 await new Promise((resolve) => setTimeout(resolve, pollIntervalMs))
79 uploaded = await client.files.get({ name: fileName })
80 }
81
82 if (uploaded.state === FileState.FAILED) {
83 throw new Error(
84 `Gemini file processing failed: ${uploaded.error?.message ?? String(uploaded.state)}`,
85 )
86 }
87 if (!uploaded.uri) {
88 throw new Error('Gemini file upload did not return a URI.')
89 }
90
91 return {
92 name: fileName,
93 uri: uploaded.uri,
94 mimeType: uploaded.mimeType ?? mimeType ?? 'application/octet-stream',
95 }
96}
97
98/**
99 * Build a TanStack AI video content part from an uploaded Gemini file.
100 *
101 * Pass `metadata` to control understanding — e.g.
102 * `{ processing: 'agentic' }` to route through the agentic Interactions path,
103 * or `{ fps, startOffset, endOffset }` for single-pass sampling controls.
104 */
105export function geminiVideoPart(
106 file: GeminiUploadedFile,
107 metadata?: GeminiVideoMetadata,
108): VideoPart<GeminiVideoMetadata> {
109 return {
110 type: 'video',
111 source: { type: 'url', value: file.uri, mimeType: file.mimeType },
112 ...(metadata && { metadata }),
113 }
114}