2026年3月14日土曜日

Part 3/6: Complete Claude Agent SDK Setup Guide: From Local Environment to First Run

Introduction

In the previous Part 2, we explained the architecture and design philosophy of the Claude Team Agent. In this article (Part 3), we present concrete steps for setting up the Claude Agent SDK in a local environment and getting a minimal multi-agent system running. The goal is to deepen understanding by actually running the code, and this will serve as a stepping stone to the applied implementation in Part 4.


1. Verifying Prerequisites

The Claude Agent SDK requires Python 3.10 or higher. First, check your current Python environment.

python3 --version # Python 3.11.x or higher is recommended 

For virtual environment management, venv or uv is recommended. uv is a high-speed package manager written in Rust, and dependency resolution is significantly faster compared to the traditional pip [Source: https://docs.astral.sh/uv/].

# Using uv pip install uv uv venv .venv source .venv/bin/activate  # Windows: .venv\Scripts\activate 

2. Obtaining and Configuring the API Key

An Anthropic API key is required to use the Claude Agent SDK. Access the Anthropic Console, create an account, and then issue an API key [Source: https://console.anthropic.com/].

Setting the API key as an environment variable is the security-recommended best practice.

export ANTHROPIC_API_KEY="sk-ant-XXXXXXXXXXXXXXXX" 

From a project management perspective, using a .env file and loading it with python-dotenv is also a common approach. However, be sure to always exclude the .env file from Git version control.

# .env file ANTHROPIC_API_KEY=sk-ant-XXXXXXXXXXXXXXXX 
from dotenv import load_dotenv import os  load_dotenv() api_key = os.environ.get("ANTHROPIC_API_KEY") 

3. Installing the Claude Agent SDK

The Claude Agent SDK provided by Anthropic is distributed as the anthropic package. Install the latest version, which includes multi-agent functionality [Source: https://github.com/anthropics/anthropic-sdk-python].

uv pip install anthropic # or pip install anthropic 

After installation, verify the version.

python -c "import anthropic; print(anthropic.__version__)" 

4. Implementing a Minimal Team Agent

Here we implement a minimal Team Agent using a two-layer structure consisting of an "orchestrator" and a "sub-agent". According to Anthropic's documentation, communication between agents in a multi-agent system is conducted through a tool-calling interface [Source: https://docs.anthropic.com/en/docs/build-with-claude/agents].

import anthropic import os  client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))  # Tool definition that functions as a sub-agent def run_sub_agent(task: str) -> str:     """A sub-agent that processes specific tasks"""     response = client.messages.create(         model="claude-opus-4-5",         max_tokens=1024,         system="You are a data analysis expert. Please process the given task concisely.",         messages=[{"role": "user", "content": task}]     )     return response.content[0].text  # Orchestrator agent def orchestrator_agent(user_query: str) -> str:     """An orchestrator that breaks down tasks and delegates them to sub-agents"""      # Define tool schema     tools = [         {             "name": "delegate_to_sub_agent",             "description": "Delegate a specific subtask to a sub-agent",             "input_schema": {                 "type": "object",                 "properties": {                     "task": {                         "type": "string",                         "description": "The content of the task to be processed by the sub-agent"                     }                 },                 "required": ["task"]             }         }     ]      messages = [{"role": "user", "content": user_query}]      # Orchestrator loop     while True:         response = client.messages.create(             model="claude-opus-4-5",             max_tokens=2048,             system="You are an orchestrator that manages tasks. Break down complex requests into subtasks and delegate them to sub-agents as needed.",             tools=tools,             messages=messages         )          # If there are no tool calls, finish         if response.stop_reason == "end_turn":             return response.content[0].text          # Process tool calls         tool_results = []         for block in response.content:             if block.type == "tool_use":                 result = run_sub_agent(block.input["task"])                 tool_results.append({                     "type": "tool_result",                     "tool_use_id": block.id,                     "content": result                 })          # Update message history and continue         messages.append({"role": "assistant", "content": response.content})         messages.append({"role": "user", "content": tool_results})  # Run if __name__ == "__main__":     result = orchestrator_agent("Please analyze the trends in the sales data and make a forecast for next month.")     print(result) 

5. Verifying Operation and Handling Common Errors

Here is a summary of commonly encountered errors and how to address them.

  • AuthenticationError: The API key is not configured correctly. Re-check the loading of the environment variable.
  • RateLimitError: The API rate limit has been reached. Implement exponential backoff and add retry logic.
  • InvalidRequestError: The tool schema format is invalid. Compare the structure of input_schema against the documentation.

Summary and Preview of Next Part

In this article, we covered everything from setting up the Python environment and configuring the API key, to installing the SDK, and implementing a minimal Team Agent. You should now be able to confirm that task delegation and result aggregation can be achieved through a two-layer agent structure.

In Part 4, we will take this foundation and dive deeper into practical tool integration and error handling design patterns. We also plan to explain parallel agent execution and result aggregation strategies with implementation examples.


Category: LLM | Tags: Claude, AgentSDK, マルチエージェント, Python, LLM実装

0 件のコメント:

コメントを投稿