Embeddings

Gemini API 提供嵌入模型,用于为文本、图片、视频和其他内容生成嵌入。然后,这些生成的嵌入可用于语义搜索、分类和聚类等任务,与基于关键字的方法相比,可提供更准确、更贴合情境的结果。

最新模型 gemini-embedding-2-preview 是 Gemini API 中的首个多模态嵌入模型。它将文本、图片、视频、音频和文档映射到统一的嵌入空间中,从而能够以 100 多种语言进行跨模态搜索、分类和聚类。如需了解详情,请参阅多模态嵌入部分。对于纯文本用例,gemini-embedding-001 仍然可用。

构建检索增强生成 (RAG) 系统是 AI 产品的一种常见使用场景。嵌入在显著提升模型输出方面发挥着关键作用,可提高事实准确性、连贯性和上下文丰富度。如果您更喜欢使用托管式 RAG 解决方案,我们构建了文件搜索工具,可让 RAG 更易于管理且更具成本效益。

生成嵌入

使用 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 "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -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 "Content-Type: application/json" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -d '{
    "content": {
        "parts": [
        {
            "text": "What is the meaning of life?"
        },
        {
            "text": "How much wood would a woodchuck chuck?"
        },
        {
            "text": "How does the brain work?"
        }
        ]
    },
    "taskType": "SEMANTIC_SIMILARITY"
    }'

指定任务类型以提高性能

您可以将嵌入用于从分类到文档搜索的各种任务。指定正确的任务类型有助于针对预期关系优化嵌入,从而最大限度地提高准确性和效率。如需查看支持的任务类型的完整列表,请参阅支持的任务类型表格。

以下示例展示了如何使用 SEMANTIC_SIMILARITY 来检查文本字符串在含义上的相似程度。

Python

from google import genai
from google.genai import types
import pandas as pd
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 = client.models.embed_content(
    model="gemini-embedding-001",
    contents=texts,
    config=types.EmbedContentConfig(task_type="SEMANTIC_SIMILARITY")
)

# Create a 3x3 table to show the similarity matrix
df = pd.DataFrame(
    cosine_similarity([e.values for e in result.embeddings]),
    index=texts,
    columns=texts,
)

print(df)

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 "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -d '{
    "taskType": "SEMANTIC_SIMILARITY",
    "content": {
        "parts": [
        {
            "text": "What is the meaning of life?"
        },
        {
            "text": "How much wood would a woodchuck chuck?"
        },
        {
            "text": "How does the brain work?"
        }
        ]
    }
    }'

代码段将展示运行后不同文本块之间的相似程度。

支持的任务类型

任务类型 说明 示例
SEMANTIC_SIMILARITY 经过优化以评估文本相似度的嵌入。 推荐系统、重复内容检测
分类 经过优化的嵌入,可根据预设标签对文本进行分类。 情感分析、垃圾信息检测
聚类 经过优化的嵌入,可根据文本的相似性对文本进行聚类。 文档整理、市场调研、异常检测
RETRIEVAL_DOCUMENT 针对文档搜索进行了优化的嵌入。 为搜索编制文章、图书或网页的索引。
RETRIEVAL_QUERY 针对一般搜索查询进行了优化的嵌入。 使用 RETRIEVAL_QUERY 表示查询;使用 RETRIEVAL_DOCUMENT 表示要检索的文档。 自定义搜索
CODE_RETRIEVAL_QUERY 经过优化的嵌入,可根据自然语言查询检索代码块。 使用 CODE_RETRIEVAL_QUERY 进行查询;使用 RETRIEVAL_DOCUMENT 检索代码块。 代码建议和搜索
QUESTION_ANSWERING 问答系统中问题的嵌入,经过优化,可用于查找回答问题的文档。使用 QUESTION_ANSWERING 提出问题;使用 RETRIEVAL_DOCUMENT 指定要检索的文档。 Chatbox
FACT_VERIFICATION 需要验证的陈述的嵌入,针对检索包含支持或反驳陈述的证据的文档进行了优化。 使用 FACT_VERIFICATION 表示目标文本;使用 RETRIEVAL_DOCUMENT 表示要检索的文档 自动化事实核查系统

控制嵌入大小

