Files API
Files API 允许您上传和管理文件以与 Claude API 一起使用,而无需在每次请求时重新上传内容。这在使用代码执行工具提供输入(例如数据集和文档)然后下载输出(例如图表)时特别有用。您还可以使用 Files API 避免在多个 API 调用中不断重新上传常用的文档和图片。除了本指南之外,您还可以直接探索 API 参考。
Files API 处于测试版。请通过反馈表与我们联系,分享您使用 Files API 的体验。
此功能不符合零数据保留(ZDR)条件。数据根据功能的标准保留策略保留。
支持的模型
在 Messages 请求中引用 file_id 在所有支持给定文件类型的模型上都受支持。图片在所有当前 Claude 模型上受支持。有关 PDF 和代码执行工具支持的其他文件类型,请参阅链接页面了解模型支持情况。
Files API 在 Claude API、AWS 上的 Claude 平台和 Microsoft Foundry 上可用。目前在 Amazon Bedrock 或 Vertex AI 上不可用。
Files API 的工作原理
Files API 提供了一种简单的"创建一次,使用多次"的文件处理方法:
- 上传文件到 Anthropic 的安全存储并接收唯一的
file_id - 下载文件由技能或代码执行工具创建的文件
- 在 Messages 请求中使用
file_id引用文件,而不是重新上传内容 - 使用列出、检索和删除操作管理您的文件
如何使用 Files API
要使用 Files API,您需要包含 beta 功能头:anthropic-beta: files-api-2025-04-14。
上传文件
上传文件以在未来的 API 调用中引用:
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"
FILE_ID=$(ant beta:files upload \
--file /path/to/document.pdf \
--transform id --raw-output)
uploaded = client.beta.files.upload(
file=("document.pdf", open("/path/to/document.pdf", "rb"), "application/pdf"),
)
const uploaded = await client.beta.files.upload({
file: await toFile(
fs.createReadStream("/path/to/document.pdf"),
undefined,
{ type: "application/pdf" },
),
});
var uploaded = await client.Beta.Files.Upload(
new FileUploadParams
{
File = new BinaryContent
{
Stream = File.OpenRead("/path/to/document.pdf"),
FileName = "document.pdf",
ContentType = new("application/pdf")
}
});
Console.WriteLine(uploaded.ID);
f, err := os.Open("/path/to/document.pdf")
if err != nil {
log.Fatal(err)
}
defer f.Close()
response, err := client.Beta.Files.Upload(context.Background(),
anthropic.BetaFileUploadParams{
File: anthropic.File(f, "document.pdf", "application/pdf"),
})
if err != nil {
log.Fatal(err)
}
fmt.Println(response.ID)
FileMetadata file = client.beta().files().upload(
FileUploadParams.builder()
.file(MultipartField.<InputStream>builder()
.value(Files.newInputStream(Path.of("/path/to/document.pdf")))
.filename("document.pdf")
.contentType("application/pdf")
.build())
.build()
);
System.out.println(file.id());
$file = $client->beta->files->upload(
FileParam::fromResource(fopen('/path/to/document.pdf', 'rb'), contentType: 'application/pdf'),
);
echo $file->id;
file = client.beta.files.upload(
file: Anthropic::FilePart.new(
Pathname("/path/to/document.pdf"),
content_type: "application/pdf"
)
)
puts file.id
上传文件的响应将包含:
{
"id": "file_011CNha8iCJcU1wXNR6q4V8w",
"type": "file",
"filename": "document.pdf",
"mime_type": "application/pdf",
"size_bytes": 1024000,
"created_at": "2025-01-01T00:00:00Z",
"downloadable": false
}
在消息中使用文件
上传后,使用其 file_id 引用文件:
curl -X POST https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14" \
-H "content-type: application/json" \
-d @- <<EOF
{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Please summarize this document for me."
},
{
"type": "document",
"source": {
"type": "file",
"file_id": "$FILE_ID"
}
}
]
}
]
}
EOF
ant beta:messages create --beta files-api-2025-04-14 <<YAML
model: claude-opus-4-6
max_tokens: 1024
messages:
- role: user
content:
- type: text
text: Please summarize this document for me.
- type: document
source:
type: file
file_id: $FILE_ID
YAML
response = client.beta.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Please summarize this document for me."},
{
"type": "document",
"source": {
"type": "file",
"file_id": file_id,
},
},
],
}
],
betas=["files-api-2025-04-14"],
)
print(response)
const response = await client.beta.messages.create({
model: "claude-opus-4-6",
max_tokens: 1024,
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Please summarize this document for me.",
},
{
type: "document",
source: {
type: "file",
file_id: uploaded.id,
},
},
],
},
],
betas: ["files-api-2025-04-14"],
});
console.log(response);
var response = await client.Beta.Messages.Create(
new MessageCreateParams
{
Model = Messages::Model.ClaudeOpus4_6,
MaxTokens = 1024,
Betas = [AnthropicBeta.FilesApi2025_04_14],
Messages =
[
new BetaMessageParam
{
Role = Role.User,
Content = new List<BetaContentBlockParam>
{
new BetaTextBlockParam { Text = "Please summarize this document for me." },
new BetaRequestDocumentBlock
{
Source = new BetaFileDocumentSource { FileID = fileId }
}
}
}
]
});
Console.WriteLine(response);
msg, err := client.Beta.Messages.New(context.Background(),
anthropic.BetaMessageNewParams{
Model: anthropic.ModelClaudeOpus4_6,
MaxTokens: 1024,
Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaFilesAPI2025_04_14},
Messages: []anthropic.BetaMessageParam{
anthropic.NewBetaUserMessage(
anthropic.NewBetaTextBlock("Please summarize this document for me."),
anthropic.NewBetaDocumentBlock(anthropic.BetaFileDocumentSourceParam{
FileID: fileID,
}),
),
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(msg)
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_6)
.addBeta("files-api-2025-04-14")
.maxTokens(1024)
.addUserMessageOfBetaContentBlockParams(List.of(
BetaContentBlockParam.ofText(BetaTextBlockParam.builder()
.text("Please summarize this document for me.")
.build()),
BetaContentBlockParam.ofDocument(BetaRequestDocumentBlock.builder()
.source(BetaFileDocumentSource.builder()
.fileId(fileId)
.build())
.build())
))
.build();
BetaMessage message = client.beta().messages().create(params);
System.out.println(message);
$response = $client->beta->messages->create(
maxTokens: 1024,
messages: [
[
'role' => 'user',
'content' => [
['type' => 'text', 'text' => 'Please summarize this document for me.'],
[
'type' => 'document',
'source' => [
'type' => 'file',
'file_id' => $fileId
]
]
]
]
],
model: 'claude-opus-4-6',
betas: ['files-api-2025-04-14'],
);
print_r($response);
response = client.beta.messages.create(
model: "claude-opus-4-6",
max_tokens: 1024,
betas: ["files-api-2025-04-14"],
messages: [
{
role: "user",
content: [
{ type: "text", text: "Please summarize this document for me." },
{
type: "document",
source: {
type: "file",
file_id: file_id
}
}
]
}
]
)
puts response
文件类型和内容块
Files API 支持不同的文件类型,对应不同的内容块类型:
| 文件类型 | MIME 类型 | 内容块类型 | 用例 |
|---|---|---|---|
application/pdf | document | 文本分析、文档处理 | |
| 纯文本 | text/plain | document | 文本分析、处理 |
| 图片 | image/jpeg、image/png、image/gif、image/webp | image | 图片分析、视觉任务 |
| 数据集、其他 | 各异 | container_upload | 分析数据、创建可视化 |
处理其他文件格式
对于不支持作为 document 块的文件类型(.csv、.txt、.md、.docx、.xlsx),将文件转换为纯文本,并将内容直接包含在消息中:
# 示例:读取文本文件并作为纯文本发送
# 注意:对于包含特殊字符的文件,考虑使用 base64 编码
TEXT_CONTENT="This is a sample document. It has multiple lines."
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d @- <<EOF
{
"model": "claude-opus-4-7",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Here's the document content:\n\n${TEXT_CONTENT}\n\nPlease summarize this document."
}
]
}
]
}
EOF
printf 'This is a test document for upload.\n' > document.txt
# "@./path" 引用将文件内容直接内联到字段中。
ant messages create \
--model claude-opus-4-7 \
--max-tokens 1024 \
--transform 'content.0.text' --raw-output <<'YAML'
messages:
- role: user
content:
- type: text
text: "Here's the document content:"
- type: text
text: "@./document.txt"
- type: text
text: "Please summarize this document."
YAML
import pandas as pd
import anthropic
client = anthropic.Anthropic()
# 示例:读取 CSV 文件
df = pd.read_csv("data.csv")
csv_content = df.to_string()
# 作为纯文本在消息中发送
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": f"Here's the CSV data:\n\n{csv_content}\n\nPlease analyze this data.",
}
],
}
],
)
print(response.content[0].text)
import Anthropic from "@anthropic-ai/sdk";
import fs from "fs/promises";
const anthropic = new Anthropic();
async function analyzeDocument() {
// 示例:读取文本文件
const textContent = await fs.readFile("document.txt", "utf-8");
// 作为纯文本在消息中发送
const response = await anthropic.messages.create({
model: "claude-opus-4-7",
max_tokens: 1024,
messages: [
{
role: "user",
content: [
{
type: "text",
text: `Here's the document content:\n\n${textContent}\n\nPlease summarize this document.`
}
]
}
]
});
const block = response.content[0];
if (block.type === "text") {
console.log(block.text);
}
}
analyzeDocument();
using System;
using System.IO;
using System.Threading.Tasks;
using Anthropic;
using Anthropic.Models.Messages;
class Program
{
static async Task Main(string[] args)
{
AnthropicClient client = new();
// 示例:读取文本文件
string textContent = await File.ReadAllTextAsync("document.txt");
var parameters = new MessageCreateParams
{
Model = Model.ClaudeOpus4_7,
MaxTokens = 1024,
Messages = [new()
{
Role = Role.User,
Content = {{CONTENT}}quot;Here's the document content:\n\n{textContent}\n\nPlease summarize this document."
}]
};
var message = await client.Messages.Create(parameters);
Console.WriteLine(message);
}
}
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/anthropics/anthropic-sdk-go"
)
func init() {
os.WriteFile("document.txt", []byte("This is a test document for upload."), 0644)
}
func main() {
client := anthropic.NewClient()
// 示例:读取文本文件
textContent, err := os.ReadFile("document.txt")
if err != nil {
log.Fatal(err)
}
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(
fmt.Sprintf("Here's the document content:\n\n%s\n\nPlease summarize this document.", string(textContent)),
)),
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(response.Content[0].Text)
}
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.Model;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class FileUploadExample {
public static void main(String[] args) throws IOException {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
// 示例:读取文本文件
String textContent = Files.readString(Paths.get("document.txt"));
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_7)
.maxTokens(1024L)
.addUserMessage("Here's the document content:\n\n" + textContent + "\n\nPlease summarize this document.")
.build();
Message response = client.messages().create(params);
response.content().stream()
.flatMap(block -> block.text().stream())
.forEach(textBlock -> System.out.println(textBlock.text()));
}
}
<?php
use Anthropic\Client;
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
// 示例:读取文本文件
$textContent = file_get_contents("document.txt");
$message = $client->messages->create(
maxTokens: 1024,
messages: [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => "Here's the document content:\n\n{$textContent}\n\nPlease summarize this document."
]
]
]
],
model: 'claude-opus-4-7',
);
echo $message->content[0]->text;
require "anthropic"
client = Anthropic::Client.new
# 示例:读取文本文件
text_content = File.read("document.txt")
message = client.messages.create(
model: "claude-opus-4-7",
max_tokens: 1024,
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Here's the document content:\n\n#{text_content}\n\nPlease summarize this document."
}
]
}
]
)
puts message.content.first.text
对于包含图片的 .docx 文件,请先将它们转换为 PDF 格式,然后使用 PDF 支持来利用内置的图片解析。这允许使用 PDF 文档中的引用。
Document 块
对于 PDF 和文本文件,使用 document 内容块:
{
"type": "document",
"source": {
"type": "file",
"file_id": "file_011CNha8iCJcU1wXNR6q4V8w"
},
"title": "Document Title", // 可选
"context": "Context about the document", // 可选
"citations": { "enabled": true } // 可选,启用引用
}
Image 块
对于图片,使用 image 内容块:
{
"type": "image",
"source": {
"type": "file",
"file_id": "file_011CPMxVD3fHLUhvTqtsQA5w"
}
}
管理文件
列出文件
检索您上传的文件列表:
curl 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"
ant beta:files list
import anthropic
client = anthropic.Anthropic()
files = client.beta.files.list()
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic();
const files = await anthropic.beta.files.list();
using System;
using System.Threading.Tasks;
using Anthropic;
using Anthropic.Models.Beta.Files;
class Program
{
static async Task Main(string[] args)
{
AnthropicClient client = new();
var files = await client.Beta.Files.List();
Console.WriteLine(files);
}
}
package main
import (
"context"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
)
func main() {
client := anthropic.NewClient()
files, err := client.Beta.Files.List(context.TODO(), anthropic.BetaFileListParams{})
if err != nil {
log.Fatal(err)
}
fmt.Println(files)
}
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.beta.files.FileListPage;
public class ListFiles {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
FileListPage files = client.beta().files().list();
System.out.println(files);
}
}
<?php
use Anthropic\Client;
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
$files = $client->beta->files->list();
print_r($files);
require "anthropic"
client = Anthropic::Client.new
files = client.beta.files.list
puts files
获取文件元数据
检索特定文件的信息:
curl "https://api.anthropic.com/v1/files/$FILE_ID" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14"
ant beta:files retrieve-metadata \
--file-id "$FILE_ID"
file = client.beta.files.retrieve_metadata(file_id)
const file = await client.beta.files.retrieveMetadata(uploaded.id);
var file = await client.Beta.Files.RetrieveMetadata(fileId);
Console.WriteLine(file);
metadata, err := client.Beta.Files.GetMetadata(
context.TODO(),
fileID,
anthropic.BetaFileGetMetadataParams{},
)
if err != nil {
log.Fatal(err)
}
fmt.Println(metadata)
FileMetadata metadata = client.beta().files().retrieveMetadata(fileId);
System.out.println(metadata);
$file = $client->beta->files->retrieveMetadata($fileId);
echo $file;
file = client.beta.files.retrieve_metadata(file_id)
puts file
删除文件
从您的工作区中移除文件:
curl -X DELETE "https://api.anthropic.com/v1/files/$FILE_ID" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14"
ant beta:files delete \
--file-id "$FILE_ID"
result = client.beta.files.delete(file_id)
await client.beta.files.delete(uploaded.id);
await client.Beta.Files.Delete(fileId);
_, err = client.Beta.Files.Delete(
context.TODO(),
fileID,
anthropic.BetaFileDeleteParams{},
)
if err != nil {
log.Fatal(err)
}
client.beta().files().delete(fileId);
$result = $client->beta->files->delete($fileId);
result = client.beta.files.delete(file_id)
下载文件
下载由技能或代码执行工具创建的文件:
curl -X GET "https://api.anthropic.com/v1/files/$FILE_ID/content" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: files-api-2025-04-14" \
--output downloaded_file.txt
ant beta:files download \
--file-id "$FILE_ID" \
--output downloaded_file.txt
file_content = client.beta.files.download(file_id)
# 保存到文件
file_content.write_to_file("downloaded_file.txt")
const content = await client.beta.files.download(uploaded.id);
const bytes = Buffer.from(await content.arrayBuffer());
await fsp.writeFile("downloaded_file.txt", bytes);
using var fileContent = await client.Beta.Files.Download(fileId);
await using var source = await fileContent.ReadAsStream();
await using var destination = File.Create("downloaded_file.txt");
await source.CopyToAsync(destination);
func downloadFile(client anthropic.Client, fileID string) error {
resp, err := client.Beta.Files.Download(
context.TODO(),
fileID,
anthropic.BetaFileDownloadParams{},
)
if err != nil {
return err
}
defer resp.Body.Close()
fileContent, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return os.WriteFile("downloaded_file.txt", fileContent, 0644)
}
try (HttpResponse response = client.beta().files().download(fileId)) {
try (InputStream body = response.body()) {
Files.copy(body, Path.of("downloaded_file.txt"),
StandardCopyOption.REPLACE_EXISTING);
}
}
$fileContent = $client->beta->files->download($fileId);
file_put_contents("downloaded_file.txt", $fileContent);
file_content = client.beta.files.download(file_id)
File.binwrite("downloaded_file.txt", file_content.read)
文件存储和限制
存储限制
- 最大文件大小: 每个文件 500 MB
- 总存储: 每个组织 500 GB
文件生命周期
- 文件限定在 API 密钥的工作区内。其他 API 密钥可以使用与同一工作区关联的任何其他 API 密钥创建的文件
- 文件会持续存在直到您删除它们
- 已删除的文件无法恢复
- 文件在删除后不久即无法通过 API 访问,但它们可能仍存在于活跃的
MessagesAPI 调用和关联的工具使用中 - 用户删除的文件将根据 Anthropic 的数据保留策略进行删除。
数据保留
通过 Files API 上传的文件会保留到使用 DELETE /v1/files/{file_id} 端点显式删除为止。文件存储以供跨多个 API 请求重用。
有关所有功能的 ZDR 资格,请参阅API 和数据保留。
错误处理
使用 Files API 时的常见错误包括:
- 文件未找到(404): 指定的
file_id不存在或您无权访问 - 无效文件类型(400): 文件类型与内容块类型不匹配(例如,在 document 块中使用图片文件)
- 超出上下文窗口大小(400): 文件大于上下文窗口大小(例如,在
/v1/messages请求中使用 500 MB 的纯文本文件) - 无效文件名(400): 文件名不符合长度要求(1-255 个字符)或包含禁止字符(
<、>、:、"、|、?、*、\、/或 unicode 字符 0-31) - 文件太大(413): 文件超过 500 MB 限制
- 超出存储限制(403): 您的组织已达到 500 GB 存储限制
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "File not found: file_011CNha8iCJcU1wXNR6q4V8w"
}
}
使用量和计费
File API 操作免费:
- 上传文件
- 下载文件
- 列出文件
- 获取文件元数据
- 删除文件
在 Messages 请求中使用的文件内容按输入 token 计价。您只能下载由技能或代码执行工具创建的文件。
速率限制
在测试版期间:
- 文件相关 API 调用限制为每分钟约 100 个请求
- 如果您的用例需要更高的限制,请联系我们