Skip to main content
智能体应用程序允许大型语言模型自行决定解决问题的下一步。这种灵活性非常强大,但模型的黑盒特性使得预测对智能体某一部分的调整将如何影响其他部分变得困难。为了构建可用于生产的智能体,彻底的测试是必不可少的。 有几种方法可以测试您的智能体:
  • 单元测试通过使用内存中的模拟来单独锻炼智能体的微小、确定性的部分,以便您可以快速且确定性地断言确切的行为。
  • 集成测试 通过使用真实的网络调用来测试智能体,以确认组件协同工作、凭据和模式匹配,以及延迟可接受。
智能体应用往往更倾向于集成,因为它们将多个组件串联起来,并且必须处理由于大型语言模型非确定性本质而产生的不可靠性。

集成测试

许多智能体行为只有在使用真实的LLM时才会出现,例如智能体决定调用哪个工具、如何格式化响应,或者提示修改是否影响整个执行轨迹。LangChain的agentevals包提供了专门为测试智能体轨迹与实时模型而设计的评估器。 AgentEvals 允许您通过执行 轨迹匹配 或使用 LLM 判定器,轻松评估您的智能体(包括工具调用的确切消息序列)的轨迹。

Trajectory match

为给定输入硬编码一个参考轨迹,并通过逐步比较来验证运行。非常适合测试定义明确的流程,其中您知道预期的行为。当您对应该调用哪些工具以及调用顺序有具体期望时使用。这种方法是确定性的、快速的且成本效益高,因为它不需要额外的LLM调用。

LLM-as-judge

使用大型语言模型(LLM)对智能体的执行轨迹进行定性验证。“裁判” LLM 将智能体的决策与提示准则(可能包括参考轨迹)进行对比。更灵活,可以评估细微方面,如效率和适宜性,但需要调用LLM,且确定性较低。当您想评估智能体轨迹的整体质量和合理性,而不需要严格的工具调用或排序要求时使用。

安装 AgentEvals

npm install agentevals @langchain/core
或者,直接克隆 AgentEvals 仓库

轨迹匹配评估器

AgentEvals 提供了 createTrajectoryMatchEvaluator 函数,用于将您的智能体轨迹与参考轨迹进行匹配。有四种模式可供选择:
模式描述应用场景
strict按相同顺序匹配消息和工具调用测试特定序列(例如,在授权前查找策略)
unordered允许任何顺序的工具调用验证信息检索时顺序不重要
subset智能体仅调用参考工具(无额外工具)确保智能体不超过预期范围
superset智能体至少调用参考工具(允许额外工具)验证是否采取了所需的最小行动
strict 模式确保轨迹包含相同顺序的相同工具调用的相同消息,尽管它允许消息内容存在差异。这在需要强制执行特定操作顺序时很有用,例如在授权操作之前要求查找策略。
import { createAgent, tool, HumanMessage, AIMessage, ToolMessage } from "langchain"
import { createTrajectoryMatchEvaluator } from "agentevals";
import * as z from "zod";

const getWeather = tool(
  async ({ city }: { city: string }) => {
    return `It's 75 degrees and sunny in ${city}.`;
  },
  {
    name: "get_weather",
    description: "Get weather information for a city.",
    schema: z.object({
      city: z.string(),
    }),
  }
);

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [getWeather]
});

const evaluator = createTrajectoryMatchEvaluator({  
  trajectoryMatchMode: "strict",  
});  

async function testWeatherToolCalledStrict() {
  const result = await agent.invoke({
    messages: [new HumanMessage("What's the weather in San Francisco?")]
  });

  const referenceTrajectory = [
    new HumanMessage("What's the weather in San Francisco?"),
    new AIMessage({
      content: "",
      tool_calls: [
        { id: "call_1", name: "get_weather", args: { city: "San Francisco" } }
      ]
    }),
    new ToolMessage({
      content: "It's 75 degrees and sunny in San Francisco.",
      tool_call_id: "call_1"
    }),
    new AIMessage("The weather in San Francisco is 75 degrees and sunny."),
  ];

  const evaluation = await evaluator({
    outputs: result.messages,
    referenceOutputs: referenceTrajectory
  });
  // {
  //     'key': 'trajectory_strict_match',
  //     'score': true,
  //     'comment': null,
  // }
  expect(evaluation.score).toBe(true);
}
unordered 模式允许以任何顺序调用相同的工具,这在您想验证是否检索到特定信息但不在乎顺序时很有帮助。例如,一个智能体可能需要检查一个城市的天气和事件,但顺序并不重要。
import { createAgent, tool, HumanMessage, AIMessage, ToolMessage } from "langchain"
import { createTrajectoryMatchEvaluator } from "agentevals";
import * as z from "zod";

