평가할 대상 함수 정의하기
평가할 대상 함수 정의하기
평가를 실행하려면 세 가지 주요 요소가 필요해요:
이 가이드는 애플리케이션의 어느 부분을 평가하는지에 따라 대상 함수를 정의하는 방법을 보여줘요. 데이터셋 만드는 방법과 평가자 정의 방법은 여기, 평가 실행의 엔드투엔드 예시는 여기를 참고하세요.
출처: 문서
본문
대상 함수 시그니처
코드에서 애플리케이션을 평가하려면 애플리케이션을 실행할 방법이 필요해요. evaluate()(Python / JavaScript)를 사용할 때는 대상 함수 인자를 전달해 이를 수행해요. 대상 함수는 데이터셋 예시(Example)의 입력을 받아 애플리케이션 출력을 dict로 반환하는 함수예요. 이 함수 안에서 원하는 방식으로 애플리케이션을 호출할 수 있어요. 출력을 원하는 방식으로 형식화할 수도 있어요. 핵심은 우리가 정의한 모든 평가자 함수가 대상 함수에서 반환하는 출력 형식과 함께 작동해야 한다는 것이에요.
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],
...
)
evaluate()는 대상 함수를 자동으로 추적해요. 즉 대상 함수 내에서 추적 가능한 코드를 실행하면 이것도 대상 트레이스의 하위 런으로 추적돼요.
예시: 단일 LLM 호출
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}
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 };
}
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}
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이 아닌 구성 요소
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}
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 };
}
예시: 애플리케이션 또는 에이전트
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
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;
}
데이터셋에 정의된 입력을 받아들이고 평가자에서 사용하려는 출력 형식을 반환하는 LangGraph/LangChain 에이전트가 있다면, 그 객체를 대상으로 직접 전달할 수 있어요:
from my_agent import agent from langsmith import Client client = Client() client.evaluate(agent, ...)