您可以通过 Files API 上传文件并将其挂载到会话的沙箱(sandbox)中,从而为您的智能体提供文件。
上传文件
首先,使用 Files API 上传文件:
cURL
curl --fail-with-body -sS https://api.anthropic.com/v1/files \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: managed-agents-2026-04-01" \
-F file=@data.csv
CLI
ant files upload --file data.csv
Python
file = client.files.upload(file=Path("data.csv"))
print(f"File ID: {file.id}")
TypeScript
const file = await client.files.upload({
file: await toFile(readFile("data.csv"), "data.csv", { type: "text/csv" })
});
console.log(`File ID: ${file.id}`);
C#
await using var stream = File.OpenRead(csvPath);
var file = await client.Files.Upload(new() { File = stream });
Console.WriteLine($"File ID: {file.ID}");
Go
csvFile, err := os.Open("data.csv")
if err != nil {
panic(err)
}
defer csvFile.Close()
file, err := client.Files.Upload(ctx, anthropic.FileUploadParams{
File: csvFile,
})
if err != nil {
panic(err)
}
fmt.Printf("File ID: %s\n", file.ID)
Java
var file = client.files().upload(
FileUploadParams.builder()
.file(dataCsv)
.build()
);
IO.println("File ID: " + file.id());
PHP
$file = $client->files->upload(
file: FileParam::fromResource(fopen($csvPath, 'r'), filename: 'data.csv', contentType: 'text/csv'),
);
echo "File ID: {$file->id}\n";
Ruby
file = client.files.upload(file: Pathname(csv_path))
puts "File ID: #{file.id}"
在会话中挂载文件
在创建会话时,将已上传的文件添加到 resources (csharp, go: Resources) 数组中,即可将其挂载到沙箱中:
提示
mount_path(java, php:mountPath; csharp, go:MountPath) 是可选的,但请确保上传的文件具有描述性的名称,以便智能体能够识别它。
cURL
curl --fail-with-body -sS https://api.anthropic.com/v1/sessions \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: managed-agents-2026-04-01" \
-H "content-type: application/json" \
-d '{
"agent": "'"$AGENT_ID"'",
"environment_id": "'"$ENVIRONMENT_ID"'",
"resources": [
{
"type": "file",
"file_id": "'"$FILE_ID"'",
"mount_path": "/data.csv"
}
]
}'
CLI
ant beta:sessions create \
--agent "$AGENT_ID" \
--environment-id "$ENVIRONMENT_ID" <<EOF
resources:
- type: file
file_id: $FILE_ID
mount_path: /data.csv
EOF
Python
session = client.beta.sessions.create(
agent=agent.id,
environment_id=environment.id,
resources=[
{
"type": "file",
"file_id": file.id,
"mount_path": "/data.csv",
},
],
)
TypeScript
const session = await client.beta.sessions.create({
agent: agent.id,
environment_id: environment.id,
resources: [
{
type: "file",
file_id: file.id,
mount_path: "/data.csv"
}
]
});
C#
var session = await client.Beta.Sessions.Create(new()
{
Agent = agent.ID,
EnvironmentID = environment.ID,
Resources =
[
new BetaManagedAgentsFileResourceParams
{
FileID = file.ID,
MountPath = "/data.csv",
},
],
});
Go
session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
Agent: anthropic.BetaSessionNewParamsAgentUnion{
OfString: anthropic.String(agent.ID),
},
EnvironmentID: environment.ID,
Resources: []anthropic.BetaSessionNewParamsResourceUnion{{
OfFile: &anthropic.BetaManagedAgentsFileResourceParams{
FileID: file.ID,
MountPath: anthropic.String("/data.csv"),
},
}},
})
if err != nil {
panic(err)
}
Java
var session = client.beta().sessions().create(
SessionCreateParams.builder()
.agent(agent.id())
.environmentId(environment.id())
.addResource(
BetaManagedAgentsFileResourceParams.builder()
.fileId(file.id())
.mountPath("/data.csv")
.build()
)
.build()
);
PHP
$session = $client->beta->sessions->create(
agent: $agent->id,
environmentID: $environment->id,
resources: [
BetaManagedAgentsFileResourceParams::with(
fileID: $file->id,
mountPath: '/data.csv',
),
],
);
Ruby
session = client.beta.sessions.create(
agent: agent.id,
environment_id: environment.id,
resources: [
{
type: "file",
file_id: file.id,
mount_path: "/data.csv"
}
]
)
使用上述 mount_path (java, php: mountPath; csharp, go: MountPath) 时,智能体会在 /mnt/session/uploads/data.csv 读取该文件(请参阅文件路径)。
系统会创建一个新的 file_id (java: fileId; php: fileID; csharp, go: FileID),用于引用该文件在会话中的实例。这些副本不计入您的存储限制。
多个文件
通过向 resources (csharp, go: Resources) 数组添加条目来挂载多个文件:
cURL
curl -fsSL https://api.anthropic.com/v1/sessions \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: managed-agents-2026-04-01" \
-H "content-type: application/json" \
-d '{
"agent": "agent_01J8XkN5uT3vHpLqRfWdY2",
"environment_id": "env_01K2mPsT7hNwR4jXuLvCqD8",
"resources": [
{
"type": "file",
"file_id": "file_011CNha8iCJcU1wXNR6q4V8w",
"mount_path": "/data.csv"
},
{
"type": "file",
"file_id": "file_011CPMxVD3fHLUhvTqtsQA5w",
"mount_path": "/config.json"
},
{
"type": "file",
"file_id": "file_011CRb3kQ7tWx9ZsLmDe2Vh4",
"mount_path": "/src/main.py"
}
]
}'
CLI
ant beta:sessions create \
--agent agent_01J8XkN5uT3vHpLqRfWdY2 \
--environment-id env_01K2mPsT7hNwR4jXuLvCqD8 <<YAML
resources:
- type: file
file_id: file_011CNha8iCJcU1wXNR6q4V8w
mount_path: /data.csv
- type: file
file_id: file_011CPMxVD3fHLUhvTqtsQA5w
mount_path: /config.json
- type: file
file_id: file_011CRb3kQ7tWx9ZsLmDe2Vh4
mount_path: /src/main.py
YAML
Python
resources = [
{"type": "file", "file_id": "file_abc123", "mount_path": "/data.csv"},
{"type": "file", "file_id": "file_def456", "mount_path": "/config.json"},
{"type": "file", "file_id": "file_ghi789", "mount_path": "/src/main.py"},
]
TypeScript
resources: [
{ type: "file", file_id: "file_abc123", mount_path: "/data.csv" },
{ type: "file", file_id: "file_def456", mount_path: "/config.json" },
{ type: "file", file_id: "file_ghi789", mount_path: "/src/main.py" }
]
C#
using Anthropic.Models.Beta.Sessions;
var resources = new[]
{
new BetaManagedAgentsFileResourceParams { FileID = "file_abc123", MountPath = "/data.csv" },
new BetaManagedAgentsFileResourceParams { FileID = "file_def456", MountPath = "/config.json" },
new BetaManagedAgentsFileResourceParams { FileID = "file_ghi789", MountPath = "/src/main.py" },
};
Go
resources := []anthropic.BetaSessionNewParamsResourceUnion{
{OfFile: &anthropic.BetaManagedAgentsFileResourceParams{Type: "file", FileID: "file_abc123", MountPath: anthropic.String("/data.csv")}},
{OfFile: &anthropic.BetaManagedAgentsFileResourceParams{Type: "file", FileID: "file_def456", MountPath: anthropic.String("/config.json")}},
{OfFile: &anthropic.BetaManagedAgentsFileResourceParams{Type: "file", FileID: "file_ghi789", MountPath: anthropic.String("/src/main.py")}},
}
Java
import com.anthropic.models.beta.sessions.*;
import java.util.List;
var resources = List.of(
BetaManagedAgentsFileResourceParams.builder()
.fileId("file_abc123")
.mountPath("/data.csv")
.build(),
BetaManagedAgentsFileResourceParams.builder()
.fileId("file_def456")
.mountPath("/config.json")
.build(),
BetaManagedAgentsFileResourceParams.builder()
.fileId("file_ghi789")
.mountPath("/src/main.py")
.build()
);
PHP
$resources = [
['type' => 'file', 'fileID' => 'file_abc123', 'mountPath' => '/data.csv'],
['type' => 'file', 'fileID' => 'file_def456', 'mountPath' => '/config.json'],
['type' => 'file', 'fileID' => 'file_ghi789', 'mountPath' => '/src/main.py'],
];
Ruby
resources = [
{type: "file", file_id: "file_abc123", mount_path: "/data.csv"},
{type: "file", file_id: "file_def456", mount_path: "/config.json"},
{type: "file", file_id: "file_ghi789", mount_path: "/src/main.py"}
]
每个会话最多支持 500 个文件。
管理运行中会话的文件
创建会话后,您可以使用会话资源 API 向会话添加文件或从中移除文件。每个资源在被添加(或列出)时都会返回一个 id (csharp, go: ID),您可以使用它来执行删除操作。
cURL
curl --fail-with-body -sS "https://api.anthropic.com/v1/sessions/$SESSION_ID/resources" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: managed-agents-2026-04-01" \
-H "content-type: application/json" \
-d '{
"type": "file",
"file_id": "'"$FILE_ID"'"
}'
CLI
ant beta:sessions:resources add \
--session-id "$SESSION_ID" \
--type file \
--file-id "$FILE_ID"
Python
resource = client.beta.sessions.resources.add(
session.id,
type="file",
file_id=file.id,
)
print(resource.id) # "sesrsc_01ABC..."
TypeScript
const resource = await client.beta.sessions.resources.add(session.id, {
type: "file",
file_id: file.id
});
if (resource.type !== "file") {
throw new Error(`Unexpected resource type: ${resource.type}`);
}
console.log(resource.id); // "sesrsc_01ABC..."
C#
var resource = await client.Beta.Sessions.Resources.Add(session.ID, new()
{
FileID = file.ID,
});
Console.WriteLine(resource.ID); // "sesrsc_01ABC..."
Go
resource, err := client.Beta.Sessions.Resources.Add(ctx, session.ID, anthropic.BetaSessionResourceAddParams{
BetaManagedAgentsFileResourceParams: anthropic.BetaManagedAgentsFileResourceParams{
FileID: file.ID,
},
})
if err != nil {
panic(err)
}
fmt.Println(resource.ID) // "sesrsc_01ABC..."
Java
var resource = client.beta().sessions().resources().add(
session.id(),
ResourceAddParams.builder()
.betaManagedAgentsFileResourceParams(
BetaManagedAgentsFileResourceParams.builder()
.fileId(file.id())
.build()
)
.build()
);
IO.println(resource.id()); // "sesrsc_01ABC..."
PHP
$resource = $client->beta->sessions->resources->add(
$session->id,
fileID: $file->id,
);
echo "{$resource->id}\n"; // "sesrsc_01ABC..."
Ruby
resource = client.beta.sessions.resources.add(
session.id,
type: "file",
file_id: file.id
)
puts resource.id # "sesrsc_01ABC..."
使用 GET /v1/sessions/{session_id}/resources (python, typescript, ruby: client.beta.sessions.resources.list(); go, csharp: client.Beta.Sessions.Resources.List(); java: client.beta().sessions().resources().list(); php: $client->beta->sessions->resources->list(); cli: ant beta:sessions:resources list) 列出会话上的所有资源。要移除文件,请使用资源 ID 调用 DELETE /v1/sessions/{session_id}/resources/{resource_id} (python, typescript, ruby: client.beta.sessions.resources.delete(); go, csharp: client.Beta.Sessions.Resources.Delete(); java: client.beta().sessions().resources().delete(); php: $client->beta->sessions->resources->delete(); cli: ant beta:sessions:resources delete):
cURL
curl --fail-with-body -sS "https://api.anthropic.com/v1/sessions/$SESSION_ID/resources" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: managed-agents-2026-04-01"
curl --fail-with-body -sS -X DELETE "https://api.anthropic.com/v1/sessions/$SESSION_ID/resources/$RESOURCE_ID" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: managed-agents-2026-04-01"
CLI
ant beta:sessions:resources list --session-id "$SESSION_ID"
ant beta:sessions:resources delete \
--session-id "$SESSION_ID" \
--resource-id "$RESOURCE_ID"
Python
listed = client.beta.sessions.resources.list(session.id)
for entry in listed.data:
print(entry.id, entry.type)
client.beta.sessions.resources.delete(resource.id, session_id=session.id)
TypeScript
const listed = await client.beta.sessions.resources.list(session.id);
for (const entry of listed.data) {
if (entry.type !== "memory_store") {
console.log(entry.id, entry.type);
}
}
await client.beta.sessions.resources.delete(resource.id, {
session_id: session.id
});
C#
var listed = await client.Beta.Sessions.Resources.List(session.ID);
await foreach (var entry in listed.Paginate())
{
Console.WriteLine($"{entry.ID} {entry.Type.Raw()}");
}
await client.Beta.Sessions.Resources.Delete(resource.ID, new() { SessionID = session.ID });
Go
listed, err := client.Beta.Sessions.Resources.List(ctx, session.ID, anthropic.BetaSessionResourceListParams{})
if err != nil {
panic(err)
}
for _, entry := range listed.Data {
fmt.Println(entry.ID, entry.Type)
}
if _, err := client.Beta.Sessions.Resources.Delete(ctx, resource.ID, anthropic.BetaSessionResourceDeleteParams{
SessionID: session.ID,
}); err != nil {
panic(err)
}
Java
var listed = client.beta().sessions().resources().list(session.id());
for (var entry : listed.data()) {
switch (entry.type().value()) {
case FILE -> {
var fileResource = entry.asFile();
IO.println(fileResource.id() + " " + fileResource._type());
}
case GITHUB_REPOSITORY -> {
var repoResource = entry.asGitHubRepository();
IO.println(repoResource.id() + " " + repoResource._type());
}
}
}
client.beta().sessions().resources().delete(
resource.id(),
ResourceDeleteParams.builder()
.sessionId(session.id())
.build()
);
PHP
$listed = $client->beta->sessions->resources->list($session->id);
foreach ($listed->data as $entry) {
echo "{$entry->id} {$entry->type}\n";
}
$client->beta->sessions->resources->delete($resource->id, sessionID: $session->id);
Ruby
listed = client.beta.sessions.resources.list(session.id)
listed.data.each { puts "#{it.id} #{it.type}" }
client.beta.sessions.resources.delete(resource.id, session_id: session.id)
列出和下载会话文件
使用 Files API 列出限定于某个会话的文件并下载它们。智能体写入 /mnt/session/outputs/ 的文件会在智能体完成写入后不久出现在列表中,有时会在会话进入空闲状态后几秒钟才出现。如果您预期的输出文件缺失,请稍等片刻后再次列出;一旦它出现在列表中,就表示其上传已完成。
按 scope_id (java: scopeId; php: scopeID; csharp, go: ScopeID) 进行筛选需要 managed-agents-2026-04-01 beta 请求头,因此列表示例会调用 GET /v1/files (python, typescript, ruby: client.beta.files.list(); go, csharp: client.Beta.Files.List(); java: client.beta().files().list(); php: $client->beta->files->list(); cli: ant beta:files list) 并显式传递该请求头。
cURL
# 列出与会话关联的文件
curl -fsSL "https://api.anthropic.com/v1/files?scope_id=sesn_abc123" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: managed-agents-2026-04-01"
# 下载文件
curl -fsSL "https://api.anthropic.com/v1/files/$FILE_ID/content" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-o output.txt
CLI
# 列出与会话关联的文件
ant beta:files list --scope-id sesn_abc123 --beta managed-agents-2026-04-01
# 下载文件
ant files download --file-id "$FILE_ID" --output output.txt
Python
# 列出与会话关联的文件
files = client.beta.files.list(
scope_id="sesn_abc123",
betas=["managed-agents-2026-04-01"],
)
for file in files:
print(file.id, file.filename)
# 下载文件
content = client.files.download(files.data[0].id)
content.write_to_file("output.txt")
TypeScript
import { writeFile } from "node:fs/promises";
// 列出与会话关联的文件
const files = await client.beta.files.list({
scope_id: "sesn_abc123",
betas: ["managed-agents-2026-04-01"]
});
for (const file of files.data) {
console.log(file.id, file.filename);
}
// 下载文件
const content = await client.files.download(files.data[0].id);
await writeFile("output.txt", new Uint8Array(await content.arrayBuffer()));
C#
// 列出与会话关联的文件
var files = await client.Beta.Files.List(new()
{
ScopeID = "sesn_abc123",
Betas = ["managed-agents-2026-04-01"],
});
// 下载文件
using var content = await client.Files.Download(files.Items[0].ID);
await using var output = File.Create("output.txt");
await (await content.ReadAsStream()).CopyToAsync(output);
Go
// 列出与会话关联的文件
files, err := client.Beta.Files.List(ctx, anthropic.BetaFileListParams{
ScopeID: anthropic.String("sesn_abc123"),
Betas: []anthropic.AnthropicBeta{"managed-agents-2026-04-01"},
})
if err != nil {
panic(err)
}
// 下载文件
resp, err := client.Files.Download(ctx, files.Data[0].ID, anthropic.FileDownloadParams{})
if err != nil {
panic(err)
}
defer resp.Body.Close()
out, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer out.Close()
if _, err := io.Copy(out, resp.Body); err != nil {
panic(err)
}
Java
// 列出与会话关联的文件
var files = client.beta().files().list(FileListParams.builder()
.scopeId("sesn_abc123")
.addBeta(AnthropicBeta.of("managed-agents-2026-04-01"))
.build());
// 下载文件
try (HttpResponse response = client.files().download(files.data().get(0).id())) {
try (InputStream body = response.body()) {
Files.copy(body, Path.of("output.txt"), StandardCopyOption.REPLACE_EXISTING);
}
}
PHP
// 列出与会话关联的文件
$files = $client->beta->files->list(
scopeID: 'sesn_abc123',
betas: ['managed-agents-2026-04-01'],
);
foreach ($files->getItems() as $file) {
echo "{$file->id} {$file->filename}\n";
}
// 下载文件
$content = $client->files->download($files->getItems()[0]->id);
file_put_contents('output.txt', $content);
Ruby
# 列出与会话关联的文件
files = client.beta.files.list(
scope_id: "sesn_abc123",
betas: ["managed-agents-2026-04-01"]
)
# 下载文件
content = client.files.download(files.data[0].id)
File.binwrite("output.txt", content.read)
支持的文件类型
智能体可以处理任何文件类型,包括:
- 源代码(
.py、.js、.ts、.go、.rs等) - 数据文件(
.csv、.json、.xml、.yaml) - 文档(
.txt、.md) - 归档文件(
.zip、.tar.gz)- 智能体可以使用 bash 解压这些文件 - 二进制文件 - 智能体可以使用适当的工具处理这些文件
文件路径
注意
挂载到沙箱中的文件是只读副本。智能体可以读取它们,但无法修改原始上传的文件。若要使用修改后的版本,智能体会将其写入沙箱内的新路径。
- 您指定的路径以会话的上传目录为根:
mount_path(java, php:mountPath; csharp, go:MountPath) 为/data.csv时,文件会放置在沙箱中的/mnt/session/uploads/data.csv。 - 如果您省略
mount_path(java, php:mountPath; csharp, go:MountPath),文件会放置在/mnt/session/uploads/<file_id>。 - 父目录会自动创建。
- 路径应为绝对路径(以
/开头)。 - 智能体写入
/mnt/session/outputs/的文件可通过 Files API 获取,其范围限定于该会话;请参阅列出和下载会话文件。