const getWeather = tool(
  async ({ city }: { city: string }) => {
    return `It's 75 degrees and sunny in ${city}.`;
  },
  {
    name: "get_weather",
    description: "Get weather information for a city.",
    schema: z.object({ city: z.string() }),
  }
);

const getEvents = tool(
  async ({ city }: { city: string }) => {
    return `Concert at the park in ${city} tonight.`;
  },
  {
    name: "get_events",
    description: "Get events happening in a city.",
    schema: z.object({ city: z.string() }),
  }
);

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [getWeather, getEvents]
});

const evaluator = createTrajectoryMatchEvaluator({  
  trajectoryMatchMode: "unordered",  
});  

async function testMultipleToolsAnyOrder() {
  const result = await agent.invoke({
    messages: [new HumanMessage("What's happening in SF today?")]
  });

  // Reference shows tools called in different order than actual execution
  const referenceTrajectory = [
    new HumanMessage("What's happening in SF today?"),
    new AIMessage({
      content: "",
      tool_calls: [
        { id: "call_1", name: "get_events", args: { city: "SF" } },
        { id: "call_2", name: "get_weather", args: { city: "SF" } },
      ]
    }),
    new ToolMessage({
      content: "Concert at the park in SF tonight.",
      tool_call_id: "call_1"
    }),
    new ToolMessage({
      content: "It's 75 degrees and sunny in SF.",
      tool_call_id: "call_2"
    }),
    new AIMessage("Today in SF: 75 degrees and sunny with a concert at the park tonight."),
  ];

  const evaluation = await evaluator({
    outputs: result.messages,
    referenceOutputs: referenceTrajectory,
  });
  // {
  //     'key': 'trajectory_unordered_match',
  //     'score': true,
  // }
  expect(evaluation.score).toBe(true);
}
supersetsubset 模式匹配部分轨迹。superset 模式验证智能体至少调用了参考轨迹中的工具,允许调用更多工具。subset 模式确保智能体没有调用参考轨迹之外的任何工具。
import { createAgent } from "langchain"
import { tool } from "@langchain/core/tools";
import { HumanMessage, AIMessage, ToolMessage } from "@langchain/core/messages";
import { createTrajectoryMatchEvaluator } from "agentevals";
import * as z from "zod";

const getWeather = tool(
  async ({ city }: { city: string }) => {
    return `It's 75 degrees and sunny in ${city}.`;
  },
  {
    name: "get_weather",
    description: "Get weather information for a city.",
    schema: z.object({ city: z.string() }),
  }
);

const getDetailedForecast = tool(
  async ({ city }: { city: string }) => {
    return `Detailed forecast for ${city}: sunny all week.`;
  },
  {
    name: "get_detailed_forecast",
    description: "Get detailed weather forecast for a city.",
    schema: z.object({ city: z.string() }),
  }
);

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [getWeather, getDetailedForecast]
});

const evaluator = createTrajectoryMatchEvaluator({  
  trajectoryMatchMode: "superset",  
});  

async function testAgentCallsRequiredToolsPlusExtra() {
  const result = await agent.invoke({
    messages: [new HumanMessage("What's the weather in Boston?")]
  });

  // Reference only requires getWeather, but agent may call additional tools
  const referenceTrajectory = [
    new HumanMessage("What's the weather in Boston?"),
    new AIMessage({
      content: "",
      tool_calls: [
        { id: "call_1", name: "get_weather", args: { city: "Boston" } },
      ]
    }),
    new ToolMessage({
      content: "It's 75 degrees and sunny in Boston.",
      tool_call_id: "call_1"
    }),
    new AIMessage("The weather in Boston is 75 degrees and sunny."),
  ];

  const evaluation = await evaluator({
    outputs: result.messages,
    referenceOutputs: referenceTrajectory,
  });
  // {
  //     'key': 'trajectory_superset_match',
  //     'score': true,
  //     'comment': null,
  // }
  expect(evaluation.score).toBe(true);
}
您还可以设置 toolArgsMatchMode 属性和/或 toolArgsMatchOverrides 来自定义评估器如何考虑实际轨迹与参考之间工具调用之间的相等性。默认情况下,只有对同一工具使用相同参数的工具调用被视为相等。有关更多详细信息,请访问 仓库

