View a markdown version of this page

配置 Amazon Bedrock AgentCore 生命周期设置 - 亚马逊基岩 AgentCore

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

配置 Amazon Bedrock AgentCore 生命周期设置

的LifecycleConfiguration输入参数CreateAgentRuntime允许您在 Amazon Bedrock AgentCore Runtime 中管理运行时会话和资源的生命周期。此配置通过自动清理空闲会话和防止长时间运行的实例无限期消耗资源来帮助优化资源利用率。

您还可以使用该UpdateAgentRuntime操作为现有 AgentCore 运行时配置生命周期设置。

配置属性

属性 Type 范围(秒) 必需 说明

idleRuntimeSessionTimeout

整数

60—28800(微型虚拟机)

60—1209600(实例)

否

空闲运行时会话的超时时间(以秒为单位)。当会话在这段时间内保持空闲状态时,它将触发终止。由于日志记录和其他进程完成,终止可能持续长达 15 秒。默认值:900 秒(15 分钟)

maxLifetime

整数

60—28800(微型虚拟机)

60—1209600(实例)

否

实例的最大生命周期(以秒为单位)。一旦达到,实例将初始化终止。由于日志记录和其他进程完成,终止可能持续长达 15 秒。默认值:28800 秒(8 小时)。预置新实例后,会话本身可以持续到此之后。

注意

这两个属性的最大值取决于 AgentCore 运行时的计算类型。使用微虚拟机的运行时最多可接受 28800 秒(8 小时)。使用容量提供商(实例)的运行时最多可接受 1209600 秒(14 天)。如果您为计算类型指定的值大于最大值,则请求将失败并显示ValidationException。有关更多信息,请参阅 实例。

约束

  • idleRuntimeSessionTimeout必须小于或等于 maxLifetime

  • 这两个值均以秒为单位进行测量

  • 使用微虚拟机的运行时的有效范围:60 到 28800 秒(最多 8 小时)

  • 使用容量提供商(实例)的运行时的有效范围:60 到 1209600 秒(最多 14 天)

  • 对于使用容量提供器的运行时,还maxLifetime必须小于或等于容量提供者在其中定义的 maxLifetime InstanceLifecycleConfiguration

默认 行为

当LifecycleConfiguration未提供或包含空值时,平台将应用以下逻辑:

客户输入 空闲 RuntimeSessionTimeout 最大寿命 结果

没有配置

900 秒

28800

使用默认值:900 和 28800

仅提供 MaxLifetime

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)

验证和限制

生命周期配置包括验证规则和约束条件,以防止配置无效。如果您的请求违反了以下任何规则,则会失败并显示ValidationException:

  • 任一值低于 60 秒,或高于运行时计算类型的最大值(微型虚拟机为 28800 秒,实例为 1209600 秒)。

  • idleRuntimeSessionTimeout大于maxLifetime。

  • 对于使用容量提供器的运行时,大maxLifetime于容量提供者在其中定义的值InstanceLifecycleConfiguration。maxLifetime要运行会话的时间超过容量提供商允许的时间,请maxLifetime先增加容量提供商的容量提供商的容量。

常见的验证错误

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

验证辅助函数

MICROVM_MAX_SECONDS = 28800 # 8 hours INSTANCES_MAX_SECONDS = 1209600 # 14 days MIN_SECONDS = 60 def validate_lifecycle_config(idle_timeout, max_lifetime, uses_capacity_provider=False): """Validate lifecycle configuration before API call""" errors = [] # The maximum depends on the compute type of the runtime maximum = INSTANCES_MAX_SECONDS if uses_capacity_provider else MICROVM_MAX_SECONDS # Check range constraints if not (MIN_SECONDS <= idle_timeout <= maximum): errors.append(f"idleRuntimeSessionTimeout must be between {MIN_SECONDS} and {maximum} seconds") if not (MIN_SECONDS <= max_lifetime <= maximum): errors.append(f"maxLifetime must be between {MIN_SECONDS} and {maximum} 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 秒)开始,然后根据使用模式进行调整

  • 在将计算类型提高到 8 小时maxLifetime以上之前,请检查您的计算类型——只有使用容量提供商(实例)的运行时才接受更长的值

  • 监控会话持续时间以优化超时值

  • 缩短开发环境的超时时间以节省成本

  • 考虑用户体验 ——超时时间过短可能会打断活跃用户

  • 首先在非生产环境中测试配置更改

  • 记录您的特定用例的超时理由

常见模式

使用场景 空闲超时 最大寿命 理由

互动聊天

10-15 分钟

2-4 小时

平衡响应能力和资源使用量

批处理

30 分钟

8 小时

允许长时间运行的操作

开发

5 分钟

30 分钟

快速清理以优化成本

生产 API

15 分钟

4 小时

标准生产工作负载

Demo/Testing

2 分钟

15 分钟

主动清理以供临时使用