Files API 让你把文件上传到 Anthropic,并在后续 Claude API 请求中用 file_id 引用,而不是每次都重新上传。它适合长文档、多轮分析、图片理解和代码执行数据处理场景。
Files API 解决什么问题?
没有 Files API 时,应用常常需要:
- 每次请求都把 PDF base64 放进去
- 重复上传同一份文档
- 难以管理代码执行生成的输出文件
- 图片或文档多轮分析时请求体很大
Files API 提供 create-once, use-many-times 的模式。
当前状态与限制
Files API 是 beta,需要 header:
anthropic-beta: files-api-2025-04-14重要限制:
- 不适用于 Zero Data Retention
- Claude API、Claude Platform on AWS、Microsoft Foundry 可用
- 当前不支持 Amazon Bedrock 或 Vertex AI
- 文件会按功能标准保留策略保存
如果组织有严格 ZDR 要求,使用前需要确认合规边界。
上传文件
curl -X POST https://api.anthropic.com/v1/files \
-H "x-api-key: ${ANTHROPIC_API_KEY}" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14" \
-F "file=@/path/to/document.pdf"响应中会得到:
{
"id": "file_011CNha8iCJcU1wXNR6q4V8w",
"type": "file",
"filename": "document.pdf",
"mime_type": "application/pdf",
"size_bytes": 1024000,
"created_at": "2025-01-01T00:00:00Z"
}后续请求使用 id 即可。
在 Messages 中引用文件
PDF 或文本文件作为 document block:
{
"type": "document",
"source": {
"type": "file",
"file_id": "file_011CNha8iCJcU1wXNR6q4V8w"
}
}图片作为 image block:
{
"type": "image",
"source": {
"type": "file",
"file_id": "file_011CPMxVD3fHLUhvTqtsQA5w"
}
}数据集、表格等文件可与 code execution tool 结合,用于分析和可视化。
支持哪些文件?
| 文件类型 | Content Block | 用途 |
|---|---|---|
| document | 文档分析、合同、报告 | |
| Plain text | document | 文本处理 |
| JPEG/PNG/GIF/WebP | image | 图片理解 |
| 数据集/其他 | container_upload | 代码执行、数据分析 |
.csv、.md、.docx、.xlsx 等并非都能直接作为 document block。很多格式需要先转成 plain text,或配合代码执行工具处理。
与 Citations 的组合
上传 PDF 后,可以在 document block 上启用 citations:
{
"type": "document",
"source": { "type": "file", "file_id": "file_xxx" },
"title": "Annual Report",
"citations": { "enabled": true }
}这样 Claude 的回答可以引用 PDF 页码,适合法律、财务、研究报告等需要可验证来源的应用。
管理文件
生产系统需要实现:
- 文件列表查看
- 按业务 ID 映射 file_id
- 删除不再使用的文件
- 记录上传者、用途、过期时间
- 对敏感文件做访问控制
不要把 Files API 当成永久对象存储。它是 Claude 工作流的文件引用层,不是通用网盘。
最佳实践
- 对同一文件只上传一次,复用 file_id
- 在数据库保存 file_id 与业务对象映射
- 对敏感文档明确保留策略
- 大批量文档分析配合 Batch Processing
- 长文档问答配合 Citations
- 数据分析任务配合 Code Execution
来源:Anthropic 官方文档 - Files API | 整理:ClaudeEagle