以编程方式使用文档

评估 是一种量化衡量 LLM 应用性能的方法。LLM 的行为可能难以预测,即使是对提示词、模型或输入的微小更改也可能显著影响结果。评估提供了一种结构化方法来识别失败、比较版本,并构建更可靠的 AI 应用。

在 LangSmith 中运行评估需要三个关键组件:

  • - 数据集:一组测试输入(以及可选的预期输出)。
  • - 目标函数:您想要测试的应用部分——这可能是一个带有新提示词的单个 LLM 调用、一个模块,或您整个工作流程。
  • - 评估器:对目标函数输出进行评分的函数。

本快速入门指南将引导您完成运行一个用于检查 LLM 响应正确性的入门级评估,可使用 LangSmith SDK 或 UI。

前提条件

在开始之前,请确保您已具备:

选择 UI 或 SDK 筛选器以获取说明:

UI

1. 设置工作区密钥

2. 创建提示词

Playground 使您能够对不同的提示词、新模型或不同的模型配置运行评估。

  1. LangSmith UI中,点击 **Playground** 在侧边栏中。
  2. 在 **提示词** 面板下,修改 **系统** 提示词为:
    Answer the following question accurately:
    

保留 **用户** 消息不变: {question}.

3. 创建数据集

  1. 点击 **设置评估**,这将打开一个 **新实验** 表格在页面底部。
  2. 在 **选择或创建新数据集** 下拉菜单中,点击 **+ 新建** 按钮以创建新数据集。
带有编辑后的系统提示和用于创建新数据集的下拉菜单的新实验的 Playground。 带有编辑后的系统提示和用于创建新数据集的下拉菜单的新实验的 Playground。
  1. 将以下示例添加到数据集:
输入参考输出
问题:乞力马扎罗山位于哪个国家?输出:乞力马扎罗山位于坦桑尼亚。
问题:地球的最低点是什么?输出:地球的最低点是死海。
  1. 点击 **保存** 并输入名称以保存新创建的数据集。

4. 添加评估器

  1. 点击 **+ Evaluator** 并选择 **Correctness** 从 **预置评估器** options.
  2. 在 **Correctness** 面板中点击 **保存**.

5. 运行评估

  1. 选择 **Start** 在右上角来运行您的评估。这将创建一个 实验 并在新实验表中预览。您可以点击实验名称查看完整内容。 **New Experiment** table. You can view in full by clicking the experiment name.
使用示例数据集的实验结果的完整视图。 使用示例数据集的实验结果的完整视图。

后续步骤

SDK

1. 安装依赖项

在您的终端中,为您的项目创建一个目录并安装环境中的依赖项:

mkdir ls-evaluation-quickstart && cd ls-evaluation-quickstart
python -m venv .venv && source .venv/bin/activate
python -m pip install --upgrade pip
pip install -U langsmith openevals openai
mkdir ls-evaluation-quickstart-ts && cd ls-evaluation-quickstart-ts
npm init -y
npm install langsmith openevals openai
npx tsc --init

2. 设置环境变量

设置以下环境变量:

  • - LANGSMITH_TRACING
  • - LANGSMITH_API_KEY
  • - OPENAI_API_KEY (或您的LLM提供商的API密钥)
  • - (可选) LANGSMITH_WORKSPACE_ID:如果您的LangSmith API密钥链接到多个 工作区,请设置此变量以指定要使用的工作区。

3. 创建数据集

  1. 创建一个文件并添加以下代码,这将:
  • - 导入 Client 以连接到LangSmith。
  • - 创建数据集。
  • - 定义示例 _输入_ 和 _输出_.
  • - 在LangSmith中将输入和输出对与该数据集关联,以便它们可用于评估。
    # dataset.py
    from langsmith import Client

    def main():
        client = Client()

        # Programmatically create a dataset in LangSmith
        dataset = client.create_dataset(
            dataset_name="Sample dataset",
            description="A sample dataset in LangSmith."
        )

        # Create examples
        examples = [
            {
                "inputs": {"question": "Which country is Mount Kilimanjaro located in?"},
                "outputs": {"answer": "Mount Kilimanjaro is located in Tanzania."},
            },
            {
                "inputs": {"question": "What is Earth's lowest point?"},
                "outputs": {"answer": "Earth's lowest point is The Dead Sea."},
            },
        ]

        # Add examples to the dataset
        client.create_examples(dataset_id=dataset.id, examples=examples)
        print("Created dataset:", dataset.name)

    if __name__ == "__main__":
        main()

    
    // dataset.ts


    async function main() {
    const client = new Client();

    const dataset = await client.createDataset(
        "Sample dataset",
        { description: "A sample dataset in LangSmith." }
    );

    // Define examples
    const inputs = [
        { question: "Which country is Mount Kilimanjaro located in?" },
        { question: "What is Earth's lowest point?" },
    ];
    const outputs = [
        { answer: "Mount Kilimanjaro is located in Tanzania." },
        { answer: "Earth's lowest point is The Dead Sea." },
    ];

    await client.createExamples({
        datasetId: dataset.id,
        inputs,
        outputs,
    });

    console.log("Created dataset:", dataset.name);
    }

    if (require.main === module) {
    main().catch((e) => {
        console.error(e);
        process.exit(1);
    });
    }
    
  1. 在终端中,运行 dataset 文件以创建用于评估您的应用的数据集:
    python dataset.py
    
    npx ts-node dataset.ts
    

