配置 Amazon Bedrock AgentCore 生命周期设置
的LifecycleConfiguration输入参数CreateAgentRuntime允许您在 Amazon Bedrock AgentCore Runtime 中管理运行时会话和资源的生命周期。此配置可自动清理空闲会话并防止长时间运行的实例无限期消耗资源,从而帮助优化资源利用率。
您还可以使用该UpdateAgentRuntime操作为现有 AgentCore 运行时配置生命周期设置。
主题
配置属性
| 属性 | Type | 范围(秒) | 必需 | 说明 |
|---|---|---|---|---|
|
|
整数 |
60-28800 |
否 |
空闲运行时会话的超时时间(以秒为单位)。当会话在这段时间内保持空闲状态时,它将触发终止。由于日志记录和其他过程的完成,终止可能持续长达 15 秒。默认值:900 秒(15 分钟) |
|
|
整数 |
60-28800 |
否 |
实例的最大生命周期(以秒为单位)。一旦到达,实例将初始化终止。由于日志记录和其他过程的完成,终止可能持续长达 15 秒。默认值:28800 秒(8 小时)。预配置了新实例后,会话本身可以持续到此之后。 |
约束
-
idleRuntimeSessionTimeout必须小于或等于maxLifetime -
两个值均以秒为单位测量
-
有效范围:60 到 28800 秒(最长 8 小时)
默认 行为
如果LifecycleConfiguration未提供或包含空值,则平台将应用以下逻辑:
| 客户反馈 | 闲着 RuntimeSessionTimeout | 最大寿命 | 结果 |
|---|---|---|---|
|
没有配置 |
900 秒 |
28800 |
使用默认值:900 和 28800 |
|
仅提供最大生命周期 |
900 秒 |
客户价值 |
如果 maxLifetime ≤ 900 秒:两者都使用 maxLifetime 如果 maxLifetime > 900 秒:空闲时间使用 900 秒,使用客户值表示最大值 |
|
仅提供 idleTimeout |
客户价值 |
28800 |
空闲时使用客户价值,最大值为 28800 秒 |
|
两个值都已提供 |
客户价值 |
客户价值 |
按原样使用客户价值 |
默认值
-
idleRuntimeSessionTimeout: 900 秒(15 分钟) -
maxLifetime: 28800 秒(8 小时)
使用生命周期配置创建 AgentCore 运行时
您可以在创建 AgentCore 运行时时指定生命周期配置。
import boto3 client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') try: response = client.create_agent_runtime( agentRuntimeName='my_agent_runtime', agentRuntimeArtifact={ 'containerConfiguration': { 'containerUri': '123456789012.dkr.ecr.us-west-2.amazonaws.com/my-agent:latest' } }, lifecycleConfiguration={ 'idleRuntimeSessionTimeout': 1800, # 30 minutes, configurable 'maxLifetime': 14400 # 4 hours }, networkConfiguration={'networkMode': 'PUBLIC'}, roleArn='arn:aws:iam::123456789012:role/AgentRuntimeRole' ) print(f"Agent runtime created: {response['agentRuntimeArn']}") except client.exceptions.ValidationException as e: print(f"Validation error: {e}") except Exception as e: print(f"Error creating agent runtime: {e}")
更新 AgentCore 运行时的生命周期配置
您可以更新现有 AgentCore 运行时的生命周期配置。
import boto3 client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') agent_runtime_id = 'my_agent_runtime' try: response = client.update_agent_runtime( agentRuntimeId=agent_runtime_id, agentRuntimeArtifact={ 'containerConfiguration': { 'containerUri': '123456789012.dkr.ecr.us-west-2.amazonaws.com/my-agent:latest' } }, networkConfiguration={'networkMode': 'PUBLIC'}, roleArn='arn:aws:iam::123456789012:role/AgentRuntimeRole', lifecycleConfiguration={ 'idleRuntimeSessionTimeout': 600, # 10 minutes 'maxLifetime': 7200 # 2 hours } ) print("Lifecycle configuration updated successfully") except client.exceptions.ValidationException as e: print(f"Validation error: {e}") except client.exceptions.ResourceNotFoundException: print("Agent runtime not found") except Exception as e: print(f"Error updating configuration: {e}")
获取 AgentCore 运行时的生命周期配置
您可以获取现有 AgentCore 运行时的生命周期配置。
import boto3 client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') def get_lifecycle_config(): try: response = client.get_agent_runtime(agentRuntimeId="my_agent_runtime") lifecycle_config = response.get('lifecycleConfiguration', {}) idle_timeout = lifecycle_config.get('idleRuntimeSessionTimeout', 900) max_lifetime = lifecycle_config.get('maxLifetime', 28800) print(f"Current configuration:") print(f" Idle timeout: {idle_timeout}s ({idle_timeout//60} minutes)") print(f" Max lifetime: {max_lifetime}s ({max_lifetime//3600} hours)") return lifecycle_config except Exception as e: print(f"Error retrieving configuration: {e}") return None # Usage config = get_lifecycle_config() print(config)
验证和约束
生命周期配置包括验证规则和约束,以防止配置无效。
常见的验证错误
import boto3 client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') try: client.create_agent_runtime( agentRuntimeName='invalid_config_agent', agentRuntimeArtifact={ 'containerConfiguration': { 'containerUri': '123456789012.dkr.ecr.us-west-2.amazonaws.com/my-agent:latest' } }, lifecycleConfiguration={ 'idleRuntimeSessionTimeout': 3600, # 1 hour, configurable 'maxLifetime': 1800 # 30 minutes - INVALID! }, networkConfiguration={'networkMode': 'PUBLIC'}, roleArn='arn:aws:iam::123456789012:role/AgentRuntimeRole', ) except client.exceptions.ValidationException as e: print(f"Validation failed: {e}") # Output: idleRuntimeSessionTimeout must be less than or equal to maxLifetime
验证辅助函数
def validate_lifecycle_config(idle_timeout, max_lifetime): """Validate lifecycle configuration before API call""" errors = [] # Check range constraints if not (1 <= idle_timeout <= 28800): errors.append(f"idleRuntimeSessionTimeout must be between 1 and 28800 seconds") if not (1 <= max_lifetime <= 28800): errors.append(f"maxLifetime must be between 1 and 28800 seconds") # Check relationship constraint if idle_timeout > max_lifetime: errors.append(f"idleRuntimeSessionTimeout ({idle_timeout}s) must be ≤ maxLifetime ({max_lifetime}s)") return errors # Usage errors = validate_lifecycle_config(3600, 1800) if errors: for error in errors: print(f"Validation error: {error}") else: print("Configuration is valid")
生命周期设置和运行时会话
您定义的生命周期配置设置将应用于每个单独的运行时会话。当您使用特定的代理调用代理时runtimeSessionId, AgentCore Runtime 会为该会话预置一个专用 microVM。生命周期超时(idleRuntimeSessionTimeout和maxLifetime)控制着该特定 microVM 实例的生命周期。
import boto3 import json import uuid client = boto3.client('bedrock-agentcore', region_name='us-west-2') # Each unique runtimeSessionId gets its own microVM with lifecycle settings applied session_id_user_1 = str(uuid.uuid4()) # User 1's session session_id_user_2 = str(uuid.uuid4()) # User 2's session # First invocation for User 1 - creates new microVM with lifecycle timers response1 = client.invoke_agent_runtime( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', runtimeSessionId=session_id_user_1, # Dedicated microVM for this session payload=json.dumps({"prompt": "Hello from User 1"}).encode() ) # First invocation for User 2 - creates separate microVM with its own lifecycle timers response2 = client.invoke_agent_runtime( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', runtimeSessionId=session_id_user_2, # Different microVM for this session payload=json.dumps({"prompt": "Hello from User 2"}).encode() ) # Subsequent invocations to same session reuse the existing microVM # The idle timeout resets with each invocation to the same session response3 = client.invoke_agent_runtime( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', runtimeSessionId=session_id_user_1, # Reuses User 1's existing microVM payload=json.dumps({"prompt": "Follow-up from User 1"}).encode() )
关于生命周期设置和会话的要点:
-
Per-session 隔离:每个
runtimeSessionId都有自己的 microVM 和独立的生命周期计时器 -
空闲计时器重置:每次调用同一个会话时的重置
idleRuntimeSessionTimeout -
最大生命周期强制执行:
maxLifetime计时器在 microVM 首次创建时启动,无法重置 -
会话终止:当达到任一超时时,仅终止该特定会话的 microVM。在配置了新的 microVM 后,可以恢复会话。
提示
每个 microVM 会话都使用在创建 microVM 时部署的代码资产 (agentRuntimeArtifact)。如果您使用新代码更新代理运行时,现有会话将继续使用以前的版本,直到它们终止并创建新会话。
最佳实践
在配置生命周期设置时,请遵循以下最佳实践,以实现最佳资源利用率和用户体验。
建议
-
从@@ 默认值开始(空闲时间 900 秒,最大 28800 秒),然后根据使用模式进行调整
-
监控会话持续时间以优化超时值
-
为开发环境@@ 使用更短的超时时间以节省成本
-
考虑用户体验 ——超时时间过短可能会打断活跃用户
-
首先在非生产环境中@@ 测试配置更改
-
记录特定用例的超时理由
常见模式
| 使用场景 | 空闲超时 | 最大使用寿命 | 理由 |
|---|---|---|---|
|
互动聊天 |
10-15 分钟 |
2-4 小时 |
平衡响应能力和资源使用量 |
|
批处理 |
30 分钟 |
8 小时 |
允许长时间运行的操作 |
|
开发 |
5 分钟 |
30 分钟 |
快速清理以优化成本 |
|
生产 API |
15 分钟 |
4 小时 |
标准生产工作负载 |
|
Demo/Testing |
2 分钟 |
15 分钟 |
积极清理以备临时使用 |