text
stringlengths
0
59.1k
Use AI SDK's `generateObject` to build LLM-based evaluators:
```ts
import { buildScorer } from "@voltagent/core";
import { openai } from "@ai-sdk/openai";
import { generateObject } from "ai";
import { z } from "zod";
const JUDGE_SCHEMA = z.object({
score: z.number().min(0).max(1).describe("Score from 0 to 1"),
reason: z.string().describe("Detailed explanation"),
});
const helpfulnessScorer = buildScorer({
id: "helpfulness",
label: "Helpfulness Judge",
})
.score(async ({ payload }) => {
const prompt = `Rate the response for clarity and helpfulness.
User Input: ${payload.input}
Assistant Response: ${payload.output}
Provide a score from 0 to 1 with an explanation.`;
const response = await generateObject({
model: openai("gpt-4o-mini"),
schema: JUDGE_SCHEMA,
prompt,
maxTokens: 200,
});
return {
score: response.object.score,
metadata: {
reason: response.object.reason,
},
};
})
.build();
```
The judge calls the LLM with a structured schema, ensuring consistent scoring output.
## Prebuilt Scorers
### Moderation
```ts
import { createModerationScorer } from "@voltagent/scorers";
createModerationScorer({
model: openai("gpt-4o-mini"),
threshold: 0.5, // fail if score < 0.5
});
```
Flags unsafe content (toxicity, bias, etc.) using LLM-based classification.
### Answer Correctness
```ts
import { createAnswerCorrectnessScorer } from "@voltagent/scorers";
const scorer = createAnswerCorrectnessScorer({
buildPayload: ({ payload, params }) => ({
input: payload.input,
output: payload.output,
expected: params.expectedAnswer,
}),
});
```
Evaluates factual accuracy. Requires `expected` in params. Users implement scoring logic.
### Answer Relevancy
```ts
import { createAnswerRelevancyScorer } from "@voltagent/scorers";
const scorer = createAnswerRelevancyScorer({
strictness: 3,
buildPayload: ({ payload, params }) => ({
input: payload.input,
output: payload.output,
context: params.referenceContext,
}),
});
```
Checks if the output addresses the input. Strictness controls evaluation level.
### Keyword Match
```ts
import { buildScorer } from "@voltagent/core";
const keywordScorer = buildScorer({
id: "keyword-match",