Embeddings

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

最新模型 gemini-embedding-2 是 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-2",
        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-2',
        contents: 'What is the meaning of life?',
    });

    console.log(response.embeddings);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.types.EmbedContentResponse;

Client client = new Client();

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-2", "What is the meaning of life?", null);

System.out.println(response.embeddings().orElse(null));

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

指定任务类型以提升性能

您可以将嵌入用于从分类到文档搜索的各种任务。指定正确的任务类型有助于针对预期关系优化嵌入,从而最大限度地提高准确性和效率。

Embeddings 2 的任务类型

对于使用 gemini-embedding-2 的纯文本任务,我们强烈建议您在提示中添加任务指令。为此,您可以使用正确的任务前缀来设置查询和文档的格式。

在基于多模态输入生成单个嵌入时,我们通常不建议在输入的文本部分添加任务指令前缀。在某些情况下,它会提高性能,但在其他情况下,它会降低性能。

下表展示了如何使用 gemini-embedding-2 模型为对称和非对称用例设置查询和文档格式的示例。

检索用例(非对称格式)

在非对称用例中,请将任务前缀添加到查询中,并为要嵌入和检索的内容应用文档结构。

使用场景 查询结构 文档结构
搜索查询 task: search result | query: {content} title: {title} | text: {content}
如果没有标题,请使用 title: none。
问答 task: question answering | query: {content} title: {title} | text: {content}
事实核查 task: fact checking | query: {content} title: {title} | text: {content}
代码检索 task: code retrieval | query: {content} title: {title} | text: {content}

用法示例

Python

# Generate embedding for a task's query. Use your correct task here:
def prepare_query(query):
    # return f"task: question answering | query: {query}"
    # return f"task: fact checking | query: {query}"
    # return f"task: code retrieval | query: {query}"
    return f"task: search result | query: {query}"

# Generate embedding for document of an asymmetric retrieval task:
def prepare_document(content, title=None):
    if title is None:
        title = "none"
    return f"title: {title} | text: {content}"

单输入源用例(对称格式)

在对称用例中,对于同一任务,请对查询和文档使用相同的格式。

使用场景 输入结构
分类 task: classification | query: {content}
聚簇 task: clustering | query: {content}
语义相似度 task: sentence similarity | query: {content}
请勿将其用于搜索或检索。它适用于语义文本相似度。

用法示例

Python

# Generate embedding for query & document of your task.
def prepare_query_and_document(content):
    # return f'task: clustering | query: {content}'
    # return f'task: sentence similarity | query: {content}'
    return f'task: classification | query: {content}'

请务必始终如一地使用该任务。例如,如果文档使用 f'task: classification | query: {content}' 嵌入,则查询也应按照此任务格式嵌入。

Embeddings 1 的任务类型

对于 gemini-embedding-001,您可以在 embedContent 方法中指定 task_type。如需查看受支持任务类型的完整列表,请参阅受支持的任务类型表。

以下示例展示了如何使用 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";
// npm i compute-cosine-similarity
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,
        config: { 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();

Java

import java.util.Arrays;
import com.google.genai.Client;
import com.google.genai.types.ContentEmbedding;
import com.google.genai.types.EmbedContentConfig;
import com.google.genai.types.EmbedContentResponse;
import java.util.List;

Client client = new Client();

List<String> texts =
    Arrays.asList(
        "What is the meaning of life?",
        "What is the purpose of existence?",
        "How do I bake a cake?");

EmbedContentConfig config =
    EmbedContentConfig.builder().taskType("SEMANTIC_SIMILARITY").build();

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-001", texts, config);

List<ContentEmbedding> embeddings = response.embeddings().get();

for (int i = 0; i < texts.size(); i++) {
  for (int j = i + 1; j < texts.size(); j++) {
    List<Float> v1 = embeddings.get(i).values().get();
    List<Float> v2 = embeddings.get(j).values().get();
    double dotProduct = 0.0;
    double normA = 0.0;
    double normB = 0.0;
    for (int k = 0; k < v1.size(); k++) {
      dotProduct += v1.get(k) * v2.get(k);
      normA += v1.get(k) * v1.get(k);
      normB += v2.get(k) * v2.get(k);
    }
    double similarity = dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    System.out.printf(
        "Similarity between '%s' and '%s': %.4f%n", texts.get(i), texts.get(j), similarity);
  }
}

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?"
        }
        ]
    }
    }'