LLM-as-Judge 评估器

您还可以使用一个LLM来使用 createTrajectoryLLMAsJudge 函数评估智能体的执行路径。与轨迹匹配评估器不同,它不需要参考轨迹,但如果有的话,也可以提供。
import { createAgent } from "langchain"
import { tool } from "@langchain/core/tools";
import { HumanMessage, AIMessage, ToolMessage } from "@langchain/core/messages";
import { createTrajectoryLLMAsJudge, TRAJECTORY_ACCURACY_PROMPT } from "agentevals";
import * as z from "zod";

const getWeather = tool(
  async ({ city }: { city: string }) => {
    return `It's 75 degrees and sunny in ${city}.`;
  },
  {
    name: "get_weather",
    description: "Get weather information for a city.",
    schema: z.object({ city: z.string() }),
  }
);

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [getWeather]
});

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

async function testTrajectoryQuality() {
  const result = await agent.invoke({
    messages: [new HumanMessage("What's the weather in Seattle?")]
  });

  const evaluation = await evaluator({
    outputs: result.messages,
  });
  // {
  //     'key': 'trajectory_accuracy',
  //     'score': true,
  //     'comment': 'The provided agent trajectory is reasonable...'
  // }
  expect(evaluation.score).toBe(true);
}
如果您有一个参考轨迹,您可以在提示中添加一个额外的变量并传入参考轨迹。下面,我们使用预构建的 TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE 提示并配置 reference_outputs 变量:
import { TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE } from "agentevals";

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

const evaluation = await evaluator({
  outputs: result.messages,
  referenceOutputs: referenceTrajectory,
});
为了更灵活地配置LLM评估轨迹的方式,请访问仓库

LangSmith 集成

为了跟踪随时间进行的实验,您可以将评估器结果记录到LangSmith,这是一个用于构建生产级LLM应用的平台,包括跟踪、评估和实验工具。 首先,通过设置所需的环境变量来设置 LangSmith:
export LANGSMITH_API_KEY="your_langsmith_api_key"
export LANGSMITH_TRACING="true"
LangSmith提供了两种主要的运行评估方法:Vitest/Jest集成和evaluate函数。
import * as ls from "langsmith/vitest";
// import * as ls from "langsmith/jest";

import { createTrajectoryLLMAsJudge, TRAJECTORY_ACCURACY_PROMPT } from "agentevals";

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

ls.describe("trajectory accuracy", () => {
  ls.test("accurate trajectory", {
    inputs: {
      messages: [
        {
          role: "user",
          content: "What is the weather in SF?"
        }
      ]
    },
    referenceOutputs: {
      messages: [
        new HumanMessage("What is the weather in SF?"),
        new AIMessage({
          content: "",
          tool_calls: [
            { id: "call_1", name: "get_weather", args: { city: "SF" } }
          ]
        }),
        new ToolMessage({
          content: "It's 75 degrees and sunny in SF.",
          tool_call_id: "call_1"
        }),
        new AIMessage("The weather in SF is 75 degrees and sunny."),
      ],
    },
  }, async ({ inputs, referenceOutputs }) => {
    const result = await agent.invoke({
      messages: [new HumanMessage("What is the weather in SF?")]
    });

    ls.logOutputs({ messages: result.messages });

    await trajectoryEvaluator({
      inputs,
      outputs: result.messages,
      referenceOutputs,
    });
  });
});
运行您的测试运行器进行评估:
vitest run test_trajectory.eval.ts
# or
jest test_trajectory.eval.ts
或者,您可以在LangSmith中创建一个数据集并使用 evaluate 函数:
import { evaluate } from "langsmith/evaluation";
import { createTrajectoryLLMAsJudge, TRAJECTORY_ACCURACY_PROMPT } from "agentevals";

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

async function runAgent(inputs: any) {
  const result = await agent.invoke(inputs);
  return result.messages;
}

await evaluate(
  runAgent,
  {
    data: "your_dataset_name",
    evaluators: [trajectoryEvaluator],
  }
);
结果将自动记录到LangSmith。
要了解更多关于评估您的智能体的信息,请参阅LangSmith 文档