Skip to content
LangSmith 文档版本 跟随上游 源快照 8c7bdb94 更新于 2026-10-18

如何定义代码评估器

在 LangSmith UI 中,代码评估器允许你直接在界面中使用 Python 或 TypeScript 代码编写自定义评估逻辑。与使用模型来评估输出的 LLM-as-a-judge 评估器不同,代码评估器使用你定义的确定性逻辑。

NOTE

若要以编程方式创建出现在 LangSmith UI 中的代码评估器,请参阅使用 SDK 管理评估器。若要定义传递给 evaluate() 的代码评估器函数,请参阅如何定义代码评估器(SDK)。若要依据数据集示例上保存的断言对输出进行评分,请参阅使用断言。

步骤 1. 创建评估器

  1. 在 LangSmith UI 的以下任一页面中创建评估器:
    • 在 Playground 中或从数据集:选择 + Evaluator 按钮。
    • 选择 Add rules,配置你的规则并选择 Apply evaluator。
  2. 为评估器取一个清晰的名称,用于描述它度量的内容(例如 "Exact Match")。
  3. 从评估器类型选项中选择 Create code evaluator。

步骤 2. 编写评估器代码

NOTE

自定义代码评估器的限制。

允许的依赖库:你可以导入所有标准库函数,以及以下公开软件包:

numpy (v2.2.2): "numpy"
pandas (v1.5.2): "pandas"
jsonschema (v4.21.1): "jsonschema"
scipy (v1.14.1): "scipy"
sklearn (v1.26.4): "scikit-learn"

网络访问:你无法在自定义代码评估器中访问互联网。

在 Add Custom Code Evaluator(添加自定义代码评估器)页面中,使用 Python 或 TypeScript 定义你的评估逻辑。

你的评估器函数必须命名为 perform_eval,并且应当:

  1. 接收 run 和 example 参数。
  2. 通过 run['inputs']、run['outputs'] 和 example['outputs'] 访问数据。
  3. 返回一个字典,其中每个键是 metric 名称,每个值是该 metric 的得分。每个键代表你想要返回的一条反馈。例如,{"correctness": 1, "silliness": 0} 会在该次运行上创建两条反馈。

函数签名

python
def perform_eval(run, example):
    # Access the data
    inputs = run['inputs']
    outputs = run['outputs']
    reference_outputs = example['outputs']  # Optional: reference/expected outputs

    # Your evaluation logic here
    score = ...

    # Return a dict with your metric name
    return {"metric_name": score}

示例:完全匹配评估器

python
def perform_eval(run, example):
    """Check if the answer exactly matches the expected answer."""
    actual = run['outputs']['answer']
    expected = example['outputs']['answer']

    is_correct = actual == expected
    return {"exact_match": is_correct}

示例:基于输入的评估器

python
def perform_eval(run, example):
    """Check if the input text contains toxic language."""
    text = run['inputs'].get('text', '').lower()
    toxic_words = ["idiot", "stupid", "hate", "awful"]

    is_toxic = any(word in text for word in toxic_words)
    return {"is_toxic": is_toxic}

步骤 3. 测试并保存

  1. 在示例数据上测试你的评估器,确保其按预期工作
  2. 点击 Save 使该评估器可供使用

使用你的代码评估器

创建完成后,你就可以使用你的代码评估器:

相关


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。