这些代码段在运行时会显示不同文本块之间的相似程度。

支持的任务类型

gemini-embedding-001 支持的任务类型:

任务类型 说明 示例
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-001 和 gemini-embedding-2 均使用 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-2",
    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-2',
        contents: 'What is the meaning of life?',
        config: { outputDimensionality: 768 },
    });

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

main();

Java

import com.google.genai.Client;
import com.google.genai.types.ContentEmbedding;
import com.google.genai.types.EmbedContentConfig;
import com.google.genai.types.EmbedContentResponse;

Client client = new Client();

EmbedContentConfig config =
    EmbedContentConfig.builder().outputDimensionality(768).build();

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-2", "What is the meaning of life?", config);

ContentEmbedding embeddingObj = response.embeddings().get().get(0);
int embeddingLength = embeddingObj.values().get().size();

System.out.println("Length of embedding: " + embeddingLength);

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-2",
        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-2: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 维嵌入始终会进行归一化,但 Gemini Embedding 2 也会自动对截断的维度(例如 768、1536)进行归一化。这可确保通过向量方向(而非大小)计算语义相似度,从而提供更准确的结果。

旧模型:如果您使用的是 gemini-embedding-001,则必须手动对非 3072 维度进行归一化,如下所示:

Python

import numpy as np
from numpy.linalg import norm

# Only for embeddings from `gemini-embedding-001`
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 维度 MTEB 得分 (Gemini Embedding 001)
2048 68.16
1536 68.17
768 67.99
512 67.55
256 66.19
128 63.31

多模态嵌入

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

支持的模态和限制

输入词元总数上限为 8192 个词元。

模态 规范和限制
文本 最多支持 8,192 个词元。
Image 每个请求最多可包含 6 张图片。支持的格式:PNG、JPEG。
音频 时长上限为 180 秒。支持的格式:MP3、WAV。
视频 时长上限为 120 秒。支持的格式:MP4、MOV。支持的编解码器:H264、H265、AV1、VP9。
系统每个视频最多处理 32 帧:短视频(≤32 秒)按 1 fps 的速率采样,而较长视频则均匀采样至 32 帧。系统不会处理视频文件中的音轨。
文档 (PDF) 每个请求最多 1 个文件,最多 6 页。

嵌入图片

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

图片可以作为内嵌数据提供,也可以通过 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',
    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',
        contents: [{
            inlineData: {
                mimeType: 'image/png',
                data: imgBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.EmbedContentResponse;
import com.google.genai.types.Part;
import java.nio.file.Files;
import java.nio.file.Paths;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("example.png"));

Content content = Content.fromParts(Part.fromBytes(imageBytes, "image/png"));

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-2", content, null);

System.out.println(response.embeddings().orElse(null));

REST

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2: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 参数添加多个输入会为所有输入生成一个汇总嵌入。
  • 多个 Content 对象(单独):将每个输入封装在 Content 对象中,并在 contents 参数中传递这些对象,会为每个条目返回单独的嵌入。
  • 帖子级表示法:对于包含多个媒体文件项的社交媒体帖子等复杂对象,我们建议汇总单独的嵌入(例如,通过求平均值)来创建连贯的帖子级表示法。

以下示例展示了如何为文本和图片输入创建一个汇总嵌入。只需向 contents 参数添加多个输入即可:

Python

from google import genai
from google.genai import types

client = genai.Client()

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

result = client.models.embed_content(
    model='gemini-embedding-2',
    contents=[
        "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',
        contents: [
            'An image of a dog',
            {
                inlineData: {
                    mimeType: 'image/png',
                    data: imgBase64,
                },
            },
        ],
    });

    // This produces one embedding
    for (const embedding of response.embeddings) {
        console.log(embedding.values);
    }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.ContentEmbedding;
import com.google.genai.types.EmbedContentResponse;
import com.google.genai.types.Part;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("dog.png"));

Content content =
    Content.fromParts(
        Part.fromText("An image of a dog"),
        Part.fromBytes(imageBytes, "image/png"));

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-2", content, null);

// This produces one embedding
for (ContentEmbedding embedding : response.embeddings().orElse(Collections.emptyList())) {
  System.out.println(embedding.values().orElse(Collections.emptyList()));
}

REST

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2: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}"'"
                    }
                }
            ]
        }
    }'

