Python 스트랜드 에이전트
도구를 갖춘 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-agent
yarn nx g @aws/nx-plugin:py#strands-agent
npx nx g @aws/nx-plugin:py#strands-agent
bunx nx g @aws/nx-plugin:py#strands-agent
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:py#strands-agent --dry-run
yarn nx g @aws/nx-plugin:py#strands-agent --dry-run
npx nx g @aws/nx-plugin:py#strands-agent --dry-run
bunx 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 | CDK | The preferred IaC provider |
생성기 출력 결과
섹션 제목: “생성기 출력 결과”생성기는 기존 Python 프로젝트에 다음 파일들을 추가합니다:
디렉터리your-project/
디렉터리your_module/
디렉터리agent/ (지정한 경우 사용자 정의 이름 사용)
- __init__.py Python 패키지 초기화
- 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"{city}의 날씨: 맑음, 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 문서를 참조하세요.
Bedrock AgentCore Python SDK
섹션 제목: “Bedrock AgentCore Python SDK”생성기는 AgentCore의 에이전트가 구현해야 하는 기본 HTTP 계약을 관리하기 위해 Bedrock AgentCore Python SDK를 구성합니다.
SDK 기능에 대한 자세한 내용은 공식 문서에서 확인할 수 있습니다.
Strands 에이전트 실행하기
섹션 제목: “Strands 에이전트 실행하기”로컬 개발 환경
섹션 제목: “로컬 개발 환경”생성기는 <your-agent-name>-serve
타겟을 구성하여 개발 및 테스트를 위해 Strands 에이전트를 로컬에서 시작합니다.
pnpm nx run your-project:agent-serve
yarn nx run your-project:agent-serve
npx nx run your-project:agent-serve
bunx 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 또는 테라폼 인프라가 생성됩니다.
생성기는 기본적으로 name
으로 선택한 이름 또는 <ProjectName>Agent
를 기반으로 CDK 구문을 생성합니다.
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 런타임 계약에 따라 에이전트를 실행하는 도커 이미지 빌드
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}
관측성
섹션 제목: “관측성”에이전트는 Dockerfile
에 자동 계측을 구성하여 AWS Distro for Open Telemetry(ADOT)를 사용해 관측성이 자동으로 구성됩니다.
CloudWatch AWS 콘솔에서 “GenAI Observability”를 선택해 추적을 확인할 수 있습니다. 추적이 표시되려면 트랜잭션 검색을 활성화해야 합니다.
자세한 내용은 AgentCore 관측성 문서를 참조하세요.