跳到主要内容
要评估代理的性能,您可以使用 LangSmith 评估。您首先需要定义一个评估器函数来判断代理的结果,例如最终输出或轨迹。根据您的评估技术,这可能涉及或不涉及参考输出
def evaluator(*, outputs: dict, reference_outputs: dict):
    # compare agent outputs against reference outputs
    output_messages = outputs["messages"]
    reference_messages = reference_outputs["messages"]
    score = compare_messages(output_messages, reference_messages)
    return {"key": "evaluator_score", "score": score}
要开始使用,您可以使用 AgentEvals 包中的预构建评估器
pip install -U agentevals

创建评估器

评估代理性能的一种常见方法是将其轨迹(调用工具的顺序)与参考轨迹进行比较
import json
from agentevals.trajectory.match import create_trajectory_match_evaluator  

outputs = [
    {
        "role": "assistant",
        "tool_calls": [
            {
                "function": {
                    "name": "get_weather",
                    "arguments": json.dumps({"city": "san francisco"}),
                }
            },
            {
                "function": {
                    "name": "get_directions",
                    "arguments": json.dumps({"destination": "presidio"}),
                }
            }
        ],
    }
]
reference_outputs = [
    {
        "role": "assistant",
        "tool_calls": [
            {
                "function": {
                    "name": "get_weather",
                    "arguments": json.dumps({"city": "san francisco"}),
                }
            },
        ],
    }
]

# Create the evaluator
evaluator = create_trajectory_match_evaluator(
    trajectory_match_mode="superset",    
)

# Run the evaluator
result = evaluator(
    outputs=outputs, reference_outputs=reference_outputs
)
  1. 指定如何比较轨迹。如果输出轨迹是参考轨迹的超集,则 superset 将接受其为有效轨迹。其他选项包括:严格匹配无序匹配子集匹配
下一步,了解如何自定义轨迹匹配评估器

LLM-即-评判者

您可以使用 LLM-即-评判者评估器,它使用大型语言模型(LLM)将轨迹与参考输出进行比较并输出分数
import json
from agentevals.trajectory.llm import (
    create_trajectory_llm_as_judge,  
    TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE
)

evaluator = create_trajectory_llm_as_judge(
    prompt=TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE,
    model="openai:o3-mini"
)

运行评估器

要运行评估器,您首先需要创建一个 LangSmith 数据集。要使用预构建的 AgentEvals 评估器,您需要一个具有以下模式的数据集
  • 输入{"messages": [...]} 用于调用代理的输入消息。
  • 输出{"messages": [...]} 代理输出中预期的消息历史。对于轨迹评估,您可以选择只保留助手消息。
from langsmith import Client
from langchain.agents import create_agent
from agentevals.trajectory.match import create_trajectory_match_evaluator


client = Client()
agent = create_agent(...)
evaluator = create_trajectory_match_evaluator(...)

experiment_results = client.evaluate(
    lambda inputs: agent.invoke(inputs),
    # replace with your dataset name
    data="<Name of your dataset>",
    evaluators=[evaluator]
)

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.