停止正在运行的会话
该StopRuntimeSession操作允许您立即终止活动代理 AgentCore 运行时会话,以便进行适当的资源清理和会话生命周期管理。
调用后,此操作会立即终止指定的会话并停止所有正在进行的流式传送响应。这样可以正确释放系统资源并防止孤立会话积累。
StopRuntimeSession在以下场景中使用:
-
User-initiated 结束:当用户明确结束对话时
-
应用程序关闭:应用程序终止前主动清理
-
错误处理:强制终止无响应或停滞的会话
-
配额管理:关闭未使用的会话,保持在会话限制之内
-
超时处理:清理超过预期持续时间的会话
先决条件
要使用 StopRuntimeSession,你需要:
-
bedrock-agentcore:StopRuntimeSessionIAM 权限 -
有效的代理 AgentCore 运行时 ARN
-
要终止的活动会话的 ID
例
响应格式
成功StopRuntimeSession操作的预期响应格式。
{ "ResponseMetadata": { "RequestId": "12345678-1234-1234-1234-123456789012", "HTTPStatusCode": 200 } }
错误处理
常见错误响应:
| 状态代码 | 错误 | 说明 |
|---|---|---|
|
404 |
ResourceNotFoundException |
未找到会话或会话已终止 |
|
403 |
AccessDeniedException |
权限不足 |
|
400 |
ValidationException |
参数无效 |
|
500 |
InternalServerException |
服务错误 |
最佳实践
会话生命周期管理
class SessionManager: def __init__(self, client, agent_arn): self.client = client self.agent_arn = agent_arn self.active_sessions = set() def invoke_agent(self, session_id, payload): """Invoke agent and track session""" try: response = self.client.invoke_agent_runtime( agentRuntimeArn=self.agent_arn, runtimeSessionId=session_id, payload=payload ) self.active_sessions.add(session_id) return response except Exception as e: print(f"Failed to invoke agent: {e}") raise def stop_session(self, session_id): """Stop session and remove from tracking""" try: self.client.stop_runtime_session( agentRuntimeArn=self.agent_arn, runtimeSessionId=session_id, qualifier=endpoint_name ) self.active_sessions.discard(session_id) print(f"Session {session_id} stopped") except Exception as e: print(f"Failed to stop session {session_id}: {e}") def cleanup_all_sessions(self): """Stop all tracked sessions""" for session_id in list(self.active_sessions): self.stop_session(session_id)
建议
-
停止会话时@@ 一定要处理异常
-
跟踪应用程序中的活动会话以进行清理
-
为停止请求@@ 设置超时以避免挂起
-
记录会话终止情况,以便进行调试和监控
-
使用会话管理器管理具有多个会话的复杂应用程序