gemini-embedding-001gemini-embedding-2-preview 均使用 Matryoshka 表征学习 (MRL) 技术进行训练,该技术可教导模型学习具有初始段(或前缀)的高维嵌入,这些初始段也是相同数据的有用且更简单的版本。

使用 output_dimensionality 参数控制输出嵌入向量的大小。选择较小的输出维度可以节省存储空间并提高下游应用的计算效率,同时在质量方面几乎不会有任何损失。默认情况下,这两个模型都会输出一个 3072 维的嵌入,但您可以将其截断为较小的尺寸,这样既能节省存储空间,又不会影响质量。建议使用 768、1536 或 3072 输出维度。

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 'Content-Type: application/json' \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -d '{
        "content": {"parts":[{ "text": "What is the meaning of life?"}]},
        "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

下表显示了不同维度下的 MTEB 分数(一种常用的嵌入模型基准)。值得注意的是,结果表明,性能并不严格取决于嵌入维度的规模,较低的维度可以实现与较高维度相当的分数。

MRL Dimension MTEB 得分
2048 68.16
1536 68.17
768 67.99
512 67.55
256 66.19
128 63.31

多模态嵌入

gemini-embedding-2-preview 模型支持多模态输入,让您可以在文本中嵌入图片、视频、音频和文档内容。所有模态都映射到同一嵌入空间中,从而实现跨模态搜索和比较。

支持的模态和限制

输入词元的总数上限为 8,192 个。

模态 规范和限制
文本 最多支持 8,192 个 token。
Image 每个请求最多可包含 6 张图片。支持的格式:PNG、JPEG。
音频 时长上限为 80 秒。支持的格式:MP3、WAV。
视频 时长上限为 128 秒。支持的格式:MP4、MOV,支持的编解码器:H264、H265、AV1、VP9
文档 (PDF) 最多 6 页。

嵌入图片

以下示例展示了如何使用 gemini-embedding-2-preview 嵌入图片。

图片可以通过内嵌数据或通过 Files API 上传的文件提供。

Python

from google import genai
from google.genai import types

with open('example.png', 'rb') as f:
    image_bytes = f.read()

client = genai.Client()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents=[
        types.Part.from_bytes(
            data=image_bytes,
            mime_type='image/png',
        ),
    ]
)

print(result.embeddings)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

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

    const imgBase64 = fs.readFileSync("example.png", { encoding: "base64" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-2-preview',
        contents: [{
            inlineData: {
                mimeType: 'image/png',
                data: imgBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

REST

IMG_PATH="/path/to/your/image.png"
IMG_BASE64=$(base64 -w0 "${IMG_PATH}")

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -d '{
        "content": {
            "parts": [{
                "inline_data": {
                    "mime_type": "image/png",
                    "data": "'"${IMG_BASE64}"'"
                }
            }]
        }
    }'

嵌入汇总

处理多模态内容时,输入内容的结构会影响嵌入输出:

  • 单个内容条目:在单个内容条目中提交多个部分(例如,文本和图片)会为该条目中的所有模态生成一个汇总嵌入。
  • 多个条目:在 contents 数组中发送多个条目会为每个条目返回单独的嵌入内容。
  • 帖子级表示法:对于包含多个媒体项的社交媒体帖子等复杂对象,我们建议汇总单独的嵌入内容(例如通过求平均值),以创建连贯的帖子级表示法。

以下示例展示了如何为文本和图片输入创建一个聚合嵌入。 使用 parts 字段可合并多个输入:

Python

from google import genai
from google.genai import types

with open('dog.png', 'rb') as f:
    image_bytes = f.read()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents=[
        types.Content(
            parts=[
                types.Part(text="An image of a dog"),
                types.Part.from_bytes(
                    data=image_bytes,
                    mime_type='image/png',
                )
            ]
        )
    ]
)

# This produces one embedding
for embedding in result.embeddings:
    print(embedding.values)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

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

    const imgBase64 = fs.readFileSync("dog.png", { encoding: "base64" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-2-preview',
        contents: {
            parts: [
                { text: 'An image of a dog' },
                { inlineData: { mimeType: 'image/png', data: imgBase64 } },
            ],
        },
    });

    console.log(response.embeddings);
}

main();

REST

IMG_PATH="/path/to/your/dog.png"
IMG_BASE64=$(base64 -w0 "${IMG_PATH}")

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -d '{
        "content": {
            "parts": [
                {"text": "An image of a dog"},
                {
                    "inline_data": {
                        "mime_type": "image/png",
                        "data": "'"${IMG_BASE64}"'"
                    }
                }
            ]
        }
    }'

另一方面,以下示例在一个嵌入调用中创建多个嵌入:

Python

from google import genai
from google.genai import types

with open('dog.png', 'rb') as f:
    image_bytes = f.read()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents=[
        "The dog is cute",
        types.Part.from_bytes(
            data=image_bytes,
            mime_type='image/png',
        ),
    ]
)

