

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 AgentCore 執行期上開始使用 Amazon Bedrock 受管代理程式 （使用 OpenAI)
<a name="runtime-get-started-bma"></a>

**注意**  
Amazon Bedrock 受管代理程式 （使用 OpenAI) 處於預覽狀態。在一般可用性之前，功能和 APIs 可能會變更。

Amazon Bedrock Managed Agents 會在其上執行 OpenAI Codex 繫帶 AWS。繫帶會在模型和工具之間執行迴圈、保留工作階段，並在對話成長時壓縮內容。當代理程式必須執行命令或使用檔案時， Bedrock Managed Agents 會將工作傳送至 環境。您可以決定環境執行的位置。

您可以在自己的電腦上執行 Codex exec-server 以進行本機開發。對於其他工作負載，Bedrock 受管代理程式會叫用您帳戶中的 AgentCore 執行期。執行期會為每個工作階段提供自己的 microVM。工作階段會以您控制的執行角色執行，而執行期可以連線到您的 VPC，以便代理程式可以連接私有資源。模型呼叫會保留在 Bedrock 受管代理程式中，因此容器只會執行代理程式傳送的命令。

在本教學課程中，您會執行下列任務：
+ 使用 AgentCore CLI 建立和部署執行期。
+ 使用 OpenAI 開發套件啟動工作階段。代理程式會在您的執行時間中使用範例技能。
+ （選用） 新增您自己的技能。

步驟 1 到 4 大約需要 15 分鐘。

