Loading...
  • 建構
  • 管理
  • 模型與定價
  • 客戶端 SDK
  • API 參考
Search...
⌘K
Log in
遷移
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
管理

遷移

將在 Messages API 或 Claude Agent SDK 上建立的現有代理遷移到 Claude Managed Agents。

Claude Managed Agents 用受管基礎設施取代了您手寫的代理迴圈。本頁涵蓋從在 Messages API 上建立的自訂迴圈或從 Claude Agent SDK 遷移時的變更。

所有 Managed Agents API 請求都需要 managed-agents-2026-04-01 beta 標頭。SDK 會自動設定 beta 標頭。

從 Messages API 代理迴圈

如果您透過在 while 迴圈中呼叫 messages.create、自行執行工具呼叫,以及將結果附加到對話歷史記錄來建立代理,大部分該程式碼都會消失。

您停止管理的內容

之前之後
您維護對話歷史記錄陣列,並在每個回合都將其傳回。工作階段在伺服器端儲存歷史記錄。傳送事件,接收事件。
您解析 stop_reason: "tool_use"、執行工具,並使用 tool_result 訊息迴圈回來。預先建立的工具在容器內自動執行。您只能透過 agent.custom_tool_use 事件處理自訂工具。
您為執行代理生成的程式碼佈建自己的沙箱。工作階段容器處理程式碼執行、檔案操作和 bash。
您決定迴圈何時完成。當代理沒有更多事情要做時,工作階段會發出 session.status_idle。

程式碼比較

之前(Messages API 迴圈,簡化版):

messages = [{"role": "user", "content": task}]
while True:
    response = client.messages.create(
        model="claude-opus-4-7",
        max_tokens=1024,
        messages=messages,
        tools=tools,
    )
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason == "end_turn":
        break
    for block in response.content:
        if block.type == "tool_use":
            result = execute_tool(block.name, block.input)
            messages.append(
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": result,
                        }
                    ],
                }
            )

之後(Claude Managed Agents):

agent = client.beta.agents.create(
    name="Task Runner",
    model="claude-opus-4-7",
    tools=[{"type": "agent_toolset_20260401"}],
)

session = client.beta.sessions.create(
    agent={"type": "agent", "id": agent.id, "version": agent.version},
    environment_id=environment.id,
)

with client.beta.sessions.events.stream(session.id) as stream:
    client.beta.sessions.events.send(
        session.id,
        events=[{"type": "user.message", "content": [{"type": "text", "text": task}]}],
    )
    for event in stream:
        if event.type == "session.status_idle":
            break

您仍然控制的內容

  • 系統提示和模型: 相同的欄位,現在在代理定義上。
  • 自訂工具: 仍然使用 JSON Schema 宣告。執行從內聯處理移至回應 agent.custom_tool_use 事件。請參閱 Session 事件流。
  • 上下文: 您仍然可以透過系統提示、檔案資源 或 技能 注入上下文。

從 Claude Agent SDK

如果您使用 Claude Agent SDK 進行建立,您已經在使用代理、工具和工作階段作為概念。區別在於它們執行的位置:SDK 在您操作的程序中執行,而 Managed Agents 在 Anthropic 的基礎設施中執行。大部分遷移是將 SDK 配置物件對應到其 API 端等效項。

變更的內容

Agent SDKManaged Agents
ClaudeAgentOptions(...) 每次執行時構造client.beta.agents.create(...) 一次;Agent 在伺服器端持久化和版本化。請參閱 Agent 設定。
async with ClaudeSDKClient(...) 或 query(...)client.beta.sessions.create(...) 然後傳送和接收 事件。
@tool 裝飾函數由 SDK 自動分派在 Agent 上宣告為 {"type": "custom", ...};您的用戶端處理 agent.custom_tool_use 事件並使用 user.custom_tool_result 回覆。請參閱 工具。
內建工具在您的程序中針對您的檔案系統執行{"type": "agent_toolset_20260401"} 在工作階段容器內針對 /workspace 執行相同的工具。
cwd、add_dirs 指向本地路徑上傳或掛載 檔案 作為工作階段資源。
system_prompt 和 CLAUDE.md 層級結構Agent 上的單一 system 字串。每次更新都會產生新的伺服器端版本;將工作階段固定到特定版本以推廣或回滾,無需部署。請參閱 Agent 設定。
mcp_servers 在一個地方配置和驗證在 Agent 上宣告伺服器;透過工作階段上的 Vault 提供認證。
permission_mode、can_use_tool每個工具 permission_policy;回應 always_ask 工具的 user.tool_confirmation 事件。

程式碼比較

之前(Agent SDK):

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ClaudeSDKClient,
    create_sdk_mcp_server,
    tool,
)


