การฝัง

Gemini API มีโมเดลการฝังข้อความเพื่อสร้างการฝังสำหรับคำ วลี ประโยค และโค้ด การฝังพื้นฐานเหล่านี้ขับเคลื่อนงาน NLP ขั้นสูง เช่น การค้นหาเชิงความหมาย การจัดประเภท และการจัดกลุ่ม ซึ่งให้ผลลัพธ์ที่แม่นยำและคำนึงถึงบริบทมากกว่าแนวทางที่อิงตามคีย์เวิร์ด

การสร้างระบบการสร้างข้อความโดยใช้การดึงข้อมูล (RAG) เป็น Use Case ทั่วไปสำหรับ การฝัง Embedding มีบทบาทสำคัญในการปรับปรุงเอาต์พุตของโมเดลอย่างมาก ด้วยความถูกต้องตามข้อเท็จจริง ความสอดคล้อง และความสมบูรณ์ตามบริบทที่ได้รับการปรับปรุง โดยจะดึงข้อมูลที่เกี่ยวข้องจากฐานความรู้ได้อย่างมีประสิทธิภาพ ซึ่งแสดงโดยการฝัง จากนั้นจะส่งเป็นบริบทเพิ่มเติมในพรอมต์อินพุตไปยังโมเดลภาษา เพื่อเป็นแนวทางในการสร้างคำตอบที่มีข้อมูลครบถ้วนและถูกต้องมากขึ้น

สำหรับแอปพลิเคชันระดับองค์กรและปริมาณงานสูง เราขอแนะนำให้ใช้ โมเดลการฝังใน Vertex AI

การสร้างการฝัง

ใช้embedContentเพื่อสร้างการฝังข้อความ

Python

from google import genai

client = genai.Client()

result = client.models.embed_content(
        model="gemini-embedding-001",
        contents="What is the meaning of life?")

print(result.embeddings)

JavaScript

import { GoogleGenAI } from "@google/genai";

async function main() {

    const ai = new GoogleGenAI({});

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-001',
        contents: 'What is the meaning of life?',
    });

    console.log(response.embeddings);
}

main();

Go

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    contents := []*genai.Content{
        genai.NewContentFromText("What is the meaning of life?", genai.RoleUser),
    }
    result, err := client.Models.EmbedContent(ctx,
        "gemini-embedding-001",
        contents,
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }

    embeddings, err := json.MarshalIndent(result.Embeddings, "", "  ")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(embeddings))
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model": "models/gemini-embedding-001",
     "content": {"parts":[{"text": "What is the meaning of life?"}]}
    }'

นอกจากนี้ คุณยังสร้างการฝังสำหรับหลายๆ ก้อนพร้อมกันได้โดยส่งเป็นรายการสตริง

Python

from google import genai

client = genai.Client()

result = client.models.embed_content(
        model="gemini-embedding-001",
        contents= [
            "What is the meaning of life?",
            "What is the purpose of existence?",
            "How do I bake a cake?"
        ])

for embedding in result.embeddings:
    print(embedding)

JavaScript

import { GoogleGenAI } from "@google/genai";

async function main() {

    const ai = new GoogleGenAI({});

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-001',
        contents: [
            'What is the meaning of life?',
            'What is the purpose of existence?',
            'How do I bake a cake?'
        ],
    });

    console.log(response.embeddings);
}

main();

Go

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    contents := []*genai.Content{
        genai.NewContentFromText("What is the meaning of life?"),
        genai.NewContentFromText("How does photosynthesis work?"),
        genai.NewContentFromText("Tell me about the history of the internet."),
    }
    result, err := client.Models.EmbedContent(ctx,
        "gemini-embedding-001",
        contents,
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }

    embeddings, err := json.MarshalIndent(result.Embeddings, "", "  ")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(embeddings))
}

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model": "models/gemini-embedding-001",
     "content": [
        {"parts": [{"text": "What is the meaning of life?"}]},
        {"parts": [{"text": "What is the purpose of existence?"}]},
        {"parts": [{"text": "How do I bake a cake?"}]}
        ]
    }'

