파이썬 스트랜드 에이전트
도구를 갖춘 AI 에이전트를 구축하고 Amazon Bedrock AgentCore Runtime에 배포할 수 있는 Python Strands Agent를 생성합니다.
Strands란?
섹션 제목: “Strands란?”Strands는 AI 에이전트 구축을 위한 가볍고 프로덕션 준비가 된 Python 프레임워크입니다. 주요 기능은 다음과 같습니다:
- 가볍고 사용자 정의 가능: 간단한 에이전트 루프로 개발자 방해 최소화
- 프로덕션 준비 완료: 완전한 관측성, 추적 및 확장을 위한 배포 옵션
- 모델 및 제공자 독립적: 다양한 제공자의 여러 모델 지원
- 커뮤니티 주도 도구: 강력한 커뮤니티 기여 도구 세트
- 다중 에이전트 지원: 에이전트 팀 및 자율 에이전트와 같은 고급 기법
- 유연한 상호작용 모드: 대화형, 스트리밍 및 비스트리밍 지원
사용 방법
섹션 제목: “사용 방법”Strands 에이전트 생성
섹션 제목: “Strands 에이전트 생성”두 가지 방법으로 Python Strands 에이전트를 생성할 수 있습니다:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - py#strands-agent - 필수 매개변수 입력
- 클릭
Generate
pnpm nx g @aws/nx-plugin:py#strands-agentyarn nx g @aws/nx-plugin:py#strands-agentnpx nx g @aws/nx-plugin:py#strands-agentbunx nx g @aws/nx-plugin:py#strands-agent어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:py#strands-agent --dry-runyarn nx g @aws/nx-plugin:py#strands-agent --dry-runnpx nx g @aws/nx-plugin:py#strands-agent --dry-runbunx nx g @aws/nx-plugin:py#strands-agent --dry-run| 매개변수 | 타입 | 기본값 | 설명 |
|---|---|---|---|
| project 필수 | string | - | The project to add the Strands Agent to |
| computeType | string | BedrockAgentCoreRuntime | The type of compute to host your Strands Agent. |
| name | string | - | The name of your Strands Agent (default: agent) |
| iacProvider | string | Inherit | The preferred IaC provider. By default this is inherited from your initial selection. |
생성기 출력
섹션 제목: “생성기 출력”생성기는 기존 Python 프로젝트에 다음 파일들을 추가합니다:
디렉터리your-project/
디렉터리your_module/
디렉터리agent/ (지정한 경우 사용자 정의 이름 사용)
- __init__.py 파이썬 패키지 초기화
- agent.py 샘플 도구가 포함된 주요 에이전트 정의
- main.py Bedrock AgentCore Runtime용 진입점
- agentcore_mcp_client.py Bedrock AgentCore Runtime에 호스팅된 MCP 서버 호출에 유용한 클라이언트 팩토리
- Dockerfile 에이전트 호스팅용 도커 파일 (
computeType이None으로 설정된 경우 제외)
- pyproject.toml Strands 종속성으로 업데이트
- project.json 에이전트 서빙 타겟으로 업데이트
인프라
섹션 제목: “인프라”이 생성기는 선택한 iacProvider 기반으로 인프라를 코드 형태로 제공하므로, packages/common 디렉터리에 관련 CDK 구축 요소 또는 Terraform 모듈을 포함하는 프로젝트를 생성합니다.
공통 인프라스트럭처 코드 프로젝트의 구조는 다음과 같습니다:
디렉터리packages/common/constructs
디렉터리src
디렉터리app/ 특정 프로젝트/생성기에 종속적인 인프라를 위한 구축 요소
- …
디렉터리core/
app내 구축 요소에서 재사용되는 일반적 구축 요소- …
- index.ts
app의 구축 요소를 익스포트하는 진입점
- project.json 프로젝트 빌드 대상 및 구성
디렉터리packages/common/terraform
디렉터리src
디렉터리app/ 특정 프로젝트/생성기 전용 Terraform 모듈
- …
디렉터리core/
app내 모듈에서 재사용되는 일반적 모듈- …
- project.json 프로젝트 빌드 대상 및 구성
Strands 에이전트 배포를 위해 다음 파일들이 생성됩니다:
디렉터리packages/common/constructs/src
디렉터리app
디렉터리agents
디렉터리<project-name>
- <project-name>.ts 에이전트 배포용 CDK 컨스트럭트
- Dockerfile CDK 컨스트럭트에서 사용하는 도커 파일
디렉터리core
디렉터리agent-core
- runtime.ts Bedrock AgentCore Runtime 배포용 일반 CDK 컨스트럭트
디렉터리packages/common/terraform/src
디렉터리app
디렉터리agents
디렉터리<project-name>
- <project-name>.tf 에이전트 배포용 테라폼 모듈
디렉터리core
디렉터리agent-core
- runtime.tf Bedrock AgentCore Runtime 배포용 일반 모듈
Strands 에이전트 작업
섹션 제목: “Strands 에이전트 작업”도구 추가
섹션 제목: “도구 추가”도구는 AI 에이전트가 작업 수행을 위해 호출할 수 있는 함수입니다. Strands 프레임워크는 도구 정의를 위해 간단한 데코레이터 기반 접근 방식을 사용합니다.
agent.py 파일에 새 도구를 추가할 수 있습니다:
from strands import Agent, tool
@tooldef calculate_sum(numbers: list[int]) -> int: """숫자 리스트의 합계 계산""" return sum(numbers)
@tooldef get_weather(city: str) -> str: """도시의 날씨 정보 조회""" # 날씨 API 통합 구현 return f"Weather in {city}: Sunny, 25°C"
# 에이전트에 도구 추가agent = Agent( system_prompt="다양한 도구에 접근 가능한 유용한 어시스턴트입니다.", tools=[calculate_sum, get_weather],)Strands 프레임워크는 다음을 자동으로 처리합니다:
- 함수 타입 힌트 기반 타입 검증
- 도구 호출을 위한 JSON 스키마 생성
- 오류 처리 및 응답 포맷팅
사전 제작 도구 사용
섹션 제목: “사전 제작 도구 사용”Strands는 strands-tools 패키지를 통해 사전 제작된 도구 컬렉션을 제공합니다:
from strands_tools import current_time, http_request, file_read
agent = Agent( system_prompt="유용한 어시스턴트입니다.", tools=[current_time, http_request, file_read],)모델 구성
섹션 제목: “모델 구성”기본적으로 Strands 에이전트는 Claude 4 Sonnet을 사용하지만 모델 제공자를 사용자 정의할 수 있습니다. 구성 옵션은 Strands 모델 제공자 문서를 참조하세요:
from strands import Agentfrom strands.models import BedrockModel
# BedrockModel 생성bedrock_model = BedrockModel( model_id="anthropic.claude-sonnet-4-20250514-v1:0", region_name="us-west-2", temperature=0.3,)
agent = Agent(model=bedrock_model)MCP 서버 사용
섹션 제목: “MCP 서버 사용”Strands 에이전트에 MCP 서버 도구 추가가 가능합니다.
py#mcp-server 또는 ts#mcp-server 생성기(또는 Bedrock AgentCore Runtime에 호스팅된 기타 서버)를 사용하여 생성한 MCP 서버의 경우, agentcore_mcp_client.py에 클라이언트 팩토리가 생성됩니다.
agent.py의 get_agent 메서드를 업데이트하여 MCP 클라이언트를 생성하고 도구를 추가할 수 있습니다. 다음 예제는 IAM(SigV4) 인증을 사용하는 방법을 보여줍니다:
import osfrom contextlib import contextmanager
import boto3from strands import Agent
from .agentcore_mcp_client import AgentCoreMCPClient
# 리전 및 자격 증명 획득region = os.environ["AWS_REGION"]boto_session = boto3.Session(region_name=region)credentials = boto_session.get_credentials()
@contextmanagerdef get_agent(session_id: str): mcp_client = AgentCoreMCPClient.with_iam_auth( agent_runtime_arn=os.environ["MCP_AGENTCORE_RUNTIME_ARN"], credentials=credentials, region=region, session_id=session_id, )
with mcp_client: mcp_tools = mcp_client.list_tools_sync()
yield Agent( system_prompt="..." tools=[*mcp_tools], )위 IAM 인증 예제를 사용하려면 인프라스트럭처에서 두 가지를 구성해야 합니다. 먼저 MCP 서버의 AgentCore Runtime ARN을 위한 환경 변수를 추가하고, 두 번째로 에이전트에 MCP 서버 호출 권한을 부여해야 합니다. 이는 다음과 같이 구현할 수 있습니다:
import { MyProjectAgent, MyProjectMcpServer } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const mcpServer = new MyProjectMcpServer(this, 'MyProjectMcpServer');
const agent = new MyProjectAgent(this, 'MyProjectAgent', { environment: { MCP_AGENTCORE_RUNTIME_ARN: mcpServer.agentCoreRuntime.arn, }, });
mcpServer.agentCoreRuntime.grantInvoke(agent.agentCoreRuntime); }}# MCP 서버module "my_project_mcp_server" { source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"}
# 에이전트module "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
env = { MCP_AGENTCORE_RUNTIME_ARN = module.my_project_mcp_server.agent_core_runtime_arn }
additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_mcp_server.agent_core_runtime_arn, "${module.my_project_mcp_server.agent_core_runtime_arn}/*" ] } ]}추가 정보
섹션 제목: “추가 정보”Strands 에이전트 작성에 대한 심층 가이드는 Strands 문서를 참조하세요.
FastAPI 서버
섹션 제목: “FastAPI 서버”생성기는 FastAPI를 사용하여 Strands 에이전트용 HTTP 서버를 생성합니다. FastAPI는 자동 API 문서화 및 타입 검증 기능을 갖춘 Python API 구축을 위한 현대적이고 빠른 웹 프레임워크를 제공합니다.
생성된 서버에는 다음이 포함됩니다:
- CORS 미들웨어가 포함된 FastAPI 애플리케이션 설정
- 오류 처리 미들웨어
- OpenAPI 스키마 생성
- 헬스 체크 엔드포인트 (
/ping) - 에이전트 호출 엔드포인트 (
/invocations)
Pydantic을 사용한 호출 입력 및 출력 사용자 정의
섹션 제목: “Pydantic을 사용한 호출 입력 및 출력 사용자 정의”에이전트의 호출 엔드포인트는 Pydantic 모델을 사용하여 요청 및 응답 스키마를 정의하고 검증합니다. main.py에서 이러한 모델을 에이전트의 요구사항에 맞게 사용자 정의할 수 있습니다.
입력 모델 정의
섹션 제목: “입력 모델 정의”기본 InvokeInput 모델은 프롬프트와 세션 ID를 받습니다.
from pydantic import BaseModel
class InvokeInput(BaseModel): prompt: str session_id: str에이전트에 필요한 추가 필드를 포함하도록 이 모델을 확장할 수 있습니다.
출력 모델 정의
섹션 제목: “출력 모델 정의”스트리밍 응답의 경우 엔드포인트의 반환 타입 어노테이션은 생성기 함수가 yield하는 각 값의 타입에 해당합니다. 기본적으로 에이전트는 Strands에서 스트리밍되는 에이전트의 응답 텍스트를 포함하는 문자열을 yield합니다:
@app.post("/invocations", openapi_extra={"x-streaming": True})async def invoke(input: InvokeInput) -> str: """Entry point for agent invocation""" return StreamingResponse(handle_invoke(input), media_type="text/event-stream")구조화된 데이터를 yield하도록 Pydantic 모델을 정의할 수 있습니다:
from pydantic import BaseModel
class StreamChunk(BaseModel): content: str timestamp: str token_count: int
@app.post("/invocations", openapi_extra={"x-streaming": True})async def invoke(input: InvokeInput) -> StreamChunk: return StreamingResponse(handle_invoke(input), media_type="application/json")Bedrock AgentCore Python SDK
섹션 제목: “Bedrock AgentCore Python SDK”생성기는 PingStatus 상수를 위해 Bedrock AgentCore Python SDK에 대한 종속성을 포함합니다. 원하는 경우 FastAPI 대신 BedrockAgentCoreApp을 사용하는 것도 간단하지만, 타입 안전성이 손실된다는 점에 유의하세요.
SDK 기능에 대한 자세한 내용은 문서에서 확인할 수 있습니다.
Strands 에이전트 실행
섹션 제목: “Strands 에이전트 실행”로컬 개발
섹션 제목: “로컬 개발”생성기는 개발 및 테스트를 위해 Strands 에이전트를 로컬에서 시작하는 <your-agent-name>-serve 타겟을 구성합니다.
pnpm nx run your-project:agent-serveyarn nx run your-project:agent-servenpx nx run your-project:agent-servebunx nx run your-project:agent-serve이 명령은 Bedrock AgentCore Python SDK를 사용하여 Strands 에이전트를 실행하기 위해 uv run을 사용합니다.
Bedrock AgentCore Runtime에 Strands 에이전트 배포
섹션 제목: “Bedrock AgentCore Runtime에 Strands 에이전트 배포”인프라스트럭처 코드
섹션 제목: “인프라스트럭처 코드”computeType으로 BedrockAgentCoreRuntime을 선택한 경우 Amazon Bedrock AgentCore Runtime에 Strands 에이전트를 배포하는 데 필요한 CDK 또는 Terraform 인프라가 생성됩니다.
생성기 실행 시 선택한 name을 기반으로 이름이 지정된 CDK 컨스트럭트를 생성합니다(기본값은 <ProjectName>Agent).
CDK 애플리케이션에서 이 CDK 컨스트럭트를 사용할 수 있습니다:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // 스택에 에이전트 추가 const agent = new MyProjectAgent(this, 'MyProjectAgent');
// Bedrock 관련 모델 호출 권한 부여 agent.agentCoreRuntime.role.addToPolicy( new PolicyStatement({ actions: [ 'bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream', ], // 사용하는 특정 모델로 범위 축소 가능 resources: ['arn:aws:bedrock:*::foundation-model/*'], }), ); }}생성기 실행 시 선택한 name을 기반으로 이름이 지정된 테라폼 모듈을 생성합니다(기본값은 <ProjectName>-agent).
테라폼 프로젝트에서 이 모듈을 사용할 수 있습니다:
# 에이전트module "my_project_agent" { # common/terraform 프로젝트 내 생성된 모듈 상대 경로 source = "../../common/terraform/src/app/agents/my-project-agent"
# Bedrock 관련 모델 호출 권한 부여 additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ] Resource = [ "arn:aws:bedrock:*::foundation-model/*" ] } ]}번들 및 도커 타겟
섹션 제목: “번들 및 도커 타겟”Bedrock AgentCore Runtime용 Strands 에이전트 빌드를 위해 프로젝트에 bundle 타겟이 추가됩니다. 이 타겟은:
uv export를 사용하여 Python 종속성을requirements.txt파일로 내보냄- 대상 플랫폼(
aarch64-manylinux2014)용 종속성을uv pip install로 설치
또한 Strands 에이전트 전용 docker 타겟이 추가되어:
- AgentCore 런타임 계약에 따라 에이전트를 실행하는
Dockerfile에서 도커 이미지 빌드
IAM
섹션 제목: “IAM”기본적으로 Strands 에이전트는 IAM 인증으로 보호되며, 인수 없이 배포할 수 있습니다:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}에이전트 호출 권한을 부여하려면 grantInvoke 메서드를 사용할 수 있습니다. 예시:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent'); const lambdaFunction = new Function(this, ...);
agent.agentCoreRuntime.grantInvoke(lambdaFunction); }}# 에이전트module "my_project_agent" { # common/terraform 프로젝트 내 생성된 모듈 상대 경로 source = "../../common/terraform/src/app/agents/my-project-agent"}에이전트 호출 권한을 부여하려면 module.my_project_agent.agent_core_runtime_arn 출력을 참조하는 다음과 같은 정책을 추가해야 합니다:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_agent.agent_core_runtime_arn, "${module.my_project_agent.agent_core_runtime_arn}/*" ]}Cognito JWT 인증
섹션 제목: “Cognito JWT 인증”다음은 에이전트에 Cognito 인증을 구성하는 방법을 보여줍니다.
JWT 인증을 구성하려면 에이전트 컨스트럭트에 authorizerConfiguration 속성을 전달할 수 있습니다. 다음은 Cognito 사용자 풀 및 클라이언트를 구성하여 에이전트를 보호하는 예시입니다:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const userPool = new UserPool(this, 'UserPool'); const client = userPool.addClient('Client', { authFlows: { userPassword: true, }, });
new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: { customJwtAuthorizer: { discoveryUrl: `https://cognito-idp.${Stack.of(userPool).region}.amazonaws.com/${userPool.userPoolId}/.well-known/openid-configuration`, allowedClients: [client.userPoolClientId], }, }, }); }}JWT 인증을 구성하려면 에이전트 모듈의 customJWTAuthorizer 변수를 다음과 같이 편집할 수 있습니다:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.name
# 사용자 풀 및 클라이언트 ID로 교체하거나 변수로 노출 user_pool_id = "xxx" user_pool_client_ids = ["yyy"]}
module "agent_core_runtime" { source = "../../../core/agent-core" agent_runtime_name = "MyProjectAgent" docker_image_tag = "my-scope-my-project-agent:latest" server_protocol = "HTTP" customJWTAuthorizer = { discoveryUrl = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration", allowedClients = local.user_pool_client_ids } env = var.env additional_iam_policy_statements = var.additional_iam_policy_statements tags = var.tags}관측성
섹션 제목: “관측성”에이전트는 AWS Distro for Open Telemetry(ADOT)를 사용하여 Dockerfile의 자동 계측 구성으로 관측성이 자동 구성됩니다.
CloudWatch AWS 콘솔에서 “GenAI Observability”를 선택하여 추적을 찾을 수 있습니다. 추적이 표시되려면 트랜잭션 검색을 활성화해야 합니다.
자세한 내용은 AgentCore 관측성 문서를 참조하세요.