另一方面,如果您在 contents 参数中使用 Content 对象,则会返回单独的嵌入。此示例在一次嵌入调用中创建多个嵌入:

Python

from google import genai
from google.genai import types

client = genai.Client()

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

result = client.models.embed_content(
    model="gemini-embedding-2",
    contents=[
        types.Content(parts=[types.Part.from_text(text="task: classification | query: An image of a dog")]),
        types.Content(
            parts=[
                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',
        contents: [
            { parts: [{ text: 'task: classification | query: An image of a dog' }] },
            {
                parts: [{
                    inlineData: {
                        mimeType: 'image/png',
                        data: imgBase64,
                    },
                }],
            },
        ],
    });

    // This produces two embeddings
    for (const embedding of response.embeddings) {
        console.log(embedding.values);
    }
}

main();

Java

import java.util.Arrays;
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.ContentEmbedding;
import com.google.genai.types.EmbedContentResponse;
import com.google.genai.types.Part;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("dog.png"));

List<Content> contents =
    Arrays.asList(
        Content.fromParts(Part.fromText("task: classification | query: An image of a dog")),
        Content.fromParts(Part.fromBytes(imageBytes, "image/png")));

// Embed each Content object separately to produce separate embeddings
for (Content content : contents) {
  EmbedContentResponse response =
      client.models.embedContent("gemini-embedding-2", content, null);
  for (ContentEmbedding embedding : response.embeddings().orElse(Collections.emptyList())) {
    System.out.println(embedding.values().orElse(Collections.emptyList()));
  }
}

REST

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

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

嵌入音频

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

音频文件可以作为内嵌数据提供,也可以通过 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',
    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',
        contents: [{
            inlineData: {
                mimeType: 'audio/mpeg',
                data: audioBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.EmbedContentResponse;
import com.google.genai.types.Part;
import java.nio.file.Files;
import java.nio.file.Paths;

Client client = new Client();

byte[] audioBytes = Files.readAllBytes(Paths.get("example.mp3"));

Content content = Content.fromParts(Part.fromBytes(audioBytes, "audio/mpeg"));

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-2", content, null);

System.out.println(response.embeddings().orElse(null));

REST

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2: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 嵌入视频。

视频可以作为内嵌数据提供,也可以通过 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',
    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',
        contents: [{
            inlineData: {
                mimeType: 'video/mp4',
                data: videoBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.EmbedContentResponse;
import com.google.genai.types.Part;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;

Client client = new Client();

byte[] videoBytes = Files.readAllBytes(Paths.get("example.mp4"));

Content content = Content.fromParts(Part.fromBytes(videoBytes, "video/mp4"));

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-2", content, null);

System.out.println(
    response.embeddings().get().get(0).values().orElse(Collections.emptyList()));

REST

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2: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}"'"
                }
            }]
        }
    }'

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

嵌入文档

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

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

模型如何处理 PDF