ระบุประเภทงานเพื่อปรับปรุงประสิทธิภาพ

คุณใช้การฝังสำหรับงานที่หลากหลายได้ ตั้งแต่การจัดประเภทไปจนถึงการค้นหาเอกสาร การระบุประเภทงานที่ถูกต้องจะช่วยเพิ่มประสิทธิภาพการฝังสำหรับ ความสัมพันธ์ที่ต้องการ ซึ่งจะช่วยเพิ่มความแม่นยำและประสิทธิภาพ ดูรายการประเภทงานที่รองรับทั้งหมดได้ในตารางประเภทงานที่รองรับ

ตัวอย่างต่อไปนี้แสดงวิธีใช้ SEMANTIC_SIMILARITY เพื่อตรวจสอบว่าข้อความ 2 ข้อความมีความหมายคล้ายกันมากน้อยเพียงใด

Python

from google import genai
from google.genai import types
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

client = genai.Client()

texts = [
    "What is the meaning of life?",
    "What is the purpose of existence?",
    "How do I bake a cake?"]

result = [
    np.array(e.values) for e in client.models.embed_content(
        model="gemini-embedding-001",
        contents=texts, 
        config=types.EmbedContentConfig(task_type="SEMANTIC_SIMILARITY")).embeddings
]

# Calculate cosine similarity. Higher scores = greater semantic similarity.

embeddings_matrix = np.array(result)
similarity_matrix = cosine_similarity(embeddings_matrix)

for i, text1 in enumerate(texts):
    for j in range(i + 1, len(texts)):
        text2 = texts[j]
        similarity = similarity_matrix[i, j]
        print(f"Similarity between '{text1}' and '{text2}': {similarity:.4f}")

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as cosineSimilarity from "compute-cosine-similarity";

async function main() {
    const ai = new GoogleGenAI({});

    const texts = [
        "What is the meaning of life?",
        "What is the purpose of existence?",
        "How do I bake a cake?",
    ];

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-001',
        contents: texts,
        taskType: 'SEMANTIC_SIMILARITY'
    });

    const embeddings = response.embeddings.map(e => e.values);

    for (let i = 0; i < texts.length; i++) {
        for (let j = i + 1; j < texts.length; j++) {
            const text1 = texts[i];
            const text2 = texts[j];
            const similarity = cosineSimilarity(embeddings[i], embeddings[j]);
            console.log(`Similarity between '${text1}' and '${text2}': ${similarity.toFixed(4)}`);
        }
    }
}

main();

Go

package main

import (
    "context"
    "fmt"
    "log"
    "math"

    "google.golang.org/genai"
)

// cosineSimilarity calculates the similarity between two vectors.
func cosineSimilarity(a, b []float32) (float64, error) {
    if len(a) != len(b) {
        return 0, fmt.Errorf("vectors must have the same length")
    }

    var dotProduct, aMagnitude, bMagnitude float64
    for i := 0; i < len(a); i++ {
        dotProduct += float64(a[i] * b[i])
        aMagnitude += float64(a[i] * a[i])
        bMagnitude += float64(b[i] * b[i])
    }

    if aMagnitude == 0 || bMagnitude == 0 {
        return 0, nil
    }

    return dotProduct / (math.Sqrt(aMagnitude) * math.Sqrt(bMagnitude)), nil
}

