Chuyển đến nội dung chính

How to Build a Claude Sonnet 5 Managed Agent

Build a Claude Managed Agent with Anthropic’s Python SDK, cloud sandbox, tools, skills, file uploads, session management, code execution, and automated Excel report generation.
5 thg 7, 2026  · 9 phút đọc

Have you ever wanted to run a Claude Code–style workflow from a Python script, where the model can work inside a managed environment with access to tools, files, skills, and instructions?

Claude Managed Agents are designed for this type of workflow, helping you build agents that can carry out multi-step tasks in a controlled environment.

In this tutorial, I will show you how to use Claude Sonnet 5, a recent model from Anthropic designed for advanced reasoning, coding, and data analysis tasks. It powers the agent’s ability to inspect data, use tools, write and execute code, and produce structured outputs.

You will create a Managed Agent, configure its environment, upload a CSV file, and give the agent access to tools and an XLSX skill. 

The agent will analyze the data, generate Python, JSON, and Excel files, verify the results, and make the completed outputs available to download.

If you're totally new to Claude, I recommend first checking out the Claude Code 101 course.

What Are Claude Managed Agents?

Claude Managed Agents is Anthropic’s managed framework for running Claude as an autonomous agent. 

Instead of writing your own loop to send prompts, execute tool calls, save results, and manage the runtime, you define the agent and let Anthropic handle that infrastructure. 

It is designed for longer, multi-step tasks where the model may need to use several tools before completing the work.

Managed Agents are built around four main parts:

  • Agent: the reusable configuration that contains the model, system prompt, tools, MCP servers, and skills.
  • Environment: where the agent runs, either in Anthropic’s cloud sandbox or in your own self-hosted sandbox.
  • Session: a running instance of the agent that performs a specific task.
  • Events: the messages, tool calls, results, and status updates exchanged while the session runs.

1. Prerequisites For Your Claude Agent Workspace

To follow this tutorial, install Python 3.12 or later and Jupyter Notebook on your computer. We will use a Jupyter Notebook to create, run, and inspect the Managed Agent step by step.

You will also need an Anthropic Console account. 

Create a new API key in the Console, add at least $5 in API credits, and save the key securely. 

Managed Agents can make several model and tool calls in a single session, so they may cost more than a standard API request.

Store the key as an ANTHROPIC_API_KEY environment variable rather than adding it directly to the notebook or committing it to GitHub.

For macOS, Linux, or WSL, run this in your terminal:

export ANTHROPIC_API_KEY="your-api-key-here"

For Windows PowerShell, use:

$env:ANTHROPIC_API_KEY="your-api-key-here"

2. Set Up the Anthropic Python SDK

Before creating a Managed Agent, install the official Anthropic Python SDK and import the modules needed for this notebook. 

The SDK provides the Anthropic client, which you will use to create agents, environments, files, and sessions. 

%pip install -q --upgrade anthropic

Next, load your Anthropic API key from an environment variable. 

Keeping the key outside the notebook is safer than placing it directly in the code, especially if you plan to share the project or push it to GitHub.

import os
from anthropic import Anthropic

api_key = os.environ.get("ANTHROPIC_API_KEY")
assert api_key, "Set ANTHROPIC_API_KEY in your environment or in a local .env file."

Managed Agents is currently accessed through Anthropic’s beta API. The managed-agents-2026-04-01 beta flag enables this feature, although the official SDK automatically sends the required beta header for Managed Agents requests. 

We keep the flag in the notebook because it is later needed when listing and downloading session files. 

BETA_FLAG = "managed-agents-2026-04-01"

client = Anthropic(api_key=api_key)

Finally, create a dictionary to store the IDs of every resource created during the tutorial. 

This includes the agent, environment, uploaded file, and session. Saving these IDs makes cleanup easier at the end, even if a later step fails.

created = {"agent": None, "environment": None, "file": None, "session": None}
print("✓ Anthropic client initialized.")

The client is now ready. 

3. Create the Managed Agent

A Managed Agent is the reusable configuration for your workflow. 

When creating one, you choose the Claude model, write the system prompt that defines its role and instructions, and attach the tools and skills it can use. 

