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 트랜잭션 검색을 활성화합니다. AgentCore
uv 설치
이 예제에서는 Python 유틸리티 또는 uv 패키지 관리자를 사용할 수 있지만 패키지 관리자를 사용합니다. macOSuv에를 설치하려면:
curl -LsSf https://astral.sh/uv/install.sh | sh
다른 플랫폼에 대한 설치 지침은 uv 설명서를
에이전트 프로젝트 생성
프로젝트 설정
-
프로젝트 디렉터리를 생성하고 해당 디렉터리로 이동합니다.
mkdir my-custom-agent && cd my-custom-agent -
Python 3.11을 사용하여 프로젝트를 초기화합니다.
uv init --python 3.11 -
필요한 종속성을 추가합니다(uv는 .venv를 자동으로 생성).
uv add fastapi 'uvicorn[standard]' pydantic httpx strands-agents
에이전트 계약 요구 사항
사용자 지정 에이전트는 다음과 같은 핵심 요구 사항을 충족해야 합니다.
-
/invocations 엔드포인트: 에이전트 상호 작용을 위한 POST 엔드포인트(필수)
-
/ping 엔드포인트: 상태 확인을 위한 GET 엔드포인트(필수)
-
Docker 컨테이너: ARM64 컨테이너화된 배포 패키지
프로젝트 구조
참고: 편의를 위해 아래 예제에서는 FastAPI 서버를 요청을 처리하기 위한 웹 서버 프레임워크로 사용합니다.
프로젝트에는 다음과 같은 구조가 있어야 합니다.
my-custom-agent/ ├── agent.py # FastAPI application ├── Dockerfile # ARM64 container configuration ├── pyproject.toml # Created by uv init └── uv.lock # Created automatically by uv
전체 스트랜드 에이전트 예제
다음 콘텐츠를 사용하여 프로젝트 루트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 에이전트를 초기화합니다.
-
에이전트 상호 작용을 위한
/invocationsPOST 엔드포인트를 구현합니다. -
상태 확인을 위한
/pingGET 엔드포인트를 구현합니다. -
호스트
0.0.0.0및 포트에서 실행되도록 서버를 구성합니다.8080
로컬에서 테스트
에이전트 테스트
-
애플리케이션을 실행합니다.
uv run uvicorn agent:app --host 0.0.0.0 --port 8080 -
/ping엔드포인트 테스트(다른 터미널에서):curl http://localhost:8080/ping -
/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용 빌드 및 로컬 테스트
이미지 빌드 및 테스트
-
테스트를 위해 로컬에서 이미지를 빌드합니다.
docker buildx build --platform linux/arm64 -t my-agent:arm64 --load. -
자격 증명을 사용하여 로컬에서 테스트합니다(스트랜드 에이전트에 자격 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에 배포
-
ECR 리포지토리 생성:
aws ecr create-repository --repository-name my-strands-agent --region us-west-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 -
빌드 및 ECR로 푸시:
docker buildx build --platform linux/arm64 -t account-id.dkr.ecr.us-west-2.amazonaws.com/my-strands-agent:latest --push. -
이미지가 푸시되었는지 확인합니다.
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-id 및 agentArn을 실제 값으로 바꿔야 합니다.
에이전트를 OAuth와 통합하려는 경우 AWS SDK를 사용하여 InvokeAgentRuntime를 호출할 수 없습니다. 대신 InvokeAgentRuntime에 HTTPS를 요청합니다. 자세한 내용은 Authenticate and authorize with Inbound Auth and Outbound Auth를 참조하세요.
예상 응답 형식
에이전트를 호출하면 다음과 같은 응답을 받게 됩니다.
예제 샘플 응답
{ "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 -
엔드포인트:
/invocationsPOST 및/pingGET은 필수입니다. -
ECR : 이미지를 ECR에 배포해야 합니다.
-
포트 : 애플리케이션이 포트 8080에서 실행됨
-
Strands 통합: AI 처리에 Strands 에이전트 사용
-
자격 증명: Strands 에이전트는 작업을 위해 AWS 자격 증명이 필요합니다.
결론
이 가이드에서는 다음을 수행하는 방법을 배웠습니다.
-
사용자 지정 에이전트를 빌드하기 위한 개발 환경 설정
-
필요한 엔드포인트를 구현하는 FastAPI 애플리케이션 생성
-
ARM64 아키텍처를 위한 에이전트 컨테이너화
-
로컬에서 에이전트 테스트
-
ECR에 에이전트 배포
-
Amazon Bedrock AgentCore에서 에이전트 런타임 생성
-
배포된 에이전트 간접 호출
-
에이전트 런타임 세션 중지
이 단계에 따라 에이전트의 구현을 완전히 제어하면서 Amazon Bedrock AgentCore의 성능을 활용하는 사용자 지정 에이전트를 생성하고 배포할 수 있습니다.