View a markdown version of this page

在沒有 AgentCore CLI 的情況下開始使用 - Amazon Bedrock AgentCore

在沒有 AgentCore CLI 的情況下開始使用

您可以在沒有 AgentCore CLI 的情況下建立 AgentCore 執行期代理程式。反之,您可以使用命令列工具的組合來設定代理程式並將其部署到 AgentCore 執行期。

本教學課程示範如何在不使用 AgentCore CLI 的情況下部署自訂代理程式。自訂代理程式是不使用 AgentCore Python SDK 建置的代理程式。在本教學課程中,自訂代理程式是使用 FastAPI 和 Docker 建置。自訂代理程式遵循 AgentCore 執行期要求 ,這表示代理程式必須公開 /invocations POST 和 /ping GET 端點,並封裝在 Docker 容器中。Amazon Bedrock AgentCore 需要所有部署代理程式的 ARM64 架構。

注意

您也可以針對使用 AgentCore Python SDK 建置的代理程式使用此方法。

快速入門設定

為您的代理程式啟用可觀測性

Amazon Bedrock AgentCore 可觀測性可協助您追蹤、偵錯和監控您在 AgentCore 執行期中託管的代理程式。若要觀察代理程式,請先遵循啟用 AgentCore 可觀測性中的指示來啟用 CloudWatch 交易搜尋。

安裝 uv

在此範例中,我們將使用uv套件管理員,但您可以使用任何 Python 公用程式或套件管理員。若要uv在 macOS 上安裝 :

curl -LsSf https://astral.sh/uv/install.sh | sh

如需其他平台上的安裝說明,請參閱 uv 文件

建立您的代理程式專案

設定您的專案

  1. 建立並導覽至您的專案目錄:

    mkdir my-custom-agent && cd my-custom-agent
  2. 使用 Python 3.11 初始化專案:

    uv init --python 3.11
  3. 新增必要的相依性 (uv 會自動建立 .venv):

    uv add fastapi 'uvicorn[standard]' pydantic httpx strands-agents

客服人員合約要求

您的自訂代理程式必須滿足這些核心需求:

  • /invocations 端點 :客服人員互動的 POST 端點 (必要)

  • /ping 端點 :運作狀態檢查的 GET 端點 (必要)

  • Docker 容器 :ARM64 容器化部署套件

專案結構

注意:為了方便起見,以下範例使用 FastAPI Server 做為處理請求的 Web 伺服器架構。

您的專案應具有下列結構:

my-custom-agent/ ├── agent.py # FastAPI application ├── Dockerfile # ARM64 container configuration ├── pyproject.toml # Created by uv init └── uv.lock # Created automatically by uv

完整的 strands 代理程式範例

使用下列內容在專案根agent.py中建立 :

範例 agent.py

from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Dict, Any from datetime import datetime from strands import Agent app = FastAPI(title="Strands Agent Server", version="1.0.0") # Initialize Strands agent strands_agent = Agent() class InvocationRequest(BaseModel): input: Dict[str, Any] class InvocationResponse(BaseModel): output: Dict[str, Any] @app.post("/invocations", response_model=InvocationResponse) async def invoke_agent(request: InvocationRequest): try: user_message = request.input.get("prompt", "") if not user_message: raise HTTPException( status_code=400, detail="No prompt found in input. Please provide a 'prompt' key in the input." ) result = strands_agent(user_message) response = { "message": result.message, "timestamp": datetime.utcnow().isoformat() } return InvocationResponse(output=response) except Exception as e: raise HTTPException(status_code=500, detail=f"Agent processing failed: {str(e)}") @app.get("/ping") async def ping(): return {"status": "healthy"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8080)

此實作:

  • 使用所需的端點建立 FastAPI 應用程式

  • 初始化 Strands 代理程式以處理使用者訊息

  • 實作客服人員互動的 /invocations POST 端點

  • 實作運作狀態檢查的 /ping GET 端點

  • 設定要在主機0.0.0.0和連接埠上執行的伺服器 8080