You can then reuse the same agent across multiple sessions instead of recreating the configuration each time. 

We will name our agent Sonnet 5 Data Analyst and use claude-sonnet-5

The system prompt tells it to behave like a careful data analyst: inspect files mounted in /workspace, use code execution for analysis, keep its results concise, and save final files to /mnt/session/outputs.

agent = client.beta.agents.create(
    name="Sonnet 5 Data Analyst",
    model="claude-sonnet-5",
    system=(
        "You are a meticulous data analyst. When asked about data, always read the "
        "file mounted at /workspace, analyse it with the code execution tool, and "
        "report concise, numeric results. Use the XLSX skill for spreadsheet work. "
        "Save final artifacts to /mnt/session/outputs."
    ),
    tools=[
        {"type": "agent_toolset_20260401"},
    ],
    skills=[{"type": "anthropic", "skill_id": "xlsx"}],
)

The agent_toolset_20260401 gives the agent access to Anthropic’s built-in tools in a session, while the xlsx skill provides task-specific guidance for creating and analyzing Excel workbooks. 

Anthropic also provides pre-built skills for PowerPoint, Word, and PDF workflows.

Finally, save the agent ID. 

You will use it when creating a session later, and it also allows the cleanup section to archive the agent once the tutorial is complete.

created["agent"] = agent.id
print(f"✓ Created agent: {agent.id}")

You should see an output similar to:

✓ Created agent: agent_01EVcgvQsAkLxNnJFp6aynwm

4. Configure the Anthropic Cloud Sandbox

Next, we will create the environment where the Managed Agent runs during a session. 

An environment acts as a secure sandbox, giving the agent a separate workspace to read mounted files, write code, and run commands.

We will use Anthropic’s cloud environment with limited networking. The agent will use this sandbox later to analyze the uploaded CSV file with Python.

environment = client.beta.environments.create(
    name="code-exec-sandbox",
    config={"type": "cloud", "networking": {"type": "limited"}},
)

created["environment"] = environment.id
print(f"✓ Created environment: {environment.id}")

After running the cell, you should see an environment ID similar to:

✓ Created environment: env_01FzWACEf9UJDL65ovBPA1zf

5. Upload Data with the Anthropic Files API

Next, we will upload the dataset that the agent will analyze. 

Managed Agents use Anthropic’s Files API to upload local files, which can then be mounted inside the session environment.

For this guide, we are using the example 12-row dataset called sales_data.csv

Before uploading it, we check that the file exists and confirm that it contains the expected number of data rows.

from pathlib import Path

csv_path = Path("sales_data.csv")
assert csv_path.exists(), f"Missing input file: {csv_path.resolve()}"

row_count = sum(1 for _ in csv_path.open(encoding="utf-8")) - 1
assert row_count == 12, f"Expected 12 data rows, found {row_count}"

We then upload the file and store its ID for later cleanup.

uploaded = client.beta.files.upload(file=csv_path)

created["file"] = uploaded.id
print(f"✓ Uploaded {csv_path}: {uploaded.id} ({row_count} rows)")

After running the cell, you should see output similar to:

✓ Uploaded sales_data.csv: file_011Cch3EubJkswPdo3gMBvM2 (12 rows)

6. Initialize an Agent Execution Session

Now, we will create a session. 

A session connects the agent, the environment, and the resources it needs for a specific task. Here, we mount the uploaded CSV file at /workspace/sales_data.csv, so the agent can access it from inside the sandbox.

session = client.beta.sessions.create(
    agent=agent.id,
    environment_id=environment.id,
    resources=[
        {
            "type": "file",
            "file_id": uploaded.id,
            "mount_path": "/workspace/sales_data.csv",
        },
    ],
)

created["session"] = session.id
print(f"✓ Created session: {session.id}")

You should see a session ID similar to:

✓ Created session: sesn_015mNhrKhqqfe7u8VP6GuFdr

7. Stream the Agent’s Response

Now, we will send the task to the session and stream the agent’s activity as it works. 

Creating a session only prepares the agent and sandbox; the agent starts working after it receives a user.message event. 

