View a markdown version of this page

배치 평가 시작하기 - Amazon Bedrock AgentCore

배치 평가 시작하기

이 연습에서는 Acme Store 고객 지원 에이전트를 사용하여 배포된 에이전트에서 배치 평가 결과로 안내합니다. 에이전트를 생성하고, 배포하고, 샘플 세션을 생성하고, 배치 평가를 실행하고, 결과를 읽습니다.

시작하기 전 준비 사항

다음 사항을 갖추었는지 확인하세요.

  • AgentCore CLI 설치됨(agentcore --version)

  • AWS bedrock-agentcore 및에 대한 권한이 있는 자격 증명 logs

  • CloudWatch에서 트랜잭션 검색 활성화

  • Python 3.10 이상(boto3 예제의 경우)

자세한 내용은 사전 조건을 참조하세요.

다음 상수는 boto3 예제에서 사용됩니다. 에이전트를 배포한 후 고유한 값으로 바꿉니다.

REGION = "us-west-2" AGENT_ARN = "arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/AcmeSupport-abc123" SERVICE_NAME = "AcmeSupport-abc123.DEFAULT" LOG_GROUP = "/aws/bedrock-agentcore/runtimes/AcmeSupport-abc123-DEFAULT"

1단계: 샘플 에이전트 생성 및 배포

AgentCore 프로젝트를 생성하고 기본 에이전트 코드를 Acme Store 고객 지원 에이전트로 바꿉니다. 이 에이전트에는 주문, 반품, 배송, 할인 및 에스컬레이션을 처리하는 다섯 가지 도구가 있습니다.

프로젝트 생성

agentcore create --name AcmeSupport --framework Strands --model-provider Bedrock --memory none cd AcmeSupport

에이전트 코드 교체

app/AcmeSupport/main.py를 열고 내용을 다음과 같이 바꿉니다.

"""Acme Store customer support agent.""" from strands import Agent, tool from strands.models.bedrock import BedrockModel from bedrock_agentcore.runtime import BedrockAgentCoreApp app = BedrockAgentCoreApp() MODEL_ID = "global.anthropic.claude-sonnet-4-6" SYSTEM_PROMPT = ( "You are a helpful customer support assistant for Acme Store. " "Help customers with their orders, returns, and shipping questions." ) @tool def lookup_order(order_id: str) -> str: """Look up an order by ID and return its status, item, and delivery details.""" orders = { "ORD-1001": { "status": "delivered", "item": "Blue T-Shirt (L)", "delivered": "2026-03-28", "total": "$29.99", }, "ORD-1002": { "status": "in_transit", "item": "Running Shoes (10)", "shipped": "2026-03-30", "est_delivery": "2026-04-05", "total": "$89.99", }, "ORD-1003": { "status": "delayed", "item": "Wireless Headphones", "shipped": "2026-03-25", "est_delivery": "2026-03-29", "days_late": 5, "total": "$59.99", }, "ORD-1004": { "status": "processing", "item": "Yoga Mat", "ordered": "2026-04-02", "total": "$34.99", }, "ORD-1005": { "status": "delivered", "item": "Coffee Maker", "delivered": "2026-03-20", "total": "$149.99", }, } return str(orders.get(order_id, {"error": f"Order {order_id} not found"})) @tool def initiate_return(order_id: str, reason: str) -> str: """Initiate a return for an order. Sends a return label to the customer.""" return ( f"Return initiated for {order_id}. Reason: {reason}. " "Return label sent to customer email. Please ship within 14 days." ) @tool def check_shipping_status(order_id: str) -> str: """Check detailed shipping status including carrier location and delays.""" statuses = { "ORD-1002": ( "Package is with carrier, currently in Portland OR. " "On schedule for April 5." ), "ORD-1003": ( "Package delayed at distribution center in Memphis TN. " "Original delivery was March 29. Now 5 days late. " "Acme Store policy: orders delayed 3+ days qualify for 15% discount." ), } return statuses.get(order_id, f"No active shipment found for {order_id}.") @tool def apply_discount(order_id: str, discount_percent: int, reason: str) -> str: """Apply a percentage discount to an order and issue a refund.""" return ( f"Applied {discount_percent}% discount to {order_id}. " f"Reason: {reason}. Refund will appear in 3-5 business days." ) @tool def escalate_to_human(reason: str) -> str: """Escalate the conversation to a human support agent.""" return ( f"Escalated to human agent. Reason: {reason}. " "Estimated wait time: 3 minutes." ) agent = Agent( model=BedrockModel(model_id=MODEL_ID), tools=[lookup_order, initiate_return, check_shipping_status, apply_discount, escalate_to_human], system_prompt=SYSTEM_PROMPT, ) @app.entrypoint def invoke(payload, context): result = agent(payload.get("prompt", "Hello")) return {"response": str(result)} if __name__ == "__main__": app.run()

