파일 추가하기

파일 추가하기 (Adding files)

Files API로 파일을 업로드하고 세션의 샌드박스에 마운트하면 에이전트에게 파일을 제공할 수 있어요. 이 페이지에서는 업로드 방법, 세션 생성 시 파일 마운트, 실행 중인 세션에서 파일을 추가·제거하는 방법, 그리고 세션 파일을 나열하고 다운로드하는 방법을 차근차근 알려드려요.

출처: 문서

본문

Files API로 파일을 업로드하고 세션의 샌드박스에 마운트하면 에이전트에게 파일을 제공할 수 있어요.

Uploading files

먼저 Files API를 사용해 파일을 업로드하세요:

```bash cURL file=$(curl --fail-with-body -sS "${auth[@]}" \ "${base_url}/files" \ -F [email protected]) FILE_ID=$(jq -er '.id' <<<"${file}") ```
FILE_ID=$(ant files upload --file data.csv --transform id --raw-output)
file = client.files.upload(file=Path("data.csv"))
print(f"File ID: {file.id}")
const file = await client.files.upload({
  file: await toFile(readFile("data.csv"), "data.csv", { type: "text/csv" }),
});
console.log(`File ID: ${file.id}`);
await using var stream = File.OpenRead(csvPath);
var file = await client.Files.Upload(new() { File = stream });
Console.WriteLine($"File ID: {file.ID}");
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)
var file = client.files().upload(
    FileUploadParams.builder().file(dataCsv).build()
);
IO.println("File ID: " + file.id());
$file = $client->files->upload(
    file: FileParam::fromResource(fopen($csvPath, 'r'), filename: 'data.csv', contentType: 'text/csv'),
);
echo "File ID: {$file->id}\n";
file = client.files.upload(file: Pathname(csv_path))
puts "File ID: #{file.id}"

Mounting files in a session

세션을 만들 때 resources 배열에 업로드한 파일을 추가해 샌드박스에 마운트하세요:

The `mount_path` is optional, but make sure the uploaded file has a descriptive name so the agent can identify it. ```bash cURL jq -n \ --arg agent_id "${AGENT_ID}" \ --arg environment_id "${ENVIRONMENT_ID}" \ --arg file_id "${FILE_ID}" \ '{ agent: $agent_id, environment_id: $environment_id, resources: [ { type: "file", file_id: $file_id, mount_path: "/data.csv" } ] }' | curl --fail-with-body -sS "${auth[@]}" "${base_url}/sessions" --json @- ```
ant beta:sessions create \
  --agent "$AGENT_ID" \
  --environment-id "$ENVIRONMENT_ID" <<EOF
resources:
  - type: file
    file_id: $FILE_ID
    mount_path: /data.csv
EOF
session = client.beta.sessions.create(
    agent=agent.id,
    environment_id=environment.id,
    resources=[
        {
            "type": "file",
            "file_id": file.id,
            "mount_path": "/data.csv",
        },
    ],
)
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",
    },
  ],
});
var session = await client.Beta.Sessions.Create(new()
{
    Agent = agent.ID,
    EnvironmentID = environment.ID,
    Resources =
    [
        new BetaManagedAgentsFileResourceParams
        {
            Type = "file",
            FileID = file.ID,
            MountPath = "/data.csv",
        },
    ],
});
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{
			Type:      anthropic.BetaManagedAgentsFileResourceParamsTypeFile,
			FileID:    file.ID,
			MountPath: anthropic.String("/data.csv"),
		},
	}},
})
if err != nil {
	panic(err)
}
var session = client.beta().sessions().create(
    SessionCreateParams.builder()
        .agent(agent.id())
        .environmentId(environment.id())
        .addResource(
            BetaManagedAgentsFileResourceParams.builder()
                .type(BetaManagedAgentsFileResourceParams.Type.FILE)
                .fileId(file.id())
                .mountPath("/data.csv")
                .build()
        )
        .build()
);
$session = $client->beta->sessions->create(
    agent: $agent->id,
    environmentID: $environment->id,
    resources: [
        BetaManagedAgentsFileResourceParams::with(
            type: 'file',
            fileID: $file->id,
            mountPath: '/data.csv',
        ),
    ],
);
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를 쓰면 에이전트는 /mnt/session/uploads/data.csv에서 파일을 읽어요(File paths 참고).

세션의 파일 인스턴스를 참조하는 새 file_id가 생성돼요. 이 복사본들은 저장 한도에 포함되지 않아요.