The event stream lets us see the agent’s messages, tool calls, and final session status in real time. 

The prompt tells the agent to analyze the mounted CSV file, write and run a Python script, create a JSON summary, and build an Excel report. 

We also create three variables to collect the agent’s text, record the tools it uses, and confirm whether the session finishes successfully.

agent_text_parts = []
tools_used = []
final_status = None

with client.beta.sessions.events.stream(session.id) as stream:
    # Send the user message once the stream is open.
    client.beta.sessions.events.send(
        session.id,
        events=[
            {
                "type": "user.message",
                "content": [
                    {
                        "type": "text",
                        "text": (
                            "Use the XLSX skill and analyze /workspace/sales_data.csv. "
                            "Write /mnt/session/outputs/analyze_sales.py, run that Python "
                            "script, and have it create /mnt/session/outputs/summary.json. "
                            "Also create /mnt/session/outputs/sales_report.xlsx with the "
                            "source data, monthly profit, and a summary sheet."
                        ),
                    }
                ],
            }
        ],
    )

    for event in stream:
        etype = getattr(event, "type", None)

        if etype == "agent.message":
            for block in event.content:
                txt = getattr(block, "text", None)
                if txt:
                    print(txt, end="")
                    agent_text_parts.append(txt)

        elif etype == "agent.tool_use":
            name = getattr(event, "name", "<tool>")
            print(f"\n[tool_use] {name}")
            tools_used.append(name)

        elif etype == "session.status_idle":
            final_status = "idle"
            print("\n\n✓ Agent finished; session is idle.")
            break

        elif etype == "session.status_error":
            final_status = "error"
            print("\n✗ Session reported an error.")
            break

print("Tools used:", tools_used)

During the run, you should see tool events such as read, bash, write, and edit

These show that the agent is inspecting the available instructions and files, writing the analysis script, running it inside the sandbox, and correcting issues it finds.

A session becomes idle when the agent has no further work to do. In this example, session.status_idle indicates that the task is complete, so we stop listening to the stream. 

Anthropic manages execution for its built-in tools inside the sandbox; you only need to handle tool results yourself when using custom tools. 

Output of the Claude Managed Agents

8. Retrieve Generated Files and Event History

Once the session is complete, we can inspect its saved event history and download the files created by the agent. 

The event history provides a full record of the session, including model requests, tool calls, tool results, and status changes.

history = client.beta.sessions.events.list(session.id, order="asc")

print("--- Session event history ---")
for event in history.data:
    print(event.type)

print(f"({len(history.data)} events total)")

History of the tools use, LLM message, tool results, status, and more for the Claude Managed Agents

Next, we list the files attached to the session and download any files marked as downloadable. The files are saved locally in an outputs folder.

import os

os.makedirs("outputs", exist_ok=True)

files = client.beta.files.list(scope_id=session.id, betas=[BETA_FLAG])
downloadable = [f for f in files.data if f.downloadable]

print(f"Found {len(downloadable)} downloadable file(s) for this session.")

downloaded_paths = []

for f in downloadable:
    try:
        content = client.beta.files.download(f.id, betas=[BETA_FLAG])
        local_path = os.path.join("outputs", f.filename)

        content.write_to_file(local_path)
        downloaded_paths.append(local_path)

        print(f"  downloaded {f.id} -> {local_path}")
    except Exception as exc:
        print(f"  skip {f.id}: {exc}")

Finally, we check that all expected outputs were downloaded successfully:

expected_outputs = {"analyze_sales.py", "summary.json", "sales_report.xlsx"}
downloaded_names = {os.path.basename(path) for path in downloaded_paths}

assert expected_outputs <= downloaded_names, (
    f"Missing expected outputs: {sorted(expected_outputs - downloaded_names)}"
)

The generated Python script, JSON summary, and Excel report are now available in the local outputs folder.

9. Analyze the Python, JSON, and Excel Outputs

After the agent completes the task, the generated files are downloaded into the local outputs/ directory. 

These files show that the agent did more than return a text response: it wrote and executed code, created structured data, and produced a spreadsheet report that can be reviewed independently.

File

What it contains

