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 事件,包含工具名称和输入。session.status_idle 事件,包含 stop_reason: requires_action。阻塞事件 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?