การเขียนปลั๊กอิน Genkit Evaluator

คุณสามารถขยาย Firebase Genkit เพื่อรองรับการประเมินผลลัพธ์ของกรอบการทดสอบแบบกำหนดเองได้ ไม่ว่าจะใช้ LLM เป็นผู้ตัดสินหรือจะใช้โปรแกรมเพียงอย่างเดียว

คำจำกัดความของผู้ประเมิน

ผู้ประเมินคือฟังก์ชันที่ประเมินเนื้อหาที่ LLM กำหนดและสร้างขึ้น การประเมินอัตโนมัติ (การทดสอบ) มี 2 วิธีหลัก ได้แก่ การประเมินฮิวริสติกและการประเมินโดยใช้ LLM ในแนวทางการเรียนรู้แบบฮิวริสติก คุณจะกำหนดฟังก์ชันเชิงกำหนดเช่นเดียวกับการพัฒนาซอฟต์แวร์แบบดั้งเดิม ในการประเมินโดยใช้ LLM ระบบจะฟีดเนื้อหากลับไปยัง LLM และขอให้ LLM ให้คะแนนผลลัพธ์ตามเกณฑ์ที่กำหนดไว้ในพรอมต์

ผู้ประเมินที่ใช้ LLM

ผู้ประเมินที่ใช้ LLM ใช้ประโยชน์จาก LLM เพื่อประเมินอินพุต บริบท หรือเอาต์พุตของฟีเจอร์ Generative AI

ผู้ประเมินที่ใช้ LLM ใน Genkit ประกอบด้วย 3 องค์ประกอบดังนี้

  • ข้อความแจ้ง
  • ฟังก์ชันการให้คะแนน
  • การดำเนินการของผู้ประเมิน

กำหนดพรอมต์

สำหรับตัวอย่างนี้ พรอมต์จะขอให้ LLM ตัดสินความอร่อยของผลลัพธ์ ขั้นแรก ให้บริบทกับ LLM จากนั้นอธิบายสิ่งที่คุณต้องการให้ LLM ทำ และสุดท้าย แสดงตัวอย่าง 2-3 รายการเพื่ออ้างอิง

Genkit มาพร้อมกับ dotprompt ซึ่งมอบวิธีง่ายๆ ในการกำหนดและจัดการพรอมต์พร้อมฟีเจอร์ เช่น การตรวจสอบสคีมาอินพุต/เอาต์พุต มาดูวิธีใช้ dotprompt เพื่อกำหนดข้อความแจ้งให้ประเมิน

import { defineDotprompt } from '@genkit-ai/dotprompt';

// Define the expected output values
const DELICIOUSNESS_VALUES = ['yes', 'no', 'maybe'] as const;

// Define the response schema expected from the LLM
const DeliciousnessDetectionResponseSchema = z.object({
  reason: z.string(),
  verdict: z.enum(DELICIOUSNESS_VALUES),
});
type DeliciousnessDetectionResponse = z.infer<
  typeof DeliciousnessDetectionResponseSchema
>;

const DELICIOUSNESS_PROMPT = defineDotprompt(
  {
    input: {
      schema: z.object({
        output: z.string(),
      }),
    },
    output: {
      schema: DeliciousnessDetectionResponseSchema,
    },
  },
  `You are a food critic with a wide range in taste. Given the output, decide if it sounds delicious and provide your reasoning. Use only "yes" (if delicous), "no" (if not delicious), "maybe" (if you can't decide) as the verdict.

Here are a few examples:

Output:
Chicken parm sandwich
Response:
{ "reason": "This is a classic sandwich enjoyed by many - totally delicious", "verdict":"yes"}

Output:
Boston logan international airport tarmac
Response:
{ "reason": "This is not edible and definitely not delicious.", "verdict":"no"}

Output:
A juicy piece of gossip
Response:
{ "reason": "Gossip is sometimes metaphorically referred to as tasty.", "verdict":"maybe"}

Here is a new submission to assess:

Output:
{{output}}
Response:
`
);

กำหนดฟังก์ชันการให้คะแนน

ต่อไป ให้กำหนดฟังก์ชันที่จะใช้เป็นตัวอย่าง ซึ่งรวมถึง output ตามที่พรอมต์กำหนดและให้คะแนนผลลัพธ์ กรอบการทดสอบ Genkit ประกอบด้วย input เป็นช่องที่ต้องกรอก โดยมีช่องที่ไม่บังคับสำหรับ output และ context ผู้ประเมินมีหน้าที่ตรวจสอบว่ามีช่องที่จำเป็นทั้งหมดสำหรับการประเมิน

/**
 * Score an individual test case for delciousness.
 */
export async function deliciousnessScore<
  CustomModelOptions extends z.ZodTypeAny,