배포 및 확인

agentcore deploy

배포 후 에이전트가 실행 중인지 확인합니다.

agentcore invoke --prompt "What's the status of order ORD-1001?"

주문 세부 정보가 포함된 응답이 표시됩니다. 의 런타임 ARN, 서비스 이름 및 로그 그룹을 기록해 둡니다. boto3 예제에는 이러한 로그 그룹이 agentcore status --json 필요합니다.

참고

관찰성이 활성화된 AgentCore 런타임에 에이전트가 이미 배포되어 있는 경우이 단계를 건너뛰고 나머지 연습에서는 자체 에이전트를 사용합니다.

2단계: 샘플 세션 생성

다양한 프롬프트로 에이전트를 호출하여 평가를 위한 세션을 생성합니다. 이러한 프롬프트는 주문 조회, 반품, 배송 지연, 할인 요청, 다중 도구 상호 작용 등 다양한 시나리오를 다룹니다.

AgentCore CLI
agentcore invoke --runtime AcmeSupport --prompt "What's the status of my order ORD-1001?" agentcore invoke --runtime AcmeSupport --prompt "I need to return order ORD-1001, the shirt doesn't fit." agentcore invoke --runtime AcmeSupport --prompt "What's the shipping status on ORD-1002?" agentcore invoke --runtime AcmeSupport --prompt "My order ORD-1003 is delayed, can you help?" agentcore invoke --runtime AcmeSupport --prompt "I'd like to check on order ORD-1004 please." agentcore invoke --runtime AcmeSupport --prompt "Can you look up order ORD-1005 for me?" agentcore invoke --runtime AcmeSupport --prompt "I want to return the coffee maker from order ORD-1005, it's defective." agentcore invoke --runtime AcmeSupport --prompt "Where is my order ORD-1002? It should have arrived by now." agentcore invoke --runtime AcmeSupport --prompt "ORD-1003 is really late, I want a discount." agentcore invoke --runtime AcmeSupport --prompt "Can you check order ORD-1001 and tell me when it was delivered?"
AWS SDK (boto3)
import boto3 import json import uuid client = boto3.client("bedrock-agentcore", region_name=REGION) prompts = [ "What's the status of my order ORD-1001?", "I need to return order ORD-1001, the shirt doesn't fit.", "What's the shipping status on ORD-1002?", "My order ORD-1003 is delayed, can you help?", "I'd like to check on order ORD-1004 please.", "Can you look up order ORD-1005 for me?", "I want to return the coffee maker from order ORD-1005, it's defective.", "Where is my order ORD-1002? It should have arrived by now.", "ORD-1003 is really late, I want a discount.", "Can you check order ORD-1001 and tell me when it was delivered?", ] for i, prompt in enumerate(prompts): session_id = f"acme-eval-{uuid.uuid4().hex[:12]}" print(f"[{i+1}/10] {prompt[:60]}...") response = client.invoke_agent_runtime( agentRuntimeArn=AGENT_ARN, runtimeSessionId=session_id, payload=json.dumps({"prompt": prompt}).encode(), ) response_body = response["response"].read() print(f" Done (session: {session_id})") print("\nAll sessions created.")

CloudWatch가 원격 측정을 수집할 수 있도록 마지막 호출 후 2~3분을 기다린 후 계속 진행합니다.

3단계: 배치 평가 실행

배치 평가를 시작하여 최근 세션을 모두 채점합니다. 이 서비스는 CloudWatch Logs에서 세션을 검색하고 각 세션에 대해 각 평가자를 실행하며 집계 결과를 반환합니다.

AgentCore CLI
agentcore run batch-evaluation \ --runtime AcmeSupport \ --evaluator Builtin.GoalSuccessRate Builtin.Helpfulness Builtin.Faithfulness \ --wait

기본적으로는 작업을 agentcore run batch-evaluation 시작하고 즉시 반환합니다(차단 없음). 작업이 터미널 상태에 도달할 때까지 --wait 블록에 전달합니다. --wait를 사용하면 CLI는 프로젝트 구성에서 CloudWatch 로그 그룹 및 서비스 이름을 확인하고, 작업을 시작하고, 최종 상태에 도달할 때까지 차단한 다음, 평가자당 평균 점수를 인쇄합니다.