# This produces two embeddings
for embedding in result.embeddings:
    print(embedding.values)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

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

    const imgBase64 = fs.readFileSync("dog.png", { encoding: "base64" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-2-preview',
        contents: [
            'The dog is cute',
            {
                inlineData: {
                    mimeType: 'image/png',
                    data: imgBase64,
                },
            },
        ],
    });

    console.log(response.embeddings);
}

main();

REST

IMG_PATH="/path/to/your/dog.png"
IMG_BASE64=$(base64 -w0 "${IMG_PATH}")

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:batchEmbedContents" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -d '{
        "requests": [
            {
                "model": "models/gemini-embedding-2-preview",
                "content": {"parts": [{"text": "The dog is cute"}]}
            },
            {
                "model": "models/gemini-embedding-2-preview",
                "content": {"parts": [{"inline_data": {"mime_type": "image/png", "data": "'"${IMG_BASE64}"'"}}]}
            }
        ]
    }'

嵌入音频

以下示例展示了如何使用 gemini-embedding-2-preview 嵌入音频文件。

音频文件可以作为内嵌数据提供,也可以通过 Files API 作为上传的文件提供。

Python

from google import genai
from google.genai import types

with open('example.mp3', 'rb') as f:
    audio_bytes = f.read()

client = genai.Client()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents=[
        types.Part.from_bytes(
            data=audio_bytes,
            mime_type='audio/mpeg',
        ),
    ]
)

