

# 基于代码的自定义评估器
<a name="code-based-evaluators"></a>

基于自定义代码的评估器允许您使用自己的 Lamb AWS da 函数以编程方式评估代理性能，而不必使用 LLM 作为评判。这使您可以完全控制评估逻辑——您可以实现确定性检查、调用外部 API、运行正则表达式匹配、计算自定义指标或应用任何特定于业务的规则。

## 先决条件
<a name="code-based-evaluators-prerequisites"></a>

要使用基于代码的自定义赋值器，您需要：
+ 与您的 AgentCore 评估资源部署在同一区域的 AWS Lambda 函数。
+ 一个 IAM 执行角色，用于向 AgentCore 评估服务授予调用您的 Lambda 函数的权限。
+ [Lambda 函数必须返回符合响应架构中描述的响应架构的 JSON 响应。](#code-based-response-schema)

## IAM 权限
<a name="code-based-evaluators-iam"></a>

您的服务执行角色需要以下额外权限才能调用 Lambda 函数进行基于代码的评估：

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

## Lambda 函数合约
<a name="code-based-lambda-contract"></a>

**注意**  
Lambda 函数的最大运行时超时时间为 5 分钟（300 秒）。发送到 Lambda 函数的最大输入负载大小为 6 MB。

### 输入架构
<a name="code-based-input-schema"></a>

您的 Lambda 函数会收到具有以下结构的 JSON 有效负载：

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


| 字段 | Type | 说明 | 
| --- | --- | --- | 
|  `schemaVersion`  | 字符串 | 有效载荷的架构版本。目前`"1.0"`。 | 
|  `evaluatorId`  | 字符串 | 基于代码的评估者的 ID。 | 
|  `evaluatorName`  | 字符串 | 基于代码的评估器的名称。 | 
|  `evaluationLevel`  | 字符串 | 评估级别：`TRACE``TOOL_CALL`、或`SESSION`。 | 
|  `evaluationInput`  | 对象 | 包含用于评估的会话跨度。 | 
|  `evaluationInput.sessionSpans`  | 列表 | 会话跨度进行评估。如果原始有效载荷超过 6 MB，则可能会被截断。 | 
|  `evaluationReferenceInputs`  | 列表 | 提供给评估者的参考输入，根据评估级别进行过滤。请参阅在[基于代码的赋值器中使用基本真相](#code-based-ground-truth)。 | 
|  `evaluationTarget`  | 对象 | 标识要评估的特定轨迹或跨度。对于会话级别的评估者，此值为。`None` | 
|  `evaluationTarget.traceIds`  | 列表 | 评估目标的跟踪 ID。用于跟踪级和工具级评估。 | 
|  `evaluationTarget.spanIds`  | 列表 | 评估目标的跨度 ID。用于工具级评估。 | 

### 响应 schema
<a name="code-based-response-schema"></a>

您的 Lambda 函数必须返回与以下两种格式之一匹配的 JSON 对象：

 **成功响应** 

```
{
    "label": "PASS",
    "value": 1.0,
    "explanation": "All validation checks passed."
}
```


| 字段 | 必填 | Type | Description | 
| --- | --- | --- | --- | 
|  `label`  | 是 | 字符串 | 评估结果的分类标签（例如，“通过”、“失败”、“良好”、“差”）。 | 
|  `value`  | 否 | 数字 | 数字分数（例如，0.0 到 1.0）。 | 
|  `explanation`  | 否 | 字符串 | 对评估结果的易于理解的解释。 | 

 **错误响应** 

```
{
    "errorCode": "VALIDATION_FAILED",
    "errorMessage": "Input spans missing required tool call attributes."
}
```


| 字段 | 必填 | Type | Description | 
| --- | --- | --- | --- | 
|  `errorCode`  | 是 | 字符串 | 识别错误的代码。 | 
|  `errorMessage`  | 是 | 字符串 | 人类可读的错误描述。 | 

## 创建基于代码的评估器
<a name="create-code-based-evaluator"></a>

`CreateEvaluator`API 通过指定 Lambda 函数 ARN 和可选的超时时间来创建基于代码的评估器。

 **必需参数：**唯一的评估者姓名、评估级别（`TRACE``TOOL_CALL`、或`SESSION`）以及包含 Lambda ARN 的基于代码的评估器配置。

 **Code-based 评估器配置：**

```
{
    "codeBased": {
        "lambdaConfig": {
            "lambdaArn": "arn:aws:lambda:region:account-id:function:function-name",
            "lambdaTimeoutInSeconds": 60
        }
    }
}
```


| 字段 | 必填 | 默认值 | Description | 
| --- | --- | --- | --- | 
|  `lambdaArn`  | 是 | — | 要调用的 Lambda 函数的 ARN。 | 
|  `lambdaTimeoutInSeconds`  | 否 | 60 | Lambda 调用的超时时间（以秒为单位）(1—300)。 | 

以下代码示例演示了如何使用不同的开发方法创建基于代码的赋值器。

**Example**  

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

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

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']}")
   ```

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

## 使用基于代码的评估器进行按需评估
<a name="run-on-demand-code-based"></a>

创建完成后，将基于代码的自定义评估器与 `Evaluate` API 一起使用，就像使用任何其他评估器一样。该服务会自动处理 Lambda 调用、并行扇出和结果映射。

**Example**  

1. 

   ```
   agentcore run eval \
     --runtime "your_runtime_name" \
     --session-id "your_session_id" \
     --evaluator "code-based-evaluator-id"
   ```

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",
   )
   ```

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', '')}")
   ```

1. 

   ```
   aws bedrock-agentcore evaluate \
       --cli-input-json file://session_span_logs.json
   ```

### 使用评估目标
<a name="code-based-evaluation-targets"></a>

你可以瞄准特定的轨迹或跨度，就像使用 LLM-based 赋值器一样：

```
# 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"]}
)
```

### 在基于代码的赋值器中使用基本真相
<a name="code-based-ground-truth"></a>

配置基本真相参考输入后，您的 Lambda 函数会在字段中`evaluationReferenceInputs`接收它们。包括的参考输入取决于评估级别：


| 评估级别 | Lambda 收到 | 
| --- | --- | 
|  `SESSION`  | 所有参考输入。 | 
|  `TRACE`  | Session-level 参考输入加上与目标 traceID 匹配的参考输入。 | 
|  `TOOL_CALL`  | Session-level 参考输入加上与目标 spanID 匹配的参考输入。 | 

**注意**  
有关使用地面实况评估的更多信息，请参阅[地面实况评估](ground-truth-evaluations.md)。

## 使用基于代码的评估器进行在线评估
<a name="run-online-code-based"></a>

您可以在在线评估配置中使用基于代码的自定义评估器来持续监控代理的实时流量。致`CreateOnlineEvaluationConfig`电时在`evaluators`列表中传递评估者 ID。

**Example**  

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`）中运行它。

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']}")
   ```

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']}")
   ```

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

**注意**  
启用引用基于代码的评估器的在线评估配置时，评估器会自动锁定，并且在禁用或删除该配置之前无法修改或删除。要对评估器进行更改，请先禁用在线评估配置，或者克隆评估器并创建新配置。