View a markdown version of this page

実行中のセッションを停止する - Amazon Bedrock AgentCore

実行中のセッションを停止する

StopRuntimeSession オペレーションを使用すると、アクティブなエージェント AgentCore ランタイムセッションを直ちに終了して、適切なリソースクリーンアップとセッションライフサイクル管理を行うことができます。

呼び出されると、このオペレーションは指定されたセッションを即座に終了し、進行中のストリーミングレスポンスを停止します。これにより、システムリソースが適切に解放され、孤立したセッションの蓄積を防ぐことができます。

以下のシナリオStopRuntimeSessionで を使用します。

  • ユーザーが開始した終了: ユーザーが会話を明示的に終了する場合

  • アプリケーションのシャットダウン: アプリケーション終了前のプロアクティブクリーンアップ

  • エラー処理: 応答しないセッションまたは停止したセッションを強制終了する

  • クォータ管理: 未使用のセッションを閉じてセッション制限内に保つ

  • タイムアウト処理: 予想期間を超えるセッションをクリーンアップする

前提条件

StopRuntimeSession を使用するには、以下が必要です。

  • bedrock-agentcore:StopRuntimeSession IAM 許可

  • 有効なエージェント AgentCore ランタイム ARN

  • 終了するアクティブなセッションの ID

AWS SDK
  1. AWS SDK を使用して、プログラムで AgentCore ランタイムセッションを停止できます。

    boto3 を使用して AgentCore ランタイムセッションを停止する Python の例。

    import boto3 # Initialize the AgentCore client client = boto3.client('bedrock-agentcore', region_name='us-west-2') try: # Stop the runtime session response = client.stop_runtime_session( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', runtimeSessionId='your-session-id', qualifier='DEFAULT' # Optional: endpoint name ) print(f"Session terminated successfully") print(f"Request ID: {response['ResponseMetadata']['RequestId']}") except client.exceptions.ResourceNotFoundException: print("Session not found or already terminated") except client.exceptions.AccessDeniedException: print("Insufficient permissions to stop session") except Exception as e: print(f"Error stopping session: {str(e)}")
HTTPS request
  1. OAuth 認証を使用するアプリケーションの場合は、直接 HTTPS リクエストを行います。

    import requests import urllib.parse def stop_session_with_oauth(agent_arn, session_id, bearer_token, qualifier="DEFAULT"): # URL encode the agent ARN encoded_arn = agent_arn.replace(':', '%3A').replace('/', '%2F') # Construct the endpoint URL url = f"https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/{encoded_arn}/stopruntimesession?qualifier={qualifier}" headers = { "Authorization": f"Bearer {bearer_token}", "Content-Type": "application/json", "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id": session_id } try: response = requests.post(url, headers=headers) response.raise_for_status() print(f"Session {session_id} terminated successfully") return response.json() except requests.exceptions.HTTPError as e: if e.response.status_code == 404: print("Session not found or already terminated") elif e.response.status_code == 403: print("Insufficient permissions or invalid token") else: print(f"HTTP error: {e.response.status_code}") raise except requests.exceptions.RequestException as e: print(f"Request failed: {str(e)}") raise # Usage stop_session_with_oauth( agent_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent", session_id="your-session-id", bearer_token="your-oauth-token" )

レスポンスの形式

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)

推奨事項

  • セッションを停止するときは、常に例外を処理する

  • クリーンアップのためにアプリケーション内のアクティブなセッションを追跡する

  • 停止リクエストのタイムアウトを設定してハングを回避する

  • デバッグとモニタリングのためのログセッションの終了

  • 複数のセッションで複雑なアプリケーションにセッションマネージャーを使用する