ツール呼び出し精度スコアリングの例
Mastra では、ツール呼び出しの精度を評価するために 2 つのスコアラーを提供しています:
- 決定的な評価向けの コードベーススコアラー
- 意味的な評価向けの LLM ベーススコアラー
インストール
npm install @mastra/evals
API の詳細なドキュメントと設定オプションについては、
Tool Call Accuracy Scorers
を参照してください。
コードベーススコアラーの例
コードベーススコアラーは、ツールの厳密一致に基づく決定的な二値スコア(0 または 1)を提供します。
インポート
import { createToolCallAccuracyScorerCode } from "@mastra/evals/scorers/code";
import { createAgentTestRun, createUIMessage, createToolInvocation } from "@mastra/evals/utils";
正しいツール選択
src/example-correct-tool.ts
const scorer = createToolCallAccuracyScorerCode({
expectedTool: 'weather-tool'
});
// ツール呼び出しを伴う LLM の入出力をシミュレート
const inputMessages = [
createUIMessage({
content: 'What is the weather like in New York today?',
role: 'user',
id: 'input-1'
})
];
const output = [
createUIMessage({
content: 'Let me check the weather for you.',
role: 'assistant',
id: 'output-1',
toolInvocations: [
createToolInvocation({
toolCallId: 'call-123',
toolName: 'weather-tool',
args: { location: 'New York' },
result: { temperature: '72°F', condition: 'sunny' },
state: 'result'
})
]
})
];
const run = createAgentTestRun({ inputMessages, output });
const result = await scorer.run(run);
console.log(result.score); // 1
console.log(result.preprocessStepResult?.correctToolCalled); // true
ストリクトモードでの評価
ちょうど 1 つのツールが呼び出された場合のみ合格します:
src/example-strict-mode.ts
const strictScorer = createToolCallAccuracyScorerCode({
expectedTool: 'weather-tool',
strictMode: true
});
// 複数のツールが呼び出されたため、ストリクトモードでは不合格
const output = [
createUIMessage({
content: 'Let me help you with that.',
role: 'assistant',
id: 'output-1',
toolInvocations: [
createToolInvocation({
toolCallId: 'call-1',
toolName: 'search-tool',
args: {},
result: {},
state: 'result',
}),
createToolInvocation({
toolCallId: 'call-2',
toolName: 'weather-tool',
args: { location: 'New York' },
result: { temperature: '20°C' },
state: 'result',
})
]
})
];
const result = await strictScorer.run(run);
console.log(result.score); // 0 - 複数のツールが呼び出されたため不合格
ツール順序の検証
ツールが特定の順序で呼び出されることを検証します:
src/example-order-validation.ts
const orderScorer = createToolCallAccuracyScorerCode({
expectedTool: 'auth-tool', // 順序が指定されている場合は無視
expectedToolOrder: ['auth-tool', 'fetch-tool'],
strictMode: true // 余分なツールは不可
});
const output = [
createUIMessage({
content: 'I will authenticate and fetch the data.',
role: 'assistant',
id: 'output-1',
toolInvocations: [
createToolInvocation({
toolCallId: 'call-1',
toolName: 'auth-tool',
args: { token: 'abc123' },
result: { authenticated: true },
state: 'result'
}),
createToolInvocation({
toolCallId: 'call-2',
toolName: 'fetch-tool',
args: { endpoint: '/data' },
result: { data: ['item1'] },
state: 'result'
})
]
})
];
const result = await orderScorer.run(run);
console.log(result.score); // 1 - 正しい順序
柔軟な順序モード
期待されるツールが相対的な順序を保っている限り、追加のツールを許可します:
src/example-flexible-order.ts
const flexibleOrderScorer = createToolCallAccuracyScorerCode({
expectedTool: 'auth-tool',
expectedToolOrder: ['auth-tool', 'fetch-tool'],
strictMode: false // 追加のツールを許可する
});
const output = [
createUIMessage({
content: '包括的な処理を実行します。',
role: 'assistant',
id: 'output-1',
toolInvocations: [
createToolInvocation({
toolCallId: 'call-1',
toolName: 'auth-tool',
args: { token: 'abc123' },
result: { authenticated: true },
state: 'result'
}),
createToolInvocation({
toolCallId: 'call-2',
toolName: 'log-tool', // 追加のツール - フレキシブルモードでは許可
args: { message: '取得を開始' },
result: { logged: true },
state: 'result'
}),
createToolInvocation({
toolCallId: 'call-3',
toolName: 'fetch-tool',
args: { endpoint: '/data' },
result: { data: ['item1'] },
state: 'result'
})
]
})
];
const result = await flexibleOrderScorer.run(run);
console.log(result.score); // 1 - auth-tool が fetch-tool より先に実行される
LLMベースのスコアラー例
LLMベースのスコアラーは、ユーザーのリクエストに対してツール選択が適切かどうかをAIで評価します。
インポート
import { createToolCallAccuracyScorerLLM } from "@mastra/evals/scorers/llm";
import { openai } from "@ai-sdk/openai";
基本的なLLM評価
src/example-llm-basic.ts
const llmScorer = createToolCallAccuracyScorerLLM({
model: openai('gpt-4o-mini'),
availableTools: [
{
name: 'weather-tool',
description: 'Get current weather information for any location'
},
{
name: 'calendar-tool',
description: 'Check calendar events and scheduling'
},
{
name: 'search-tool',
description: 'Search the web for general information'
}
]
});
const inputMessages = [
createUIMessage({
content: 'What is the weather like in San Francisco today?',
role: 'user',
id: 'input-1'
})
];
const output = [
createUIMessage({
content: 'Let me check the current weather for you.',
role: 'assistant',
id: 'output-1',
toolInvocations: [
createToolInvocation({
toolCallId: 'call-123',
toolName: 'weather-tool',
args: { location: 'San Francisco', date: 'today' },
result: { temperature: '68°F', condition: 'foggy' },
state: 'result'
})
]
})
];
const run = createAgentTestRun({ inputMessages, output });
const result = await llmScorer.run(run);
console.log(result.score); // 1.0 - 適切なツール使用
console.log(result.reason); // "エージェントはユーザーの天気情報リクエストに対して、weather-toolを正しく使用しました。"
不適切なツール使用の扱い
src/example-llm-inappropriate.ts
const inputMessages = [
createUIMessage({
content: 'What is the weather in Tokyo?',
role: 'user',
id: 'input-1'
})
];
const inappropriateOutput = [
createUIMessage({
content: 'Let me search for that information.',
role: 'assistant',
id: 'output-1',
toolInvocations: [
createToolInvocation({
toolCallId: 'call-456',
toolName: 'search-tool', // weather-toolより適切性が低い
args: { query: 'Tokyo weather' },
result: { results: ['Tokyo weather data...'] },
state: 'result'
})
]
})
];
const run = createAgentTestRun({ inputMessages, output: inappropriateOutput });
const result = await llmScorer.run(run);
console.log(result.score); // 0.5 - 一部は適切
console.log(result.reason); // "直接的な天気の問い合わせにはweather-toolのほうが適切であるにもかかわらず、エージェントはsearch-toolを使用しました。"
確認(明確化)要求の評価
LLMスコアラーは、エージェントが適切に明確化を求めている場合を認識します:
src/example-llm-clarification.ts
const vagueInput = [
createUIMessage({
content: 'I need help with something',
role: 'user',
id: 'input-1'
})
];
const clarificationOutput = [
createUIMessage({
content: "お手伝いします!どのような点でお困りか、もう少し詳しく教えていただけますか?",
role: 'assistant',
id: 'output-1',
// ツールは未使用 - 代わりに明確化を依頼
})
];
const run = createAgentTestRun({
inputMessages: vagueInput,
output: clarificationOutput
});
const result = await llmScorer.run(run);
console.log(result.score); // 1.0 - 明確化を求めるのは適切
console.log(result.reason); // "情報が不十分な状態でツールを呼び出すのではなく、エージェントは適切に明確化を求めました。"
2つのスコアラーを比較する
同じデータに両方のスコアラーを適用する例を示します:
src/example-comparison.ts
import { createToolCallAccuracyScorerCode as createCodeScorer } from '@mastra/evals/scorers/code';
import { createToolCallAccuracyScorerLLM as createLLMScorer } from '@mastra/evals/scorers/llm';
import { openai } from '@ai-sdk/openai';
// 両方のスコアラーをセットアップ
const codeScorer = createCodeScorer({
expectedTool: 'weather-tool',
strictMode: false
});
const llmScorer = createLLMScorer({
model: openai('gpt-4o-mini'),
availableTools: [
{ name: 'weather-tool', description: 'Get weather information' },
{ name: 'search-tool', description: 'Search the web' }
]
});
// テストデータ
const run = createAgentTestRun({
inputMessages: [
createUIMessage({
content: 'What is the weather?',
role: 'user',
id: 'input-1'
})
],
output: [
createUIMessage({
content: 'その情報を見つけますね。',
role: 'assistant',
id: 'output-1',
toolInvocations: [
createToolInvocation({
toolCallId: 'call-1',
toolName: 'search-tool',
args: { query: 'weather' },
result: { results: ['weather data'] },
state: 'result'
})
]
})
]
});
// 両方のスコアラーを実行
const codeResult = await codeScorer.run(run);
const llmResult = await llmScorer.run(run);
console.log('Code Scorer:', codeResult.score); // 0 - 不適切なツール
console.log('LLM Scorer:', llmResult.score); // 0.3 - 部分的に適切
console.log('LLM Reason:', llmResult.reason); // search-tool がより不適切な理由の説明
設定オプション
コードベースのスコアラーのオプション
// 標準モード - 期待どおりのツールが呼び出されれば合格
const lenientScorer = createCodeScorer({
expectedTool: 'search-tool',
strictMode: false
});
// 厳格モード - ツールがちょうど1回だけ呼び出された場合に合格
const strictScorer = createCodeScorer({
expectedTool: 'search-tool',
strictMode: true
});
// 厳格モードでの順序チェック
const strictOrderScorer = createCodeScorer({
expectedTool: 'step1-tool',
expectedToolOrder: ['step1-tool', 'step2-tool', 'step3-tool'],
strictMode: true // 余計なツールは不可
});
LLMベースのスコアラーのオプション
// 基本設定
const basicLLMScorer = createLLMScorer({
model: openai('gpt-4o-mini'),
availableTools: [
{ name: 'tool1', description: 'Description 1' },
{ name: 'tool2', description: 'Description 2' }
]
});
// 別のモデルを使用
const customModelScorer = createLLMScorer({
model: openai('gpt-4'), // より複雑な評価に適した高性能モデル
availableTools: [...]
});
結果の理解
コードベースのスコアラーの結果
{
runId: string,
preprocessStepResult: {
expectedTool: string,
actualTools: string[],
strictMode: boolean,
expectedToolOrder?: string[],
hasToolCalls: boolean,
correctToolCalled: boolean,
correctOrderCalled: boolean | null,
toolCallInfos: ToolCallInfo[]
},
score: number // 常に 0 または 1
}
LLM ベースのスコアラーの結果
{
runId: string,
score: number, // 0.0 〜 1.0
reason: string, // 人間が理解しやすい説明
analyzeStepResult: {
evaluations: Array<{
toolCalled: string,
wasAppropriate: boolean,
reasoning: string
}>,
missingTools?: string[]
}
}
スコアラーの使い分け
Code-Based Scorer を使う場面
- ユニットテスト
- CI/CD パイプライン
- 回帰テスト
- ツールの厳密な一致要件
- ツール呼び出し順序の検証
LLM-Based Scorer を使う場面
- 本番環境での評価
- 品質保証
- ユーザー意図との整合
- 文脈を踏まえた評価
- 例外的・境界的なケースへの対応
View Example on GitHub