本機測試

測試您的代理程式

  1. 執行應用程式:

    uv run uvicorn agent:app --host 0.0.0.0 --port 8080
  2. 測試/ping端點 (在另一個終端機中):

    curl http://localhost:8080/ping
  3. 測試/invocations端點:

    curl -X POST http://localhost:8080/invocations \ -H "Content-Type: application/json" \ -d '{ "input": {"prompt": "What is artificial intelligence?"} }'

建立 dockerfile

使用下列內容在專案根Dockerfile中建立 :

範例 Dockerfile

# Use uv's ARM64 Python base image FROM --platform=linux/arm64 ghcr.io/astral-sh/uv:python3.11-bookworm-slim WORKDIR /app # Copy uv files COPY pyproject.toml uv.lock ./ # Install dependencies (including strands-agents) RUN uv sync --frozen --no-cache # Copy agent file COPY agent.py ./ # Expose port EXPOSE 8080 # Run application CMD ["uv", "run", "uvicorn", "agent:app", "--host", "0.0.0.0", "--port", "8080"]

此 Dockerfile:

  • 使用 ARM64 Python 基礎映像 (Amazon Bedrock AgentCore 需要)

  • 設定工作目錄

  • 複製相依性檔案並安裝相依性

  • 複製代理程式程式碼

  • 公開連接埠 8080

  • 設定 命令以執行應用程式

建置和部署 ARM64 映像

設定 docker buildx

Docker buildx 可讓您為不同的架構建置映像。使用 進行設定:

docker buildx create --use

為 ARM64 建置並在本機測試

建置和測試您的映像

  1. 在本機建置映像進行測試:

    docker buildx build --platform linux/arm64 -t my-agent:arm64 --load.
  2. 使用登入資料在本機進行測試 (Strands 代理程式需要 AWS 登入資料):

    docker run --platform linux/arm64 -p 8080:8080 \ -e AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" \ -e AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" \ -e AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN" \ -e AWS_REGION="$AWS_REGION" \ my-agent:arm64

建立 ECR 儲存庫並部署

部署至 ECR

  1. 建立 ECR 儲存庫:

    aws ecr create-repository --repository-name my-strands-agent --region us-west-2
  2. 登入 ECR:

    aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin account-id.dkr.ecr.us-west-2.amazonaws.com
  3. 建置並推送至 ECR:

    docker buildx build --platform linux/arm64 -t account-id.dkr.ecr.us-west-2.amazonaws.com/my-strands-agent:latest --push.
  4. 確認已推送映像:

    aws ecr describe-images --repository-name my-strands-agent --region us-west-2

部署代理程式執行時間

建立名為 deploy_agent.py 且具有下列內容的檔案:

範例 deploy_agent.py

import boto3 client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') response = client.create_agent_runtime( agentRuntimeName='strands_agent', agentRuntimeArtifact={ 'containerConfiguration': { 'containerUri': 'account-id.dkr.ecr.us-west-2.amazonaws.com/my-strands-agent:latest' } }, networkConfiguration={"networkMode": "PUBLIC"}, roleArn='arn:aws:iam::account-id:role/AgentRuntimeRole', lifecycleConfiguration={ 'idleRuntimeSessionTimeout': 300, # 5 min, configurable 'maxLifetime': 1800 # 30 minutes, configurable }, ) print(f"Agent Runtime created successfully!") print(f"Agent Runtime ARN: {response['agentRuntimeArn']}") print(f"Status: {response['status']}")

執行指令碼以部署您的代理程式:

uv run deploy_agent.py

此指令碼使用 create_agent_runtime操作將您的代理程式部署到 Amazon Bedrock AgentCore。請務必將 account-id 取代為您的實際 AWS 帳戶 ID,並確保 IAM 角色具有必要的許可。如需詳細資訊,請參閱 AgentCore 執行期的 IAM 許可