您在本教學課程中建立 AWS 的資源可能會對 AWS 您的帳戶收取費用。這些資源包括執行期、 AWS CodeBuild 映像組建和 Bedrock 受管代理程式模型呼叫。如需詳細資訊，請參閱 [AgentCore 定價](https://aws.amazon.com/bedrock/agentcore/pricing/)。若要停止費用，請移除 中的資源[步驟 8：清理](#runtime-get-started-bma-clean-up)。

## 先決條件
<a name="runtime-get-started-bma-prerequisites"></a>
+  **Node.js 20 或更新版本。**AgentCore CLI 以 npm 套件的形式分佈。使用 檢查 `node --version`。
+  **uv.** 範例用戶端使用 [uv](https://docs.astral.sh/uv/) 來安裝其 Python 相依性。
+  **已設定登入資料的 AWS 帳戶。**若要建立 帳戶，請參閱 [AWS 帳戶入門](https://docs.aws.amazon.com/accounts/latest/reference/getting-started.html)。若要設定登入資料，請參閱[設定 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)。
+  **IAM 許可。**您的身分需要許可才能進行 AgentCore API 呼叫，並擔任部署期間使用的 CDK 引導角色。請參閱[使用 AgentCore CLI](runtime-permissions.md#runtime-permissions-cli)。範例用戶端也需要 IAM 許可。請參閱 [工作階段角色](#runtime-get-started-bma-session-role)。
+  **模型存取。**您的帳戶需要存取 Bedrock 受管代理程式模型 `openai.gpt-5.6-luna`。

CLI 會在您的帳戶中使用 AWS CodeBuild 建置容器映像。

## 步驟 1：建立專案
<a name="runtime-get-started-bma-create"></a>

安裝 AgentCore CLI，並設定您的登入資料和區域：

```
npm install -g @aws/agentcore
agentcore --version

export AWS_PROFILE=your-profile
export AWS_REGION=us-east-1
```

使用 `BedrockManagedAgents` 架構建立專案。您也可以在沒有旗標`agentcore create`的情況下執行 。選取**代理**程式，然後選取 **Bedrock 受管代理程式**做為架構。

```
agentcore create --name MyManagedAgent --framework BedrockManagedAgents
cd MyManagedAgent
```

專案在 中具有執行期組態，`agentcore/agentcore.json`在 中具有容器來源`app/MyManagedAgent/`。容器會執行 `codex exec-server`，這會連接至 Bedrock 受管代理程式，並執行代理程式的命令。

專案會使用下列預設值設定執行期：
+ 30 分鐘的閒置逾時和最長 8 小時的生命週期。請參閱[設定生命週期設定](runtime-lifecycle-settings.md)。
+ 在 中具有 許可的執行角色`policies/bma-acr-policy.json`。

### 專案結構
<a name="runtime-get-started-bma-project-structure"></a>

```
MyManagedAgent/
├── agentcore/
│   ├── agentcore.json
│   └── cdk/
└── app/MyManagedAgent/
    ├── Dockerfile
    ├── lifecycle/server.py
    ├── otel/collector.yaml
    ├── plugins/acr-report/
    ├── policies/
    │   ├── bma-acr-policy.json
    │   ├── bma-session-trust.json
    │   └── bma-session-policy.json
    ├── pyproject.toml
    ├── client.py
    └── README.md
```

金鑰檔案：
+  `lifecycle/server.py` - 生命週期伺服器。Bedrock Managed Agents 會呼叫它以在執行期工作階段`codex exec-server`中啟動。請勿變更此檔案。
+  `Dockerfile` - 安裝 Codex、CloudWatch 代理程式和 Python，並將 `lifecycle/`、 `otel/`和 複製到 `plugins/` `/opt/bma`。
+  `otel/collector.yaml` - 將 exec-server 的範圍和日誌傳送至 CloudWatch。
+  `plugins/acr-report/` - 具有一項技能的範例外掛程式。技能會儲存在工作區`acr-report.txt`中。
+  `policies/bma-acr-policy.json` - 執行時間執行角色的政策。允許 `bedrock-mantle:RegisterEnvironment` 和 `bedrock-mantle:ConnectEnvironment`。若要將其限制為一個專案，請將 `Resource`變更為 `arn:aws:bedrock-mantle:<region>:<account-id>:project/<project-id>`。
+  `pyproject.toml` - Python 相依性。`dev` 群組`client.py`僅適用於 。
+  `policies/bma-session-trust.json` 和 `policies/bma-session-policy.json` - 信任政策和工作階段角色的許可。請參閱 [工作階段角色](#runtime-get-started-bma-session-role)。
+  `client.py` - 啟動工作階段的範例用戶端。您可以在步驟 3 中執行它。

### 在 VPC 中部署執行期
<a name="runtime-get-started-bma-vpc"></a>

將網路選項新增至 `agentcore create`：

```
agentcore create --name MyManagedAgent --framework BedrockManagedAgents \
  --network-mode VPC --vpc-id <vpc-id> --subnets <subnet-ids> \
  --security-groups <security-group-ids>
```

VPC 必須具有指向 Bedrock 受管代理程式端點的路由，因為 exec-server 會與其連線。映像組建會下載 Codex 和 Python，因此也需要網際網路的路由。請參閱[設定 AgentCore for VPC](agentcore-vpc.md)。

### 在執行個體上執行執行期
<a name="runtime-get-started-bma-instances"></a>

相同的專案會在**執行個體**運算類型上執行。將容量提供者新增至專案，然後使用容量提供者新增代理程式：

```
agentcore create --name MyManagedAgent --no-agent
cd MyManagedAgent
agentcore add capacity-provider --name MyCapacityProvider \
  --subnets <subnet-ids> --security-groups <security-group-ids> \
  --os LINUX_ARM64 --instance-types c7g.large
agentcore add agent --name MyManagedAgent --framework BedrockManagedAgents \
  --capacity-provider MyCapacityProvider
```

然後繼續 [步驟 2：部署](#runtime-get-started-bma-deploy)。 `agentcore deploy`也會建立容量提供者及其運算子角色。
+ 使用 `LINUX_ARM64`和 Graviton 執行個體類型，因為映像建置會產生 ARM64 映像。
+ 容量提供者會提供網路。子網路必須具有指向 Bedrock 受管代理程式端點的路由。

若要連接不在專案中的容量提供者，請將其 ARN 提供給 `agentcore create --framework BedrockManagedAgents --capacity-provider <capacity-provider-arn>`。請參閱[執行期執行個體和容量提供者](runtime-instances.md)。

## 步驟 2：部署
<a name="runtime-get-started-bma-deploy"></a>

```
agentcore deploy
agentcore status
```

CLI 會在您的帳戶中使用 AWS CodeBuild 建置映像，並部署執行期及其執行角色。Bedrock 受管代理程式會為您叫用執行期。

從 的輸出儲存執行期 ARN`agentcore status`：

```
arn:aws:bedrock-agentcore:us-east-1:<account-id>:runtime/<runtime-id>
```

## 步驟 3：執行工作階段
<a name="runtime-get-started-bma-client"></a>

Bedrock 受管代理程式使用工作階段角色來呼叫模型並叫用您的執行期。工作階段角色不是執行期執行角色。**當您執行 時`client.py`，它會在您的 帳戶中建立工作階段角色。** `agentcore deploy` 不會建立工作階段角色，`agentcore remove`也不會將其刪除。請參閱 [工作階段角色](#runtime-get-started-bma-session-role)。

從代理程式目錄執行用戶端：

```
cd app/MyManagedAgent
uv run client.py --runtime <runtime-arn>
```

用戶端會建立工作階段並列印工作階段 ID、每個命令及其輸出，以及客服人員的答案。根據預設，客服人員會使用`acr-report`技能來儲存在工作區`acr-report.txt`中。

下一節會告訴您用戶端如何管理工作階段角色，以及執行用戶端所需的 IAM 許可。

### 工作階段角色
<a name="runtime-get-started-bma-session-role"></a>

工作階段角色不是執行期執行角色。 會使用 `agentcore deploy`建立執行角色`policies/bma-acr-policy.json`。用戶端在建立工作階段時，會將工作階段角色提供給 `role_arn` 欄位中的 Bedrock 受管代理程式。

當您啟動新的工作階段但不提供 時`--role-arn`，用戶端會執行下列步驟：

1. 如果角色`BmaSessionRole-<region>`不存在，用戶端會建立該角色。

1. 用戶端會將角色`BmaSession`的信任政策和內嵌政策與 `policies/bma-session-trust.json`和 進行比較`policies/bma-session-policy.json`。如果政策不同，用戶端會將檔案寫入角色。這些檔案僅限於 帳戶和執行時間的區域。

1. 如果用戶端變更角色，則會等待 15 秒。IAM 這次需要 Bedrock 受管代理程式才能使用變更。

若要變更角色，請變更檔案。用戶端不會移除其他人新增至角色的其他政策。當您提供 時，它不會檢查角色`--session-id`，也不會變更您使用 提供的角色`--role-arn`。

對於生產，請使用 為用戶端提供一個執行期和一個閘道的角色`--role-arn`。若要建立角色，請使用 中的兩個檔案`policies/`。放入您的分割區、區域和帳戶 ID，並將 ` ` 中的 `runtime/` 和 `gateway/*` 變更為您的執行期 ID 和閘道 ID。請勿變更專案中的檔案，因為區域中的所有專案都會共用 `BmaSessionRole-<region>`。

執行用戶端的身分需要工作階段角色`iam:PassRole`上的 Bedrock Managed Agents 用戶端許可 `bedrock-mantle:CallWithBearerToken`和 。若要讓用戶端建立和修復角色，也請在 `iam:PutRolePolicy`上提供 `iam:GetRole`、`iam:GetRolePolicy`、、 `iam:CreateRole` `iam:UpdateAssumeRolePolicy`和 `arn:aws:iam::<account-id>:role/BmaSessionRole-*`。如果您提供 `--role-arn`，用戶端不需要這五個許可。

如需信任政策、工作階段角色的許可和用戶端許可，請參閱《*Amazon Bedrock 使用者指南*》中的[安全和 IAM 角色](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-managed-agents-openai-security.html)。

### 用戶端的運作方式
<a name="runtime-get-started-bma-client-code"></a>

用戶端使用 `openai`套件`client.beta.agents`的資源。Bedrock Managed Agents 會執行代理程式迴圈。

當用戶端建立工作階段時，會在 中設定這些值`environment`：
+  `type` - `aws_bedrock_agentcore`，告知 Bedrock 受管代理程式使用 AgentCore 執行期。
+  `runtime_arn` - 您的執行時間。工作階段會在執行時間的 區域中執行。
+  `workspace_directory` - 代理程式執行其命令的目錄。用戶端使用 `/home/app/workspace`。生命週期伺服器會建立 目錄。
+  `runtime_qualifier` - 執行時間的端點。用戶端使用 `DEFAULT`。
+  `capability_directories` - Bedrock 受管代理程式尋找技能的目錄。用戶端使用 `/opt/bma/plugins`。

用戶端也會將 `role_arn``extra_body`中的 設定為工作階段角色。`openai` 套件沒有此欄位的參數。

`provide_token` 協助程式會使用您的 AWS 登入資料來取得每個請求的短期 Amazon Bedrock 承載字符。

如果您將閘道新增至專案，請使用 `agentcore deploy` 提供其來自 輸出的 ARN`--gateway`。僅將 旗標用於新的工作階段。用戶端會將閘道新增為在 中使用 ARN `mcp`的工具`connector_id`。Bedrock Managed Agents 會使用工作階段角色呼叫閘道。閘道必須支援 MCP 版本 `2025-03-26`。如果沒有，代理程式不會取得閘道工具，而且 Bedrock 受管代理程式不會顯示錯誤。

```
"""Send an input to a Bedrock Managed Agents session that uses this project's ACR."""

import argparse
import json
import time
from pathlib import Path
from typing import Any

import boto3
from aws_bedrock_token_generator import provide_token
from botocore.exceptions import ClientError
from openai import NotFoundError, OpenAI

BMA_MODEL_ID = "openai.gpt-5.6-luna"
# The agent runs its commands in this directory. The lifecycle server creates it.
WORKSPACE_DIRECTORY = "/home/app/workspace"
# Plugins and skills that the agent can use. The image has the acr-report plugin
# at this path. Add the path of an S3 Files mount to use the skills in a bucket.
CAPABILITY_DIRECTORIES = ["/opt/bma/plugins"]
TURN_END = ("completed", "failed", "cancelled")
TOOL_CALLS = ("mcp_call", "function_call", "web_search_call")
POLICIES = Path(__file__).parent / "policies"
SESSION_ROLE = "BmaSessionRole-{region}"
SESSION_POLICY = "BmaSession"


def show(data: dict[str, Any]) -> None:
    """Prints the session ID, the commands, the tool calls, and the answer."""
    kind = data["type"].removeprefix("agent.session.")
    item = data.get("item") or {}
    if kind == "created":
        print(f"Session {data['session']['id']}")
    elif kind == "turn.output_text.delta":
        print(data["delta"], end="", flush=True)
    elif kind == "turn.item.done" and item.get("type") == "command_execution":
        print(f"\n$ {item['command']}\n{item.get('output') or ''}".rstrip())
    elif kind == "turn.item.done" and item.get("type") in TOOL_CALLS:
        print(f"\nTool {item.get('name') or item['type']} {item.get('status')}")
    elif kind == "error" or kind.split(".")[-1] in TURN_END:
        source = data.get("turn") or data.get("environment") or data.get("session")
        print(f"\n{kind} {(source or data).get('error') or ''}".rstrip())


def load_policy(name: str, partition: str, region: str, account: str) -> str:
    """Reads a policy file and puts in the partition, the Region, and the account."""
    text = (POLICIES / name).read_text()
    for key, value in (("Partition", partition), ("Region", region), ("AccountId", account)):
        text = text.replace("${AWS::" + key + "}", value)
    return text


def session_role(runtime_arn: str) -> str:
    """Creates or repairs the session role, and returns its ARN.

    If the trust policy or the policy of the role is not the same as the file in `policies/`,
    the client writes the file to the role.
    """
    _, partition, _, region, account = runtime_arn.split(":")[:5]
    name = SESSION_ROLE.format(region=region)
    trust = load_policy("bma-session-trust.json", partition, region, account)
    policy = load_policy("bma-session-policy.json", partition, region, account)
    iam = boto3.client("iam")
    changed = False
    try:
        role = iam.get_role(RoleName=name)["Role"]
    except iam.exceptions.NoSuchEntityException:
        role = iam.create_role(RoleName=name, AssumeRolePolicyDocument=trust)["Role"]
        print(f"Created the session role {name}")
        changed = True
    else:
        if role["AssumeRolePolicyDocument"] != json.loads(trust):
            iam.update_assume_role_policy(RoleName=name, PolicyDocument=trust)
            print(f"Updated the trust policy of {name}")
            changed = True
    try:
        current = iam.get_role_policy(RoleName=name, PolicyName=SESSION_POLICY)["PolicyDocument"]
    except iam.exceptions.NoSuchEntityException:
        current = None
    if current != json.loads(policy):
        iam.put_role_policy(RoleName=name, PolicyName=SESSION_POLICY, PolicyDocument=policy)
        if not changed:
            print(f"Updated the policy of {name}")
        changed = True
    if changed:
        # IAM needs some seconds before Bedrock Managed Agents can use a new or changed role.
        time.sleep(15)
    return role["Arn"]


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--runtime", required=True, help="The ACR ARN.")
    parser.add_argument(
        "--session-id",
        help="The BMA session ID. If it does not exist, the client creates a session.",
    )
    parser.add_argument(
        "--input",
        default="Use the acr-report skill to save an ACR report in the workspace.",
    )
    parser.add_argument(
        "--gateway",
        help="The Gateway ARN from the output of `agentcore deploy`.",
    )
    parser.add_argument(
        "--role-arn",
        help="The session role that BMA assumes. If you do not give it, the client creates a role.",
    )
    parser.add_argument("--delete", action="store_true", help="Delete the session.")
    parser.add_argument("--raw", action="store_true", help="Print events as JSON.")
    args = parser.parse_args()
    # BMA must run in the Region of the ACR.
    region = args.runtime.split(":")[3]

    with OpenAI(
        api_key=lambda: provide_token(region=region),
        base_url=f"https://bedrock-mantle.{region}.api.aws/openai/v1",
    ) as client:
        sessions = client.beta.agents.sessions
        session_id = args.session_id
        if session_id:
            try:
                session = sessions.retrieve(session_id).model_dump(warnings=False)
            except NotFoundError:
                print(f"Session {session_id} does not exist.")
                session_id = None
            else:
                if session["environment"].get("runtime_arn") != args.runtime:
                    raise ValueError(f"Session {session_id} uses another ACR.")
        if not session_id and not args.role_arn:
            try:
                args.role_arn = session_role(args.runtime)
            except ClientError as error:
                parser.error(
                    f"The client cannot create or check the session role: {error}. "
                    "Get the IAM permissions in README.md, or give --role-arn."
                )
            print(f"Session role {args.role_arn}")

        if session_id:
            # BMA opens the stream only with stream=true, and the SDK does not send it.
            events = sessions.events.stream(session_id, extra_query={"stream": "true"})
            message = {
                "role": "user",
                "content": [{"type": "input_text", "text": args.input}],
            }
            sessions.events.create(
                session_id,
                events=[{"type": "agent.session.input.message", "input": [message]}],
            )
        else:
            agent: dict[str, Any] = {
                "model": BMA_MODEL_ID,
                "instructions": "Use the available tools to complete the task.",
            }
            if args.gateway:
                # Bedrock Managed Agents calls Gateway with the session role from the service side.
                agent["tools"] = [
                    {"type": "mcp", "server_label": "team_tools", "connector_id": args.gateway}
                ]
                args.input += " Then list the tools that the Gateway gives you."
            events = sessions.create(
                agent=agent,
                environment={
                    "type": "aws_bedrock_agentcore",
                    "runtime_arn": args.runtime,
                    "runtime_qualifier": "DEFAULT",
                    "workspace_directory": WORKSPACE_DIRECTORY,
                    "capability_directories": CAPABILITY_DIRECTORIES,
                },
                input=args.input,
                stream=True,
                # The SDK has no role_arn parameter. BMA assumes this role to call the ACR.
                extra_body={"role_arn": args.role_arn},
            )

        with events:
            for event in events:
                data = event.model_dump(mode="json", warnings=False)
                session_id = session_id or (data.get("session") or {}).get("id")
                if args.raw:
                    print(json.dumps(data), flush=True)
                else:
                    show(data)
                if data["type"].removeprefix("agent.session.turn.") in TURN_END:
                    break

        if args.delete:
            sessions.delete(session_id)
            print(f"\nDeleted session {session_id}")


if __name__ == "__main__":
    main()
```

## 步驟 4：繼續工作階段
<a name="runtime-get-started-bma-continue"></a>

若要將另一個輸入傳送至相同的工作階段，請新增工作階段 ID。輪換使用相同的工作區。若要在閒置停止後保留工作區，請將工作階段儲存新增至 。 [在閒置停止後保留檔案](#runtime-get-started-bma-keep-files)

```
uv run client.py --runtime <runtime-arn> --session-id <session-id> \
  --input "Run cat acr-report.txt and show the output."
```

如果工作階段不存在，用戶端會建立新的工作階段。新增 `--delete`以在輪換後刪除工作階段，或`--raw`將每個事件列印為 JSON。

### 在閒置停止後保留檔案
<a name="runtime-get-started-bma-keep-files"></a>

在 microVM 執行時間上，將 exec-server 的主目錄放在工作階段儲存體上。然後工作區、連線狀態，並在閒置停止後`CODEX_HOME`保持。

1. 使用工作階段儲存來建立專案，而不是步驟 1 中的 命令：

   ```
   agentcore create --name MyManagedAgent --framework BedrockManagedAgents \
     --session-storage-mount-path /mnt/home
   cd MyManagedAgent
   ```

1. 在 中`agentcore/agentcore.json`，將此變數新增至執行期的項目：

   ```
   "envVars": [{ "name": "BMA_HOME_DIR", "value": "/mnt/home" }]
   ```

1. 在 中`client.py`，設定 `WORKSPACE_DIRECTORY = "/mnt/home/workspace"`。

1. 部署並執行用戶端。

如需工作階段儲存體的詳細資訊，請參閱 [ AgentCore 執行期的檔案系統組態](runtime-filesystem-configurations.md)。

## 步驟 5：（選用） 新增技能
<a name="runtime-get-started-bma-skills"></a>

若要將技能新增至映像，請在 下新增外掛程式`plugins/`並部署。外掛程式具有`.codex-plugin/plugin.json`檔案和`skills/`目錄。`skills/` 目錄每個技能都有一個子目錄，其中包含 `SKILL.md` 檔案。映像會將其複製到 `/opt/bma/plugins`，用戶端已將其提供給 Bedrock 受管代理程式。

若要開始，請複製 `plugins/acr-report/`，並將外掛程式目錄和 重新命名`skills/acr-report/`為外掛程式的名稱和技能。在 中`plugin.json`，設定 `name`、`description`、 `version`和 `"skills": "./skills/"`。每個 都`SKILL.md`從具有 `name`和 的前端開始`description`。部署之後，請使用 啟動新的工作階段`--input "Use the <skill-name> skill to …​"`。

### 從 Amazon S3 儲存貯體共用技能
<a name="runtime-get-started-bma-skills-s3"></a>

在執行時間掛載 S3 檔案存取點。然後，當儲存貯體變更時，技能會變更，而映像會保持不變。如需 S3 檔案檔案系統、存取點和安全群組規則，請參閱 [ AgentCore 執行期的檔案系統組態](runtime-filesystem-configurations.md)。

S3 檔案掛載需要在 VPC 網路模式中執行時間。使用 中的網路選項建立專案[在 VPC 中部署執行期](#runtime-get-started-bma-vpc)。

在 儲存貯體中，將每個外掛程式放在存取點根目錄下的專屬目錄中。使用與 `plugins/acr-report/`： `<plugin>/.codex-plugin/plugin.json`和 相同的配置`<plugin>/skills/<skill>/SKILL.md`。

將掛載新增至 中執行期的項目`agentcore/agentcore.json`：

```
{
  "filesystemConfigurations": [
    {
      "s3FilesAccessPoint": {
        "accessPointArn": "arn:aws:s3files:us-east-1:111122223333:file-system/fs-0123456789abcdef0/access-point/fsap-0123456789abcdef0",
        "mountPath": "/mnt/skills"
      }
    }
  ]
}
```

然後將 `CAPABILITY_DIRECTORIES` 中的 設定為 `client.py` `["/opt/bma/plugins", "/mnt/skills"]`，然後部署。

## 步驟 6：檢視日誌和追蹤
<a name="runtime-get-started-bma-observe"></a>

```
agentcore logs --since 15m
```

第一個部署會在您的帳戶中開啟 CloudWatch 交易搜尋。追蹤會在大約 10 分鐘後顯示。若要查看追蹤，請開啟 CloudWatch 主控台，然後選擇 **GenAI 可觀測性**。從 Bedrock 受管代理程式到生命週期伺服器的每個呼叫都有一個跨`bma.invocation`度。如需詳細資訊，請參閱[檢視 Amazon Bedrock AgentCore 代理程式的可觀測性資料](observability-view.md)。

**交易搜尋設定會套用至整個帳戶**  
交易搜尋及其跨度索引會套用至 區域中的整個帳戶，且可能需支付額外費用。若要保留目前的設定，請在部署`~/.agentcore/config.json`之前將 `"disableTransactionSearch": true`新增至 。

## 步驟 7：更新並重新部署
<a name="runtime-get-started-bma-update"></a>

變更 中的執行時間設定`agentcore/agentcore.json`或映像的檔案，然後再次部署。例如，此設定會在 10 分鐘後停止閒置工作階段。這些值以秒為單位。

```
{
  "lifecycleConfiguration": {
    "idleRuntimeSessionTimeout": 600,
    "maxLifetime": 28800
  }
}
```

```
agentcore deploy
```

這些變更會套用至新的工作階段。

### 生命週期伺服器的環境變數
<a name="runtime-get-started-bma-env-vars"></a>

在執行期的項目`envVars`中將變數新增至 ，例如 `{ "name": "DISABLE_ADOT_OBSERVABILITY", "value": "true" }`。


| 變數 | 預設 | 說明 | 
| --- | --- | --- | 
|  `DISABLE_ADOT_OBSERVABILITY`  | 未設定 | 設定為 `true` 關閉追蹤和 exec-server 日誌。生命週期伺服器仍會將自己的日誌寫入執行期的日誌群組。 | 
|  `BMA_HOME_DIR`  |  `/home/app`  |  `HOME` exec-server 的 。 | 
|  `BMA_STATE_DIR`  |  `.bma` 中的 `BMA_HOME_DIR`  | 的目錄`state.json`，其會保留工作階段的連線狀態。 | 
|  `BMA_CODEX_HOME`  |  `.codex` 中的 `BMA_HOME_DIR`  |  `CODEX_HOME` exec-server 的 。 | 
|  `BMA_CODEX_BINARY`  |  `/opt/bma/bin/codex`  | Codex 二進位檔。 | 
|  `BMA_MAX_TURN_LEASE`  |  `300`  | 最長的輪換租用，以秒為單位。 | 

每個映像組建都會安裝最新的 Codex 版本。生命週期伺服器需要 Codex 0.154.0 或更新版本。若要鎖定版本，請在 `CODEX_NON_INTERACTIVE=1` 中新增 `CODEX_RELEASE=<version>` 旁邊的 `Dockerfile`。

## 步驟 8：清理
<a name="runtime-get-started-bma-clean-up"></a>

若要刪除工作階段，請將 `--delete`新增至該工作階段的用戶端上次執行。然後移除專案的資源，並部署 來刪除執行期、其執行角色和堆疊。

```
agentcore remove all
agentcore deploy
```

部署不會刪除這些資源：
+ 執行期的 CloudWatch Logs 日誌群組、建置映像的 CodeBuild 專案，以及啟動建置的 Lambda 函數。
+ Amazon ECR 儲存庫的 AWS KMS 金鑰。金鑰會保持**待定刪除**狀態 30 天，然後 AWS KMS 會將其刪除。
+ `CDKToolkit` 堆疊，如果第一個部署引導帳戶和區域。其他 AWS CDK 應用程式可以使用此堆疊。只有在沒有其他應用程式使用它時才刪除它。
+ 步驟 6 的交易搜尋設定。
+ 在步驟 3 中`client.py`建立的工作階段角色。

若要刪除工作階段角色，請執行下列命令：

```
aws iam delete-role-policy --role-name BmaSessionRole-<region> --policy-name BmaSession
aws iam delete-role --role-name BmaSessionRole-<region>
```

若要尋找日誌群組，請執行這些命令。然後刪除每個日誌群組。

```
aws logs describe-log-groups --log-group-name-prefix /aws/bedrock-agentcore/runtimes/<project-name>_<agent-name>- --query 'logGroups[].logGroupName'
aws logs describe-log-groups --log-group-name-prefix /aws/codebuild/AgentCore-<project-name>-<target-name>- --query 'logGroups[].logGroupName'
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/AgentCore- --query 'logGroups[].logGroupName'
aws logs delete-log-group --log-group-name <log-group-name>
```

取代這些值：
+  `<project-name>` - 專案的名稱。在步驟 1 中，它是 `MyManagedAgent`。
+  `<agent-name>` - 代理程式的名稱。在步驟 1 中，它也是 `MyManagedAgent`。
+  `<target-name>` - 中部署目標的名稱`agentcore/aws-targets.json`。預設值為 `default`。在 CodeBuild 名稱中，專案名稱和目標名稱中的每個底線 (`_`) 都會變更為連字號 (`-`)。

Lambda 日誌群組的名稱會縮短，如本範例所示：

```
/aws/lambda/AgentCore-MyManagedAgent--ApplicationAgentMyManage-<suffix>
```

命令會列出區域中所有 AgentCore CLI 專案的 Lambda 日誌群組。僅刪除專案的日誌群組。

如果您已將其他資源新增至專案，例如閘道或記憶體，請檢查部署是否已將其刪除。

## 相關資源
<a name="runtime-get-started-bma-related"></a>
+  [使用 AgentCore CLI](runtime-permissions.md#runtime-permissions-cli) 
+  [設定生命週期設定](runtime-lifecycle-settings.md) 
+  [AgentCore 執行期的檔案系統組態](runtime-filesystem-configurations.md) 
+  [為 VPC 設定 AgentCore ](agentcore-vpc.md) 
+  [執行期執行個體和容量提供者](runtime-instances.md) 
+  [檢視 Amazon Bedrock AgentCore 代理程式的可觀測性資料](observability-view.md) 