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

files-api.md

316 lines11.5 KB

1---
2title: Files API
3id: files-api
4description: "Upload a PDF, image, or other file to the provider one time, then put a small handle in each message. Works with OpenAI, Anthropic, Gemini, Grok, and fal."
5keywords:
6 - tanstack ai
7 - files api
8 - file upload
9 - file_id
10 - fileData
11 - public url
12 - multimodal
13---
14​
15The files API uploads a file once and sends the file id on later turns. Each request then skips a fresh base64 upload of the same PDF.
16​
17## Quick setup
18​
19This setup uploads a PDF to Anthropic and asks Claude about it. It takes about 10 minutes. Set `ANTHROPIC_API_KEY` on the server first.
20​
21### 1. Add an upload route
22​
23The upload needs the provider key, so it runs on the server. `uploadFile` takes a `Blob` and returns a `FileHandle`:
24​
25```typescript
26// api/upload.ts
27import { uploadFile } from "@tanstack/ai";
28import { anthropicFiles } from "@tanstack/ai-anthropic";
29​
30export async function POST(request: Request) {
31 const form = await request.formData();
32 const [file] = form.getAll("file");
33 if (!(file instanceof Blob)) {
34 return new Response("Missing file", { status: 400 });
35 }
36​
37 const handle = await uploadFile({ adapter: anthropicFiles(), input: file });
38 return Response.json(handle);
40```
41​
42### 2. Keep the handle in the browser and send it
43​
44Store the handle that the upload route returns. Then put it in the message with `fileSourceFromHandle`. Import it from `@tanstack/ai/client`, because that entry does not load server code:
45​
46```tsx
47import { useState } from "react";
48import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
49import { fileSourceFromHandle } from "@tanstack/ai/client";
50import type { FileHandle } from "@tanstack/ai/client";
51​
52export function AskAboutPdf() {
53 const [handle, setHandle] = useState<FileHandle | null>(null);
54 const { sendMessage } = useChat({
55 connection: fetchServerSentEvents("/api/chat"),
56 threadId: "support-chat",
57 });
58​
59 async function upload(file: File) {
60 const body = new FormData();
61 body.append("file", file);
62 const response = await fetch("/api/upload", { method: "POST", body });
63 const uploaded: FileHandle = await response.json();
64 setHandle(uploaded);
65 }
66​
67 return (
68 <>
69 <input
70 type="file"
71 accept="application/pdf"
72 onChange={(event) => {
73 const file = event.target.files?.[0];
74 if (file) void upload(file);
75 }}
76 />
77 <button
78 type="button"
79 disabled={!handle}
80 onClick={() => {
81 if (!handle) return;
82 void sendMessage({
83 content: [
84 { type: "text", content: "Summarize this PDF" },
85 { type: "document", source: fileSourceFromHandle(handle) },
86 ],
87 });
88 }}
89 >
90 Ask
91 </button>
92 </>
93 );
95```
96​
97### 3. Use the same provider in the chat route
98​
99The file part arrives in the messages. Use a text adapter from the provider that issued the handle:
100​
101```typescript
102// api/chat.ts
103import {
104 chat,
105 chatParamsFromRequest,
106 toServerSentEventsResponse,
107} from "@tanstack/ai";
108import { anthropicText } from "@tanstack/ai-anthropic";
109​
110export async function POST(request: Request) {
111 const { messages, threadId, runId } = await chatParamsFromRequest(request);
112​
113 const stream = chat({
114 adapter: anthropicText("claude-sonnet-5-5"),
115 messages,
116 threadId,
117 runId,
118 });
119​
120 return toServerSentEventsResponse(stream);
122```
123​
124Pick a PDF, click **Ask**, and Claude answers about it. Ask again with the same handle, and no bytes go up a second time.
125​
126## How it works
127​
1281. `uploadFile` sends the bytes to the provider and returns a `FileHandle`.
1292. `fileSourceFromHandle(handle)` turns the handle into a `{ type: 'file' }` [content source](./multimodal-content#file-handle-files-api).
1303. The adapter maps that source to the field of its provider, for example `file_id` on Anthropic.
1314. A handle works only with the provider that issued it. If you send it to another provider, the adapter throws before any request goes out.
132​
133## Advanced
134​
135### Files adapters
136​
137Each provider with a Files API has a factory:
138​
139| Provider | Factory | Key from |
140| --- | --- | --- |
141| OpenAI | `openaiFiles()` or `createOpenaiFiles(apiKey)` | `OPENAI_API_KEY`, or the argument |
142| Anthropic | `anthropicFiles()` or `createAnthropicFiles(apiKey)` | `ANTHROPIC_API_KEY`, or the argument |
143| Gemini | `geminiFiles()` or `createGeminiFiles(apiKey)` | the same env as the Gemini adapters, or the argument |
144| Grok (xAI) | `grokFiles()` or `createGrokFiles(apiKey)` | the same env as the Grok adapters, or the argument |
145| fal | `falFiles(config)` | the config object |
146​
147For a Bearer token, use `createAnthropicFiles(token, { auth: 'bearer' })`. See [Bearer and OAuth tokens](../adapters/anthropic-advanced#bearer-and-oauth-tokens).
148​
149```typescript
150import { createOpenaiFiles, openaiFiles } from "@tanstack/ai-openai";
151​
152const files = openaiFiles(); // reads OPENAI_API_KEY
153const filesWithKey = createOpenaiFiles("sk-your-key");
154```
155​
156### Upload input
157​
158`uploadFile` accepts one of these:
159​
160- A `Blob`. This uses less memory, so it is better for large files.
161- `{ data, mimeType, filename? }`, where `data` is base64.
162​
163```typescript
164import { uploadFile } from "@tanstack/ai";
165import { openaiFiles } from "@tanstack/ai-openai";
166import { pdfBase64 } from "./pdf-data";
167​
168const handle = await uploadFile({
169 adapter: openaiFiles(),
170 input: { data: pdfBase64, mimeType: "application/pdf" },
171});
172// handle: { id, provider, uri?, mimeType?, sizeBytes?, expiresAt?, filename? }
173```
174​
175The fields of the handle:
176​
177- `id`: the provider handle for `get` and `delete`. This is the OpenAI or Anthropic `file_id`, the Gemini file resource name, or the fal storage URL.
178- `uri`: the URL form of the handle, when the provider has one (Gemini file URI, fal storage URL, Grok public URL). It is `undefined` for OpenAI and Anthropic, because their handles are opaque ids.
179- `expiresAt`: epoch milliseconds, when the provider plans to expire the handle.
180​
181### getFile and deleteFile
182​
183Providers with a lifecycle API support `getFile()` and `deleteFile()`. Both take the handle or its raw `id`. If you can, pass the handle. Its provider type rejects a handle from another provider at compile time.
184​
185```typescript
186import { deleteFile, getFile, uploadFile } from "@tanstack/ai";
187import { openaiFiles } from "@tanstack/ai-openai";
188import { pdfBase64 } from "./pdf-data";
189​
190const files = openaiFiles();
191const handle = await uploadFile({
192 adapter: files,
193 input: { data: pdfBase64, mimeType: "application/pdf" },
194});
195​
196const meta = await getFile({ adapter: files, id: handle });
197await deleteFile({ adapter: files, id: handle });
198```
199​
200fal storage is upload-only. `falFiles()` has no `get` or `delete`, so `getFile()` and `deleteFile()` throw with it.
201​
202### Grok (xAI): handles are public URLs
203​
204`grokFiles()` uploads to the xAI Files API. Then it mints a [public URL](https://docs.x.ai/developers/files/public-urls) for the file and uses that URL as the reference of the handle.
205​
206xAI takes a `file_id` only on `input_file` (documents), and only on agentic models. Its image path takes a URL. A public URL works for both, so one handle works for every input type on every chat model.
207​
208```typescript
209import { uploadFile } from "@tanstack/ai";
210import { grokFiles } from "@tanstack/ai-grok";
211import { pngBase64 } from "./image-data";
212​
213const handle = await uploadFile({
214 // Omit `expiresAfter` for a URL that does not expire.
215 adapter: grokFiles({ expiresAfter: 86_400 }),
216 input: { data: pngBase64, mimeType: "image/png" },
217});
218// handle.id -> 'file_abc123' (lifecycle)
219// handle.uri -> 'https://files-cdn.x.ai/...' (sent in the request)
220```
221​
222xAI limits:
223​
224- 50 MiB for each file. PNG, JPEG, MP4, or PDF only.
225- `expiresAfter` is from 3600 seconds (one hour) to 2592000 (thirty days).
226- Up to 1000 active public URLs for each team.
227- Minting is idempotent. If you upload the same file again, you get the same URL.
228​
229To stop a URL without deleting the file, call `revokePublicUrl(handle.id)` on the adapter. `deleteFile()` deletes the file itself.
230​
231`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.
232​
233### The file source
234​
235`fileSourceFromHandle(handle)` returns this shape. You can also write it yourself:
236​
237```typescript
238import type { ContentPartFileSource } from "@tanstack/ai";
239​
240const source: ContentPartFileSource = {
241 type: "file",
242 value: "file-abc",
243 provider: "openai",
244};
245```
246​
247- `value` is the handle exactly as the provider issued it. Treat it as opaque. `fileSourceFromHandle` uses `uri` when the handle has one, and `id` if not.
248- `provider` names the adapter that issued it.
249​
250You can also upload and send in one server function:
251​
252```typescript
253import { chat, fileSourceFromHandle, uploadFile } from "@tanstack/ai";
254import { anthropicFiles, anthropicText } from "@tanstack/ai-anthropic";
255​
256export async function askAboutPdf(
257 pdfBase64: string,
258 request: string,
259 threadId: string,
260) {
261 // Upload one time. Use the handle again on later turns.
262 const handle = await uploadFile({
263 adapter: anthropicFiles(),
264 input: { data: pdfBase64, mimeType: "application/pdf" },
265 });
266​
267 return chat({
268 adapter: anthropicText("claude-sonnet-5-5"),
269 messages: [
270 {
271 role: "user",
272 content: [
273 { type: "text", content: request },
274 { type: "document", source: fileSourceFromHandle(handle) },
275 ],
276 },
277 ],
278 threadId,
279 });
281```
282​
283### Provider support
284​
285| Provider | Adapter | Handle sent as | Lifecycle |
286| --- | --- | --- | --- |
287| OpenAI | `openaiFiles()` | Responses `input_image` / `input_file` `file_id` | `get`, `delete` |
288| Anthropic | `anthropicFiles()` | `file_id` message source (sends the `files-api-2025-04-14` beta) | `get`, `delete` |
289| Gemini | `geminiFiles()` | `fileData.fileUri` (the handle URI) | `get`, `delete` |
290| fal | `falFiles()` | storage URL (used like any URL) | upload-only |
291| Grok (xAI) | `grokFiles()` | public URL (used like any URL) | `get`, `delete` |
292​
293Gemini and fal handles are URLs, so they also work in a plain `{ type: 'url' }` source. OpenAI and Anthropic handles are opaque ids, so they need the `{ type: 'file' }` source.
294​
295### Providers and endpoints that cannot use a handle
296​
297Adapters that can use file handles declare a `supportsFileSources` capability. For all other adapters, `chat()`, `generateImage()`, `generateVideo()`, and `embed()` reject a `{ type: 'file' }` source before they build a request. This applies to:
298​
299- Groq, Bedrock, Mistral, OpenRouter, Ollama, BytePlus, and Cohere.
300- Any adapter that does not declare `supportsFileSources`.
301​
302So a handle never goes out by mistake as a URL or as data.
303​
304Some endpoints of supported providers also need the bytes, and throw an error for that endpoint:
305​
306- OpenAI `images/edits` and the Sora `input_reference` need the bytes.
307- Gemini Veo needs the bytes or a `gs://` URI.
308- The image path of OpenAI **Chat Completions** takes only a URL or a data URI. Use the Responses adapter (`openaiText`) for `file_id` images.
309​
310### Gemini upload on some server runtimes
311​
312`geminiFiles().upload()` uses the resumable upload of `@google/genai`. It sets a `Content-Length` header on a request with a `Blob` body. Some server runtimes reject that header with `fetch failed` or `InvalidArgumentError: invalid content-length header`.
313​
314- On TanStack Start or Nitro, older Nitro fails (seen on `nitro@3.0.1-alpha.2`). Current Nitro works (tested on `nitro@3.0.260610-beta`). If you get this error, upgrade Nitro.
315- Native Node and the production `node-server` build work.
316- OpenAI, Anthropic, and fal uploads use a different transport and do not hit this error.