Open History to see the last commit
1---
2title: Multimodal Content
3id: multimodal-content
4order: 4
5description: "Send images, audio, video, and PDFs with the text of a message. Build the parts in the browser, and the adapter sends them to the model."
6keywords:
7 - tanstack ai
8 - multimodal
9 - vision
10 - images
11 - audio
12 - video
13 - documents
14 - ContentPart
15 - ImagePart
16---
17
18A message part can carry an image, audio clip, video, or PDF. The model then answers about that file.
19
20Make the `content` of the message an array of parts. One part holds the text, and the other parts hold the image, audio, video, or document.
21
22## Quick setup
23
24This setup lets a user pick an image and ask about it. It takes about 5 minutes.
25
26### 1. Use a model that reads images
27
28Your chat route does not change. Pick a model that takes image input:
29
30```typescript
31// api/chat.ts
32import {
33 chat,
34 chatParamsFromRequest,
35 toServerSentEventsResponse,
36} from "@tanstack/ai";
37import { openaiText } from "@tanstack/ai-openai";
38
39export async function POST(request: Request) {
40 const { messages, threadId, runId } = await chatParamsFromRequest(request);
41
42 const stream = chat({
43 adapter: openaiText("gpt-6.1-sol"),
44 messages,
45 threadId,
46 runId,
47 });
48
49 return toServerSentEventsResponse(stream);
50}
51```
52
53### 2. Send the image from the browser
54
55Read the file as base64. Then send a text part and an image part together:
56
57```tsx
58import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
59
60function readAsBase64(file: File): Promise<string> {
61 return new Promise((resolve, reject) => {
62 const reader = new FileReader();
63 reader.onload = () => {
64 const result = reader.result;
65 if (typeof result !== "string") {
66 reject(new Error("Could not read the file"));
67 return;
68 }
69 // Remove the "data:image/png;base64," prefix.
70 resolve(result.slice(result.indexOf(",") + 1));
71 };
72 reader.onerror = () => reject(reader.error);
73 reader.readAsDataURL(file);
74 });
75}
76
77export function AskAboutImage() {
78 const { sendMessage } = useChat({
79 connection: fetchServerSentEvents("/api/chat"),
80 threadId: "support-chat",
81 });
82
83 async function send(file: File) {
84 const base64 = await readAsBase64(file);
85 await sendMessage({
86 content: [
87 { type: "text", content: "What is in this image?" },
88 {
89 type: "image",
90 source: { type: "data", value: base64, mimeType: file.type },
91 },
92 ],
93 });
94 }
95
96 return (
97 <input
98 type="file"
99 accept="image/*"
100 onChange={(event) => {
101 const file = event.target.files?.[0];
102 if (file) void send(file);
103 }}
104 />
105 );
106}
107```
108
109Pick an image, and the model describes it in the chat.
110
111## How it works
112
113- `content` is a string or an array of parts. A string is the same as one text part.
114- Each part has a `type`: `text`, `image`, `audio`, `video`, or `document`.
115- Each media part has a `source` that says where the bytes are. See [Source types](#source-types).
116- The adapter turns each part into the format of its provider.
117- The types of `chat()` allow only the input types that the selected model supports.
118
119## Advanced
120
121### Content parts
122
123The part types come from `@tanstack/ai`:
124
125```typescript
126import type { ImagePart, TextPart } from "@tanstack/ai";
127
128const textPart: TextPart = {
129 type: "text",
130 content: "What do you see in this image?",
131};
132
133// Image from base64 data. `mimeType` is required for data sources.
134const imagePart: ImagePart = {
135 type: "image",
136 source: {
137 type: "data",
138 value: "base64EncodedImageData...",
139 mimeType: "image/jpeg",
140 },
141 metadata: {
142 detail: "high", // OpenAI detail level
143 },
144};
145
146// Image from a URL. `mimeType` is optional for URL sources.
147const imageUrlPart: ImagePart = {
148 type: "image",
149 source: {
150 type: "url",
151 value: "https://example.com/image.jpg",
152 mimeType: "image/jpeg",
153 },
154};
155```
156
157All the part types:
158
159```typescript
160import type {
161 AudioPart,
162 ContentPart,
163 DocumentPart,
164 ImagePart,
165 TextPart,
166 VideoPart,
167} from "@tanstack/ai";
168
169// Metadata types for each provider
170import type { OpenAIImageMetadata } from "@tanstack/ai-openai";
171import type { AnthropicImageMetadata } from "@tanstack/ai-anthropic";
172import type { GeminiImageMetadata } from "@tanstack/ai-gemini";
173```
174
175On the server, you can build the same message in a `chat()` call:
176
177```typescript
178import { chat } from "@tanstack/ai";
179import { openaiText } from "@tanstack/ai-openai";
180
181const stream = chat({
182 adapter: openaiText("gpt-6.1-sol"),
183 messages: [
184 {
185 role: "user",
186 content: [
187 { type: "text", content: "What is in this image?" },
188 {
189 type: "image",
190 source: { type: "url", value: "https://example.com/photo.jpg" },
191 },
192 ],
193 },
194 ],
195 threadId: "thread-1",
196});
197```
198
199### Source types
200
201Each media part has one of three sources.
202
203#### Data (base64)
204
205Use `type: 'data'` for inline base64 bytes. The `mimeType` field is required, so the provider gets the correct content type:
206
207```typescript
208import type { AudioPart, ImagePart } from "@tanstack/ai";
209
210const imagePart: ImagePart = {
211 type: "image",
212 source: {
213 type: "data",
214 value: "iVBORw0KGgoAAAANSUhEUgAAAAUA...",
215 mimeType: "image/png",
216 },
217};
218
219const audioPart: AudioPart = {
220 type: "audio",
221 source: {
222 type: "data",
223 value: "base64AudioData...",
224 mimeType: "audio/mp3",
225 },
226};
227```
228
229Data is good for small files, or when the file is not on a public URL.
230
231#### URL
232
233Use `type: 'url'` for a file at a URL. The `mimeType` field is optional, because the provider can often find the type from the URL or the response headers:
234
235```typescript
236import type { ImagePart } from "@tanstack/ai";
237
238const imagePart: ImagePart = {
239 type: "image",
240 source: {
241 type: "url",
242 value: "https://example.com/image.jpg",
243 mimeType: "image/jpeg",
244 },
245};
246```
247
248A URL is good for large files that are already online. Not all providers accept a URL for all input types. Read the provider docs.
249
250#### File handle (Files API)
251
252Use `type: 'file'` for a file that you uploaded one time with the [Files API](./files-api) of a provider. The provider keeps the bytes, and each request sends a small reference. The source holds the opaque handle and the provider that issued it: `{ type: 'file', value: 'file-...', provider: 'openai' }`.
253
254```typescript
255import { chat, fileSourceFromHandle, uploadFile } from "@tanstack/ai";
256import { openaiFiles, openaiText } from "@tanstack/ai-openai";
257import { pdfBase64 } from "./pdf-data";
258
259// Upload one time.
260const handle = await uploadFile({
261 adapter: openaiFiles(),
262 input: { data: pdfBase64, mimeType: "application/pdf" },
263});
264
265// Then use the handle in as many requests as you want.
266const stream = chat({
267 adapter: openaiText("gpt-5.5"),
268 messages: [
269 {
270 role: "user",
271 content: [
272 { type: "text", content: "Summarize this document" },
273 { type: "document", source: fileSourceFromHandle(handle) },
274 ],
275 },
276 ],
277 threadId: "thread-1",
278});
279```
280
281What `fileSourceFromHandle(handle)` does:
282
283- It builds the `{ type: 'file', value, provider }` source.
284- It picks the handle URL for Gemini, fal, and Grok, and the opaque id for OpenAI and Anthropic.
285- Each adapter maps `value` to the native field of the provider (`file_id`, `fileData.fileUri`, or a URL).
286
287These cases throw an error:
288
289- A handle that you send to a different provider.
290- A handle that you send to an adapter with no Files API support. The adapter rejects it before it builds the request.
291- A handle that you send to an endpoint that needs the bytes, such as image edits or Veo.
292
293See [Files API](./files-api) to upload, get, and delete handles.
294
295### Images in tool results
296
297A tool can return an array of `ContentPart`. Use it to give the model a screenshot or a chart:
298
299```typescript
300import { toolDefinition } from "@tanstack/ai";
301import type { ContentPart } from "@tanstack/ai";
302import { z } from "zod";
303
304const getScreenshot = toolDefinition({
305 name: "get_screenshot",
306 description: "Get a screenshot of the page",
307 inputSchema: z.object({}),
308}).server(async (): Promise<Array<ContentPart>> => [
309 { type: "text", content: "Page screenshot" },
310 {
311 type: "image",
312 source: { type: "data", value: "iVBORw0KGgo...", mimeType: "image/png" },
313 },
314]);
315```
316
317The adapter sends the image in the form that its API accepts:
318
319- **Responses APIs** (`openaiText`, `openRouterResponsesText`): the image stays in the tool output.
320- **Chat Completions APIs** (`openRouterText`, `openaiChatCompletions`, and the other Chat Completions adapters built on `@tanstack/openai-base`): a tool message holds text only. The text goes in the tool message. The images go in one user message after the tool results. If a result has only images, its tool text is `(see attached image)`.
321
322Some more rules:
323
324- If these adapters know that the model has no image input, they do not send the images.
325- An adapter that does not know the input types of the model sends the images. A result with only images then has the text `(image omitted: this model has no image input)`.
326- The Chat Completions adapters and `openRouterResponsesText` send only the text and the images of a result that has images. They do not send audio, video, or documents from it.
327- When an adapter sends an image from a tool result, a `file` source is an error, except on `openaiText`. Use a `data` or `url` source.
328
329### Provider support
330
331| Provider | Adapter | Input besides text |
332| --- | --- | --- |
333| OpenAI | `openaiText` | Image on `gpt-6.1-sol` and most new models. Image and PDF document on `gpt-5.5`. Audio on `gpt-4o-audio`. |
334| Anthropic | `anthropicText` | Image and PDF document on all Claude models, for example `claude-sonnet-5-5`. |
335| Gemini | `geminiText` | Image, audio, video, and document, for example on `gemini-3.8-flash`. |
336| Ollama | `ollamaText` | Image on vision models, such as `llama3.2-vision`. Support changes by model. |
337
338For the full list of each model, read `supports.input` in the `model-meta.ts` file of the adapter package.
339
340`ollamaText(model)` reads the host from the `OLLAMA_HOST` environment variable. The default is `http://localhost:11434`.
341
342#### OpenAI image detail and PDF filename
343
344OpenAI reads two metadata fields:
345
346- `detail` on an image: `'auto'`, `'low'`, or `'high'`.
347- `filename` on a document. The API needs a filename with inline data. The default is `document.pdf`.
348
349```typescript
350import { chat } from "@tanstack/ai";
351import { openaiText } from "@tanstack/ai-openai";
352import { imageBase64, pdfBase64 } from "./data";
353
354const stream = chat({
355 adapter: openaiText("gpt-5.5"),
356 messages: [
357 {
358 role: "user",
359 content: [
360 { type: "text", content: "Does the chart match the report?" },
361 {
362 type: "image",
363 source: { type: "data", value: imageBase64, mimeType: "image/jpeg" },
364 metadata: { detail: "high" },
365 },
366 {
367 type: "document",
368 source: { type: "data", value: pdfBase64, mimeType: "application/pdf" },
369 metadata: { filename: "report.pdf" },
370 },
371 ],
372 },
373 ],
374 threadId: "thread-1",
375});
376```
377
378### Send any file type from the browser
379
380This input accepts images, audio, video, and PDFs. It picks the part type from the MIME type of the file. It uses `readAsBase64` from the [quick setup](#2-send-the-image-from-the-browser):
381
382```tsx
383import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
384import { readAsBase64 } from "./read-as-base64";
385
386export function ChatWithFileUpload() {
387 const { sendMessage } = useChat({
388 connection: fetchServerSentEvents("/api/chat"),
389 threadId: "support-chat",
390 });
391
392 async function handleFileUpload(file: File) {
393 const base64 = await readAsBase64(file);
394
395 const type = file.type.startsWith("image/")
396 ? "image"
397 : file.type.startsWith("audio/")
398 ? "audio"
399 : file.type.startsWith("video/")
400 ? "video"
401 : "document";
402
403 await sendMessage({
404 content: [
405 { type: "text", content: `Please analyze this ${type}` },
406 {
407 type,
408 source: { type: "data", value: base64, mimeType: file.type },
409 },
410 ],
411 });
412 }
413
414 return (
415 <input
416 type="file"
417 accept="image/*,audio/*,video/*,.pdf"
418 onChange={(event) => {
419 const file = event.target.files?.[0];
420 if (file) void handleFileUpload(file);
421 }}
422 />
423 );
424}
425```
426
427The model on the server must accept each type that you allow here.
428
429### Message ID and per-message props
430
431`sendMessage` takes a string or a `MultimodalContent` object. These examples use `ChatClient` from `@tanstack/ai-client`. The `sendMessage` of `useChat` takes the same first argument. For per-message props, it takes `{ body }` as the second argument.
432
433Give the message your own ID:
434
435```typescript
436import { ChatClient, fetchServerSentEvents } from "@tanstack/ai-client";
437
438const client = new ChatClient({
439 connection: fetchServerSentEvents("/api/chat"),
440 threadId: "support-chat",
441});
442
443await client.sendMessage({
444 content: "Hello!",
445 id: "custom-message-id-123",
446});
447```
448
449The second argument adds `forwardedProps` for that one request. They are shallow-merged with the base `forwardedProps` of the client, and the values of the message win:
450
451```typescript
452import { ChatClient, fetchServerSentEvents } from "@tanstack/ai-client";
453
454const client = new ChatClient({
455 connection: fetchServerSentEvents("/api/chat"),
456 threadId: "support-chat",
457 forwardedProps: { model: "gpt-6.1-sol" },
458});
459
460await client.sendMessage("Analyze this complex problem", {
461 temperature: 0.2,
462});
463```
464
465### Validate messages from a request
466
467`request.json()` returns `any`. TanStack AI does not ship a runtime message validator. Define a schema with a Standard Schema library (Zod, Valibot, ArkType, and more), and parse the body before you give it to `chat()`:
468
469```typescript ignore
470import { chat } from "@tanstack/ai";
471import { openaiText } from "@tanstack/ai-openai";
472import { z } from "zod";
473
474const ContentPartSchema = z.discriminatedUnion("type", [
475 z.object({ type: z.literal("text"), content: z.string() }),
476 z.object({
477 type: z.literal("image"),
478 source: z.object({ type: z.enum(["url", "data"]), value: z.string() }),
479 }),
480]);
481
482const MessageSchema = z.object({
483 // `ModelMessage.role` is 'user' | 'assistant' | 'tool'. There is no
484 // 'system' role. Pass system instructions with the `systemPrompts`
485 // option of `chat()`.
486 role: z.enum(["user", "assistant", "tool"]),
487 content: z.union([z.string(), z.array(ContentPartSchema)]),
488});
489
490const BodySchema = z.object({
491 messages: z.array(MessageSchema),
492 threadId: z.string(),
493});
494
495// In an API route handler
496const { messages, threadId } = BodySchema.parse(await request.json());
497
498const stream = chat({
499 adapter: openaiText("gpt-6.1-sol"),
500 messages,
501 threadId,
502});
503```
504
505The types of `chat()` still limit anything that you add at the call site to the input types of the selected model.