

# 設定 Amazon Bedrock AgentCore 生命週期設定
<a name="runtime-lifecycle-settings"></a>

[CreateAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateAgentRuntime.html) 的`LifecycleConfiguration`輸入參數可讓您管理 Amazon Bedrock AgentCore 執行期中執行期工作階段和資源的生命週期。此組態透過自動清除閒置工作階段並防止長時間執行的執行個體無限期地耗用資源，協助最佳化資源使用率。

您也可以使用 [UpdateAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_UpdateAgentRuntime.html) 操作來設定現有 AgentCore 執行期的生命週期設定。

**Topics**
+ [組態屬性](#configuration-attributes)
+ [預設行為](#default-behavior)
+ [使用生命週期組態建立 AgentCore 執行期](#create-agent-runtime-with-lifecycle)
+ [更新 AgentCore 執行期的生命週期組態](#update-lifecycle-configuration)
+ [取得 AgentCore 執行期的生命週期組態](#update-lifecycle-configuration)
+ [驗證和限制條件](#validation-and-constraints)
+ [生命週期設定和執行期工作階段](#lifecycle-and-session-relationship)
+ [最佳實務](#best-practices)

## 組態屬性
<a name="configuration-attributes"></a>


| 屬性 | Type | 範圍 （秒） | 必要 | 說明 | 
| --- | --- | --- | --- | --- | 
|  `idleRuntimeSessionTimeout`  | Integer | 60-28800 | 否 | 閒置執行時間工作階段的逾時，以秒為單位。當工作階段在此期間保持閒置狀態時，將會觸發終止。由於記錄和其他程序完成，終止最多可持續 15 秒。預設：900 秒 (15 分鐘） | 
|  `maxLifetime`  | Integer | 60-28800 | 否 | 執行個體的生命週期上限，以秒為單位。到達後，執行個體會初始化終止。由於記錄和其他程序完成，終止最多可持續 15 秒。預設：28800 秒 (8 小時）。佈建新的執行個體時，工作階段本身可以保留超過此值。 | 

### Constraints
<a name="constraints"></a>
+  `idleRuntimeSessionTimeout` 必須小於或等於 `maxLifetime` 
+ 兩個值都以秒為單位
+ 有效範圍：60 到 28800 秒 （最多 8 小時）

## 預設行為
<a name="default-behavior"></a>

當 `LifecycleConfiguration` 未提供或包含 null 值時，平台會套用下列邏輯：


| 客戶輸入 | idleRuntimeSessionTimeout | maxLifetime | 結果 | 
| --- | --- | --- | --- | 
|  **無組態**  | 900 秒 | 28800 年代 | 使用預設值：900 和 28800 | 
|  **僅提供 maxLifetime **  | 900 秒 | 客戶值 | 如果 maxLifetime ≤ 900 秒：將 maxLifetime 用於兩者 如果 maxLifetime > 900 秒：將 900 秒用於閒置，將客戶值用於最大值 | 
|  **僅提供 idleTimeout **  | 客戶值 | 28800 年代 | 將客戶值用於閒置，將 28800 秒用於上限 | 
|  **提供的兩個值**  | 客戶值 | 客戶值 | 依原狀使用客戶值 | 

### 預設值
<a name="default-values"></a>
+  `idleRuntimeSessionTimeout` ：**900 秒** (15 分鐘）
+  `maxLifetime` ：**28800 秒** (8 小時）

## 使用生命週期組態建立 AgentCore 執行期
<a name="create-agent-runtime-with-lifecycle"></a>

您可以在建立 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 執行期的生命週期組態
<a name="update-lifecycle-configuration"></a>

您可以更新現有 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 執行期的生命週期組態
<a name="update-lifecycle-configuration"></a>

您可以取得現有 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)
```

## 驗證和限制條件
<a name="validation-and-constraints"></a>

生命週期組態包含驗證規則和限制條件，以防止無效的組態。

### 常見的驗證錯誤
<a name="common-validation-errors"></a>

```
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
```

### 驗證協助程式函數
<a name="validation-helper-function"></a>

```
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")
```

## 生命週期設定和執行期工作階段
<a name="lifecycle-and-session-relationship"></a>

您定義的生命週期組態設定會套用至每個個別執行階段工作階段。當您使用特定 `runtimeSessionId` 叫用代理程式時，AgentCore 執行期會為該工作階段佈建專用的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()
)
```

生命週期設定和工作階段的重點：
+  **每個工作階段隔離**：每個 都會使用獨立的生命週期計時器`runtimeSessionId`取得自己的 microVM 
+  **閒置計時器重設** ：每次您叫用相同工作階段時`idleRuntimeSessionTimeout`重設
+  **最長生命週期強制執行** ：`maxLifetime`計時器會在首次建立 microVM 且無法重設時啟動
+  **工作階段終止** ：達到任一逾時時，只會終止該特定工作階段的 microVM。可以使用佈建新的 microVM 來繼續工作階段。

**提示**  
每個 microVM `agentRuntimeArtifact` 工作階段都會使用在建立 microVM 時部署的程式碼資產 ()。如果您使用新程式碼更新代理程式執行期，現有的工作階段將繼續使用先前的版本，直到終止並建立新的工作階段為止。

## 最佳實務
<a name="best-practices"></a>

設定生命週期設定以獲得最佳資源使用率和使用者體驗時，請遵循這些最佳實務。

### 建議
<a name="recommendations"></a>
+  從**預設值 (900s 閒置，最多 28800s) 開始**，並根據用量模式進行調整
+  **監控工作階段持續時間**以最佳化逾時值
+  使用**較短的開發環境逾時**來節省成本
+  **考慮使用者體驗** - 過短的逾時可能會中斷作用中的使用者
+  先**測試非生產環境中的組態變更** 
+  記錄特定使用案例的**逾時理由** 

### 常見模式
<a name="common-patterns"></a>


| 使用案例 | 閒置逾時 | 最長存留期 | 理由 | 
| --- | --- | --- | --- | 
|  **互動式聊天**  | 10-15 分鐘 | 2-4 小時 | 平衡回應能力與資源用量 | 
|  **批次處理**  | 30 分鐘 | 8 hours | 允許長時間執行的操作 | 
|  **開發**  | 5 分鐘 | 30 分鐘 | 成本最佳化的快速清除 | 
|  **生產 API**  | 15 分鐘 | 4 小時 | 標準生產工作負載 | 
|  **示範/測試**  | 2 分鐘 | 15 分鐘 | 臨時用途的積極清理 | 