View a markdown version of this page

バッチデータセットランナー - Amazon Bedrock AgentCore

バッチデータセットランナー

BatchEvaluationRunner 代理人は、 および GetBatchEvaluation API を介して、収集StartBatchEvaluationと評価全体をサービスにスパンします。 APIs 各シナリオでエージェントを呼び出した後、ランナーはバッチジョブを送信し、完了するまでポーリングして集計結果を返します。

スパンコレクションを自分で管理せずに、多くのセッションで集計スコアが必要な場合は、バッチランナーを使用します。ベースライン測定、大規模なデータセット、前後の比較に使用します。

仕組み

ランナーはシナリオを 4 つのフェーズで処理します。

  1. 呼び出し: すべてのシナリオは、スレッドプールを使用して同時に実行されます。各シナリオは一意のセッション ID を取得し、シナリオ内で順番に実行して会話コンテキストを維持します。

  2. 待機: 設定可能な取り込み遅延 (デフォルト: 180 秒) により、CloudWatch はテレメトリデータを取り込むことができます。この遅延はシナリオごとではなく 1 回支払われます。

  3. 送信: ランナーは、CloudWatch ロググループ、呼び出しフェーズIDs、評価者 IDs、データセットのグラウンドトゥルースStartBatchEvaluationを使用して を呼び出します。

  4. ポーリング: ランナーは、ジョブGetBatchEvaluationが終了状態になるまでポーリングし、集計結果を返します。

エージェント呼び出し

ランナーには、エージェントを 1 ターン呼び出す呼び出し可能なエージェント呼び出し元が必要です。呼び出し元はフレームワークに依存しません。boto3 、直接関数呼び出しinvoke_agent_runtime、HTTP リクエスト、またはその他の方法でエージェントを呼び出すことができます。

import json import boto3 from bedrock_agentcore.evaluation import AgentInvokerInput, AgentInvokerOutput REGION = "<region-code>" AGENT_ARN = "arn:aws:bedrock-agentcore:<region-code>:<account-id>:runtime/<agent-id>" LOG_GROUP = "/aws/bedrock-agentcore/runtimes/<agent-id>-DEFAULT" SERVICE_NAME = "<agent-id>.DEFAULT" agentcore_client = boto3.client("bedrock-agentcore", region_name=REGION) def agent_invoker(invoker_input: AgentInvokerInput) -> AgentInvokerOutput: payload = invoker_input.payload if isinstance(payload, str): payload = json.dumps({"prompt": payload}).encode() elif isinstance(payload, dict): payload = json.dumps(payload).encode() print(f"[{invoker_input.session_id}] > sending payload: {payload.decode()}") response = agentcore_client.invoke_agent_runtime( agentRuntimeArn=AGENT_ARN, runtimeSessionId=invoker_input.session_id, payload=payload, ) response_body = response["response"].read() print(f"[{invoker_input.session_id}] < received response: {response_body.decode()}") return AgentInvokerOutput(agent_output=json.loads(response_body))
フィールド タイプ 説明

AgentInvokerInput.payload

str または dict

データセットからのターン入力。

AgentInvokerInput.session_id

str

シナリオのすべてのターンで安定しています。これをエージェントに渡して、会話コンテキストを維持します。

AgentInvokerOutput.agent_output

Any

エージェントのレスポンス。

次の例では、JSON ファイルからデータセットをロードし、バッチ評価を実行します。データセット形式については、「データセットスキーマ」を参照してください。

from bedrock_agentcore.evaluation import ( BatchEvaluationRunner, BatchEvaluationRunConfig, BatchEvaluatorConfig, CloudWatchDataSourceConfig, FileDatasetProvider, ) # Load dataset from a local file (see Dataset schema for format) dataset = FileDatasetProvider("dataset.json").get_dataset() # Or load from the Dataset Management service from bedrock_agentcore.evaluation import DatasetClient, DatasetManagementServiceProvider ds_client = DatasetClient(region_name=REGION) dataset = DatasetManagementServiceProvider(dataset_id="my-dataset-id", client=ds_client).get_dataset() # Configure the batch evaluation config = BatchEvaluationRunConfig( batch_evaluation_name="dataset-batch-eval", evaluator_config=BatchEvaluatorConfig( evaluator_ids=[ "Builtin.GoalSuccessRate", "Builtin.Correctness", "Builtin.TrajectoryExactOrderMatch", "Builtin.Helpfulness", ], ), data_source=CloudWatchDataSourceConfig( service_names=[SERVICE_NAME], log_group_names=[LOG_GROUP], ingestion_delay_seconds=180, ), polling_timeout_seconds=1800, polling_interval_seconds=30, ) # Run runner = BatchEvaluationRunner(region=REGION) result = runner.run_dataset_evaluation( agent_invoker=agent_invoker, dataset=dataset, config=config, ) # Display aggregate results print(f"Status: {result.status}") print(f"Batch evaluation ID: {result.batch_evaluation_id}") if result.evaluation_results: er = result.evaluation_results print(f"Sessions completed: {er.number_of_sessions_completed}") print(f"Sessions failed: {er.number_of_sessions_failed}") print(f"Total sessions: {er.total_number_of_sessions}") for summary in er.evaluator_summaries or []: avg = summary.statistics.average_score if summary.statistics else None print(f" {summary.evaluator_id}: avg={avg}")

