停止執行中的工作階段
StopRuntimeSession 操作可讓您立即終止作用中的 AgentCore 執行期工作階段,以進行適當的資源清除和工作階段生命週期管理。
呼叫 時,此操作會立即終止指定的工作階段,並停止任何持續的串流回應。這可讓系統資源正確釋出,並防止孤立工作階段的累積。
StopRuntimeSession 在這些案例中使用 :
-
使用者起始的結束 :當使用者明確結束對話時
-
應用程式關閉 :在應用程式終止前主動清除
-
處理錯誤:強制終止無回應或停滯的工作階段
-
配額管理:關閉未使用的工作階段,保持在工作階段限制內
-
處理逾時:清除超過預期持續時間的工作階段
先決條件
若要使用 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)
建議
-
停止工作階段時一律處理例外狀況
-
追蹤應用程式中的作用中工作階段以進行清除
-
設定停止請求的逾時,以避免掛起
-
用於偵錯和監控的日誌工作階段終止
-
針對具有多個工作階段的複雜應用程式使用工作階段管理員