

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# バッチ評価の開始方法
<a name="batch-evaluations-getting-started"></a>

このチュートリアルでは、デプロイされたエージェントから、Acme Store カスタマーサポートエージェントを使用して評価結果をバッチ処理します。エージェントの作成、デプロイ、サンプルセッションの生成、バッチ評価の実行、結果の読み取りを行います。

**Topics**
+ [[開始する前に]](#batch-gs-before-you-begin)
+ [ステップ 1: サンプルエージェントを作成してデプロイする](#batch-gs-step1)
+ [ステップ 2: サンプルセッションを生成する](#batch-gs-step2)
+ [ステップ 3: バッチ評価を実行する](#batch-gs-step3)
+ [ステップ 4: セッションごとの詳細を読み取る](#batch-gs-step4)
+ [次の手順](#batch-gs-next-steps)

## [開始する前に]
<a name="batch-gs-before-you-begin"></a>

以下を確認してください。
+ AgentCore CLI がインストールされました (`agentcore --version`)
+  AWS `bedrock-agentcore`および のアクセス許可を持つ 認証情報 `logs` 
+ CloudWatch でトランザクション検索が有効になっている
+ Python 3.10\+ (boto3 の例の場合)

詳細については、[「前提条件](batch-evaluations-prereqs.md)」を参照してください。

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: サンプルエージェントを作成してデプロイする
<a name="batch-gs-step1"></a>

AgentCore プロジェクトを作成し、デフォルトのエージェントコードを Acme Store カスタマーサポートエージェントに置き換えます。このエージェントには、注文、返品、配送、割引、エスカレーションを処理するための 5 つのツールがあります。

### プロジェクトの作成
<a name="batch-gs-step1a"></a>

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

### エージェントコードを置き換える
<a name="batch-gs-step1b"></a>

を開き`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(str(payload.get("prompt", "Hello")))
    return {"response": str(result)}


if __name__ == "__main__":
    app.run()
```

### デプロイと検証
<a name="batch-gs-step1c"></a>

```
agentcore deploy
```

デプロイ後、エージェントが実行されていることを確認します。

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

注文の詳細を含むレスポンスが表示されます。のランタイム ARN、サービス名、ロググループを書き留めます`agentcore status --json`。boto3 の例にはこれらが必要です。

**注記**  
オブザーバビリティが有効になっている エージェントがすでに AgentCore ランタイムにデプロイされている場合は、このステップをスキップし、残りのチュートリアルで独自のエージェントを使用します。

## ステップ 2: サンプルセッションを生成する
<a name="batch-gs-step2"></a>

さまざまなプロンプトでエージェントを呼び出して、評価用のセッションを作成します。これらのプロンプトは、注文検索、返品、配送遅延、割引リクエスト、マルチツールインタラクションなど、さまざまなシナリオを対象としています。

**Example**  

```
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?"
```

```
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: バッチ評価を実行する
<a name="batch-gs-step3"></a>

バッチ評価を開始して、最近のすべてのセッションをスコアリングします。このサービスは CloudWatch Logs からセッションを検出し、各セッションに対して各評価者を実行し、集計結果を返します。

**Example**  

```
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
```

```
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: セッションごとの詳細を読み取る
<a name="batch-gs-step4"></a>

集計スコアは全体像を示します。個々のセッションのターンごとの評価者ごとのスコアを表示するには、組み込みの CLI 表示コマンドを使用するか、CloudWatch Logs から直接評価イベントを読み取ります。

**Example**  
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`。

```
# 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()
```

## 次の手順
<a name="batch-gs-next-steps"></a>
+  **セッションのフィルタリング** — 特定のセッションを ID または時間範囲別に評価します。[「バッチ評価を開始する](batch-evaluations-start.md)」を参照してください。
+  **データセットに対して実行する** — 事前定義されたシナリオに対してエージェントを呼び出し、結果を自動的に評価します。[「データセットの評価](dataset-evaluations.md)」を参照してください。
+  **比較実行** — 変更の前後にバッチ評価を実行し、スコアを比較します。[「結果と出力について](batch-evaluations-results.md)」を参照してください。