跳到内容

评估

要评估智能体的性能,您可以使用 LangSmith 评估。您首先需要定义一个评估器函数来判断智能体的结果,例如最终输出或轨迹。根据您的评估技术,这可能涉及或不涉及参考输出

const evaluator = async (params: {
  inputs: Record<string, unknown>;
  outputs: Record<string, unknown>;
  referenceOutputs?: Record<string, unknown>;
}) => {
  // compare agent outputs against reference outputs
  const outputMessages = params.outputs.messages;
  const referenceMessages = params.referenceOutputs.messages;
  const score = compareMessages(outputMessages, referenceMessages);
  return { key: "evaluator_score", score: score };
};

要开始使用,您可以使用 AgentEvals 包中预构建的评估器

npm install agentevals @langchain/core

创建评估器

评估智能体性能的一种常见方法是将其轨迹(调用其工具的顺序)与参考轨迹进行比较

import { createTrajectoryMatchEvaluator } from "agentevals";

const outputs = [
  {
    role: "assistant",
    tool_calls: [
      {
        function: {
          name: "get_weather",
          arguments: JSON.stringify({ city: "san francisco" }),
        },
      },
      {
        function: {
          name: "get_directions",
          arguments: JSON.stringify({ destination: "presidio" }),
        },
      },
    ],
  },
];

const referenceOutputs = [
  {
    role: "assistant",
    tool_calls: [
      {
        function: {
          name: "get_weather",
          arguments: JSON.stringify({ city: "san francisco" }),
        },
      },
    ],
  },
];

// Create the evaluator
const evaluator = createTrajectoryMatchEvaluator({
  trajectoryMatchMode: "superset",  // (1)!
})

// Run the evaluator
const result = await evaluator({
  outputs,
  referenceOutputs,
});
  1. 指定轨迹的比较方式。如果输出轨迹是参考轨迹的超集,则 superset 将接受其为有效。其他选项包括:严格匹配无序匹配子集与超集匹配

接下来,了解如何自定义轨迹匹配评估器

LLM作为裁判

您可以使用 LLM 作为裁判的评估器,该评估器使用 LLM 将轨迹与参考输出进行比较并输出一个分数

import {
  createTrajectoryLLMAsJudge,
  TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE
} from "agentevals";

const evaluator = createTrajectoryLLMAsJudge({
  prompt: TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE,
  model: "openai:o3-mini",
});

运行评估器

要运行评估器,您首先需要创建一个 LangSmith 数据集。要使用预构建的 AgentEvals 评估器,您需要一个具有以下架构的数据集

  • input: { messages: [...] } 用于调用智能体的输入消息。
  • output: { messages": [...] } 智能体输出中预期的消息历史。对于轨迹评估,您可以选择只保留助手消息。
import { evaluate } from "langsmith/evaluation";
import { createTrajectoryMatchEvaluator } from "agentevals";
import { createReactAgent } from "@langchain/langgraph/prebuilt";

const agent = createReactAgent({ ... })
const evaluator = createTrajectoryMatchEvaluator({ ... })
await evaluate(
  async (inputs) => await agent.invoke(inputs),
  {
    // replace with your dataset name
    data: "<Name of your dataset>",
    evaluators: [evaluator],
  }
);