print(result.embeddings)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

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

    const audioBase64 = fs.readFileSync("example.mp3", { encoding: "base64" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-2-preview',
        contents: [{
            inlineData: {
                mimeType: 'audio/mpeg',
                data: audioBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

REST

AUDIO_PATH="/path/to/your/example.mp3"
AUDIO_BASE64=$(base64 -w0 "${AUDIO_PATH}")

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -d '{
        "content": {
            "parts": [{
                "inline_data": {
                    "mime_type": "audio/mpeg",
                    "data": "'"${AUDIO_BASE64}"'"
                }
            }]
        }
    }'

嵌入视频

以下示例展示了如何使用 gemini-embedding-2-preview 嵌入视频。

视频可以作为内嵌数据提供,也可以通过 Files API 作为上传的文件提供。

Python

from google import genai
from google.genai import types

client = genai.Client()

with open('example.mp4', 'rb') as f:
    video_bytes = f.read()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents=[
        types.Part.from_bytes(
            data=video_bytes,
            mime_type='video/mp4',
        ),
    ]
)

print(result.embeddings[0].values)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

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

    const videoBase64 = fs.readFileSync("example.mp4", { encoding: "base64" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-2-preview',
        contents: [{
            inlineData: {
                mimeType: 'video/mp4',
                data: videoBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

REST

VIDEO_PATH="/path/to/your/video.mp4"
VIDEO_BASE64=$(base64 -w0 "${VIDEO_PATH}")

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -d '{
        "content": {
            "parts": [{
                "inline_data": {
                    "mime_type": "video/mp4",
                    "data": "'"${VIDEO_BASE64}"'"
                }
            }]
        }
    }'

如果您需要嵌入时长超过 128 秒的视频,可以将视频分块为重叠的片段,然后单独嵌入这些片段。

嵌入文档

PDF 格式的文档可以直接嵌入。模型会处理每个网页的视觉和文本内容。

可以通过 Files API 以内嵌数据或上传文件的形式提供 PDF。

Python

from google import genai
from google.genai import types

with open('example.pdf', 'rb') as f:
    pdf_bytes = f.read()

client = genai.Client()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents=[
        types.Part.from_bytes(
            data=pdf_bytes,
            mime_type='application/pdf',
        ),
    ]
)

print(result.embeddings)

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

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

    const pdfBase64 = fs.readFileSync("example.pdf", { encoding: "base64" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-2-preview',
        contents: [{
            inlineData: {
                mimeType: 'application/pdf',
                data: pdfBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

REST

PDF_PATH="/path/to/your/example.pdf"
PDF_BASE64=$(base64 -w0 "${PDF_PATH}")

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -d '{
        "content": {
            "parts": [{
                "inline_data": {
                    "mime_type": "application/pdf",
                    "data": "'"${PDF_BASE64}"'"
                }
            }]
        }
    }'

使用场景

文本嵌入对于各种常见的 AI 应用场景至关重要,例如:

  • 检索增强生成 (RAG):通过检索相关信息并将其纳入模型的情境中,嵌入可提高生成文本的质量。
  • 信息检索:根据一段输入文本搜索语义上最相似的文本或文档。

    文档搜索教程

  • 搜索结果重新排名:根据初始结果与查询的语义相关性得分,优先显示最相关的项。

    搜索重排名教程

  • 异常值检测:比较嵌入群组有助于发现隐藏的趋势或离群点。

    异常值检测教程

  • 分类:根据文本内容自动对文本进行分类,例如情感分析或垃圾信息检测

    分类教程

  • 聚类:通过创建嵌入的聚类和可视化图表,有效掌握复杂关系。

    聚类可视化教程

存储嵌入

在将嵌入投入生产环境时,通常会使用向量数据库来高效存储、索引和检索高维嵌入。Google Cloud 提供可用于此目的的托管数据服务,包括 BigQueryAlloyDBCloud SQL

以下教程展示了如何将其他第三方向量数据库与 Gemini Embedding 搭配使用。

模型版本

Gemini Embedding 2 预览版

属性 说明
模型代码

Gemini API

gemini-embedding-2-preview

支持的数据类型

输入

文本、图片、视频、音频、PDF

输出

文本嵌入

令牌限制[*]

输入 token 限制

8192

输出维度大小

灵活,支持:128 - 3072,推荐:768、1536、3072

版本
如需了解详情,请参阅模型版本模式
  • 预览:gemini-embedding-2-preview
最新更新 2025 年 11 月

Gemini Embedding

属性 说明
模型代码

Gemini API

gemini-embedding-001

支持的数据类型

输入

文本

输出

文本嵌入

令牌限制[*]

输入 token 限制

2048

输出维度大小

灵活,支持:128 - 3072,推荐:768、1536、3072

版本
如需了解详情,请参阅模型版本模式
  • 稳定:gemini-embedding-001
最新更新 2025 年 6 月

如需了解已弃用的嵌入模型,请访问弃用页面

从 gemini-embedding-001 迁移

gemini-embedding-001gemini-embedding-2-preview 之间的嵌入空间不兼容。这意味着您无法直接比较一个模型生成的嵌入与另一个模型生成的嵌入。如果您要升级到 gemini-embedding-2-preview,则必须重新嵌入所有现有数据。

批量嵌入

如果对延迟时间没有要求,可以尝试使用 Batch API 搭配 Gemini Embeddings 模型。这样一来,只需支付默认嵌入价格的 50%,即可实现更高的吞吐量。 如需查看有关如何开始使用的示例,请参阅 Batch API 实战宝典

负责任的使用声明

与创建新内容的生成式 AI 模型不同,Gemini Embedding 模型仅用于将输入数据的格式转换为数值表示形式。虽然 Google 负责提供一种嵌入模型,将输入数据的格式转换为所需的数值格式,但用户仍需对他们输入的数据和生成的嵌入内容承担全部责任。使用 Gemini 嵌入模型,即表示您确认您拥有所上传内容的必要权利。请勿生成会侵犯他人知识产权或隐私权的内容。使用此服务时,您必须遵守我们的《使用限制政策》《Google 服务条款》

开始使用嵌入模型进行构建

您可以查看嵌入快速入门笔记本,了解模型功能,并学习如何自定义和直观呈现嵌入。