ปลั๊กอิน Google Generative AI

ปลั๊กอิน Google Generative AI ให้อินเทอร์เฟซสำหรับโมเดล Gemini ของ Google ผ่าน Gemini API

การติดตั้ง

npm i --save @genkit-ai/googleai

การกำหนดค่า

หากต้องการใช้ปลั๊กอินนี้ ให้ระบุเมื่อเรียกใช้ configureGenkit():

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

export default configureGenkit({
  plugins: [googleAI()],
  // ...
});

ปลั๊กอินต้องใช้คีย์ API สำหรับ Gemini API ซึ่งดาวน์โหลดได้จาก Google AI Studio

กำหนดค่าปลั๊กอินเพื่อใช้คีย์ API โดยทำอย่างใดอย่างหนึ่งต่อไปนี้

  • ตั้งค่าตัวแปรสภาพแวดล้อม GOOGLE_GENAI_API_KEY เป็นคีย์ API

  • ระบุคีย์ API เมื่อคุณเริ่มต้นปลั๊กอิน

    googleAI({ apiKey: yourKey });
    

    อย่างไรก็ตาม อย่าฝังคีย์ API ในโค้ดโดยตรง ใช้ฟีเจอร์นี้เท่านั้น บริการอย่างเช่น Cloud Secret Manager หรือบริการอื่นๆ ที่คล้ายกัน

บางรุ่น (เช่น Gemini 1.5 Pro) อยู่ในเวอร์ชันตัวอย่างและสามารถเรียกใช้ได้ผ่าน v1beta API คุณระบุ apiVersion เพื่อเข้าถึงโมเดลเหล่านั้นได้

configureGenkit({
  plugins: [googleAI({ apiVersion: 'v1beta' })],
});

หรือคุณสามารถระบุได้หลายเวอร์ชันหากต้องการใช้ ในเวลาเดียวกัน

configureGenkit({
  plugins: [googleAI({ apiVersion: ['v1', 'v1beta'] })],
});

การใช้งาน

ปลั๊กอินนี้จะส่งออกการอ้างอิงแบบคงที่ไปยังโมเดลที่รองรับ ดังนี้

import {
  gemini15Flash,
  gemini15Pro,
  textEmbeddingGecko001,
} from '@genkit-ai/googleai';

คุณสามารถใช้การอ้างอิงเหล่านี้เพื่อระบุโมเดลที่ generate() ใช้ ดังนี้

const llmResponse = await generate({
  model: gemini15Flash,
  prompt: 'Tell me a joke.',
});

หรือใช้เครื่องมือฝัง (เช่น textEmbeddingGecko001) กับ embed หรือรีทรีฟเวอร์:

const embedding = await embed({
  embedder: textEmbeddingGecko001,
  content: input,
});

API ไฟล์ Gemini

คุณสามารถใช้ไฟล์ที่อัปโหลดไปยัง Gemini Files API ด้วย Genkit ได้ดังนี้

import { GoogleAIFileManager } from '@google/generative-ai/server';

const fileManager = new GoogleAIFileManager(process.env.GOOGLE_GENAI_API_KEY);
const uploadResult = await fileManager.uploadFile(
  'path/to/file.jpg',
  {
    mimeType: 'image/jpeg',
    displayName: 'Your Image',
  }
);

const response = await generate({
  model: gemini15Flash,
  prompt: [
    {text: "Describe this image:},
    {media: {contentType: uploadResult.file.mimeType, url: uploadResult.file.uri}}
  ]
});