調用您的代理程式

建立名為 invoke_agent.py 且具有下列內容的檔案:

範例 invoke_agent.py

import boto3 import json agent_core_client = boto3.client('bedrock-agentcore', region_name='us-west-2') payload = json.dumps({ "input": {"prompt": "Explain machine learning in simple terms"} }) response = agent_core_client.invoke_agent_runtime( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:account-id:runtime/myStrandsAgent-suffix', runtimeSessionId='dfmeoagmreaklgmrkleafremoigrmtesogmtrskhmtkrlshmt', # Must be 33+ chars payload=payload, qualifier="DEFAULT" ) response_body = response['response'].read() response_data = json.loads(response_body) print("Agent Response:", response_data)

執行指令碼以叫用您的代理程式:

uv run invoke_agent.py

此指令碼使用 InvokeAgentRuntime AWS SDK 操作,將請求傳送至您部署的代理程式。請務必將 account-idagentArn 取代為您的實際值。

如果您打算將代理程式與 OAuth 整合,則無法使用 AWS SDK 呼叫 InvokeAgentRuntime 。請改為向 InvokeAgentRuntime 提出 HTTPS 請求。如需詳細資訊,請參閱使用傳入身分驗證和傳出身分驗證進行身分驗證和授權

預期的回應格式

當您叫用代理程式時,您會收到類似以下的回應:

範例回應

{ "output": { "message": { "role": "assistant", "content": [ { "text": "# Artificial Intelligence in Simple Terms\n\nArtificial Intelligence (AI) is technology that allows computers to do tasks that normally need human intelligence. Think of it as teaching machines to:\n\n- Learn from information (like how you learn from experience)\n- Make decisions based on what they've learned\n- Recognize patterns (like identifying faces in photos)\n- Understand language (like when I respond to your questions)\n\nInstead of following specific step-by-step instructions for every situation, AI systems can adapt to new information and improve over time.\n\nExamples you might use every day include voice assistants like Siri, recommendation systems on streaming services, and email spam filters that learn which messages are unwanted." } ] }, "timestamp": "2025-07-13T01:48:06.740668" } }

停止執行階段工作階段

若要在可設定 IdleRuntimeSessionTimeout(預設為 15 分鐘) 之前停止執行中的工作階段,並節省任何潛在的失控成本,請執行: stop_runtime_session

建立名為 stop_runtime_session.py 且具有下列內容的檔案:

stop_runtime_session.py 範例

import boto3 agent_core_client = boto3.client('bedrock-agentcore', region_name='us-west-2') response = agent_core_client.stop_runtime_session( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:account-id:runtime/myStrandsAgent-suffix', runtimeSessionId='dfmeoagmreaklgmrkleafremoigrmtesogmtrskhmtkrlshmt', qualifier="DEFAULT" )

Amazon Bedrock AgentCore 需求摘要

  • 平台 :必須是 linux/arm64

  • 端點:POST /invocations/ping GET 是強制性的

  • ECR:映像必須部署到 ECR

  • 連接埠 :應用程式在連接埠 8080 上執行

  • Strands Integration :使用 Strands Agent 進行 AI 處理

  • 登入資料:Strands 代理程式需要 AWS 登入資料才能操作

結論

在本指南中,您已了解如何:

  • 設定開發環境以建置自訂代理程式

  • 建立實作所需端點的 FastAPI 應用程式

  • 容器化 ARM64 架構的代理程式

  • 在本機測試您的代理程式

  • 將您的代理程式部署到 ECR

  • 在 Amazon Bedrock AgentCore 中建立代理程式執行時間

  • 叫用您部署的代理程式

  • 停止代理程式執行期工作階段

遵循這些步驟,您可以建立和部署自訂代理程式,利用 Amazon Bedrock AgentCore 的強大功能,同時保持對代理程式實作的完全控制。