跳到主要内容

在 CI 中运行 Scorer

在 CI Pipeline 中运行 Scorer,可以提供可量化的指标来衡量 Agent 质量随时间的变化。runEvals 函数会将多个测试用例交给 Agent 或 Workflow 处理,并返回聚合分数。

基础设置
基础设置的直接链接

可以使用任何支持 ESM 模块的测试框架,例如 VitestJestMocha

创建测试用例
创建测试用例的直接链接

使用 runEvals 针对多个测试用例评估 Agent。该函数接受数据项目数组,每个项目均包含 input,还可包含供 Scorer 验证使用的 groundTruth

src/mastra/agents/weather-agent.test.ts
import { describe, it, expect } from 'vitest'
import { createScorer, runEvals } from '@mastra/core/evals'
import { weatherAgent } from './weather-agent'
import { locationScorer } from '../scorers/location-scorer'

describe('Weather Agent Tests', () => {
it('should correctly extract locations from queries', async () => {
const result = await runEvals({
data: [
{
input: 'weather in Berlin',
groundTruth: { expectedLocation: 'Berlin', expectedCountry: 'DE' },
},
{
input: 'weather in Berlin, Maryland',
groundTruth: { expectedLocation: 'Berlin', expectedCountry: 'US' },
},
{
input: 'weather in Berlin, Russia',
groundTruth: { expectedLocation: 'Berlin', expectedCountry: 'RU' },
},
],
target: weatherAgent,
scorers: [locationScorer],
})

// Assert aggregate score meets threshold
expect(result.scores['location-accuracy']).toBe(1)
expect(result.summary.totalItems).toBe(3)
})
})

理解结果
理解结果的直接链接

runEvals 函数返回一个包含以下内容的对象:

  • scores:每个 Scorer 在所有测试用例上的平均分数
  • summary.totalItems:已处理的测试用例总数
{
scores: {
'location-accuracy': 1.0, // Average score across all items
'another-scorer': 0.85
},
summary: {
totalItems: 3
}
}

多种测试场景
多种测试场景的直接链接

为不同评估场景创建单独的测试用例:

src/mastra/agents/weather-agent.test.ts
describe('Weather Agent Tests', () => {
const locationScorer = createScorer({/* ... */})

it('should handle location disambiguation', async () => {
const result = await runEvals({
data: [
{
input: 'weather in Berlin',
groundTruth: {/* ... */},
},
{
input: 'weather in Berlin, Maryland',
groundTruth: {/* ... */},
},
],
target: weatherAgent,
scorers: [locationScorer],
})

expect(result.scores['location-accuracy']).toBe(1)
})

it('should handle typos and misspellings', async () => {
const result = await runEvals({
data: [
{
input: 'weather in Berln',
groundTruth: { expectedLocation: 'Berlin', expectedCountry: 'DE' },
},
{
input: 'weather in Parris',
groundTruth: { expectedLocation: 'Paris', expectedCountry: 'FR' },
},
],
target: weatherAgent,
scorers: [locationScorer],
})

expect(result.scores['location-accuracy']).toBe(1)
})
})

后续步骤
后续步骤的直接链接