您将看到以下输出:

    Created dataset: Sample dataset
    

4. 创建目标函数

定义一个 目标函数 包含您正在评估的内容。在本指南中,您将定义一个包含单个LLM调用的目标函数来回答问题。

将以下内容添加到 eval file:

# eval.py
from langsmith import Client, wrappers
from openai import OpenAI

# Wrap the OpenAI client for LangSmith tracing
openai_client = wrappers.wrap_openai(OpenAI())

# Define the application logic you want to evaluate inside a target function
# The SDK will automatically send the inputs from the dataset to your target function
def target(inputs: dict) -> dict:
    response = openai_client.chat.completions.create(
        model="gpt-5-mini",
        messages=[
            {"role": "system", "content": "Answer the following question accurately"},
            {"role": "user", "content": inputs["question"]},
        ],
    )
    return {"answer": response.choices[0].message.content.strip()}
// eval.ts




const openaiClient = wrapOpenAI(new OpenAI());

async function target(inputs: Record<string, any>): Promise<Record<string, any>> {
  const question = String(inputs.question ?? "");
  const resp = await openaiClient.chat.completions.create({
    model: "gpt-5-mini",
    messages: [
      { role: "system", content: "Answer the following question accurately" },
      { role: "user", content: question },
    ],
  });
  return { answer: resp.choices[0].message.content?.trim() ?? "" };
}

5. 定义评估器

在此步骤中,您要告诉LangSmith如何对应用生成的答案进行评分。

从导入预构建的评估提示(CORRECTNESS_PROMPT)从 openevals 以及一个将其包装为 LLM即评判评估器的辅助函数,这将评估应用的输出。

评估器比较:

  • - inputs:传入目标函数的内容(例如,问题文本)。
  • - outputs:目标函数返回的内容(例如,模型的答案)。
  • - reference_outputs:您在第3步中附加到每个数据集示例的标准答案 第3步.

将以下高亮代码添加到您的 eval file:

from langsmith import Client, wrappers
from openai import OpenAI
from openevals.llm import create_llm_as_judge
from openevals.prompts import CORRECTNESS_PROMPT

# Wrap the OpenAI client for LangSmith tracing
openai_client = wrappers.wrap_openai(OpenAI())

# Define the application logic you want to evaluate inside a target function
# The SDK will automatically send the inputs from the dataset to your target function
def target(inputs: dict) -> dict:
    response = openai_client.chat.completions.create(
        model="gpt-5-mini",
        messages=[
            {"role": "system", "content": "Answer the following question accurately"},
            {"role": "user", "content": inputs["question"]},
        ],
    )
    return {"answer": response.choices[0].message.content.strip()}

def correctness_evaluator(inputs: dict, outputs: dict, reference_outputs: dict):
    evaluator = create_llm_as_judge(
        prompt=CORRECTNESS_PROMPT,
        model="openai:o3-mini",
        feedback_key="correctness",
    )
    return evaluator(
        inputs=inputs,
        outputs=outputs,
        reference_outputs=reference_outputs
    )
const openaiClient = wrapOpenAI(new OpenAI());

async function target(inputs: Record<string, any>): Promise<Record<string, any>> {
  const question = String(inputs.question ?? "");
  const resp = await openaiClient.chat.completions.create({
    model: "gpt-5-mini",
    messages: [
      { role: "system", content: "Answer the following question accurately" },
      { role: "user", content: question },
    ],
  });
  return { answer: resp.choices[0].message.content?.trim() ?? "" };
}

const judge = createLLMAsJudge({
  prompt: CORRECTNESS_PROMPT,
  model: "openai:o3-mini",
  feedbackKey: "correctness",
});