嵌入 PDF 时,模型会使用视觉和文本特征来处理文档:

  • 视觉表示:模型会将每个页面渲染为图片,每页消耗 258 个 token。
  • 文本提取:模型从文档中提取文本。对于原生 PDF(包含数字文本),模型会直接提取文本。对于扫描版 PDF(包含文本图片),模型会自动运行光学字符识别 (OCR) 来提取文本。

如需计算 PDF 的总 token 数量,请将视觉 token(每页 258 个)与文本 token 相加。输入内容必须在模型的 8,192 个 token 的限制内(所有模态共享)。系统会以静默方式截断超出此限制的输入。

PDF 限制

  • 每个请求的文件数量:您最多可以提交 1 个 PDF 文件。
  • 页数限制:每个文件最多可提交 6 页。为获得最佳质量,我们强烈建议每个 PDF 文件仅包含 1 页。

以下示例展示了如何使用 gemini-embedding-2 嵌入 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',
    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',
        contents: [{
            inlineData: {
                mimeType: 'application/pdf',
                data: pdfBase64,
            },
        }],
    });

    console.log(response.embeddings);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.EmbedContentResponse;
import com.google.genai.types.Part;
import java.nio.file.Files;
import java.nio.file.Paths;

Client client = new Client();

byte[] pdfBytes = Files.readAllBytes(Paths.get("example.pdf"));

Content content = Content.fromParts(Part.fromBytes(pdfBytes, "application/pdf"));

EmbedContentResponse response =
    client.models.embedContent("gemini-embedding-2", content, null);

System.out.println(response.embeddings().orElse(null));

REST

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

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2: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 提供可用于此目的的代管式数据服务,包括 Gemini Enterprise Agent Platform Vector Search 2.0、BigQuery、AlloyDB 和 Cloud SQL。

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

模型版本

Gemini Embedding 2

属性 说明
模型代码

Gemini API

gemini-embedding-2

支持的数据类型

输入

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

输出

文本嵌入

Token 限制[*]

输入 token 限制

8192

输出维度大小

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

个版本
如需了解详情,请参阅模型版本模式。
  • 稳定:gemini-embedding-2
最后更新时间 2026 年 4 月

Gemini Embedding

属性 说明
模型代码

Gemini API

gemini-embedding-001

支持的数据类型

输入

文本

输出

文本嵌入

Token 限制[*]

输入 token 限制

2048

输出维度大小

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

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

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

从 gemini-embedding-001 迁移

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

除了不兼容之外,这两种模型之间还有其他一些显著差异:

  • 任务类型规范:使用 gemini-embedding-001 时,您可以使用 task_type 参数(例如 SEMANTIC_SIMILARITY、RETRIEVAL_DOCUMENT)指定任务类型。使用 gemini-embedding-2 时,不支持 task_type 参数。相反,对于纯文本任务,您应直接在提示中包含任务说明。如需详细了解如何针对不同应用场景设置提示格式,请参阅使用 Embeddings 2 的任务类型。

  • 嵌入聚合:gemini-embedding-001 会为输入列表中的每个字符串生成单独的嵌入。相比之下,当在一个请求中直接提供多个输入(例如文本和图片)时,gemini-embedding-2 会生成一个汇总嵌入。如需为各个输入生成单独的嵌入,请将每个输入封装在 Content 对象中,或使用 Batch API。如需了解详情,请参阅嵌入聚合。

  • 归一化:如果您使用 output_dimensionality 请求维度少于 3072 的嵌入,gemini-embedding-2 会自动对这些截断的嵌入进行归一化。使用 gemini-embedding-001 时,您需要对 3072 以外的维度执行手动归一化。如需了解详情,请参阅确保较小维度的质量。

批量嵌入

如果延迟时间不是问题,请尝试将 Gemini Embeddings 模型与 Batch API 搭配使用。这样可以实现更高的吞吐量,而价格仅为默认 Embedding 价格的 50%。如需查看有关如何开始使用的示例,请参阅 Batch API 实战宝典。

负责任使用声明

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

开始使用嵌入进行构建

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