func main() {
    ctx := context.Background()
    client, _ := genai.NewClient(ctx, nil)
    defer client.Close()

    texts := []string{
        "What is the meaning of life?",
        "What is the purpose of existence?",
        "How do I bake a cake?",
    }

    var contents []*genai.Content
    for _, text := range texts {
        contents = append(contents, genai.NewContentFromText(text, genai.RoleUser))
    }

    result, _ := client.Models.EmbedContent(ctx,
        "gemini-embedding-001",
        contents,
        &genai.EmbedContentRequest{TaskType: genai.TaskTypeSemanticSimilarity},
    )

    embeddings := result.Embeddings

    for i := 0; i < len(texts); i++ {
        for j := i + 1; j < len(texts); j++ {
            similarity, _ := cosineSimilarity(embeddings[i].Values, embeddings[j].Values)
            fmt.Printf("Similarity between '%s' and '%s': %.4f\n", texts[i], texts[j], similarity)
        }
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "contents": [
        {"parts": [{"text": "What is the meaning of life?"}]},
        {"parts": [{"text": "What is the purpose of existence?"}]},
        {"parts": [{"text": "How do I bake a cake?"}]}
    ],
    "embedding_config": {
        "task_type": "SEMANTIC_SIMILARITY"
    }
}'

ต่อไปนี้คือตัวอย่างเอาต์พุตจากข้อมูลโค้ดนี้

Similarity between 'What is the meaning of life?' and 'What is the purpose of existence?': 0.9481

Similarity between 'What is the meaning of life?' and 'How do I bake a cake?': 0.7471

Similarity between 'What is the purpose of existence?' and 'How do I bake a cake?': 0.7371

ประเภทงานที่รองรับ

ประเภทงาน คำอธิบาย ตัวอย่าง
SEMANTIC_SIMILARITY การฝังที่เพิ่มประสิทธิภาพเพื่อประเมินความคล้ายคลึงของข้อความ ระบบการแนะนำ การตรวจหาเนื้อหาที่ซ้ำกัน
การจัดประเภท การฝังที่เพิ่มประสิทธิภาพเพื่อจัดประเภทข้อความตามป้ายกำกับที่ตั้งไว้ล่วงหน้า การวิเคราะห์ความรู้สึก การตรวจจับสแปม
การจัดกลุ่ม การฝังที่ได้รับการเพิ่มประสิทธิภาพเพื่อจัดกลุ่มข้อความตามความคล้ายคลึงกัน การจัดระเบียบเอกสาร การวิจัยตลาด การตรวจจับความผิดปกติ
RETRIEVAL_DOCUMENT การฝังที่เพิ่มประสิทธิภาพสำหรับการค้นหาเอกสาร จัดทำดัชนีบทความ หนังสือ หรือหน้าเว็บสำหรับการค้นหา
RETRIEVAL_QUERY การฝังที่เพิ่มประสิทธิภาพสําหรับคําค้นหาทั่วไป ใช้ RETRIEVAL_QUERY สำหรับการค้นหา และ RETRIEVAL_DOCUMENT สำหรับเอกสารที่จะดึงข้อมูล โฆษณาการค้นหาที่กำหนดเอง
CODE_RETRIEVAL_QUERY การฝังที่เพิ่มประสิทธิภาพสำหรับการดึงข้อมูลโค้ดบล็อกตามคำค้นหาที่เป็นภาษาธรรมชาติ ใช้ CODE_RETRIEVAL_QUERY สำหรับการค้นหา และ RETRIEVAL_DOCUMENT สำหรับบล็อกโค้ดที่จะดึงข้อมูล คำแนะนำและการค้นหาโค้ด
QUESTION_ANSWERING การฝังสำหรับคำถามในระบบตอบคำถาม ซึ่งได้รับการเพิ่มประสิทธิภาพเพื่อค้นหาเอกสารที่ตอบคำถาม ใช้ QUESTION_ANSWERING สำหรับคำถาม และ RETRIEVAL_DOCUMENT สำหรับเอกสารที่จะดึงข้อมูล แชทบ็อกซ์
FACT_VERIFICATION การฝังสำหรับข้อความที่ต้องได้รับการยืนยัน ซึ่งได้รับการเพิ่มประสิทธิภาพสำหรับการดึงเอกสารที่มีหลักฐานสนับสนุนหรือหักล้างข้อความ ใช้ FACT_VERIFICATION สำหรับข้อความเป้าหมาย RETRIEVAL_DOCUMENT สำหรับเอกสารที่จะดึงข้อมูล ระบบตรวจสอบข้อเท็จจริงอัตโนมัติ

การควบคุมขนาดการฝัง

โมเดลการฝัง Gemini gemini-embedding-001 ได้รับการฝึกโดยใช้เทคนิค Matryoshka Representation Learning (MRL) ซึ่งสอนให้โมเดลgemini-embedding-001เรียนรู้การฝังที่มีมิติสูงซึ่งมีส่วนเริ่มต้น (หรือคำนำหน้า) ที่เป็นเวอร์ชันที่ง่ายกว่าและมีประโยชน์ของข้อมูลเดียวกัน คุณเลือกใช้การฝังแบบ 3072 มิติแบบเต็ม หรือจะตัดให้มีขนาดเล็กลง โดยไม่สูญเสียคุณภาพเพื่อประหยัดพื้นที่เก็บข้อมูลก็ได้ เราขอแนะนำให้ใช้ค่า 768 และ 1536 เพื่อคุณภาพที่ดีที่สุด

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

Python

from google import genai
from google.genai import types

client = genai.Client()

result = client.models.embed_content(
    model="gemini-embedding-001",
    contents="What is the meaning of life?",
    config=types.EmbedContentConfig(output_dimensionality=768)
)

[embedding_obj] = result.embeddings
embedding_length = len(embedding_obj.values)

print(f"Length of embedding: {embedding_length}")

JavaScript

import { GoogleGenAI } from "@google/genai";

async function main() {
    const ai = new GoogleGenAI({});

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-001',
        content: 'What is the meaning of life?',
        outputDimensionality: 768,
    });

    const embeddingLength = response.embedding.values.length;
    console.log(`Length of embedding: ${embeddingLength}`);
}

