Skip to navigation

Files in chat

Read user uploads and return files from a messaging agent, in web chat and Slack
View as Markdown

Web chat and Slack both send files to an agent and deliver the files it returns. Web chat shows a returned file as a download chip. Slack uploads it into the reply’s thread. Either way the agent reads and writes the same file store. Files in Slack covers what differs there.

In web chat, the transfer has two parts:

  • The Files API moves bytes between the browser and the deployment’s persistent file store.
  • The messaging API associates an uploaded file key with a user or assistant message.

The browser never puts file bytes in a chat message. The agent normally does not call the Files API either: Astropods mounts the same file store into the agent container and sets AGENT_FILES_DIR to its location (normally /data/files).

Reserve key, then upload bytes Send message with attachment key Message + attachment metadata and storage key Read AGENT_FILES_DIR/<key>.blob Write a new regular file in AGENT_FILES_DIR END chunk with the output filename Reply with a download chip Download output bytes Chat user Files API Messaging sidecar Agent container

Enable file-enabled chat

File-enabled chat needs two things: a messaging deployment with the web adapter (which provisions and mounts the file store automatically), and an agent that declares it consumes files.

First, declare a messaging agent. The file store is mounted automatically; there is no separate storage setting.

agent:
build:
context: .
dockerfile: Dockerfile
interfaces:
messaging: true
dev:
interfaces:
messaging:
adapters: [web]

Then set supportsFiles in the config your agent sends at startup. The chat’s upload controls (drag-and-drop, paste, and the Files tab) work only for agents that set this flag, so an agent that ignores uploads never gets files it would drop. The paperclip stays on screen either way, greyed out with a tooltip naming the agent as the reason, so a missing upload reads as a capability the agent lacks rather than a control the chat forgot. The flag defaults to off; having the file store mounted is not enough on its own. It gates only the upload affordances; agent-produced download chips render regardless.

getConfig() {
return { systemPrompt: "Analyze user-provided documents.", tools: [], supportsFiles: true };
}