async function correctnessEvaluator(run: {
  inputs: Record<string, any>;
  outputs: Record<string, any>;
  referenceOutputs?: Record<string, any>;
}) {
  return judge({
    inputs: run.inputs,
    outputs: run.outputs,
    // OpenEvals expects snake_case here:
    reference_outputs: run.referenceOutputs,
  });
}

6. 运行并查看结果

要运行评估实验,请调用 evaluate(...),它会:

  • - 从您在 第 3 步.
  • - 创建的数据集中拉取示例,将每个示例的输入发送到您在 第 4 步.
  • - 中的目标函数,并收集输出(模型的回答)。
  • - 将输出连同 reference_outputs 一起传递给您在 第 5 步.
  • - 中的评估器,并将所有结果记录到 LangSmith 中作为实验,以便您可以在界面中查看。
  1. 将高亮显示的代码添加到您的 eval file:
    from langsmith import Client, wrappers
    from openai import OpenAI
    from openevals.llm import create_llm_as_judge
    from openevals.prompts import CORRECTNESS_PROMPT

    # Wrap the OpenAI client for LangSmith tracing
    openai_client = wrappers.wrap_openai(OpenAI())

    # Define the application logic you want to evaluate inside a target function
    # The SDK will automatically send the inputs from the dataset to your target function
    def target(inputs: dict) -> dict:
        response = openai_client.chat.completions.create(
            model="gpt-5-mini",
            messages=[
                {"role": "system", "content": "Answer the following question accurately"},
                {"role": "user", "content": inputs["question"]},
            ],
        )
        return {"answer": response.choices[0].message.content.strip()}

    def correctness_evaluator(inputs: dict, outputs: dict, reference_outputs: dict):
        evaluator = create_llm_as_judge(
            prompt=CORRECTNESS_PROMPT,
            model="openai:o3-mini",
            feedback_key="correctness",
        )
        return evaluator(
            inputs=inputs,
            outputs=outputs,
            reference_outputs=reference_outputs
        )

    # After running the evaluation, a link will be provided to view the results in langsmith
    def main():
        client = Client()
        experiment_results = client.evaluate(
            target,
            data="Sample dataset",
            evaluators=[
                correctness_evaluator,
                # can add multiple evaluators here
            ],
            experiment_prefix="first-eval-in-langsmith",
            max_concurrency=2,
        )
        print(experiment_results)

    if __name__ == "__main__":
        main()
    
    const openaiClient = wrapOpenAI(new OpenAI());

    async function target(inputs: Record<string, any>): Promise<Record<string, any>> {
    const question = String(inputs.question ?? "");
    const resp = await openaiClient.chat.completions.create({
        model: "gpt-5-mini",
        messages: [
        { role: "system", content: "Answer the following question accurately" },
        { role: "user", content: question },
        ],
    });
    return { answer: resp.choices[0].message.content?.trim() ?? "" };
    }

    const judge = createLLMAsJudge({
    prompt: CORRECTNESS_PROMPT,
    model: "openai:o3-mini",
    feedbackKey: "correctness",
    });

    async function correctnessEvaluator(run: {
    inputs: Record<string, any>;
    outputs: Record<string, any>;
    referenceOutputs?: Record<string, any>;
    }) {
    return judge({
        inputs: run.inputs,
        outputs: run.outputs,
        // OpenEvals expects snake_case here:
        reference_outputs: run.referenceOutputs,
    });
    }

    async function main() {
    const datasetName = process.env.DATASET_NAME ?? "Sample dataset";

    const results = await evaluate(target, {
        data: datasetName,
        evaluators: [correctnessEvaluator],
        experimentPrefix: "first-eval-in-langsmith",
        maxConcurrency: 2,
    });

    console.log(results);
    }

    if (require.main === module) {
    main().catch((e) => {
        console.error(e);
        process.exit(1);
    });
    }
    
  1. 运行评估器:
    python eval.py
    
    npx ts-node eval.ts
    
  1. 您将收到一个链接,用于查看评估结果和实验结果的元数据:
    View the evaluation results for experiment: 'first-eval-in-langsmith-00000000' at: https://smith.langchain.com/o/6551f9c4-2685-4a08-86b9-1b29643deb3d/datasets/e5fde557-c274-4e49-b39d-000000000000/compare?selectedSessions=70b11778-6a28-4cdb-be81-000000000000


    
  1. 请按照评估运行输出中的链接访问 **数据集与实验** 页面 LangSmith UI,并探索实验结果。这将带您进入已创建的实验,其中包含一个显示 **输入**, **参考输出**和 **输出**。您可以选择一个数据集来打开展开的结果视图。
点击链接后在UI中显示的实验结果。 点击链接后在UI中显示的实验结果。

后续步骤

以下是您可能想要接下来探索的一些主题: