파이썬 스트랜드 에이전트
도구를 갖춘 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 컨스트럭트에서 사용하는 도커 파일
디렉터리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', { environmentVariables: { MCP_AGENTCORE_RUNTIME_ARN: mcpServer.agentCoreRuntime.agentRuntimeArn, }, });
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 모델을 정의할 수 있습니다. 이를 위해서는 handle_invoke가 yield하는 pydantic 모델을 직렬화해야 합니다:
from pydantic import BaseModel
class StreamChunk(BaseModel): content: str timestamp: str token_count: int
def handle_invoke(...): ... yield StreamChunk(content="xx", timestamp="yy", token_count=5)
def serialize_stream(generator): async for output in generator: yield (output.model_dump_json() + "\n").encode("utf-8")
@app.post("/invocations", openapi_extra={"x-streaming": True})async def invoke(input: InvokeInput) -> StreamChunk: return StreamingResponse(serialize_stream(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 에이전트 배포”Infrastructure as Code
섹션 제목: “Infrastructure as Code”computeType에 대해 BedrockAgentCoreRuntime을 선택한 경우, Strands Agent를 Amazon Bedrock AgentCore Runtime에 배포하는 데 사용할 수 있는 관련 CDK 또는 Terraform 인프라가 생성됩니다.
에이전트에 대한 CDK 구성이 생성되며, 생성기를 실행할 때 선택한 name을 기반으로 이름이 지정되거나 기본적으로 <ProjectName>Agent로 지정됩니다.
CDK 애플리케이션에서 이 CDK 구성을 사용할 수 있습니다:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Add the agent to your stack const agent = new MyProjectAgent(this, 'MyProjectAgent');
// Grant permissions to invoke the relevant models in bedrock agent.agentCoreRuntime.addToRolePolicy( new PolicyStatement({ actions: [ 'bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream', ], // You can scope the below down to the specific models you use resources: [ 'arn:aws:bedrock:*:*:foundation-model/*', 'arn:aws:bedrock:*:*:inference-profile/*', ], }), ); }}Terraform 모듈이 생성되며, 생성기를 실행할 때 선택한 name을 기반으로 이름이 지정되거나 기본적으로 <ProjectName>-agent로 지정됩니다.
Terraform 프로젝트에서 이 terraform 모듈을 사용할 수 있습니다:
# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"
# Grant permissions to invoke the relevant models in bedrock additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ] # You can scope the below down to the specific models you use Resource = [ "arn:aws:bedrock:*:*:foundation-model/*", "arn:aws:bedrock:*:*:inference-profile/*" ] } ]}IAM
섹션 제목: “IAM”기본적으로 Strands Agent는 IAM 인증을 사용하여 보호되며, 인수 없이 간단히 배포할 수 있습니다:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}grantInvoke 메서드를 사용하여 Bedrock AgentCore Runtime에서 에이전트를 호출할 수 있는 액세스 권한을 부여할 수 있습니다. 예를 들어:
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); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project 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 인증을 구성하는 방법을 보여줍니다.
Cognito를 사용하여 JWT 인증을 구성하려면 RuntimeAuthorizerConfiguration.usingCognito() 팩토리 메서드를 사용하세요:
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
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: RuntimeAuthorizerConfiguration.usingCognito( userPool, [client], ), }); }}또는 자체 OIDC 공급자를 사용하는 사용자 지정 JWT 인증의 경우 RuntimeAuthorizerConfiguration.usingJWT()를 사용하세요:
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingJWT( 'https://example.com/.well-known/openid-configuration', ['client1', 'client2'], // Allowed Client IDs (optional) ['audience1'], // Allowed Audiences (optional) ), }); }}JWT 인증을 구성하려면 다음과 같이 authorizer_configuration 변수를 구성하도록 에이전트 모듈을 편집할 수 있습니다:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.id
# Replace with your user pool and client ids or expose as variables 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" authorizer_configuration = { custom_jwt_authorizer = { discovery_url = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration" allowed_clients = local.user_pool_client_ids } } env = var.env additional_iam_policy_statements = var.additional_iam_policy_statements tags = var.tags}번들 및 도커 타겟
섹션 제목: “번들 및 도커 타겟”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 인증을 구성하는 방법을 보여줍니다.
Cognito를 사용한 JWT 인증을 구성하려면 RuntimeAuthorizerConfiguration.usingCognito() 팩토리 메서드를 사용하세요:
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
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: RuntimeAuthorizerConfiguration.usingCognito( userPool, [client], ), }); }}또는 자체 OIDC 제공자를 사용한 사용자 정의 JWT 인증의 경우 RuntimeAuthorizerConfiguration.usingJWT()를 사용하세요:
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingJWT( 'https://example.com/.well-known/openid-configuration', ['client1', 'client2'], // 허용된 클라이언트 ID (선택 사항) ['audience1'], // 허용된 오디언스 (선택 사항) ), }); }}JWT 인증을 구성하려면 에이전트 모듈의 authorizer_configuration 변수를 다음과 같이 편집할 수 있습니다:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.id
# 사용자 풀 및 클라이언트 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" authorizer_configuration = { custom_jwt_authorizer = { discovery_url = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration" allowed_clients = 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 관측성 문서를 참조하세요.
Strands 에이전트 호출
섹션 제목: “Strands 에이전트 호출”로컬 서버 호출
섹션 제목: “로컬 서버 호출”<your-agent-name>-serve 타겟을 통해 로컬에서 실행 중인 에이전트를 호출하려면 로컬 에이전트가 실행 중인 포트의 /invocations로 간단한 POST 요청을 보낼 수 있습니다. 예를 들어 curl을 사용하면:
curl -N -X POST http://localhost:8081/invocations \ -d '{"prompt": "what is 3 + 5?", "session_id": "abcdefghijklmnopqrstuvwxyz0123456789"}' \ -H "Content-Type: application/json"배포된 에이전트 호출
섹션 제목: “배포된 에이전트 호출”Bedrock AgentCore Runtime에 배포된 Agent를 호출하려면, URL 인코딩된 런타임 ARN과 함께 Bedrock AgentCore Runtime 데이터플레인 엔드포인트로 POST 요청을 보낼 수 있습니다.
다음과 같이 인프라에서 런타임 ARN을 얻을 수 있습니다:
import { CfnOutput } from 'aws-cdk-lib';import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent');
new CfnOutput(this, 'AgentArn', { value: agent.agentCoreRuntime.agentRuntimeArn, }); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"}
output "agent_arn" { value = module.my_project_agent.agent_core_runtime_arn}ARN은 다음 형식을 가집니다: arn:aws:bedrock-agentcore:<region>:<account>:runtime/<agent-runtime-id>.
그런 다음 :를 %3A로, /를 %2F로 바꿔서 ARN을 URL 인코딩할 수 있습니다.
에이전트를 호출하기 위한 Bedrock AgentCore Runtime 데이터플레인 URL은 다음과 같습니다:
https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations이 URL을 호출하는 정확한 방법은 사용된 인증 방법에 따라 다릅니다.
IAM 인증
섹션 제목: “IAM 인증”IAM 인증의 경우 AWS Signature Version 4(SigV4)를 사용하여 요청에 서명해야 합니다.
acurl <region> bedrock-agentcore -N -X POST \'https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations' \-d '{"prompt": "what is 3 + 5?", "session_id": "abcdefghijklmnopqrstuvwxyz0123456789"}' \-H 'Content-Type: application/json'Sigv4 활성화 curl
다음 스크립트를 .bashrc 파일에 추가하고 source하거나, 명령을 실행하려는 터미널에 직접 붙여넣을 수 있습니다.
acurl () { REGION=$1 SERVICE=$2 shift; shift; curl --aws-sigv4 "aws:amz:$REGION:$SERVICE" --user "$(aws configure get aws_access_key_id):$(aws configure get aws_secret_access_key)" -H "X-Amz-Security-Token: $(aws configure get aws_session_token)" "$@"}sigv4 인증된 curl 요청을 만들려면 다음과 같이 acurl을 호출하세요:
acurl <region> <service> <other-curl-arguments>예시:
API Gateway
섹션 제목: “API Gateway”acurl ap-southeast-2 execute-api -X GET https://xxxStreaming Lambda function url
섹션 제목: “Streaming Lambda function url”acurl ap-southeast-2 lambda -N -X POST https://xxx다음 함수를 PowerShell 프로필에 추가하거나, 명령을 실행하려는 PowerShell 세션에 직접 붙여넣을 수 있습니다.
# PowerShell profile or current sessionfunction acurl { param( [Parameter(Mandatory=$true)][string]$Region, [Parameter(Mandatory=$true)][string]$Service, [Parameter(ValueFromRemainingArguments=$true)][string[]]$CurlArgs )
$AccessKey = aws configure get aws_access_key_id $SecretKey = aws configure get aws_secret_access_key $SessionToken = aws configure get aws_session_token
& curl --aws-sigv4 "aws:amz:$Region`:$Service" --user "$AccessKey`:$SecretKey" -H "X-Amz-Security-Token: $SessionToken" @CurlArgs}sigv4 인증된 curl 요청을 만들려면 다음 예시를 사용하여 acurl을 호출하세요:
API Gateway
섹션 제목: “API Gateway”acurl ap-southeast-2 execute-api -X GET https://xxxStreaming Lambda function url
섹션 제목: “Streaming Lambda function url”acurl ap-southeast-2 lambda -N -X POST https://xxxJWT / Cognito 인증
섹션 제목: “JWT / Cognito 인증”Cognito 인증의 경우 Authorization 헤더에 Cognito 액세스 토큰을 전달합니다:
curl -N -X POST 'https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations' \ -d '{"prompt": "what is 3 + 5?", "session_id": "abcdefghijklmnopqrstuvwxyz0123456789"}' \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <access-token>"AWS CLI의 cognito-idp admin-initiate-auth 명령을 사용하여 액세스 토큰을 얻을 수 있습니다. 예를 들어:
aws cognito-idp admin-initiate-auth \ --user-pool-id <user-pool-id> \ --client-id <user-pool-client-id> \ --auth-flow ADMIN_NO_SRP_AUTH \ --auth-parameters USERNAME=<username>,PASSWORD=<password> \ --region <region> \ --query 'AuthenticationResult.AccessToken' \ --output text