View a markdown version of this page

自訂程式碼型評估器 - Amazon Bedrock AgentCore

自訂程式碼型評估器

自訂程式碼型評估器可讓您使用自己的 AWS Lambda 函數,以程式設計方式評估客服人員效能,而不是使用 LLM 做為判斷。這可讓您完全控制評估邏輯 — 您可以實作決定性檢查、呼叫外部 APIs、執行規則運算式比對、運算自訂指標,或套用任何業務特定的規則。

先決條件

若要使用自訂程式碼型評估器,您需要:

  • 部署在與 AgentCore Evaluations 資源相同區域中的 AWS Lambda 函數。

  • IAM 執行角色,授予 AgentCore Evaluations 服務叫用 Lambda 函數的許可。

  • Lambda 函數必須傳回符合回應結構描述中所述之回應結構描述的 JSON 回應

IAM 許可

您的服務執行角色需要下列額外許可,才能叫用 Lambda 函數以進行程式碼型評估:

{ "Sid": "LambdaInvokeStatement", "Effect": "Allow", "Action": [ "lambda:InvokeFunction", "lambda:GetFunction" ], "Resource": "arn:aws:lambda:region:account-id:function:function-name" }

Lambda 函數合約

注意

Lambda 函數的執行時間逾時上限為 5 分鐘 (300 秒)。傳送至 Lambda 函數的輸入承載大小上限為 6 MB。

輸入結構描述

您的 Lambda 函數會收到具有下列結構的 JSON 承載:

{ "schemaVersion": "1.0", "evaluatorId": "my-evaluator-abc1234567", "evaluatorName": "MyCodeEvaluator", "evaluationLevel": "TRACE", "evaluationInput": { "sessionSpans": [...] }, "evaluationReferenceInputs": [], "evaluationTarget": { "traceIds": ["trace123"], "spanIds": ["span123"] } }
欄位 Type Description

schemaVersion

String

承載的結構描述版本。目前為 "1.0"

evaluatorId

String

程式碼型評估器的 ID。

evaluatorName

String

程式碼型評估器的名稱。

evaluationLevel

String

評估層級:TRACETOOL_CALLSESSION

evaluationInput

物件

包含用於評估的工作階段範圍。

evaluationInput.sessionSpans

清單

要評估的工作階段範圍。如果原始承載超過 6 MB,可能會被截斷。

evaluationReferenceInputs

清單

提供給評估者的參考輸入,根據評估層級篩選。請參閱在程式碼型評估器中使用 Ground Truth

evaluationTarget

物件

識別要評估的特定追蹤或範圍。對於工作階段層級評估器,此值為 None

evaluationTarget.traceIds

清單

評估目標的追蹤 IDs。用於追蹤層級和工具層級評估。

evaluationTarget.spanIds

清單

評估目標的範圍 IDs。用於工具層級評估。

回應結構描述

您的 Lambda 函數必須傳回符合兩種格式之一的 JSON 物件:

成功回應

{ "label": "PASS", "value": 1.0, "explanation": "All validation checks passed." }
欄位 必要 Type 說明

label

String

評估結果的類別標籤 (例如 "PASS"、"FAIL"、"Good"、"Poor")。

value

Number

數值分數 (例如 0.0 到 1.0)。

explanation

String

評估結果的人類可讀說明。

錯誤回應

{ "errorCode": "VALIDATION_FAILED", "errorMessage": "Input spans missing required tool call attributes." }
欄位 必要 Type 說明

errorCode

String

識別錯誤的程式碼。

errorMessage

String

人類可讀取的錯誤描述。

建立程式碼型評估器

CreateEvaluator API 透過指定 Lambda 函數 ARN 和選用逾時來建立程式碼型評估器。

必要參數:唯一的評估器名稱、評估層級 TRACE (、 TOOL_CALLSESSION ),以及包含 Lambda ARN 的程式碼型評估器組態。

程式碼型評估器組態:

{ "codeBased": { "lambdaConfig": { "lambdaArn": "arn:aws:lambda:region:account-id:function:function-name", "lambdaTimeoutInSeconds": 60 } } }
欄位 必要 預設 說明

lambdaArn

要叫用的 Lambda 函數 ARN。

lambdaTimeoutInSeconds

60

Lambda 調用的逾時以秒為單位 (1–300)。

下列程式碼範例示範如何使用不同的開發方法建立程式碼型評估器。

範例
AgentCore CLI
  1. agentcore eval evaluator create \ --name "MyCodeEvaluator" \ --level TRACE \ --lambda-arn "arn:aws:lambda:us-east-1:123456789012:function:my-eval-function" \ --lambda-timeout 120
AgentCore SDK
  1. from bedrock_agentcore.evaluation.code_based_evaluators import ( EvaluatorInput, EvaluatorOutput, code_based_evaluator, ) import json as _json @code_based_evaluator() def json_response_evaluator(input: EvaluatorInput) -> EvaluatorOutput: """Check if the agent response in the target trace contains valid JSON.""" for span in input.session_spans: if span.get("traceId") != input.target_trace_id: continue if span.get("name", "").startswith("Model:") or span.get("name") == "Agent.invoke": output = span.get("attributes", {}).get("gen_ai.completion", "") try: _json.loads(output) return EvaluatorOutput( value=1.0, label="Pass", explanation="Response contains valid JSON" ) except (ValueError, TypeError): pass return EvaluatorOutput( value=0.0, label="Fail", explanation="No valid JSON found in agent response" )