Multiple files

resources 배열에 항목을 추가해 여러 파일을 마운트하세요:

```bash cURL curl -fsSL https://api.anthropic.com/v1/sessions \ -H "x-api-key: $ANTHR...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" } ] }' ```
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
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"},
]
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" }
]
using Anthropic.Models.Beta.Sessions;

var resources = new[]
{
    new BetaManagedAgentsFileResourceParams { Type = BetaManagedAgentsFileResourceParamsType.File, FileID = "file_abc123", MountPath = "/data.csv" },
    new BetaManagedAgentsFileResourceParams { Type = BetaManagedAgentsFileResourceParamsType.File, FileID = "file_def456", MountPath = "/config.json" },
    new BetaManagedAgentsFileResourceParams { Type = BetaManagedAgentsFileResourceParamsType.File, FileID = "file_ghi789", MountPath = "/src/main.py" },
};
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")}},
}
import com.anthropic.models.beta.sessions.*;
import java.util.List;

var resources = List.of(
    BetaManagedAgentsFileResourceParams.builder()
        .type(BetaManagedAgentsFileResourceParams.Type.FILE).fileId("file_abc123").mountPath("/data.csv").build(),
    BetaManagedAgentsFileResourceParams.builder()
        .type(BetaManagedAgentsFileResourceParams.Type.FILE).fileId("file_def456").mountPath("/config.json").build(),
    BetaManagedAgentsFileResourceParams.builder()
        .type(BetaManagedAgentsFileResourceParams.Type.FILE).fileId("file_ghi789").mountPath("/src/main.py").build()
);
$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'],
];
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개 파일이 지원돼요.

Managing files on a running session

세션 리소스 API를 사용해 생성 후 세션에 파일을 추가하거나 제거할 수 있어요. 각 리소스는 추가(또는 나열)될 때 반환되는 id를 가지며, 삭제에 사용해요.

```bash cURL jq -n --arg file_id "${FILE_ID}" '{type: "file", file_id: $file_id}' \ | curl --fail-with-body -sS "${auth[@]}" \ "${base_url}/sessions/${SESSION_ID}/resources" --json @- ```
ant beta:sessions:resources add \
  --session-id "$SESSION_ID" \
  --type file \
  --file-id "$FILE_ID"
resource = client.beta.sessions.resources.add(
    session.id,
    type="file",
    file_id=file.id,
)
print(resource.id)  # "sesrsc_01ABC..."
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..."
var resource = await client.Beta.Sessions.Resources.Add(session.ID, new()
{
    Type = "file",
    FileID = file.ID,
});
Console.WriteLine(resource.ID);  // "sesrsc_01ABC..."
resource, err := client.Beta.Sessions.Resources.Add(ctx, session.ID, anthropic.BetaSessionResourceAddParams{
	BetaManagedAgentsFileResourceParams: anthropic.BetaManagedAgentsFileResourceParams{
		Type:   anthropic.BetaManagedAgentsFileResourceParamsTypeFile,
		FileID: file.ID,
	},
})
if err != nil {
	panic(err)
}
fmt.Println(resource.ID) // "sesrsc_01ABC..."
var resource = client.beta().sessions().resources().add(
    session.id(),
    ResourceAddParams.builder()
        .betaManagedAgentsFileResourceParams(
            BetaManagedAgentsFileResourceParams.builder()
                .type(BetaManagedAgentsFileResourceParams.Type.FILE)
                .fileId(file.id())
                .build()
        )
        .build()
);
IO.println(resource.id()); // "sesrsc_01ABC..."
$resource = $client->beta->sessions->resources->add(
    $session->id,
    type: 'file',
    fileID: $file->id,
);
echo "{$resource->id}\n";  // "sesrsc_01ABC..."
resource = client.beta.sessions.resources.add(
  session.id,
  type: "file",
  file_id: file.id
)
puts resource.id # "sesrsc_01ABC..."

resources.list로 세션의 모든 리소스를 나열하세요. 파일을 제거하려면 리소스 ID로 resources.delete를 호출하세요:

```bash cURL curl --fail-with-body -sS "${auth[@]}" \ "${base_url}/sessions/${SESSION_ID}/resources"

curl --fail-with-body -sS "${auth[@]}" -X DELETE
"${base_url}/sessions/${SESSION_ID}/resources/${RESOURCE_ID}" >/dev/null


```bash CLI
ant beta:sessions:resources list --session-id "$SESSION_ID"

