[ PROMPT_NODE_23836 ]
files-api
[ SKILL_DOCUMENTATION ]
# Files API — Python
Files API 用于上传文件以供 Messages API 请求使用。通过内容块中的 `file_id` 引用文件,避免在多次 API 调用中重复上传。
**Beta:** 在 API 调用中传递 `betas=["files-api-2025-04-14"]`(SDK 会自动设置所需的 Header)。
## 关键事实
- 最大文件大小:500 MB
- 总存储空间:每个组织 100 GB
- 文件将持续存在直到被删除
- 文件操作(上传、列出、删除)免费;消息中使用的内容按输入 Token 计费
- 不适用于 Amazon Bedrock 或 Google Vertex AI
---
## 上传文件
python
import anthropic
client = anthropic.Anthropic()
uploaded = client.beta.files.upload(
file=("report.pdf", open("report.pdf", "rb"), "application/pdf"),
)
print(f"File ID: {uploaded.id}")
print(f"Size: {uploaded.size_bytes} bytes")
---
## 在消息中使用文件
### PDF / 文档
python
response = client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Summarize the key findings in this report."},
{
"type": "document",
"source": {"type": "file", "file_id": uploaded.id},
"title": "Q4 Report", # 可选
"citations": {"enabled": True} # 可选,启用引用
}
]
}],
betas=["files-api-2025-04-14"],
)
for block in response.content:
if block.type == "text":
print(block.text)
### 图像
python
image_file = client.beta.files.upload(
file=("photo.png", open("photo.png", "rb"), "image/png"),
)
response = client.beta.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image",
"source": {"type": "file", "file_id": image_file.id}
}
]
}],
betas=["files-api-2025-04-14"],
)
---
## 管理文件
### 列出文件
python
files = client.beta.files.list()
for f in files.data:
print(f"{f.id}: {f.filename} ({f.size_bytes} bytes)")
### 获取文件元数据
python
file_info = client.beta.files.retrieve_metadata("file_011CNha8iCJcU1wXNR6q4V8w")
print(f"Filename: {file_info.filename}")
print(f"MIME type: {file_info.mime_type}")
### 删除文件
python
client.bet