Batch evaluation completed: acme-eval-a1b2c3d4

Sessions: 10 completed, 0 failed, 10 total

Evaluator                           Avg Score
─────────────────────────────────────────────
Builtin.GoalSuccessRate             0.7200
Builtin.Helpfulness                 0.8100
Builtin.Faithfulness                0.8500

Results saved to .cli/jobs/batch-eval-results/

--json를 추가하여 스크립팅을 위해 기계 판독 가능한 결과( batchEvaluationId 및 평가자별 포함averageScore)를 내보내고 -n <name>를 추가하여 실행 간에 결과를 비교할 수 있도록 실행에 레이블을 지정합니다. 예제:

agentcore run batch-evaluation \ --runtime AcmeSupport \ --evaluator Builtin.GoalSuccessRate Builtin.Helpfulness Builtin.Faithfulness \ -n acme_baseline \ --wait
AWS SDK (boto3)
import boto3 import uuid import time import json eval_client = boto3.client("bedrock-agentcore", region_name=REGION) # Start the batch evaluation response = eval_client.start_batch_evaluation( batchEvaluationName=f"acme_baseline_{uuid.uuid4().hex[:8]}", evaluators=[ {"evaluatorId": "Builtin.GoalSuccessRate"}, {"evaluatorId": "Builtin.Helpfulness"}, {"evaluatorId": "Builtin.Faithfulness"}, ], dataSourceConfig={ "cloudWatchLogs": { "serviceNames": [SERVICE_NAME], "logGroupNames": [LOG_GROUP], } }, clientToken=str(uuid.uuid4()), ) batch_eval_id = response["batchEvaluationId"] print(f"Started: {batch_eval_id}") # Poll until complete while True: result = eval_client.get_batch_evaluation(batchEvaluationId=batch_eval_id) status = result["status"] print(f"Status: {status}") if status in ("COMPLETED", "COMPLETED_WITH_ERRORS", "FAILED", "STOPPED"): break time.sleep(30) print(json.dumps(result, indent=4, default=str))

4단계: 세션별 세부 정보 읽기

집계 점수는 전체 그림을 알려줍니다. 개별 세션에 대한 턴당, 평가자당 점수를 보려면 기본 제공 CLI 보기 명령을 사용하거나 CloudWatch Logs에서 직접 평가 이벤트를 읽습니다.

AgentCore CLI

CLI는 완료된 배치 평가 작업과 그 결과를 볼 수 있는 일류 명령을 제공합니다. 배치 평가 작업 ID별로 특정 작업을 보거나 과거 작업을 나열합니다.

# View a batch evaluation job and its results agentcore view batch-evaluation acme-eval-a1b2c3d4 # List batch evaluation jobs agentcore batch-evaluations history

이러한 명령은 플래그가 지정되지 않은 경우 대화형으로 실행됩니다. 와 같이 비대화형, 기계 판독 가능 출력--json에를 추가합니다agentcore view batch-evaluation acme-eval-a1b2c3d4 --json.

AWS SDK (boto3)
# Get the output location from the batch evaluation result output = result["outputConfig"]["cloudWatchConfig"] log_group = output["logGroupName"] log_stream = output["logStreamName"] # Read the events logs_client = boto3.client("logs", region_name=REGION) response = logs_client.get_log_events( logGroupName=log_group, logStreamName=log_stream, ) for event in response["events"]: event_attrs = json.loads(event["message"]).get("attributes", {}) print(f"Score: {event_attrs.get('gen_ai.evaluation.score.value')}") print(f"Label: {event_attrs.get('gen_ai.evaluation.score.label')}") print(f"Explanation: {event_attrs.get('gen_ai.evaluation.explanation', '')[:200]}") print()

다음 단계

  • 세션 필터링 - ID 또는 시간 범위를 기준으로 특정 세션을 평가합니다. 배치 평가 시작을 참조하세요.

  • 데이터 세트에 대해 실행 - 사전 정의된 시나리오에 대해 에이전트를 호출하고 결과를 자동으로 평가합니다. 데이터 세트 평가를 참조하세요.

  • 실행 비교 - 변경 전후에 배치 평가를 실행하고 점수를 비교합니다. 결과 및 출력 이해를 참조하세요.