Why it matters

analyze_sales.py

The Python script created and executed by the agent. It loads the CSV, calculates revenue, costs, profit, and margins, writes the JSON summary, and builds the workbook.

You can inspect, modify, or rerun the analysis without relying only on the agent’s response.

summary.json

Machine-readable totals, averages, best and worst months, and the full monthly breakdown.

Useful for dashboards, APIs, automated checks, or downstream applications.

sales_report.xlsx

A formatted workbook with the source data, monthly profit calculations, formulas, summary sheets, and charts.

Provides a human-readable report that can be opened in Excel or LibreOffice.

The screenshots below show the three generated artifacts.

This file contains the analysis code the agent wrote and executed, making the workflow reproducible and easy to inspect.

Sales data analysis Python script

This file stores the results in a structured format that can be used by dashboards, APIs, or other programs.

data analysis results in JSON format

This Excel file presents the monthly calculations visually, with revenue, costs, profit, margins, totals, and a chart.

data analysis result in the Excel file with visualization.

For the 12 rows in sales_data.csv, the verified results are:

  • Total revenue: $32,900
  • Total costs: $14,750
  • Total profit: $18,150
  • Average monthly profit: $1,512.50
  • Best month: December ($2,550 profit)
  • Worst month: January ($400 profit)

The workbook is formula-driven rather than relying only on hardcoded values. 

During the run, the agent read the attached XLSX skill instructions, created the workbook, recalculated it with LibreOffice, checked the formulas, and fixed a circular-reference issue before completing the task.

10. Clean Up Managed Agent API Resources

Managed Agent resources remain available until you remove them, so it is important to clean them up once the task is complete. 

Active resources, especially running sessions and environments, can continue to incur costs if they are left running.

A session must be idle before it can be deleted. 

In this final step, we delete the session, uploaded file, and environment, then archive the agent. 

Each cleanup action is wrapped in a helper function so that one failed deletion does not stop the remaining resources from being removed.

def safe(label, fn):
    try:
        fn()
        print(f"✓ deleted {label}")
    except Exception as exc:
        print(f"· could not delete {label}: {exc}")

if created["session"]:
    safe("session", lambda: client.beta.sessions.delete(created["session"]))

if created["file"]:
    safe("file", lambda: client.beta.files.delete(created["file"]))

if created["environment"]:
    safe("environment", lambda: client.beta.environments.delete(created["environment"]))

if created["agent"]:
    safe("agent (archived)", lambda: client.beta.agents.archive(created["agent"]))

print("\n🎉 Cleanup complete. The agent is archived; other resources were deleted.")

You should see output similar to:

✓ deleted session
✓ deleted file
✓ deleted environment
✓ deleted agent (archived)

🎉 Cleanup complete. The agent is archived; other resources were deleted.

The complete project, including the notebook, sample CSV file, and setup instructions, is available on GitHub. 

You can clone the repository and rerun the notebook to recreate the results from this guide.

Final Thoughts

I found Claude Managed Agents easy to set up and work with. 

You create an agent, give it the tools, skills, and sandbox it needs, then run it through a session. 

From there, it can handle a complete workflow, such as writing code, creating files, checking its own outputs, and returning the final results.

I first tried to use a Modal Sandbox because I wanted a more flexible external environment. 

However, the setup became too complex for the scope of this guide, so I decided to keep this project focused on Anthropic’s managed cloud sandbox.

The main downside for me was the cost. I ran this example twice using a small CSV file with only 12 rows, and it cost around $0.25

The dashboard showed the charge under the model, but I could not find a detailed breakdown. For a simple calculation and spreadsheet task, that feels expensive compared with lower-cost open-source options.

Overall, this project shows the full Managed Agent workflow: creating an agent, uploading a CSV file, running Python inside a managed sandbox, generating JSON and Excel reports, verifying the outputs, downloading the files, and cleaning up the resources afterward.

FAQs

Can I use my own custom tools with Managed Agents, or am I limited to Anthropic’s built-in toolsets?