AWS SDK
  1. import boto3 client = boto3.client('bedrock-agentcore-control') response = client.create_evaluator( evaluatorName="MyCodeEvaluator", level="TRACE", evaluatorConfig={ "codeBased": { "lambdaConfig": { "lambdaArn": "arn:aws:lambda:us-east-1:123456789012:function:my-eval-function", "lambdaTimeoutInSeconds": 120 } } } ) print(f"Evaluator ID: {response['evaluatorId']}") print(f"Evaluator ARN: {response['evaluatorArn']}")
AWS CLI
  1. aws bedrock-agentcore-control create-evaluator \ --evaluator-name 'MyCodeEvaluator' \ --level TRACE \ --evaluator-config '{ "codeBased": { "lambdaConfig": { "lambdaArn": "arn:aws:lambda:us-east-1:123456789012:function:my-eval-function", "lambdaTimeoutInSeconds": 120 } } }'

使用程式碼型評估器執行隨需評估

建立之後,使用自訂程式碼型評估器搭配 Evaluate API,就像使用任何其他評估器一樣。服務會自動處理 Lambda 調用、平行廣發和結果映射。

範例
AgentCore CLI
  1. agentcore run eval \ --runtime "your_runtime_name" \ --session-id "your_session_id" \ --evaluator "code-based-evaluator-id"
AgentCore SDK
  1. from bedrock_agentcore.evaluation.client import EvaluationClient client = EvaluationClient( region_name="region" ) results = client.run( evaluator_ids=[ "code-based-evaluator-id", ], session_id="session-id", log_group_name="log-group-name", )
AWS SDK
  1. import boto3 client = boto3.client('bedrock-agentcore') response = client.evaluate( evaluatorId="code-based-evaluator-id", evaluationInput={"sessionSpans": session_span_logs} ) for result in response["evaluationResults"]: if "errorCode" in result: print(f"Error: {result['errorCode']} - {result['errorMessage']}") else: print(f"Label: {result['label']}, Value: {result.get('value')}") print(f"Explanation: {result.get('explanation', '')}")
AWS CLI
  1. aws bedrock-agentcore evaluate \ --cli-input-json file://session_span_logs.json

使用評估目標

您可以針對特定追蹤或範圍,就像使用 LLM 型評估器一樣:

# Trace-level evaluation response = client.evaluate( evaluatorId="code-based-evaluator-id", evaluationInput={"sessionSpans": session_span_logs}, evaluationTarget={"traceIds": ["trace-id-1", "trace-id-2"]} ) # Tool-level evaluation response = client.evaluate( evaluatorId="code-based-evaluator-id", evaluationInput={"sessionSpans": session_span_logs}, evaluationTarget={"spanIds": ["span-id-1", "span-id-2"]} )

在程式碼型評估器中使用 Ground Truth

設定 Ground Truth 參考輸入時,您的 Lambda 函數會在 evaluationReferenceInputs 欄位中接收它們。包含的參考輸入取決於評估層級:

評估層級 Lambda 收到

SESSION

所有參考輸入。

TRACE

工作階段層級參考輸入加上符合目標 traceId 的參考輸入。

TOOL_CALL

工作階段層級參考輸入加上符合目標 spanId 的參考輸入。

注意

如需使用 Ground Truth 評估的詳細資訊,請參閱 Ground Truth 評估

使用程式碼型評估器執行線上評估

您可以在線上評估組態中使用自訂程式碼型評估器,以持續監控客服人員的即時流量。呼叫 時,在evaluators清單中傳遞評估器 IDCreateOnlineEvaluationConfig

範例
AgentCore CLI
  1. agentcore add online-eval \ --name "your_config_name" \ --runtime "your_runtime_name" \ --evaluator "code-based-evaluator-id" \ --sampling-rate 1.0 \ --enable-on-create

    此命令會將線上評估組態新增至本機 agentcore.json 。執行 agentcore deploy 在您的 AWS 帳戶中建立它。

    注意

    從 AgentCore 專案目錄 (使用 建立) agentcore create 內執行此操作。

AgentCore SDK
  1. from bedrock_agentcore_starter_toolkit import Evaluation eval_client = Evaluation() config = eval_client.create_online_config( config_name="my_online_eval_config", agent_id="agent-id", sampling_rate=1.0, evaluator_list=["code-based-evaluator-id"], enable_on_create=True ) print(f"Config ID: {config['onlineEvaluationConfigId']}")
AWS SDK
  1. import boto3 client = boto3.client('bedrock-agentcore-control') response = client.create_online_evaluation_config( onlineEvaluationConfigName="my_online_eval_config", rule={"samplingConfig": {"samplingPercentage": 100.0}}, dataSourceConfig={ "cloudWatchLogs": { "logGroupNames": ["/aws/agentcore/my-agent-traces"], "serviceNames": ["my-agent.DEFAULT"] } }, evaluators=[{"evaluatorId": "code-based-evaluator-id"}], evaluationExecutionRoleArn="arn:aws:iam::account-id:role/AgentCoreEvaluationRole", enableOnCreate=True ) print(f"Config ID: {response['onlineEvaluationConfigId']}")
AWS CLI
  1. aws bedrock-agentcore-control create-online-evaluation-config \ --online-evaluation-config-name "my_online_eval_config" \ --rule '{"samplingConfig": {"samplingPercentage": 100.0}}' \ --data-source-config '{"cloudWatchLogs": {"logGroupNames": ["/aws/agentcore/my-agent-traces"], "serviceNames": ["my-agent.DEFAULT"]}}' \ --evaluators '[{"evaluatorId": "code-based-evaluator-id"}]' \ --evaluation-execution-role-arn "arn:aws:iam::account-id:role/AgentCoreEvaluationRole" \ --enable-on-create
注意

當參考程式碼型評估器的線上評估組態啟用時,評估器會自動鎖定,而且在停用或刪除組態之前,無法修改或刪除。若要變更評估器,請先停用線上評估組態,或複製評估器並建立新的組態。