Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
本指南將引導您建立代理程式、設定環境、啟動工作階段,以及串流代理程式的回應。
偏好互動式逐步教學? 在最新版本的 Claude Code 中執行 /claude-api managed-agents-onboard,即可獲得引導式設定與互動式問答。
| 概念 | 說明 |
|---|---|
| Agent(代理) | 模型、系統提示、工具、MCP 伺服器與技能 |
| Environment(環境) | 工作階段執行位置的設定:由 Anthropic 管理的雲端沙箱,或在您自己的基礎架構上自行託管的沙箱 |
| Session(工作階段) | 在環境中執行的代理實例,用於執行特定任務並產生輸出 |
| Events(事件) | 您的應用程式與代理之間交換的訊息(使用者回合、工具結果、狀態更新) |
檢查安裝:
ant --version將您的 API 金鑰設定為環境變數:
export ANTHROPIC_API_KEY="your-api-key-here"所有 Managed Agents API 請求都需要 managed-agents-2026-04-01 beta 標頭。SDK 會自動設定此 beta 標頭。
建立代理程式
建立一個定義模型、系統提示和可用工具的代理程式。
ant beta:agents create \
--name "Coding Assistant" \
--model '{id: claude-opus-4-8}' \
--system "You are a helpful coding assistant. Write clean, well-documented code." \
--tool '{type: agent_toolset_20260401}'agent_toolset_20260401 工具類型會啟用完整的預建代理程式工具集(bash、檔案操作、網頁搜尋等)。請參閱工具以取得完整清單和各工具的設定選項。
儲存回傳的 agent.id。您在建立的每個工作階段中都會參照它。
建立環境
環境定義了您的代理程式執行所在的沙箱。
ant beta:environments create \
--name "quickstart-env" \
--config '{type: cloud, networking: {type: unrestricted}}'儲存回傳的 environment.id。您在建立的每個工作階段中都會參照它。
啟動工作階段
建立一個參照您的代理程式和環境的工作階段。
session = client.beta.sessions.create(
agent=agent.id,
environment_id=environment.id,
title="Quickstart session",
)
print(f"Session ID: {session.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": "Create a Python script that generates the first 20 Fibonacci numbers and saves them to fibonacci.txt",
},
],
},
],
)
# 處理串流事件
for event in stream:
match event.type:
case "agent.message":
for block in event.content:
print(block.text, end="")
case "agent.tool_use":
print(f"\n[Using tool: {event.name}]")
case "session.status_idle":
print("\n\nAgent finished.")
break代理程式會撰寫一個 Python 指令碼,在沙箱中執行它,並驗證輸出檔案已建立。您的輸出看起來類似如下:
I'll create a Python script that generates the first 20 Fibonacci numbers and saves them to a file.
[Using tool: write]
[Using tool: bash]
The script ran successfully. Let me verify the output file.
[Using tool: bash]
fibonacci.txt contains the first 20 Fibonacci numbers (0 through 4181).
Agent finished.當您傳送使用者事件時,Claude Managed Agents 會:
session.status_idle 事件。建立可重複使用、具版本控制的代理程式設定
自訂網路和沙箱設定
為您的代理程式啟用特定工具
處理事件並在執行過程中引導代理程式
依照週期性 cron 排程執行您的代理程式
Was this page helpful?