セッションごとの詳細の取得

集計結果には、すべてのセッションの平均が表示されます。セッションごと、評価者ごとのスコアを表示するには、CloudWatch から評価イベントを取得します。

if result.output_data_config: events = runner.fetch_evaluation_events(result) print(f"\nEvaluation events: {len(events)}") for ev in events: attrs = ev.get("attributes", {}) print(f" session: {attrs.get('session.id', '')[:40]}") print(f" evaluator: {attrs.get('gen_ai.evaluation.name')}") print(f" score: {attrs.get('gen_ai.evaluation.score.value')}") print(f" label: {attrs.get('gen_ai.evaluation.score.label')}") print()

設定リファレンス

BatchEvaluationRunConfig( batch_evaluation_name="my-batch-eval", # Job name evaluator_config=BatchEvaluatorConfig( evaluator_ids=["Builtin.GoalSuccessRate"], ), data_source=CloudWatchDataSourceConfig( service_names=["MyAgent.DEFAULT"], # Exactly 1 service name log_group_names=[LOG_GROUP], # 1-5 log group names ingestion_delay_seconds=180, # Wait for CW ingestion (default: 180) ), polling_timeout_seconds=1800, # Max wait for job completion (default: 1800) polling_interval_seconds=30, # Poll interval (default: 30) simulation_config=None, # Set SimulationConfig for simulated scenarios )
フィールド デフォルト 説明

batch_evaluation_name

バッチ評価ジョブの名前。

evaluator_config.evaluator_ids

評価者 IDs のリスト (組み込みまたはカスタム)。

data_source.service_names

CloudWatch でエージェントのトレースを識別するサービス名。

data_source.log_group_names

エージェントテレメトリが保存されている CloudWatch ロググループ名。

data_source.ingestion_delay_seconds

180

CloudWatch がスパンを取り込むまで、呼び出し後に待機する秒数。

polling_timeout_seconds

1800

バッチジョブが完了するまで待機する最大秒数。

polling_interval_seconds

30

ポーリングリクエスト間の秒数。

simulation_config

なし

シミュレートされたシナリオの設定。データセットにSimulatedScenarioインスタンスが含まれているSimulationConfig(model_id="…​")場合に を設定します。「ユーザーシミュレーション」を参照してください。

結果構造

ランナーは を返しますBatchEvaluationResult

BatchEvaluationResult ├── batch_evaluation_id: str ├── batch_evaluation_arn: str ├── batch_evaluation_name: str ├── status: str ├── created_at: datetime ├── evaluation_results: Optional[BatchEvaluationSummary] │ ├── number_of_sessions_completed: int │ ├── number_of_sessions_in_progress: int │ ├── number_of_sessions_failed: int │ ├── number_of_sessions_ignored: int │ ├── total_number_of_sessions: int │ └── evaluator_summaries: List │ ├── evaluator_id: str │ ├── statistics.average_score: float │ ├── total_evaluated: int │ └── total_failed: int ├── error_details: Optional[List[str]] ├── agent_invocation_failures: List[FailedScenario] └── output_data_config: Optional[CloudWatchOutputDataConfig] ├── log_group_name: str └── log_stream_name: str
  • agent_invocation_failures は、バッチジョブが送信される前にエージェントの呼び出しが失敗したシナリオを一覧表示します。これらのセッションはバッチ評価に含まれません。

  • output_data_config は、セッションごとの詳細が書き込まれる CloudWatch ログストリームを指します。runner.fetch_evaluation_events(result) を使用して読み取ります。

エラー処理

  • シナリオ呼び出しの失敗は として記録されますFailedScenarioが、バッチジョブはブロックされません。成功したセッションのみが送信されます。

  • すべてのシナリオが失敗した場合、ランナーは API を呼び出すValueError前に を起動します。

  • ポーリングタイムアウト: ジョブTimeoutErrorが を超える場合polling_timeout_seconds

  • ジョブの失敗: バッチ評価ステータスが FAILEDまたは RuntimeErrorの場合STOPPED