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、服務名稱和日誌群組 agentcore status --json- boto3 範例將需要這些項目。

注意

如果您已在啟用可觀測性的 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 或時間範圍評估特定工作階段。請參閱啟動批次評估

  • 針對資料集執行 - 根據預先定義的案例調用您的代理程式,並自動評估結果。請參閱資料集評估

  • 比較執行 — 在變更前後執行批次評估,並比較分數。請參閱了解結果和輸出