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

如何定义要评估的目标函数

运行一次评估主要需要三个部分:

  1. 一个包含测试输入和预期输出的数据集。
  2. 一个目标函数,即你要评估的对象。
  3. 为你的目标函数输出打分的评估器。

本指南将根据你要评估的应用部分,展示如何定义目标函数。有关如何创建数据集和如何定义评估器,请参阅相应页面;有关运行评估的端到端示例,请参阅这里。

目标函数签名

要在代码中评估一个应用,我们需要一种运行该应用的方式。使用 evaluate()(Python / JavaScript)时,我们通过传入一个目标函数参数来实现。这个函数接收数据集 Example 的输入,并以 dict 形式返回应用输出。在该函数内部,我们可以按任意方式调用应用,也可以按任意方式格式化输出。关键在于,我们定义的任何评估器函数都应能处理目标函数返回的输出格式。

python
from langsmith import Client

# 'inputs' will come from your dataset.
def dummy_target(inputs: dict) -> dict:
    return {"foo": 1, "bar": "two"}

# 'inputs' will come from your dataset.
# 'outputs' will come from your target function.
def evaluator_one(inputs: dict, outputs: dict) -> bool:
    return outputs["foo"] == 2

def evaluator_two(inputs: dict, outputs: dict) -> bool:
    return len(outputs["bar"]) < 3

client = Client()
results = client.evaluate(
    dummy_target,  # <-- target function
    data="your-dataset-name",
    evaluators=[evaluator_one, evaluator_two],
    ...
)

TIP

evaluate() 会自动追踪你的目标函数。这意味着,如果你在目标函数中运行任何可追踪的代码,这些代码也会作为目标 trace 的子 run 被追踪。

示例:单次 LLM 调用

python
from langsmith import wrappers
from openai import OpenAI

# Optionally wrap the OpenAI client to automatically
# trace all model calls.
oai_client = wrappers.wrap_openai(OpenAI())

def target(inputs: dict) -> dict:
  # This assumes your dataset has inputs with a 'messages' key.
  # You can update to match your dataset schema.
  messages = inputs["messages"]
  response = oai_client.chat.completions.create(
      messages=messages,
      model="gpt-5.4-mini",
  )
  return {"answer": response.choices[0].message.content}
typescript
import OpenAI from 'openai';
import { wrapOpenAI } from "langsmith/wrappers";

const client = wrapOpenAI(new OpenAI());

// This is the function you will evaluate.
const target = async(inputs) => {
  // This assumes your dataset has inputs with a `messages` key
  const messages = inputs.messages;
  const response = await client.chat.completions.create({
      messages: messages,
      model: 'gpt-5.4-mini',
  });
  return { answer: response.choices[0].message.content };
}
python
from langchain.chat_models import init_chat_model

model = init_chat_model("gpt-5.4-mini")

def target(inputs: dict) -> dict:
  # This assumes your dataset has inputs with a `messages` key
  messages = inputs["messages"]
  response = model.invoke(messages)
  return {"answer": response.content}
typescript
import { ChatOpenAI } from '@langchain/openai';

// This is the function you will evaluate.
const target = async(inputs) => {
  // This assumes your dataset has inputs with a `messages` key
  const messages = inputs.messages;
  const model = new ChatOpenAI({ model: "gpt-5.4-mini" });
  const response = await model.invoke(messages);
  return {"answer": response.content};
}

示例:非 LLM 组件

python
from langsmith import traceable

# Optionally decorate with '@traceable' to trace all invocations of this function.
@traceable
def calculator_tool(operation: str, number1: float, number2: float) -> str:
  if operation == "add":
      return str(number1 + number2)
  elif operation == "subtract":
      return str(number1 - number2)
  elif operation == "multiply":
      return str(number1 * number2)
  elif operation == "divide":
      return str(number1 / number2)
  else:
      raise ValueError(f"Unrecognized operation: {operation}.")

# This is the function you will evaluate.
def target(inputs: dict) -> dict:
  # This assumes your dataset has inputs with `operation`, `num1`, and `num2` keys.
  operation = inputs["operation"]
  number1 = inputs["num1"]
  number2 = inputs["num2"]
  result = calculator_tool(operation, number1, number2)
  return {"result": result}
typescript
import { traceable } from "langsmith/traceable";

// Optionally wrap in 'traceable' to trace all invocations of this function.
const calculatorTool = traceable(async ({ operation, number1, number2 }) => {
// Functions must return strings
if (operation === "add") {
  return (number1 + number2).toString();
} else if (operation === "subtract") {
  return (number1 - number2).toString();
} else if (operation === "multiply") {
  return (number1 * number2).toString();
} else if (operation === "divide") {
  return (number1 / number2).toString();
} else {
  throw new Error("Invalid operation.");
}
});

// This is the function you will evaluate.
const target = async (inputs) => {
// This assumes your dataset has inputs with `operation`, `num1`, and `num2` keys
const result = await calculatorTool.invoke({
  operation: inputs.operation,
  number1: inputs.num1,
  number2: inputs.num2,
});
return { result };
}

示例:应用或 agent

python
from my_agent import agent

      # This is the function you will evaluate.
def target(inputs: dict) -> dict:
  # This assumes your dataset has inputs with a `messages` key
  messages = inputs["messages"]
  # Replace `invoke` with whatever you use to call your agent
  response = agent.invoke({"messages": messages})
  # This assumes your agent output is in the right format
  return response
typescript
import { agent } from 'my_agent';

// This is the function you will evaluate.
const target = async(inputs) => {
// This assumes your dataset has inputs with a `messages` key
const messages = inputs.messages;
// Replace `invoke` with whatever you use to call your agent
const response = await agent.invoke({ messages });
// This assumes your agent output is in the right format
return response;
}

TIP

如果你有 LangGraph/LangChain agent,它接受数据集中定义的输入,并返回你希望在评估器中使用的输出格式,那么你可以直接将该对象作为目标传入:

python
from my_agent import agent
from langsmith import Client
client = Client()
client.evaluate(agent, ...)

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