ou can absolutely use custom tools. While this tutorial leverages Anthropic’s managed agent_toolset_20260401 to automatically execute Python code in the sandbox, you can also define custom tools in your agent configuration using standard JSON Schema. If the model invokes a custom tool, Anthropic pauses the session and sends a tool call event to your stream. Your local Python script must then execute the logic and send back a tool result event to resume the agent's workflow.

Can I continue a conversation or add new tasks after a session becomes "idle"?

Yes. A session maintains its state, context, and sandbox environment until you explicitly delete it. Once a session reaches the session.status_idle state, you can stream a new user.message event to the exact same session ID. The agent will remember previous steps and have access to any files or data it previously generated in the /workspace or /mnt/session/outputs directories.

Does Anthropic use the files I upload to the cloud sandbox to train its models?

No. Anthropic's standard commercial terms apply to Managed Agents and the Files API. By default, Anthropic does not use your API prompts, uploaded files, or generated sandbox outputs to train its foundational models. The cloud environment is securely isolated, and any data mounted to the workspace is ephemeral and restricted to your specific session.

What happens if the agent gets stuck in an infinite loop while writing and testing code?

Anthropic Managed Agents have built-in safeguards to prevent runaway loops and excessive API costs. The system enforces limits on the maximum number of consecutive tool calls an agent can make without user intervention, as well as a maximum runtime for the cloud environment itself. If the agent exceeds these limits, the stream will yield a session.status_error event, safely terminating the run.


Abid Ali Awan's photo
Author
Abid Ali Awan
LinkedIn
Twitter

As a certified data scientist, I am passionate about leveraging cutting-edge technology to create innovative machine learning applications. With a strong background in speech recognition, data analysis and reporting, MLOps, conversational AI, and NLP, I have honed my skills in developing intelligent systems that can make a real impact. In addition to my technical expertise, I am also a skilled communicator with a talent for distilling complex concepts into clear and concise language. As a result, I have become a sought-after blogger on data science, sharing my insights and experiences with a growing community of fellow data professionals. Currently, I am focusing on content creation and editing, working with large language models to develop powerful and engaging content that can help businesses and individuals alike make the most of their data.

Chủ đề

Top DataCamp Courses

Courses

Software Development with Claude Code

4 giờ
4.5K
Claude Code brings AI assistance to your terminal. Learn the workflows that turn it into a reliable tool for real software development.
Xem chi tiếtRight Arrow
Bắt đầu khóa học
Xem thêmRight Arrow
Có liên quan

cheat-sheet

Claude API in Python Cheat Sheet

Build with the Claude API in Python. This cheat sheet covers the Anthropic SDK essentials — messages, streaming, vision, tool use, embeddings, and token counting — with ready-to-run code.
DataCamp Team's photo

DataCamp Team

Tutorials

Claude Agent SDK Tutorial: Create Agents Using Claude Sonnet 4.5

Learn how the Claude Agent SDK works by building three projects, from one-shot to custom-tool agents.
Abid Ali Awan's photo

Abid Ali Awan

Tutorials

Claude Sonnet 4: A Hands-On Guide for Developers

Explore Claude Sonnet 4’s developer features—code execution, files API, and tool use—by building a Python-based math-solving agent.
Bex Tuychiev's photo

Bex Tuychiev

Tutorials

Claude Sonnet 3.5 API Tutorial: Getting Started With Anthropic's API

To connect through the Claude 3.5 Sonnet API, obtain your API key from Anthropic, install the anthropic Python library, and use it to send requests and receive responses from Claude 3.5 Sonnet.
Ryan Ong's photo

Ryan Ong

Tutorials

Getting Started with the Claude 2 and the Claude 2 API

The Python SDK provides convenient access to Anthropic's powerful conversational AI assistant Claude 2, enabling developers to easily integrate its advanced natural language capabilities into a wide range of applications.
Abid Ali Awan's photo

Abid Ali Awan

Tutorials

Claude Cowork Tutorial: How to Use Anthropic's AI Desktop Agent

Learn what Claude Cowork is and how to use for file organization, document generation, and browser automation. Hands-on tutorial with real examples and limitations.
Bex Tuychiev's photo

Bex Tuychiev

Xem thêmXem thêm