>(
  judgeLlm: ModelArgument<CustomModelOptions>,
  dataPoint: BaseDataPoint,
  judgeConfig?: CustomModelOptions
): Promise<Score> {
  const d = dataPoint;
  // Validate the input has required fields
  if (!d.output) {
    throw new Error('Output is required for Deliciousness detection');
  }

  //Hydrate the prompt
  const finalPrompt = DELICIOUSNESS_PROMPT.renderText({
    output: d.output as string,
  });

  // Call the LLM to generate an evaluation result
  const response = await generate({
    model: judgeLlm,
    prompt: finalPrompt,
    config: judgeConfig,
  });

  // Parse the output
  const parsedResponse = response.output();
  if (!parsedResponse) {
    throw new Error(`Unable to parse evaluator response: ${response.text()}`);
  }

  // Return a scored response
  return {
    score: parsedResponse.verdict,
    details: { reasoning: parsedResponse.reason },
  };
}

กำหนดการดำเนินการของผู้ประเมิน

ขั้นตอนสุดท้ายคือการเขียนฟังก์ชันที่กำหนดการดำเนินการของผู้ประเมิน

/**
 * Create the Deliciousness evaluator action.
 */
export function createDeliciousnessEvaluator<
  ModelCustomOptions extends z.ZodTypeAny,
>(
  judge: ModelReference<ModelCustomOptions>,
  judgeConfig: z.infer<ModelCustomOptions>
): EvaluatorAction {
  return defineEvaluator(
    {
      name: `myAwesomeEval/deliciousness`,
      displayName: 'Deliciousness',
      definition: 'Determines if output is considered delicous.',
    },
    async (datapoint: BaseDataPoint) => {
      const score = await deliciousnessScore(judge, datapoint, judgeConfig);
      return {
        testCaseId: datapoint.testCaseId,
        evaluation: score,
      };
    }
  );
}

ผู้ประเมินผลการเรียนรู้

โปรแกรมประเมินผลการเรียนรู้เป็นฟังก์ชันใดก็ได้ที่ใช้ประเมินอินพุต บริบท หรือเอาต์พุตของฟีเจอร์ Generative AI

ผู้ประเมินผลการเรียนรู้ใน Genkit ประกอบด้วย 2 องค์ประกอบดังนี้

  • ฟังก์ชันการให้คะแนน
  • การดำเนินการของผู้ประเมิน

กำหนดฟังก์ชันการให้คะแนน

กำหนดฟังก์ชันการให้คะแนนเช่นเดียวกับผู้ประเมินที่ใช้ LLM ในกรณีนี้ ฟังก์ชันการให้คะแนนไม่จำเป็นต้องทราบเกี่ยวกับ LLM ของการตัดสินหรือการกำหนดค่า

const US_PHONE_REGEX =
  /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4}$/i;

/**
 * Scores whether an individual datapoint matches a US Phone Regex.
 */
export async function usPhoneRegexScore(
  dataPoint: BaseDataPoint
): Promise<Score> {
  const d = dataPoint;
  if (!d.output || typeof d.output !== 'string') {
    throw new Error('String output is required for regex matching');
  }
  const matches = US_PHONE_REGEX.test(d.output as string);
  const reasoning = matches
    ? `Output matched regex ${regex.source}`
    : `Output did not match regex ${regex.source}`;
  return {
    score: matches,
    details: { reasoning },
  };
}

กำหนดการดำเนินการของผู้ประเมิน

/**
 * Configures a regex evaluator to match a US phone number.
 */
export function createUSPhoneRegexEvaluator(
  metrics: RegexMetric[]
): EvaluatorAction[] {
  return metrics.map((metric) => {
    const regexMetric = metric as RegexMetric;
    return defineEvaluator(
      {
        name: `myAwesomeEval/${metric.name.toLocaleLowerCase()}`,
        displayName: 'Regex Match',
        definition:
          'Runs the output against a regex and responds with 1 if a match is found and 0 otherwise.',
        isBilled: false,
      },
      async (datapoint: BaseDataPoint) => {
        const score = await regexMatchScore(datapoint, regexMetric.regex);
        return fillScores(datapoint, score);
      }
    );
  });
}

การกำหนดค่า

ตัวเลือกปลั๊กอิน

กำหนด PluginOptions ที่ปลั๊กอินสำหรับการประเมินที่กำหนดเองจะใช้ ออบเจ็กต์นี้ไม่มีข้อกำหนดที่เข้มงวดและขึ้นอยู่กับประเภทของผู้ประเมินที่กำหนด

อย่างน้อยที่สุดจะต้องมีการจำแนกเมตริกที่จะบันทึก

export enum MyAwesomeMetric {
  WORD_COUNT = 'WORD_COUNT',
  US_PHONE_REGEX_MATCH = 'US_PHONE_REGEX_MATCH',
}

export interface PluginOptions {
  metrics?: Array<MyAwesomeMetric>;
}

หากปลั๊กอินใหม่นี้ใช้ LLM เป็นตัวตัดสิน และปลั๊กอินรองรับการสลับ LLM ที่จะใช้ ให้กำหนดพารามิเตอร์เพิ่มเติมในออบเจ็กต์ PluginOptions