main();

Go

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    // The client uses Application Default Credentials.
    // Authenticate with 'gcloud auth application-default login'.
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    contents := []*genai.Content{
        genai.NewContentFromText("What is the meaning of life?", genai.RoleUser),
    }

    result, err := client.Models.EmbedContent(ctx,
        "gemini-embedding-001",
        contents,
        &genai.EmbedContentRequest{OutputDimensionality: 768},
    )
    if err != nil {
        log.Fatal(err)
    }

    embedding := result.Embeddings[0]
    embeddingLength := len(embedding.Values)
    fmt.Printf("Length of embedding: %d\n", embeddingLength)
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent" \
-H "x-goog-api-key: YOUR_GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "contents": [
        {"parts": [{"text": "What is the meaning of life?"}]}
    ],
    "embedding_config": {
        "output_dimensionality": 768
    }
}'

ตัวอย่างเอาต์พุต

Length of embedding: 768

ระบบจะทําให้การฝังมิติข้อมูล 3072 เป็นปกติ การฝังที่ปรับให้เป็นมาตรฐานจะสร้างความคล้ายคลึงเชิงความหมายที่แม่นยำยิ่งขึ้นโดยการเปรียบเทียบทิศทางเวกเตอร์ ไม่ใช่ขนาด สำหรับมิติข้อมูลอื่นๆ รวมถึง 768 และ 1536 คุณต้องทําการปรับให้เป็นมาตรฐาน ดังนี้

Python

import numpy as np
from numpy.linalg import norm

embedding_values_np = np.array(embedding_obj.values)
normed_embedding = embedding_values_np / np.linalg.norm(embedding_values_np)

print(f"Normed embedding length: {len(normed_embedding)}")
print(f"Norm of normed embedding: {np.linalg.norm(normed_embedding):.6f}") # Should be very close to 1

ตัวอย่างเอาต์พุต

Normed embedding length: 768
Norm of normed embedding: 1.000000

กรณีการใช้งาน