@tool("get_weather", "Get the current weather for a city.", {"city": str})
async def get_weather(args: dict) -> dict:
    return {"content": [{"type": "text", "text": f"{args['city']}: 18°C, clear"}]}


options = ClaudeAgentOptions(
    model="claude-opus-4-7",
    system_prompt="You are a concise weather assistant.",
    mcp_servers={
        "weather": create_sdk_mcp_server("weather", "1.0", tools=[get_weather])
    },
)

async with ClaudeSDKClient(options=options) as agent:
    await agent.query("What's the weather in Tokyo?")
    async for msg in agent.receive_response():
        print(msg)

之後(Managed Agents):

from anthropic import Anthropic

client = Anthropic()

agent = client.beta.agents.create(
    name="weather-agent",
    model="claude-opus-4-7",
    system="You are a concise weather assistant.",
    tools=[
        {
            "type": "custom",
            "name": "get_weather",
            "description": "Get the current weather for a city.",
            "input_schema": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        }
    ],
)
environment = client.beta.environments.create(
    name="weather-env",
    config={"type": "cloud", "networking": {"type": "unrestricted"}},
)

session = client.beta.sessions.create(
    agent={"type": "agent", "id": agent.id, "version": agent.version},
    environment_id=environment.id,
)


def get_weather(city: str) -> str:
    return f"{city}: 18°C, clear"


with client.beta.sessions.events.stream(session.id) as stream:
    client.beta.sessions.events.send(
        session.id,
        events=[
            {
                "type": "user.message",
                "content": [{"type": "text", "text": "What's the weather in Tokyo?"}],
            }
        ],
    )
    for ev in stream:
        if ev.type == "agent.message":
            print("".join(b.text for b in ev.content))
        elif ev.type == "agent.custom_tool_use":
            result = get_weather(**ev.input)
            client.beta.sessions.events.send(
                session.id,
                events=[
                    {
                        "type": "user.custom_tool_result",
                        "custom_tool_use_id": ev.id,
                        "content": [{"type": "text", "text": result}],
                    }
                ],
            )
        elif ev.type == "session.status_idle" and ev.stop_reason.type == "end_turn":
            break

Agent 和 Environment 建立一次,並在各個工作階段中重複使用。工具函數仍在您的程序中執行;區別在於您讀取 agent.custom_tool_use 事件並明確傳送結果,而不是 SDK 為您分派它。

移至您用戶端的功能

Anthropic 執行代理迴圈的權衡是 SDK 自動處理的一些事情變成了您用戶端的責任。

SDK 功能Managed Agents 方法
計畫模式先執行僅計畫工作階段,然後執行第二個工作階段以執行。
輸出樣式、斜線命令在傳送 user.message 之前或接收 agent.message 之後在您的用戶端中應用。
PreToolUse / PostToolUse 鉤子您的用戶端已經在回應之前看到每個 agent.custom_tool_use 事件;將邏輯放在那裡。對於內建工具,使用 permission_policy: always_ask。
max_turns在用戶端計算回合。

遷移檢查清單

  1. 建立環境,具有您的代理需要的網路和執行時。
  2. 將您的系統提示和工具選擇移植到 agent 定義。
  3. 使用 sessions.create 和 sessions.stream 取代您的迴圈。
  4. 對於代理讀取的任何本地檔案,透過 Files API 上傳它們並將其掛載為 resources。
  5. 對於任何自訂工具處理程式,將執行移至您的事件迴圈中,作為對 agent.custom_tool_use 事件的回應。
  6. 在將生產流量指向新流程之前,使用測試工作階段進行驗證。

在模型版本之間遷移

發佈新的 Claude 模型時,遷移 Claude Managed Agents 整合通常是一個欄位變更:更新 agent 定義 上的 model,變更在您建立的下一個工作階段上生效。

ant beta:agents update \
  --agent-id "$AGENT_ID" \
  --version "$AGENT_VERSION" \
  --model claude-opus-4-7

Messages API 遷移指南 中記錄的大多數模型級行為變更不需要您採取行動:

  • 請求參數變更(max_tokens 預設值、thinking 配置)由 Claude Managed Agents 執行時處理。這些欄位不會在 agent 定義上公開。
  • 助手訊息預填充在基於事件的工作階段模型中不存在,因此其在較新模型上的移除是無操作。
  • 工具引數 JSON 逃逸在您接收 agent.custom_tool_use 事件之前由執行時解析。您看到結構化資料,而不是原始字串。

Messages API 指南中的行為描述(模型的不同之處)仍然適用。遷移步驟(如何變更您的請求程式碼)則不適用。

Was this page helpful?

  • 從 Messages API 代理迴圈
  • 從 Claude Agent SDK