以编程方式使用文档

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

步骤 1. 创建评估器

1. 从以下页面之一创建评估器 LangSmith UI: - 在 Playground 或数据集中:选择 **+ 评估器** button. - 选择 **添加规则**,配置规则并选择 **应用评估器**. 1. 给您的评估器起一个清晰的名称,描述它测量的内容(例如,"精确匹配")。 1. 选择 **创建代码评估器** 来自评估器类型选项。

第2步。编写您的评估器代码

在 **添加自定义代码评估器** 页面中,使用 Python 或 TypeScript 定义您的评估逻辑。

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

  1. 接受 runexample parameters.
  2. 通过以下方式访问数据 run['inputs'], run['outputs'],以及 example['outputs'].
  3. 返回一个字典,其中每个键是指标名称,每个值是该指标的分数。每个键代表您想要返回的一条反馈。例如, {"correctness": 1, "silliness": 0} 将在运行中创建两条反馈。

函数签名

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}

示例:精确匹配评估器

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}

示例:基于输入的评估器

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. 点击 **保存** 以使评估器可供使用

使用您的代码评估器

创建后,您可以使用您的代码评估器:

相关