Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
與 Claude Managed Agents 的通訊是基於事件的。您向代理發送使用者事件,並接收代理和工作階段事件以追蹤狀態。
所有 Managed Agents API 請求都需要 managed-agents-2026-04-01 beta 標頭。SDK 會自動設定 beta 標頭。
事件在兩個方向流動。
事件類型字串遵循 {domain}.{action} 命名慣例。
每個事件都包括一個 processed_at 時間戳,指示事件在伺服器端何時被記錄。如果 processed_at 為 null,表示事件已由工具排隊,將在前面的事件完成處理後進行處理。
當代理呼叫自訂工具時:
agent.custom_tool_use 事件。stop_reason: requires_action 的 session.status_idle 事件。阻止事件 ID 在 stop_reason.requires_action.event_ids 陣列中。user.custom_tool_result 事件,在 custom_tool_use_id 參數中傳遞事件 ID 以及結果內容。running。with client.beta.sessions.events.stream(session.id) as stream:
for event in stream:
if event.type == "session.status_idle" and (stop := event.stop_reason):
match stop.type:
case "requires_action":
for event_id in stop.event_ids:
# Look up the custom tool use event and execute it
tool_event = events_by_id[event_id]
result = call_tool(tool_event.name, tool_event.input)
# Send the result back
client.beta.sessions.events.send(
session.id,
events=[
{
"type": "user.custom_tool_result",
"custom_tool_use_id": event_id,
"content": [{"type": "text", "text": result}],
},
],
)
case "end_turn":
break當權限政策要求在工具執行前進行確認時:
agent.tool_use 或 agent.mcp_tool_use 事件。session.status_idle 事件,其中包含 stop_reason: requires_action。阻止事件 ID 位於 stop_reason.requires_action.event_ids 陣列中。user.tool_confirmation 事件,在 tool_use_id 參數中傳遞事件 ID。將 result 設置為 "allow" 或 "deny"。使用 deny_message 來解釋拒絕原因。running。with client.beta.sessions.events.stream(session.id) as stream:
for event in stream:
if event.type == "session.status_idle" and (stop := event.stop_reason):
match stop.type:
case "requires_action":
for event_id in stop.event_ids:
# Approve the pending tool call
client.beta.sessions.events.send(
session.id,
events=[
{
"type": "user.tool_confirmation",
"tool_use_id": event_id,
"result": "allow",
},
],
)
case "end_turn":
break會話物件包含一個 usage 欄位,其中包含累積的令牌統計資訊。在會話進入閒置狀態後取得會話以讀取最新的總計,並使用它們來追蹤成本、強制執行預算或監控消耗。
{
"id": "sesn_01...",
"status": "idle",
"usage": {
"input_tokens": 5000,
"output_tokens": 3200,
"cache_creation_input_tokens": 2000,
"cache_read_input_tokens": 20000
}
}input_tokens 報告未快取的輸入令牌,output_tokens 報告會話中所有模型呼叫的總輸出令牌。cache_creation_input_tokens 和 cache_read_input_tokens 欄位反映提示快取活動。快取項目使用 5 分鐘的 TTL,因此在該時間窗口內的連續轉換受益於快取讀取,這降低了每個令牌的成本。
Was this page helpful?