In local development, open the chat URL printed by ast project (normally http://localhost:3100). Users can attach a file with the paperclip, drag and drop, or paste. The chat uploads the bytes when the message is sent and passes the resulting key with that message.

Read files attached by a user

When you use an Astropods adapter, each call to your agent receives the current turn’s files in StreamOptions.attachments. Treat this list as the authority for the turn. Do not enumerate the whole shared directory to decide which files belong to the current user.

Each attachment contains:

NodePythonMeaning
keykeyOpaque Files API key. Do not show it as the filename.
namenameOriginal display filename. Do not use it to construct an input path.
pathpathAbsolute path to the stored bytes. Read this path when present.
mimeTypemime_typeMIME type reported at upload time, if known.
sizesizeSize in bytes, if known.
import { readFile } from "node:fs/promises";
import type { AgentAdapter } from "@astropods/adapter-core";
const adapter: AgentAdapter = {
name: "Document analyst",
async stream(prompt, hooks, options) {
try {
for (const attachment of options.attachments ?? []) {
if (!attachment.path) {
throw new Error(
`Cannot resolve ${attachment.name}; update the messaging and adapter packages`,
);
}
const bytes = await readFile(attachment.path);
await analyzeFile({
bytes,
name: attachment.name,
mimeType: attachment.mimeType,
prompt,
});
}
hooks.onChunk("I finished analyzing the attached file.");
hooks.onFinish();
} catch (error) {
hooks.onError(error as Error);
}
},
getConfig() {
return { systemPrompt: "Analyze user-provided documents.", tools: [], supportsFiles: true };
},
};

path is absent only when an older sidecar or SDK did not carry the storage key. Never guess AGENT_FILES_DIR/<original filename>: API-managed uploads are stored by opaque key, not by their display name. Update the messaging and adapter packages before relying on file input.

Give a framework agent file tools

The Mastra, AI SDK, and LangChain adapters own stream(). They append each attached file’s name and path to the turn’s text, and the model needs tools to open those paths. fileTools() (file_tools() in Python) returns four tools that work on files of any size without loading a file into the prompt:

ToolWhat it does
inspect_fileReports a file’s kind (PDF, DOCX, XLSX, or text), its size, its text length, and for a table each sheet’s columns and row count.
read_fileReturns one 20,000-character page of a PDF, DOCX, or text file, with nextOffset (next_offset in Python) for the next page.
read_tableReturns one page of rows from a CSV or XLSX file, 100 by default, with nextOffset (next_offset in Python) for the next page.
create_fileWrites a text file, attaches it to the reply, and returns its name and the path to read it back.
import { Agent } from "@mastra/core/agent";
import { fileTools, serve } from "@astropods/adapter-mastra";
const agent = new Agent({
name: "Assistant",
model,
instructions: "Answer questions about the files the user attaches.",
tools: { ...fileTools() },
});
serve(agent, { supportsFiles: true });

The tools open only the files attached to or created in the current conversation, because every thread’s and user’s files share AGENT_FILES_DIR. A follow-up question in the same Slack thread, Slack DM, or web chat can go back to an earlier file. The adapter saves that list with the files, so it lasts through a restart or a redeploy.

The tools deliver a file’s contents and do no analysis. For counts, totals, or grouping over a large table, give the agent a tool that runs a query engine, such as DuckDB or pandas, on the attachment’s path. If the model writes the query, limit what the engine can read, because both can open any path. A scanned PDF has no text layer, so read_file returns an error that says it needs OCR, and reading one takes an OCR tool of your own.

The same functions are exported from @astropods/adapter-core/files as inspectFile, readFilePage, and readTable, and from astropods_adapter_core as inspect_file, read_file_page, and read_table, for a custom adapter or for tools you write yourself. They have the same limit and work only while the agent handles a message.

Return a file to the user

From a tool, call attachFile (Node) or attach_file (Python). It writes the file into AGENT_FILES_DIR and attaches it to the current reply, however deep the framework runs the tool. It throws when called outside a turn, and the name must be a single path segment.

import { attachFile } from "@astropods/adapter-core";
await attachFile({ name: "account-plan.csv", data: csv, mimeType: "text/csv" });

Omit the data to attach a file already in AGENT_FILES_DIR. Every conversation’s files share that dir, so a name already in it gets a number: account-plan.csv becomes account-plan-2.csv. The function returns the name it used.

In a custom adapter you can register the file with the response hook directly. Write the complete output as a regular file directly inside AGENT_FILES_DIR, then register it before finishing the response. The bridge sends the file reference on the END chunk, and the chat renders a download chip.

Use a new, single-segment filename for every output. A UUID prefix prevents concurrent conversations or different users from colliding on a shared filename. Do not use subdirectories, symlinks, or names ending in .blob, .meta.json, or .tmp; those are reserved storage artifacts and are not exposed as agent outputs.

import { randomUUID } from "node:crypto";
import { mkdir, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { StreamHooks } from "@astropods/adapter-core";
const filesDir = process.env.AGENT_FILES_DIR ?? "/data/files";
async function attachCsv(hooks: StreamHooks, csv: string) {
const name = `${randomUUID()}-analysis.csv`;
await mkdir(filesDir, { recursive: true });
await writeFile(join(filesDir, name), csv, { encoding: "utf8", flag: "wx" });
const file = await stat(join(filesDir, name));
hooks.onFile({ name, mimeType: "text/csv", size: file.size });
hooks.onChunk("Your analysis is ready.");
hooks.onFinish();
}

The file must exist before onFile / on_file, and the hook’s name must exactly match the basename on disk. If the sidecar cannot find that regular file when it processes the terminal chunk, it omits the download chip rather than creating a broken link.

Read images attached by a user

Images arrive separately from files, in StreamOptions.images. The bytes travel inline as a data: URI on each image’s url, so a model can read them without a filesystem access.

NodePythonMeaning
namenameOriginal display filename.
urlurldata: URI holding the bytes. Pass this to the model.
mimeTypemime_typeMIME type detected from the bytes.
sizesizeSize in bytes.

StreamOptions is the same for every adapter. What differs is which fields an adapter consumes, because the adapter owns stream(). The Mastra and LangChain adapters read images and pass them to the model, so a vision-capable agent describes an uploaded image with no extra code. For a non-image attachment they append its name and path to the turn’s text, which a tool can then read. Pair that with a file-reading tool: a model handed a path it cannot open tends to describe a file it never read. In a custom adapter you write stream() yourself and read both lists directly.

An uploaded image also appears in attachments with a path, so an agent that reads files keeps working unchanged. Use attachments to process the bytes and images to show the image to the model.

A message inlines up to 2 MiB of image bytes in total. A larger image, or one past that budget, arrives in attachments only, so the model does not see it.

import type { AgentAdapter } from "@astropods/adapter-core";
const adapter: AgentAdapter = {
name: "Image describer",
async stream(prompt, hooks, options) {
const images = options.images ?? [];
if (images.length === 0) {
hooks.onChunk("Attach an image and I will describe it.");
hooks.onFinish();
return;
}
const content = [
...images.map((image) => ({
type: "image_url" as const,
image_url: { url: image.url },
})),
{ type: "text" as const, text: prompt },
];
// Send `content` to your vision model, then stream its reply.
hooks.onFinish();
},
getConfig() {
return { systemPrompt: "Describe user-provided images.", tools: [], supportsFiles: true };
},
};

Files in Slack

The Slack adapter delivers files with the same attachments contract as web chat, so an agent that reads files in web chat reads them in Slack unchanged.

  • What reaches the agent: the files on an @-mention or a direct message. A mention inside a thread also brings the files from earlier messages in that thread, up to the 20 newest, so a user can drop a document in a thread and later ask the agent about it. A file posted in a channel thread without a mention waits for the next mention there.
  • Images: an image of 2 MiB or less reaches the model inline. A larger image, and every image from earlier in a thread, arrives as a file in attachments. The model sees only inline images. To let it look at a larger or earlier image, give the agent a tool that returns the image to the model.
  • Size limit: a file can be up to the deployment’s file size limit, 100 MiB unless FILES_MAX_MB changes it (see File size limit).
  • Skipped files: a file that does not reach the agent is named in the message text, one line each, so the agent can tell the user why. Reasons include a file over the cap, a download Slack refused, and a Google Drive link, which is not an upload.
[slack_file_skipped] account-plan.pdf: Slack refused the download
  • Returned files: a file the agent returns with attachFile or onFile is uploaded into the reply’s thread. The thread that first gets a file owns it, and no other thread or web chat user can get it. A file that cannot be posted, such as one over the size limit, is named in a short note in the thread with the reason.

The Slack app needs the files:read bot scope to receive files and files:write to send them. Without files:read, every file is skipped as refused.

supportsFiles gates only the web chat upload controls. Slack delivers files whether or not the agent sets it.

Use the raw messaging SDK

If you manage the gRPC stream yourself, the same rules apply without the adapter conveniences.

For an inbound web attachment:

  • Select attachments with type FILE.
  • Use storageKey (Node) or storage_key (Python), not filename, to locate the bytes.
  • Filesystem-backed uploads are stored at AGENT_FILES_DIR/<storage key>.blob.
  • An uploaded image also arrives as a second attachment with type IMAGE, carrying the bytes in a data: URI on url. Select those to pass images to a model.

For an outbound file:

  1. Write a uniquely named regular file directly inside AGENT_FILES_DIR.
  2. Send a FileAttachment on the terminal ContentChunk.
  3. Set filename to the file’s basename. Leave url empty for a filesystem file.
import { randomUUID } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
const filesDir = process.env.AGENT_FILES_DIR ?? "/data/files";
const input = message.attachments?.find((a) => a.type === "FILE");
if (input?.storageKey) {
const inputPath = join(filesDir, `${input.storageKey}.blob`);
const bytes = await readFile(inputPath);
// Process bytes...
}
const outputName = `${randomUUID()}-analysis.csv`;
const outputBytes = new TextEncoder().encode(await buildCsv());
await writeFile(join(filesDir, outputName), outputBytes, { flag: "wx" });
conversation.sendContentChunk(message.conversationId, {
type: "END",
content: "Your export is ready.",
attachments: [
{
file: {
filename: outputName,
mimeType: "text/csv",
sizeBytes: outputBytes.byteLength,
},
},
],
});

See Inbound message anatomy for the full message and response shapes.

Build a custom chat client

The Astropods built-in chat already implements this flow. A custom client must use both APIs in order:

1

Reserve a file key

Call POST /api/v1/deployments/{deploymentId}/files with the display metadata and exact byte size.

{
"name": "quarterly-results.csv",
"content_type": "text/csv",
"size": 18420
}

The response contains an opaque key and an upload descriptor:

{
"key": "2df6a4ac-cb4a-4ef0-8b8d-833d635b91cf",
"file": {
"key": "2df6a4ac-cb4a-4ef0-8b8d-833d635b91cf",
"name": "quarterly-results.csv",
"content_type": "text/csv",
"size": 18420,
"updated_at": "2026-07-16T16:00:00Z"
},
"upload": {
"url": "2df6a4ac-cb4a-4ef0-8b8d-833d635b91cf/content",
"method": "PUT"
}
}
2

Upload the bytes

Resolve a relative upload.url against /api/v1/deployments/{deploymentId}/files/. Absolute URLs are presigned storage URLs and must be used unchanged. Send the bytes with the returned method and headers. Include the user’s Astropods credentials only for a same-origin Astropods URL; never forward them to a presigned cross-origin URL.

The upload is not attachable until this request succeeds. A 413 means the declared or received file is too large; 507 means the deployment volume cannot fit it.

3

Attach the key to a message

Send only the key with the user’s text. Up to 16 files can be attached to one message, and text may be empty when at least one attachment is present.

POST /api/v1/deployments/{deploymentId}/messaging/conversations/{conversationId}/messages
Content-Type: application/json
{
"content": "Summarize this report",
"attachments": [
{ "key": "2df6a4ac-cb4a-4ef0-8b8d-833d635b91cf" }
]
}

The server reloads the file’s authoritative metadata and rejects unknown, incomplete, or differently owned keys.

4

Render and download response files

Assistant attachments arrive on the terminal SSE chunk and are also stored in chat history:

event: chunk
data: {"type":"chunk","chunk_type":"end","content":"Your analysis is ready.","attachments":[{"key":"0d94b92d-analysis.csv","name":"0d94b92d-analysis.csv","content_type":"text/csv","size":9321}]}

Download bytes from GET /api/v1/deployments/{deploymentId}/files/{key}/content. Follow redirects so the same client works with filesystem and presigned-object storage.

Ownership and storage rules

Setting supportsFiles changes what your agent ingests: it starts accepting user uploads. Treat attachment bytes, display names, and MIME types as untrusted input, and apply the same parser limits and content validation you would use for any user upload. The agent container shares the underlying volume, so use only the current turn’s attachment paths for input — do not scan or expose unrelated files.

  • Files are scoped to the authenticated user, even when several users share a deployment. List, read, download, delete, and message-attachment checks all enforce that scope.
  • Agent-produced files are assigned to the conversation owner when the reply is finalized. A file already assigned to another user is not transferred or attached.
  • Uploads are held to the deployment’s file size limit: 100 MiB unless FILES_MAX_MB changes it, or none when it is 0. Clients should treat 413 Payload Too Large as authoritative and prompt the user to choose a smaller file. The store also reserves free space for chat data; clients should surface 507 Insufficient Storage and let the user delete files before retrying.
  • Agent code writes outputs directly to the shared volume, so it must handle disk-full write errors. A returned file over the file size limit is not delivered: web chat shows no download chip, and Slack posts no upload.
  • Symlinks are never adopted or served. Only regular files directly inside AGENT_FILES_DIR can become agent-produced downloads.
  • File metadata and chat history persist, so upload and download chips survive a page reload. If a user later deletes a file, its old message metadata remains but its bytes are no longer downloadable.