ant beta:sessions:resources delete \
  --session-id "$SESSION_ID" \
  --resource-id "$RESOURCE_ID"
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)
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,
});
var listed = await client.Beta.Sessions.Resources.List(session.ID);
await foreach (var entry in listed.Paginate())
{
    var type = entry.Match<string>(repo => repo.Type, fileRes => fileRes.Type, memoryStore => memoryStore.Type);
    Console.WriteLine($"{entry.ID} {type}");
}

await client.Beta.Sessions.Resources.Delete(resource.ID, new() { SessionID = session.ID });
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)
}
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()
);
$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);
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)

Listing and downloading session files

Files API를 사용해 세션 범위의 파일을 나열하고 다운로드하세요. 에이전트가 /mnt/session/outputs/에 쓴 파일은 에이전트가 쓰기를 마친 직후, 때로는 세션이 유휴 상태가 된 후 몇 초 뒤에 목록에 나타나요. 기대한 출력 파일이 없다면 잠시 후 다시 나열하세요. 목록에 나타나면 업로드가 끝난 거예요.

scope_id로 필터링하려면 managed-agents-2026-04-01 베타 헤더가 필요하므로, 목록 예시는 beta 파일 네임스페이스를 사용하고 그 헤더를 명시적으로 전달해요.

```bash cURL # List files associated with a session curl -fsSL "https://api.anthropic.com/v1/files?scope_id=sesn_abc123" \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -H "anthropic-beta: managed-agents-2026-04-01"

Download a file

curl -fsSL "https://api.anthropic.com/v1/files/$FILE_ID/content"
-H "x-api-key: $ANTHR...KEY"
-H "anthropic-version: 2023-06-01"
-o output.txt


```bash CLI
# List files associated with a session
ant beta:files list --scope-id sesn_abc123 --beta managed-agents-2026-04-01

# Download a file
ant files download --file-id "$FILE_ID" --output output.txt
# List files associated with a session
files = client.beta.files.list(
    scope_id="sesn_abc123",
    betas=["managed-agents-2026-04-01"],
)
for file in files:
    print(file.id, file.filename)

# Download a file
content = client.files.download(files.data[0].id)
content.write_to_file("output.txt")
import { writeFile } from "node:fs/promises";

// List files associated with a session
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);
}

// Download a file
const content = await client.files.download(files.data[0].id);
await writeFile("output.txt", new Uint8Array(await content.arrayBuffer()));
// List files associated with a session
var files = await client.Beta.Files.List(new()
{
    ScopeID = "sesn_abc123",
    Betas = ["managed-agents-2026-04-01"],
});

// Download a file
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);
// List files associated with a session
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)
}

// Download a file
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)
}
// List files associated with a session
var files = client.beta().files().list(FileListParams.builder()
    .scopeId("sesn_abc123")
    .addBeta(AnthropicBeta.of("managed-agents-2026-04-01"))
    .build());

// Download a file
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);
    }
}
// List files associated with a session
$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";
}

// Download a file
$content = $client->files->download($files->getItems()[0]->id);
file_put_contents('output.txt', $content);
# List files associated with a session
files = client.beta.files.list(
  scope_id: "sesn_abc123",
  betas: ["managed-agents-2026-04-01"]
)

# Download a file
content = client.files.download(files.data[0].id)
File.binwrite("output.txt", content.read)

Supported file types

에이전트는 어떤 파일 형식이든 작업할 수 있어요, 예를 들어:

  • Source code (.py, .js, .ts, .go, .rs, and others)
  • Data files (.csv, .json, .xml, .yaml)
  • Documents (.txt, .md)
  • Archives (.zip, .tar.gz) - the agent can extract these using bash
  • Binary files - the agent can process these with appropriate tools

File paths

Files mounted in the sandbox are read-only copies. The agent can read them but cannot modify the original uploaded file. To work with modified versions, the agent writes to new paths within the sandbox.
  • The path you specify is rooted under the session's uploads directory: a mount_path of /data.csv places the file at /mnt/session/uploads/data.csv in the sandbox
  • If you omit mount_path, the file is placed at /mnt/session/uploads/<file_id>
  • Parent directories are created automatically
  • Paths should be absolute (starting with /)
  • Files the agent writes to /mnt/session/outputs/ become available through the Files API, scoped to the session; see Listing and downloading session files

더 알아보기 (Learn more)