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

如何定义代码评估器

代码评估器是一类函数,它接收数据集示例以及应用产生的输出,并返回一个或多个指标。这些函数可以直接传给 evaluate() 或 aevaluate() 函数。

TIP

要在 LangSmith 界面中定义代码评估器,请参阅如何定义代码评估器(UI)。要根据保存在数据集示例上的断言为输出打分,请参阅使用断言。

基础示例

python
from langsmith import evaluate

def correct(outputs: dict, reference_outputs: dict) -> bool:
    """检查答案是否与预期答案完全一致。"""
    return outputs["answer"] == reference_outputs["answer"]

def dummy_app(inputs: dict) -> dict:
    return {"answer": "hmm i'm not sure", "reasoning": "i didn't understand the question"}

results = evaluate(
    dummy_app,
    data="dataset_name",
    evaluators=[correct]
)
typescript
import type { EvaluationResult } from "langsmith/evaluation";

const correct = async ({ outputs, referenceOutputs }: {
  outputs: Record<string, any>;
  referenceOutputs?: Record<string, any>;
}): Promise<EvaluationResult> => {
  const score = outputs?.answer === referenceOutputs?.answer;
  return { key: "correct", score };
}

评估器参数

代码评估器函数必须使用特定的参数名。它们可以接收以下参数的任意子集:

  • run: Run:应用在给定示例上生成的完整 Run 对象。
  • example: Example:完整的数据集 Example,包括示例输入、输出(若有)和元数据(若有)。
  • inputs: dict:与数据集中单个示例相对应的输入字典。
  • outputs: dict:应用在给定 inputs 上生成的输出字典。
  • reference_outputs/referenceOutputs: dict:与该示例关联的参考输出字典(若有)。

在大多数使用场景中,你只需要 inputs、outputs 和 reference_outputs。只有在需要应用实际输入和输出之外的额外追踪或示例元数据时,run 和 example 才有用。

在使用 JS/TS 时,这些都应当作为单个对象参数的一部分传入。

评估器输出

代码评估器应返回以下类型之一:

Python 与 JS/TS

  • dict:形式为 {"score" | "value": ..., "key": ...} 的字典可以让你自定义指标类型(数值型用 "score",类别型用 "value")和指标名称。例如,当你想把某个整数记录为类别型指标时,这就很有用。

仅 Python

  • int | float | bool:这会被解释为可以求平均值、排序等的连续型指标。函数名将用作指标名称。
  • str:这会被解释为类别型指标。函数名将用作指标名称。
  • list[dict]:使用单个函数返回多个指标。

更多示例

需要 langsmith>=0.2.0

python
from langsmith import evaluate, wrappers
from langsmith.schemas import Run, Example
from openai import AsyncOpenAI
# Assumes you've installed pydantic.
from pydantic import BaseModel

# We can still pass in Run and Example objects if we'd like
def correct_old_signature(run: Run, example: Example) -> dict:
    """Check if the answer exactly matches the expected answer."""
    return {"key": "correct", "score": run.outputs["answer"] == example.outputs["answer"]}

# Just evaluate actual outputs
def concision(outputs: dict) -> int:
    """Score how concise the answer is. 1 is the most concise, 5 is the least concise."""
    return min(len(outputs["answer"]) // 1000, 4) + 1

# Use an LLM-as-a-judge
oai_client = wrappers.wrap_openai(AsyncOpenAI())

async def valid_reasoning(inputs: dict, outputs: dict) -> bool:
    """Use an LLM to judge if the reasoning and the answer are consistent."""
    instructions = """
Given the following question, answer, and reasoning, determine if the reasoning for the
answer is logically valid and consistent with question and the answer."""

    class Response(BaseModel):
        reasoning_is_valid: bool

    msg = f"Question: {inputs['question']}\nAnswer: {outputs['answer']}\nReasoning: {outputs['reasoning']}"
    response = await oai_client.beta.chat.completions.parse(
        model="gpt-5.4-mini",
        messages=[{"role": "system", "content": instructions,}, {"role": "user", "content": msg}],
        response_format=Response
    )
    return response.choices[0].message.parsed.reasoning_is_valid

def dummy_app(inputs: dict) -> dict:
    return {"answer": "hmm i'm not sure", "reasoning": "i didn't understand the question"}

results = evaluate(
    dummy_app,
    data="dataset_name",
    evaluators=[correct_old_signature, concision, valid_reasoning]
)
typescript
import { Client } from "langsmith";
import { evaluate } from "langsmith/evaluation";
import { Run, Example } from "langsmith/schemas";
import OpenAI from "openai";

// Type definitions
interface AppInputs {
    question: string;
}

interface AppOutputs {
    answer: string;
    reasoning: string;
}

interface Response {
    reasoning_is_valid: boolean;
}

// Old signature evaluator
function correctOldSignature(run: Run, example: Example) {
    return {
        key: "correct",
        score: run.outputs?.["answer"] === example.outputs?.["answer"],
    };
}

// Output-only evaluator
function concision({ outputs }: { outputs: AppOutputs }) {
    return {
        key: "concision",
        score: Math.min(Math.floor(outputs.answer.length / 1000), 4) + 1,
    };
}

// LLM-as-judge evaluator
const openai = new OpenAI();

async function validReasoning({
    inputs,
    outputs
}: {
    inputs: AppInputs;
    outputs: AppOutputs;
}) {
    const instructions = `\
  Given the following question, answer, and reasoning, determine if the reasoning for the \
  answer is logically valid and consistent with question and the answer.`;

    const msg = `Question: ${inputs.question}
Answer: ${outputs.answer}
Reasoning: ${outputs.reasoning}`;

    const response = await openai.chat.completions.create({
        model: "gpt-4",
        messages: [
            { role: "system", content: instructions },
            { role: "user", content: msg }
        ],
        response_format: { type: "json_object" },
        functions: [{
            name: "parse_response",
            parameters: {
                type: "object",
                properties: {
                    reasoning_is_valid: {
                        type: "boolean",
                        description: "Whether the reasoning is valid"
                    }
                },
                required: ["reasoning_is_valid"]
            }
        }]
    });

    const parsed = JSON.parse(response.choices[0].message.content ?? "{}") as Response;
    return {
        key: "valid_reasoning",
        score: parsed.reasoning_is_valid ? 1 : 0
    };
}

// Example application
function dummyApp(inputs: AppInputs): AppOutputs {
    return {
        answer: "hmm i'm not sure",
        reasoning: "i didn't understand the question"
    };
}

const results = await evaluate(dummyApp, {
    data: "dataset_name",
    evaluators: [correctOldSignature, concision, validReasoning],
    client: new Client()
});

相关


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