콘텐츠로 이동

Python 스트랜드 에이전트

도구를 갖춘 AI 에이전트를 구축하고 선택적으로 Amazon Bedrock AgentCore Runtime에 배포할 수 있는 Python Strands Agent를 생성합니다.

Strands는 AI 에이전트 구축을 위한 가볍고 프로덕션 준비가 된 Python 프레임워크입니다. 주요 기능은 다음과 같습니다:

  • 가볍고 사용자 정의 가능: 간단한 에이전트 루프로 개발자의 작업을 방해하지 않음
  • 프로덕션 준비 완료: 완전한 관측성, 추적 및 확장을 위한 배포 옵션
  • 모델 및 제공자 독립적: 다양한 제공자의 여러 모델 지원
  • 커뮤니티 주도 도구: 커뮤니티에서 기여한 강력한 도구 세트
  • 다중 에이전트 지원: 에이전트 팀과 자율 에이전트 같은 고급 기법
  • 유연한 상호작용 모드: 대화형, 스트리밍 및 비스트리밍 지원

다음 두 가지 방법으로 Python Strands 에이전트를 생성할 수 있습니다:

  1. 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
  2. VSCode에서 Nx 콘솔 열기
  3. 클릭 Generate (UI) "Common Nx Commands" 섹션에서
  4. 검색 @aws/nx-plugin - py#strands-agent
  5. 필수 매개변수 입력
    • 클릭 Generate
    매개변수 타입 기본값 설명
    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 에이전트 호스팅용 도커 파일 (computeTypeNone으로 설정된 경우 제외)
      • pyproject.toml Strands 종속성으로 업데이트
      • project.json 에이전트 서빙 타겟으로 업데이트

    이 생성기는 선택한 iacProvider 기반으로 인프라를 코드 형태로 제공하므로, packages/common 디렉터리에 관련 CDK 구축 요소 또는 Terraform 모듈을 포함하는 프로젝트를 생성합니다.

    공통 인프라스트럭처 코드 프로젝트의 구조는 다음과 같습니다:

    • 디렉터리packages/common/constructs
      • 디렉터리src
        • 디렉터리app/ 특정 프로젝트/생성기에 종속적인 인프라를 위한 구축 요소
        • 디렉터리core/ app 내 구축 요소에서 재사용되는 일반적 구축 요소
        • index.ts 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 구문

    도구는 AI 에이전트가 작업 수행을 위해 호출할 수 있는 함수입니다. Strands 프레임워크는 도구 정의를 위해 간단한 데코레이터 기반 접근 방식을 사용합니다.

    agent.py 파일에 새 도구를 추가할 수 있습니다:

    from strands import Agent, tool
    @tool
    def calculate_sum(numbers: list[int]) -> int:
    """리스트 내 숫자들의 합계 계산"""
    return sum(numbers)
    @tool
    def 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 Agent
    from 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)

    Strands 에이전트에 MCP 서버의 도구를 추가할 수 있습니다.

    py#mcp-server 또는 ts#mcp-server 생성기(또는 Bedrock AgentCore Runtime에 호스팅된 기타 서버)를 사용해 생성한 MCP 서버를 활용하려면 agentcore_mcp_client.py에 클라이언트 팩토리가 생성됩니다.

    agent.pyget_agent 메서드를 업데이트하여 MCP 클라이언트를 생성하고 도구를 추가할 수 있습니다. 다음 예제는 IAM(SigV4) 인증을 사용하는 방법을 보여줍니다:

    agent.py
    import os
    from contextlib import contextmanager
    import boto3
    from 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()
    @contextmanager
    def 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);
    }
    }

    Strands 에이전트 작성에 대한 더 자세한 가이드는 Strands 문서를 참조하세요.

    생성기는 AgentCore의 에이전트가 구현해야 하는 기본 HTTP 계약을 관리하기 위해 Bedrock AgentCore Python SDK를 구성합니다.

    SDK 기능에 대한 자세한 내용은 공식 문서에서 확인할 수 있습니다.

    생성기는 <your-agent-name>-serve 타겟을 구성하여 개발 및 테스트를 위해 Strands 에이전트를 로컬에서 시작합니다.

    Terminal window
    pnpm 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/*'],
    }),
    );
    }
    }

    Bedrock AgentCore Runtime용 Strands 에이전트 빌드를 위해 프로젝트에 bundle 타겟이 추가됩니다. 이 타겟은 다음을 수행합니다:

    • uv export를 사용해 Python 종속성을 requirements.txt 파일로 내보내기
    • 대상 플랫폼(aarch64-manylinux2014)용 종속성 설치를 위해 uv pip install 사용

    또한 Strands 에이전트 전용 docker 타겟이 추가되어 다음을 수행합니다:

    기본적으로 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);
    }
    }

    다음은 에이전트에 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],
    },
    },
    });
    }
    }

    에이전트는 Dockerfile에 자동 계측을 구성하여 AWS Distro for Open Telemetry(ADOT)를 사용해 관측성이 자동으로 구성됩니다.

    CloudWatch AWS 콘솔에서 “GenAI Observability”를 선택해 추적을 확인할 수 있습니다. 추적이 표시되려면 트랜잭션 검색을 활성화해야 합니다.

    자세한 내용은 AgentCore 관측성 문서를 참조하세요.