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

files-api.md

234 lines10.5 KB

1---
2title: Files API
3id: files-api
4description: "Upload media once and reference it by a provider-issued handle with TanStack AI's tree-shakeable files adapters (OpenAI, Anthropic, Gemini, Grok, fal)."
5keywords:
6 - tanstack ai
7 - files api
8 - file upload
9 - file_id
10 - fileData
11 - public url
12 - multimodal
13---
14​
15Provider **Files / storage APIs** let you upload a media asset once and reference it later by a lightweight handle, instead of re-sending base64 (or relying on the provider to re-fetch a public URL) on every request. That means large or reused inputs are uploaded a single time — lower latency and bandwidth, no re-buffering of base64 on memory-constrained runtimes (e.g. Cloudflare Workers) — plus access to provider-side file lifecycle (TTL, deletion).
16​
17TanStack AI exposes this as a tree-shakeable **`files` adapter** per provider, paired with a `{ type: 'file' }` [content source](./multimodal-content.md#file-handle-files-api) you drop into a message.
18​
19## Files adapters
20​
21Each provider with a native surface has a factory: `openaiFiles()`, `anthropicFiles()`, `geminiFiles()`, `grokFiles()`, and `falFiles()`. They read the same API-key env var as the provider's other adapters. To pass a key explicitly, use the `create*Files(apiKey)` variants (`createOpenaiFiles`, `createAnthropicFiles`, `createGeminiFiles`, `createGrokFiles`). `falFiles(config)` takes its key in the config object.
22​
23```typescript
24import { createOpenaiFiles, openaiFiles } from '@tanstack/ai-openai'
25import { geminiFiles } from '@tanstack/ai-gemini'
26import { anthropicFiles } from '@tanstack/ai-anthropic'
27import { falFiles } from '@tanstack/ai-fal'
28import { grokFiles } from '@tanstack/ai-grok'
29​
30const files = openaiFiles() // reads OPENAI_API_KEY
31const filesWithKey = createOpenaiFiles('sk-your-key') // explicit key
32```
33​
34### uploadFile
35​
36Drive an adapter with the `uploadFile()` activity function. It accepts a `Blob` (memory-efficient — preferred for large assets) or `{ data, mimeType }` where `data` is base64, and returns a `FileHandle`:
37​
38```typescript
39import { uploadFile } from '@tanstack/ai'
40import { openaiFiles } from '@tanstack/ai-openai'
41import { pdfBase64 } from './pdf-data'
42​
43const handle = await uploadFile({
44 adapter: openaiFiles(),
45 input: { data: pdfBase64, mimeType: 'application/pdf' },
46})
47// handle: { id, provider, uri?, mimeType?, sizeBytes?, expiresAt?, filename? }
48```
49​
50- `id` — the provider handle used for `get` / `delete` (OpenAI/Anthropic `file_id`, Gemini file resource name, fal storage URL).
51- `uri`: the handle's URL form when the provider exposes one (Gemini file URI, fal storage URL, Grok public URL). It is `undefined` for OpenAI and Anthropic, whose handles are opaque ids.
52- `expiresAt` — epoch milliseconds, when the provider schedules the handle to expire.
53​
54> **Runtime note (Gemini upload).** `geminiFiles().upload()` uses `@google/genai`'s
55> resumable upload, which sets an explicit `Content-Length` header on a `Blob`-body
56> request. Some server runtimes reject that with `fetch failed` /
57> `InvalidArgumentError: invalid content-length header`. On **TanStack Start / Nitro**
58> this fails on older Nitro (observed on `nitro@3.0.1-alpha.2`) and works on current
59> Nitro (verified on `nitro@3.0.260610-beta`) — upgrade Nitro if you hit it. Native
60> Node (and the production `node-server` build) are unaffected. OpenAI, Anthropic, and
61> fal uploads use different transports and don't exercise this path.
62​
63### getFile and deleteFile
64​
65Providers with a lifecycle API support `getFile()` and `deleteFile()`. Both accept the handle itself (preferred — the handle's provider type rejects a foreign provider's handle at compile time) or its raw `id`:
66​
67```typescript
68import { deleteFile, getFile, uploadFile } from '@tanstack/ai'
69import { openaiFiles } from '@tanstack/ai-openai'
70import { pdfBase64 } from './pdf-data'
71​
72const files = openaiFiles()
73const handle = await uploadFile({
74 adapter: files,
75 input: { data: pdfBase64, mimeType: 'application/pdf' },
76})
77​
78const meta = await getFile({ adapter: files, id: handle })
79await deleteFile({ adapter: files, id: handle })
80```
81​
82> fal storage is **upload-only** — `falFiles()` defines no `get` / `delete`, and calling `getFile()` / `deleteFile()` with it throws a clear error.
83​
84### Grok (xAI): handles are public URLs
85​
86`grokFiles()` uploads to the xAI Files API, then mints a [public URL](https://docs.x.ai/developers/files/public-urls) for the stored object and uses that URL as the handle's reference.
87​
88xAI takes a `file_id` only on `input_file` (documents), and only on agentic-capable models. Its image path takes a URL. A public URL works for both, so one handle covers every modality on every chat model.
89​
90```typescript
91import { uploadFile } from '@tanstack/ai'
92import { grokFiles } from '@tanstack/ai-grok'
93import { pngBase64 } from './image-data'
94​
95const handle = await uploadFile({
96 // Omit `expiresAfter` for a URL that does not expire.
97 adapter: grokFiles({ expiresAfter: 86_400 }),
98 input: { data: pngBase64, mimeType: 'image/png' },
99})
100// handle.id -> 'file_abc123' (lifecycle)
101// handle.uri -> 'https://files-cdn.x.ai/…' (wire reference)
102```
103​
104xAI limits to know:
105​
106- 50 MiB per file, and PNG, JPEG, MP4, or PDF only.
107- `expiresAfter` runs from 3600 seconds (one hour) to 2592000 (thirty days).
108- Up to 1000 active public URLs per team.
109- Minting is idempotent, so re-uploading the same file returns the same URL.
110​
111To stop a URL resolving without deleting the file, call `revokePublicUrl(handle.id)` on the adapter. `deleteFile()` removes the file itself.
112​
113`getFile()` mints the public URL to put it on the handle. After you revoke a URL, do not call `getFile()` for that file, or the file gets a public URL again.
114​
115## Referencing a handle in a message
116​
117Use `fileSourceFromHandle(handle)` to turn a `FileHandle` into a `{ type: 'file' }` content source:
118​
119```typescript
120import type { ContentPartFileSource } from '@tanstack/ai'
121​
122const source: ContentPartFileSource = {
123 type: 'file',
124 value: 'file-abc',
125 provider: 'openai',
127```
128​
129- `value` is the handle exactly as the provider issued it. Treat it as opaque.
130- `provider` names the adapter that issued it.
131​
132Each adapter maps `value` to its native wire field: OpenAI and Anthropic `file_id`, Gemini `fileData.fileUri`, fal storage URL, Grok public URL.
133​
134A handle only works with the provider that issued it. If `provider` names a different adapter, that adapter throws a clear error. Adapters that cannot consume file handles at all are rejected before any mapping starts.
135​
136### Server: upload + reference
137​
138```typescript
139import { chat, fileSourceFromHandle, uploadFile } from '@tanstack/ai'
140import { anthropicFiles, anthropicText } from '@tanstack/ai-anthropic'
141​
142export async function askAboutPdf(pdfBase64: string, request: string) {
143 // Upload once; reuse the handle across turns.
144 const handle = await uploadFile({
145 adapter: anthropicFiles(),
146 input: { data: pdfBase64, mimeType: 'application/pdf' },
147 })
148​
149 return chat({
150 adapter: anthropicText('claude-sonnet-5'),
151 messages: [
152 {
153 role: 'user',
154 content: [
155 { type: 'text', content: request },
156 { type: 'document', source: fileSourceFromHandle(handle) },
157 ],
158 },
159 ],
160 })
162```
163​
164### Client: reuse a handle across requests
165​
166Upload needs the provider key, so it happens on the server. The browser keeps the handle it gets back and puts it in the message on each turn.
167​
1681. Store the handle the upload endpoint returned. Keep `{ id, provider, uri, mimeType }`.
1692. Build the source with `fileSourceFromHandle(handle)` and put it in the message content.
1703. On the server, pass the messages to `chat()` as usual.
171​
172In the browser, import `fileSourceFromHandle` from `@tanstack/ai/client`. That entry does not load server code:
173​
174```tsx
175import { useChat } from '@tanstack/ai-react'
176import { fetchServerSentEvents } from '@tanstack/ai-client'
177import { fileSourceFromHandle } from '@tanstack/ai/client'
178import type { FileHandle } from '@tanstack/ai/client'
179​
180// `handle` came from your upload endpoint and is stored client-side.
181function AskAboutFile({ handle }: { handle: FileHandle }) {
182 const { sendMessage } = useChat({
183 connection: fetchServerSentEvents('/api/chat'),
184 })
185​
186 return (
187 <button
188 onClick={() =>
189 sendMessage({
190 content: [
191 { type: 'text', content: 'Describe this' },
192 { type: 'image', source: fileSourceFromHandle(handle) },
193 ],
194 })
195 }
196 type="button"
197 >
198 Ask
199 </button>
200 )
202```
203​
204On the server, the file part arrives in the messages. Use a text adapter from the provider that issued the handle:
205​
206```typescript
207import { chat } from '@tanstack/ai'
208import { openaiText } from '@tanstack/ai-openai'
209import type { ModelMessage } from '@tanstack/ai'
210​
211export function runTurn(messages: Array<ModelMessage>) {
212 return chat({ adapter: openaiText('gpt-5.6'), messages })
214```
215​
216> A handle from another provider throws before any request. For example, an OpenAI handle sent to a Gemini adapter fails in preflight. It is never dropped and never sent as a URL.
217​
218## Provider support
219​
220| Provider | Adapter | Handle referenced as | Lifecycle |
221| --- | --- | --- | --- |
222| OpenAI | `openaiFiles()` | Responses `input_image` / `input_file` `file_id` | `get`, `delete` |
223| Anthropic | `anthropicFiles()` | `file_id` message source (sends the `files-api-2025-04-14` beta) | `get`, `delete` |
224| Gemini | `geminiFiles()` | `fileData.fileUri` (the handle URI) | `get`, `delete` |
225| fal | `falFiles()` | storage URL (used like any URL) | upload-only |
226| Grok (xAI) | `grokFiles()` | public URL (used like any URL) | `get`, `delete` |
227​
228Gemini and fal handles are URLs, so they also round-trip through a plain `{ type: 'url' }` source; OpenAI and Anthropic handles are opaque ids that require the `{ type: 'file' }` source.
229​
230### Providers and endpoints that can't consume references
231​
232Adapters that can consume file references declare a `supportsFileSources` capability; for everyone else (Groq, Bedrock, Mistral, OpenRouter, Ollama, BytePlus, Cohere, and any adapter written before this feature existed) `chat()` / `generateImage()` / `generateVideo()` / `embed()` reject `{ type: 'file' }` sources **before any request is built**, so a reference can never be silently mis-mapped onto a URL or data field.
233​
234Some endpoints on supporting providers also have no "reference an uploaded handle" option — OpenAI's `images/edits` and Sora `input_reference`, and Gemini's Veo, need the actual bytes (or, for Veo, a `gs://` URI). The OpenAI **Chat Completions** image path also references images only by URL/data URI, not `file_id` — use the Responses adapter (`openaiText`) for `file_id` images. These throw a clear endpoint-specific error.