Skip to Content
評価カスタム評価

LLMを審査員としたカスタム評価

この例では、AIシェフエージェントを使ってレシピのグルテン含有量をチェックするために、MastraでカスタムのLLMベース評価指標を作成する方法を示します。

概要

この例では、以下の方法を示します。

  1. カスタムのLLMベースの指標を作成する
  2. エージェントを使ってレシピを生成し評価する
  3. レシピにグルテンが含まれているか確認する
  4. グルテンの由来について詳細なフィードバックを提供する

セットアップ

環境設定

環境変数を必ず設定してください:

.env
OPENAI_API_KEY=your_api_key_here

プロンプトの定義

評価システムでは、3つの異なるプロンプトが使用されており、それぞれ特定の目的を持っています。

1. インストラクションプロンプト

このプロンプトは、判定者の役割とコンテキストを設定します。

src/mastra/evals/recipe-completeness/prompts.ts
export const GLUTEN_INSTRUCTIONS = `You are a Master Chef that identifies if recipes contain gluten.`;

2. グルテン評価プロンプト

このプロンプトは、グルテンの含有を構造的に評価し、特定の成分をチェックします。

src/mastra/evals/recipe-completeness/prompts.ts
export const generateGlutenPrompt = ({ output, }: { output: string; }) => `Check if this recipe is gluten-free. Check for: - Wheat - Barley - Rye - Common sources like flour, pasta, bread Example with gluten: "Mix flour and water to make dough" Response: { "isGlutenFree": false, "glutenSources": ["flour"] } Example gluten-free: "Mix rice, beans, and vegetables" Response: { "isGlutenFree": true, "glutenSources": [] } Recipe to analyze: ${output} Return your response in this format: { "isGlutenFree": boolean, "glutenSources": ["list ingredients containing gluten"] }`;

3. 推論プロンプト

このプロンプトは、レシピが完全か不完全かについての詳細な説明を生成します。

src/mastra/evals/recipe-completeness/prompts.ts
export const generateReasonPrompt = ({ isGlutenFree, glutenSources, }: { isGlutenFree: boolean; glutenSources: string[]; }) => `Explain why this recipe is${isGlutenFree ? "" : " not"} gluten-free. ${glutenSources.length > 0 ? `Sources of gluten: ${glutenSources.join(", ")}` : "No gluten-containing ingredients found"} Return your response in this format: { "reason": "This recipe is [gluten-free/contains gluten] because [explanation]" }`;

ジャッジの作成

レシピのグルテン含有量を評価するための専門的なジャッジを作成できます。上記で定義したプロンプトをインポートし、ジャッジで使用します。

src/mastra/evals/gluten-checker/metricJudge.ts
import { type LanguageModel } from "@mastra/core/llm"; import { MastraAgentJudge } from "@mastra/evals/judge"; import { z } from "zod"; import { GLUTEN_INSTRUCTIONS, generateGlutenPrompt, generateReasonPrompt, } from "./prompts"; export class RecipeCompletenessJudge extends MastraAgentJudge { constructor(model: LanguageModel) { super("Gluten Checker", GLUTEN_INSTRUCTIONS, model); } async evaluate(output: string): Promise<{ isGlutenFree: boolean; glutenSources: string[]; }> { const glutenPrompt = generateGlutenPrompt({ output }); const result = await this.agent.generate(glutenPrompt, { output: z.object({ isGlutenFree: z.boolean(), glutenSources: z.array(z.string()), }), }); return result.object; } async getReason(args: { isGlutenFree: boolean; glutenSources: string[]; }): Promise<string> { const prompt = generateReasonPrompt(args); const result = await this.agent.generate(prompt, { output: z.object({ reason: z.string(), }), }); return result.object.reason; } }

このジャッジクラスは、主に2つのメソッドを通じてコアとなる評価ロジックを処理します。

  • evaluate(): レシピのグルテン含有量を分析し、グルテンの有無と判定結果を返します
  • getReason(): 評価結果に対する人間が理解しやすい説明を提供します

メトリックの作成

ジャッジを使用するメトリッククラスを作成します:

src/mastra/evals/gluten-checker/index.ts
export interface MetricResultWithInfo extends MetricResult { info: { reason: string; glutenSources: string[]; }; } export class GlutenCheckerMetric extends Metric { private judge: GlutenCheckerJudge; constructor(model: LanguageModel) { super(); this.judge = new GlutenCheckerJudge(model); } async measure(output: string): Promise<MetricResultWithInfo> { const { isGlutenFree, glutenSources } = await this.judge.evaluate(output); const score = await this.calculateScore(isGlutenFree); const reason = await this.judge.getReason({ isGlutenFree, glutenSources, }); return { score, info: { glutenSources, reason, }, }; } async calculateScore(isGlutenFree: boolean): Promise<number> { return isGlutenFree ? 1 : 0; } }

このメトリッククラスは、グルテン含有量の評価のためのメインインターフェースとして機能し、以下のメソッドを持ちます:

  • measure(): 評価プロセス全体を統括し、包括的な結果を返します
  • calculateScore(): 評価の判定をバイナリスコア(グルテンフリーなら1、グルテン含有なら0)に変換します

エージェントのセットアップ

エージェントを作成し、メトリックを追加します:

src/mastra/agents/chefAgent.ts
import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; import { GlutenCheckerMetric } from "../evals"; export const chefAgent = new Agent({ name: "chef-agent", instructions: "You are Michel, a practical and experienced home chef" + "You help people cook with whatever ingredients they have available.", model: openai("gpt-4o-mini"), evals: { glutenChecker: new GlutenCheckerMetric(openai("gpt-4o-mini")), }, });

使用例

このメトリックをエージェントで使用する方法は次のとおりです:

src/index.ts
import { mastra } from "./mastra"; const chefAgent = mastra.getAgent("chefAgent"); const metric = chefAgent.evals.glutenChecker; // Example: Evaluate a recipe const input = "What is a quick way to make rice and beans?"; const response = await chefAgent.generate(input); const result = await metric.measure(input, response.text); console.log("Metric Result:", { score: result.score, glutenSources: result.info.glutenSources, reason: result.info.reason, }); // Example Output: // Metric Result: { score: 1, glutenSources: [], reason: 'The recipe is gluten-free as it does not contain any gluten-containing ingredients.' }

結果の理解

この指標は以下を提供します:

  • グルテンフリーのレシピには1、グルテンを含むレシピには0のスコア
  • グルテン源のリスト(該当する場合)
  • レシピのグルテン含有量に関する詳細な理由付け
  • 以下に基づく評価:
    • 材料リスト





GitHubで例を見る