export enum MyAwesomeMetric {
  DELICIOUSNESS = 'DELICIOUSNESS',
  US_PHONE_REGEX_MATCH = 'US_PHONE_REGEX_MATCH',
}

export interface PluginOptions<ModelCustomOptions extends z.ZodTypeAny> {
  judge: ModelReference<ModelCustomOptions>;
  judgeConfig?: z.infer<ModelCustomOptions>;
  metrics?: Array<MyAwesomeMetric>;
}

คำจำกัดความของปลั๊กอิน

ระบบจะลงทะเบียนปลั๊กอินกับเฟรมเวิร์กผ่านไฟล์ genkit.config.ts ในโปรเจ็กต์ หากต้องการกำหนดค่าปลั๊กอินใหม่ ให้กำหนดฟังก์ชันที่กำหนด GenkitPlugin และกำหนดค่าด้วย PluginOptions ที่ระบุไว้ข้างต้น

ในกรณีนี้ เรามีผู้ประเมิน 2 คน DELICIOUSNESS และ US_PHONE_REGEX_MATCH ซึ่งผู้ประเมินเหล่านั้นจะมีการลงทะเบียนด้วยปลั๊กอินและ Firebase Genkit

export function myAwesomeEval<ModelCustomOptions extends z.ZodTypeAny>(
  params: PluginOptions<ModelCustomOptions>
): PluginProvider {
  // Define the new plugin
  const plugin = genkitPlugin(
    'myAwesomeEval',
    async (params: PluginOptions<ModelCustomOptions>) => {
      const { judge, judgeConfig, metrics } = params;
      const evaluators: EvaluatorAction[] = metrics.map((metric) => {
        // We'll create these functions in the next step
        switch (metric) {
          case DELICIOUSNESS:
            // This evaluator requires an LLM as judge
            return createDeliciousnessEvaluator(judge, judgeConfig);
          case US_PHONE_REGEX_MATCH:
            // This evaluator does not require an LLM
            return createUSPhoneRegexEvaluator();
        }
      });
      return { evaluators };
    }
  );

  // Create the plugin with the passed params
  return plugin(params);
}
export default myAwesomeEval;

กำหนดค่า Genkit

เพิ่มปลั๊กอินที่กำหนดไว้ใหม่ในการกำหนดค่า Genkit

สำหรับการประเมินด้วย Gemini ให้ปิดการตั้งค่าความปลอดภัยเพื่อให้ผู้ประเมินยอมรับ ตรวจจับ และให้คะแนนเนื้อหาที่อาจเป็นอันตรายได้

import { geminiPro } from '@genkit-ai/googleai';

export default configureGenkit({
  plugins: [
    ...
    myAwesomeEval({
      judge: geminiPro,
      judgeConfig: {
        safetySettings: [
          {
            category: 'HARM_CATEGORY_HATE_SPEECH',
            threshold: 'BLOCK_NONE',
          },
          {
            category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
            threshold: 'BLOCK_NONE',
          },
          {
            category: 'HARM_CATEGORY_HARASSMENT',
            threshold: 'BLOCK_NONE',
          },
          {
            category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
            threshold: 'BLOCK_NONE',
          },
        ],
      },
      metrics: [
        MyAwesomeMetric.DELICIOUSNESS,
        MyAwesomeMetric.US_PHONE_REGEX_MATCH
      ],
    }),
  ],
  ...
});

การทดสอบ

ปัญหาเดียวกับที่ใช้ในการประเมินคุณภาพของผลลัพธ์ของฟีเจอร์ Generative AI จะใช้กับการประเมินความสามารถในการตัดสินของผู้ประเมินที่ใช้ LLM

หากต้องการทราบว่าผู้ประเมินที่กำหนดเองทำงานได้ในระดับที่คาดไว้หรือไม่ ให้สร้างชุดกรอบการทดสอบที่มีคำตอบถูกและผิดอย่างชัดเจน

ตัวอย่างความอร่อย อาจดูเหมือนไฟล์ json deliciousness_dataset.json:

[
  {
    "testCaseId": "delicous_mango",
    "input": "What is a super delicious fruit",
    "output": "A perfectly ripe mango – sweet, juicy, and with a hint of tropical sunshine."
  },
  {
    "testCaseId": "disgusting_soggy_cereal",
    "input": "What is something that is tasty when fresh but less tasty after some time?",
    "output": "Stale, flavorless cereal that's been sitting in the box too long."
  }
]

ตัวอย่างเหล่านี้สร้างขึ้นโดยมนุษย์หรือคุณสามารถขอให้ LLM ช่วยสร้างชุดกรอบการทดสอบที่ดูแลจัดการได้ มีชุดข้อมูลเปรียบเทียบมากมายที่นำมาใช้ได้

จากนั้นใช้ Genkit CLI เพื่อเรียกใช้ผู้ประเมินกับกรอบการทดสอบเหล่านี้

genkit eval:run deliciousness_dataset.json

ดูผลลัพธ์ใน Genkit UI

genkit start

นำทางไปยัง localhost:4000/evaluate