การฝังข้อความมีความสําคัญอย่างยิ่งต่อ Use Case ของ AI ที่พบบ่อยต่างๆ เช่น

  • การสร้างแบบดึงข้อมูลเสริม (RAG): การฝังช่วยเพิ่มคุณภาพ ของข้อความที่สร้างขึ้นโดยการดึงและรวมข้อมูลที่เกี่ยวข้องลงใน บริบทของโมเดล
  • การดึงข้อมูล: ใช้การฝังเพื่อค้นหาข้อความหรือเอกสารที่คล้ายกันในเชิงความหมาย เมื่อได้รับข้อความนำเข้า

    บทแนะนำการค้นหาเอกสาร

  • การตรวจหาความผิดปกติ: การเปรียบเทียบกลุ่มการฝังจะช่วยระบุแนวโน้มหรือค่าผิดปกติที่ซ่อนอยู่ได้

    บทแนะนำการตรวจจับความผิดปกติ

  • การจัดประเภท: จัดหมวดหมู่ข้อความโดยอัตโนมัติตามเนื้อหา เช่น การวิเคราะห์ความเห็นหรือการตรวจหาจดหมายขยะ

    บทแนะนำการจัดประเภท

  • การจัดกลุ่ม: วิธีที่มีประสิทธิภาพในการทำความเข้าใจความสัมพันธ์คือการสร้างคลัสเตอร์และการแสดงภาพของ Embedding

    บทแนะนำการแสดงภาพการจัดกลุ่ม

การจัดเก็บ Embedding

เมื่อนำการฝังไปใช้ในเวอร์ชันที่ใช้งานจริง คุณมักจะใช้ฐานข้อมูลเวกเตอร์เพื่อจัดเก็บ จัดทำดัชนี และเรียกข้อมูลการฝังที่มีมิติสูงได้อย่างมีประสิทธิภาพ Google Cloud มีบริการข้อมูลที่มีการจัดการซึ่ง สามารถใช้เพื่อวัตถุประสงค์นี้ได้ ซึ่งรวมถึง BigQuery AlloyDB และ Cloud SQL

บทแนะนำต่อไปนี้แสดงวิธีใช้ฐานข้อมูลเวกเตอร์ของบุคคลที่สามอื่นๆ กับ Gemini Embedding

โมเดลการฝัง

โมเดลที่พร้อมใช้งานสำหรับผู้ใช้ทั่วไป

โมเดลเดิม

  • embedding-001 (เลิกใช้งานในวันที่ 14 สิงหาคม 2025)
  • text-embedding-004 (จะเลิกใช้งานในวันที่ 14 มกราคม 2026)

การใช้การฝัง

โมเดลการฝัง Gemini มีไว้เพื่อเปลี่ยนรูปแบบข้อมูลที่ป้อนให้เป็นการแสดงตัวเลขเท่านั้น ซึ่งแตกต่างจากโมเดล Generative AI ที่สร้างเนื้อหาใหม่ แม้ว่า Google จะมีหน้าที่รับผิดชอบในการจัดหาโมเดลการฝัง ที่แปลงรูปแบบข้อมูลอินพุตเป็นรูปแบบตัวเลขที่ร้องขอ แต่ผู้ใช้ยังคงมีหน้าที่รับผิดชอบอย่างเต็มที่ต่อข้อมูลที่ป้อนและการฝังที่ได้ การใช้โมเดล Gemini Embedding เป็นการยืนยันว่าคุณมีสิทธิ์ที่จำเป็นในเนื้อหาใดๆ ที่คุณอัปโหลด อย่าสร้างเนื้อหาที่ ละเมิดทรัพย์สินทางปัญญาหรือสิทธิด้านความเป็นส่วนตัวของผู้อื่น การใช้บริการนี้อยู่ภายใต้นโยบายการใช้งานที่ไม่อนุญาตและข้อกำหนดในการให้บริการของ Google

เริ่มสร้างด้วยการฝัง

ดูสมุดบันทึกการเริ่มต้นใช้งานอย่างรวดเร็วของ Embedding เพื่อสำรวจความสามารถของโมเดลและดูวิธีปรับแต่งและแสดงภาพ Embedding