# 嵌入

Gemini API 提供嵌入模型来生成文本、图像、视频和其他内容的嵌入。这些生成的嵌入可以用于语义搜索、分类和聚类等任务，从而提供比基于关键字的方法更准确、上下文感知的结果。

最新型号， `gemini-embedding-2`，是 Gemini API 中的第一个多模态嵌入模型。它将文本、图像、视频、音频和文档映射到统一的嵌入空间，从而实现跨 100 语言的跨模式搜索、分类和聚类。请参阅 [多模态嵌入部分](/docs/embeddings#multimodal) 了解更多。对于纯文本用例， `gemini-embedding-001` 仍然可用。

构建检索增强生成 (RAG) 系统是人工智能产品的常见用例。嵌入在显着增强模型输出方面发挥着关键作用，提高了事实准确性、连贯性和上下文丰富性。如果您更喜欢使用托管 RAG 解决方案，我们构建了 [文件搜索](/docs/file-search) 工具，使 RAG 更易于管理且更具成本效益。

## 生成嵌入  {% #generate-embeddings %}

使用 `embedContent` 生成文本嵌入的方法：

{% tabs %}
{% tab label="Python" %}
```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)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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));
```
{% /tab %}

{% tab label="Go" %}
```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))
}
```
{% /tab %}

{% tab label="REST" %}
```shell
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?"
        }]
        }
    }'
```
{% /tab %}
{% /tabs %}

{% callout type="note" %}
同时 `gemini-embedding-001` 允许您为字符串列表生成单独的嵌入，Gemini Embedding 2 为多个输入生成单个聚合嵌入。您可以在以下位置找到更多信息 [嵌入聚合](/docs/embeddings#embedding-aggregation)，或者您可以使用 [Batch API](/docs/batch-api#batch-embedding) 如果您想一次生成多个嵌入。
{% /callout %}

## 指定任务类型以提高性能  {% #task-types %}

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

### 带有嵌入的任务类型 2  {% #task-types-embeddings-2 %}

对于纯文本任务 `gemini-embedding-2`，我们强烈建议您在提示中添加任务说明。这可以通过使用正确的任务前缀格式化查询和文档来完成。

当生成一个 [基于多模态输入的单嵌入](/docs/embeddings#embedding-aggregation)，我们通常不建议在输入的文本部分前面添加任务指令。在某些情况下，它可以提高性能，但在其他情况下，它会降低性能。

下表显示了如何使用以下示例来格式化对称和非对称用例的查询和文档： `gemini-embedding-2` 模型。

**检索用例（非对称格式）**

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

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
使用案例
{% /doc-cell %}

{% doc-cell %}
查询结构
{% /doc-cell %}

{% doc-cell %}
文件结构
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
搜索查询
{% /doc-cell %}

{% doc-cell %}
`task: search result | query: {content}`
{% /doc-cell %}

{% doc-cell %}
`title: {title} | text: {content}`

如果没有标题，则使用 `title: none`.
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
问答
{% /doc-cell %}

{% doc-cell %}
`task: question answering | query: {content}`
{% /doc-cell %}

{% doc-cell %}
`title: {title} | text: {content}`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
事实核查
{% /doc-cell %}

{% doc-cell %}
`task: fact checking | query: {content}`
{% /doc-cell %}

{% doc-cell %}
`title: {title} | text: {content}`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
代码检索
{% /doc-cell %}

{% doc-cell %}
`task: code retrieval | query: {content}`
{% /doc-cell %}

{% doc-cell %}
`title: {title} | text: {content}`
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

**用法示例**

{% tabs %}
{% tab label="Python" %}
```python
def prepare_query(query):
    return f"task: search result | query: {query}"

def prepare_document(content, title=None):
    if title is None:
        title = "none"
    return f"title: {title} | text: {content}"
```
{% /tab %}

{% tab label="Java" %}
```java
// Generate embedding for a task's query. Use your correct task here:
String query = "What is the capital of France?";
String formattedQuery = "task: search result | query: " + query;

// Generate embedding for document of an asymmetric retrieval task:
String title = "France";
String content = "Paris is the capital and most populous city of France.";
String formattedDocument = "title: " + (title != null ? title : "none") + " | text: " + content;
```
{% /tab %}
{% /tabs %}

**单输入用例（对称格式）**

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

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
使用案例
{% /doc-cell %}

{% doc-cell %}
输入结构
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
分类
{% /doc-cell %}

{% doc-cell %}
`task: classification | query: {content}`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
聚类
{% /doc-cell %}

{% doc-cell %}
`task: clustering | query: {content}`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
语义相似度
{% /doc-cell %}

{% doc-cell %}
`task: sentence similarity | query: {content}`

请勿将其用于搜索或检索。它旨在实现语义文本相似性。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

**用法示例**

{% tabs %}
{% tab label="Python" %}
```python
def prepare_query_and_document(content):
    return f'task: classification | query: {content}'
```
{% /tab %}

{% tab label="Java" %}
```java
// Generate embedding for query & document of your task.
String content = "This movie was fantastic!";
String formattedContent = "task: classification | query: " + content;
```
{% /tab %}
{% /tabs %}

一致地使用该任务非常重要。例如，如果文档嵌入 `f'task: classification | query: {content}'`，查询也应按照此任务格式嵌入。

### 带有嵌入的任务类型 1  {% #task-types-embeddings-1 %}

对于 `gemini-embedding-001`，您可以指定 `task_type` 在 `embedContent` 方法。有关支持的任务类型的完整列表，请参阅 [支持的任务类型](/docs/embeddings#supported-task-types) 表。

{% callout type="note" %}
您不能使用 `task_type` 字段为 `gemini-embedding-2` 模型。相反，请将任务作为说明包含在提示中，详细信息请参见 [以上部分](/docs/embeddings#task-types-embeddings-2).
{% /callout %}

以下示例展示了如何使用 `SEMANTIC_SIMILARITY` 检查文本字符串的含义有多相似。

{% tabs %}
{% tab label="Python" %}
```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")
)

df = pd.DataFrame(
    cosine_similarity([e.values for e in result.embeddings]),
    index=texts,
    columns=texts,
)

print(df)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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)}`);
        }
    }
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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);
  }
}
```
{% /tab %}

{% tab label="Go" %}
```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)
        }
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
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?"
        }
        ]
    }
    }'
```
{% /tab %}
{% /tabs %}

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

{% callout type="note" %}
余弦相似度是一个很好的距离度量，因为它关注的是方向而不是幅度，这更准确地反映了概念上的接近度。值范围从 -1（相反）到 1（最大相似度）。
{% /callout %}

#### 支持的任务类型  {% #supported-task-types %}

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

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**SEMANTIC\_SIMILARITY**
{% /doc-cell %}

{% doc-cell %}
优化嵌入以评估文本相似性。
{% /doc-cell %}

{% doc-cell %}
推荐系统、重复检测
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**CLASSIFICATION**
{% /doc-cell %}

{% doc-cell %}
嵌入经过优化，可根据预设标签对文本进行分类。
{% /doc-cell %}

{% doc-cell %}
情感分析、垃圾邮件检测
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**CLUSTERING**
{% /doc-cell %}

{% doc-cell %}
嵌入优化为基于文本的相似性进行聚类。
{% /doc-cell %}

{% doc-cell %}
文档组织、市场研究、异常检测
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**RETRIEVAL\_DOCUMENT**
{% /doc-cell %}

{% doc-cell %}
针对文档搜索优化的嵌入。
{% /doc-cell %}

{% doc-cell %}
为文章、书籍或网页建立索引以供搜索。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**RETRIEVAL\_QUERY**
{% /doc-cell %}

{% doc-cell %}
针对一般搜索查询优化的嵌入。使用 `RETRIEVAL_QUERY` 用于查询； `RETRIEVAL_DOCUMENT` 用于检索文档。
{% /doc-cell %}

{% doc-cell %}
自定义搜索
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**CODE\_RETRIEVAL\_QUERY**
{% /doc-cell %}

{% doc-cell %}
针对基于自然语言查询的代码块检索而优化的嵌入。使用 `CODE_RETRIEVAL_QUERY` 用于查询； `RETRIEVAL_DOCUMENT` 用于要检索的代码块。
{% /doc-cell %}

{% doc-cell %}
代码建议和搜索
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**QUESTION\_ANSWERING**
{% /doc-cell %}

{% doc-cell %}
在问答系统中嵌入问题，并针对查找回答问题的文档进行了优化。使用 `QUESTION_ANSWERING` 提问； `RETRIEVAL_DOCUMENT` 用于检索文档。
{% /doc-cell %}

{% doc-cell %}
聊天室
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**FACT\_VERIFICATION**
{% /doc-cell %}

{% doc-cell %}
需要验证的语句的嵌入，优化以检索包含支持或反驳该语句的证据的文档。使用 `FACT_VERIFICATION` 对于目标文本； `RETRIEVAL_DOCUMENT` 用于检索文档。
{% /doc-cell %}

{% doc-cell %}
自动事实核查系统
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

## 控制嵌入大小  {% #control-embedding-size %}

两者都 `gemini-embedding-001` 和 `gemini-embedding-2` 使用俄罗斯套娃表示学习（MRL）技术进行训练，该技术教导模型学习具有初始段（或前缀）的高维嵌入，这些初始段（或前缀）也是相同数据的有用、简单版本。

使用 `output_dimensionality` 参数来控制输出嵌入向量的大小。选择较小的输出维度可以节省存储空间并提高下游应用程序的计算效率，同时在质量方面几乎没有牺牲。默认情况下，两种模型都会输出 3072 维嵌入，但您可以将其截断为较小的尺寸，而不会损失质量以节省存储空间。我们建议使用 768, 1536, 或 3072 输出尺寸。

{% tabs %}
{% tab label="Python" %}
```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}")
```
{% /tab %}

{% tab label="JavaScript" %}
```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 || 0;
    console.log(`Length of embedding: ${embeddingLength}`);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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);
```
{% /tab %}

{% tab label="Go" %}
```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)
}
```
{% /tab %}

{% tab label="REST" %}
```shell
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
    }'
```
{% /tab %}
{% /tabs %}

代码片段的示例输出：

```none
Length of embedding: 768
```

## 确保较小尺寸的质量  {% #quality-for-smaller-dimensions %}

{% callout type="note" %}
`gemini-embedding-2` 引入了非默认尺寸的自动重整化。
{% /callout %}

虽然默认的 3072 维度嵌入始终标准化，但 Gemini Embedding 2 也会自动标准化截断的维度（例如，768, 1536）。这确保了通过向量方向而不是大小来计算语义相似度，从而提供更准确的开箱即用结果。

**旧型号**: 如果您正在使用 `gemini-embedding-001`，您必须手动标准化非 3072 尺寸，如下所示：

{% tabs %}
{% tab label="Python" %}
```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
```
{% /tab %}

{% tab label="Java" %}
```java
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.ArrayList;
import java.util.List;

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);
List<Float> values = embeddingObj.values().get();

double norm = 0.0;
for (float v : values) {
  norm += v * v;
}
norm = Math.sqrt(norm);

List<Double> normedEmbedding = new ArrayList<>();
double newNorm = 0.0;
for (float v : values) {
  double normedVal = v / norm;
  normedEmbedding.add(normedVal);
  newNorm += normedVal * normedVal;
}
newNorm = Math.sqrt(newNorm);

System.out.println("Normed embedding length: " + normedEmbedding.size());
System.out.printf("Norm of normed embedding: %.6f%n", newNorm); // Should be very close to 1
```
{% /tab %}
{% /tabs %}

此代码片段的示例输出：

```none
Normed embedding length: 768
Norm of normed embedding: 1.000000
```

下表显示了不同维度的 MTEB 分数（嵌入的常用基准）。值得注意的是，结果表明，性能并不严格与嵌入维度的大小相关，较低维度的得分与较高维度的得分相当。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
2048
{% /doc-cell %}

{% doc-cell %}
68.16
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
1536
{% /doc-cell %}

{% doc-cell %}
68.17
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
768
{% /doc-cell %}

{% doc-cell %}
67.99
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
512
{% /doc-cell %}

{% doc-cell %}
67.55
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
256
{% /doc-cell %}

{% doc-cell %}
66.19
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
128
{% /doc-cell %}

{% doc-cell %}
63.31
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

## 多模态嵌入  {% #multimodal %}

该 `gemini-embedding-2` 模型支持多模态输入，允许您将图像、视频、音频和文档内容与文本一起嵌入。所有模态都映射到相同的嵌入空间，从而实现跨模态搜索和比较。

### 支持的方式和限制  {% #supported-modalities %}

总体最大输入 token 限制为 8192 token。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**文本**
{% /doc-cell %}

{% doc-cell %}
最高支持 8,192 token。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**图像**
{% /doc-cell %}

{% doc-cell %}
每个请求最多 6 图像。支持的格式：PNG、JPEG。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**音频**
{% /doc-cell %}

{% doc-cell %}
最大持续时间为 180 秒。支持的格式：MP3、WAV。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**视频**
{% /doc-cell %}

{% doc-cell %}
最大持续时间为 120 秒。支持的格式：MP4、MOV。支持的编解码器：H264、H265、AV1、VP9。

系统每个视频最多处理 32 帧：短视频（≤32s）以 1 fps 采样，而较长视频统一采样到 32 帧。视频文件中的音轨不会被处理。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**文件（PDF）**
{% /doc-cell %}

{% doc-cell %}
每个请求最多 1 文件，最多 6 页。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

### 嵌入图像  {% #embed-images %}

以下示例展示了如何使用嵌入图像 `gemini-embedding-2`.

图像可以作为内联数据或通过上传的文件提供 [Files API](/docs/files).

{% tabs %}
{% tab label="Python" %}
```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)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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));
```
{% /tab %}

{% tab label="REST" %}
```sh
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}"'"
                }
            }]
        }
    }'
```
{% /tab %}
{% /tabs %}

### 嵌入聚合  {% #embedding-aggregation %}

使用多模态内容时，输入的结构会影响嵌入输出：

* **多个部分（聚合）：** 直接添加多个输入 `contents` 参数为所有输入生成一个聚合嵌入。

* **多个 `Content` 对象（单独）：** 将每个输入包装在 `Content` 对象并将它们传递给 `contents` 参数为每个条目返回单独的嵌入。

* **后级代表：** 对于复杂的对象，例如具有多个媒体项目的社交媒体帖子，我们建议聚合单独的嵌入（例如，通过平均）以创建连贯的后期表示。

以下示例演示如何为文本和图像输入创建一个聚合嵌入。只需将多个输入添加到 `contents` 参数：

{% tabs %}
{% tab label="Python" %}
```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',
        ),
    ]
)

for embedding in result.embeddings:
    print(embedding.values)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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);
    }
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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()));
}
```
{% /tab %}

{% tab label="REST" %}
```sh
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}"'"
                    }
                }
            ]
        }
    }'
```
{% /tab %}
{% /tabs %}

{% callout type="note" %}
多模态输入的文本部分不应包含任务类型信息。
{% /callout %}

另一方面，如果您使用 `Content` 里面的物体 `contents` 参数，它返回单独的嵌入。此示例在一次嵌入调用中创建多个嵌入：

{% tabs %}
{% tab label="Python" %}
```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",
                ),
            ]
        ),
    ],
)

for embedding in result.embeddings:
    print(embedding.values)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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);
    }
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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()));
  }
}
```
{% /tab %}

{% tab label="REST" %}
```sh
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}"'"}}]}
            }
        ]
    }'
```
{% /tab %}
{% /tabs %}

### 嵌入音频  {% #embed-audio %}

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

音频文件可以作为内联数据或通过上传的文件提供 [Files API](/docs/files).

{% tabs %}
{% tab label="Python" %}
```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)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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));
```
{% /tab %}

{% tab label="REST" %}
```sh
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}"'"
                }
            }]
        }
    }'
```
{% /tab %}
{% /tabs %}

### 嵌入视频  {% #embed-video %}

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

视频可以作为内联数据或通过上传的文件提供 [Files API](/docs/files).

{% tabs %}
{% tab label="Python" %}
```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)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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()));
```
{% /tab %}

{% tab label="REST" %}
```sh
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}"'"
                }
            }]
        }
    }'
```
{% /tab %}
{% /tabs %}

如果您需要嵌入视频 >120 秒，您可以将视频分成重叠的片段并单独嵌入这些片段。

### 嵌入文档  {% #embed-documents %}

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

PDF 可以作为内联数据或通过上传的文件提供 [Files API](/docs/files).

#### 模型如何处理 PDF  {% #pdf-processing %}

当您嵌入 PDF 时，模型会使用视觉和文本功能处理文档：

* **视觉表现：** 该模型将每个页面渲染为图像，这消耗了 **258 token** 每页。
* **文本提取：** 该模型从文档中提取文本。对于 **原生 PDF** （其中包含数字文本），模型直接提取文本。对于 **扫描的 PDF** （其中包含文本图像），模型会自动运行光学字符识别 (OCR) 来提取文本。

要计算 PDF 的 token 总数，请将视觉 token（每页 258）添加到文本 token。您的输入必须适合模型的范围 **8,192 token 限制** （在所有模式中共享）。系统会默默地截断超出此限制的输入。

{% callout type="note" %}
Gemini 开发者 API 始终启用 PDF 的 OCR，不支持禁用它（ `document_ocr` 参数仅在 Vertex AI 中可用）。
{% /callout %}

#### PDF 限制  {% #pdf-limits %}

* **每个请求的文件：** 您最多可以提交 1 PDF 文件。
* **页数限制：** 每个文件最多可以提交 6 页。为了获得最佳质量，我们强烈建议每个 PDF 使用 1 页面。

以下示例展示了如何使用嵌入 PDF `gemini-embedding-2`:

{% tabs %}
{% tab label="Python" %}
```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)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
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);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```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));
```
{% /tab %}

{% tab label="REST" %}
```sh
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}"'"
                }
            }]
        }
    }'
```
{% /tab %}
{% /tabs %}

## 使用案例  {% #common-use-cases %}

文本嵌入对于各种常见的人工智能用例至关重要，例如：

* **检索增强生成 (RAG)：** 嵌入通过检索相关信息并将其合并到模型上下文中来提高生成文本的质量。

* **信息检索：** 给定一段输入文本，搜索语义最相似的文本或文档。

{% button href="https://github.com/google-gemini/cookbook/blob/main/examples/Talk_to_documents_with_embeddings.ipynb" icon="task" variant="primary" %}文档搜索教程{% /button %}

* **搜索重新排名**：通过根据查询对初始结果进行语义评分，对最相关的项目进行优先级排序。

{% button href="https://github.com/google-gemini/cookbook/blob/main/examples/Search_reranking_using_embeddings.ipynb" icon="task" variant="primary" %}搜索重新排名教程{% /button %}

* **异常检测：** 比较嵌入组可以帮助识别隐藏的趋势或异常值。

{% button href="https://github.com/google-gemini/cookbook/blob/main/examples/Anomaly_detection_with_embeddings.ipynb" icon="bubble_chart" variant="primary" %}异常检测教程{% /button %}

* **分类：** 根据内容自动对文本进行分类，例如情绪分析或垃圾邮件检测

{% button href="https://github.com/google-gemini/cookbook/blob/main/examples/Classify_text_with_embeddings.ipynb" icon="token" variant="primary" %}分类教程{% /button %}

* **聚类：** 通过创建嵌入的集群和可视化，有效掌握复杂的关系。

{% button href="https://github.com/google-gemini/cookbook/blob/main/examples/clustering_with_embeddings.ipynb" icon="bubble_chart" variant="primary" %}聚类可视化教程{% /button %}

## 存储嵌入  {% #store-embeddings %}

当您将嵌入应用于生产时，通常会使用 **矢量数据库** 有效地存储、索引和检索高维嵌入。 Google Cloud 提供可用于此目的的托管数据服务，包括 [Gemini Enterprise Agent Platform 矢量搜索 2.0](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/overview), [大查询](https://cloud.google.com/bigquery/docs/introduction), [合金数据库](https://cloud.google.com/alloydb/docs/overview), 和 [云SQL](https://cloud.google.com/sql/docs/postgres/introduction).

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

* {% button href="https://docs.trychroma.com/integrations/embedding-models/google-gemini" icon="bolt" variant="primary" %}ChromaDB 教程{% /button %}
* {% button href="https://qdrant.tech/documentation/embeddings/gemini/" icon="bolt" variant="primary" %}QDrant 教程{% /button %}
* {% button href="https://docs.weaviate.io/weaviate/model-providers/google" icon="bolt" variant="primary" %}维维特教程{% /button %}
* {% button href="https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Gemini_LangChain_QA_Pinecone_WebLoad.ipynb" icon="bolt" variant="primary" %}松果教程{% /button %}

## 型号版本  {% #model-versions %}

{% tabs %}
{% tab title="Gemini Embedding 2" %}
{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
属性
{% /doc-cell %}

{% doc-cell %}
说明
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="id_card" /%}模型代码
{% /section %}
{% /doc-cell %}

{% doc-cell %}
**Gemini API**
`gemini-embedding-2`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="save" /%}支持的数据类型
{% /section %}
{% /doc-cell %}

{% doc-cell %}
**输入**
文本、图像、视频、音频、PDF **输出**
文本嵌入
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="token_auto" /%}token 限制[[*]](/docs/tokens)
{% /section %}
{% /doc-cell %}

{% doc-cell %}
**输入token限制**
8,192 **输出尺寸**
灵活，支持：128 - 3072, 推荐：768, 1536, 3072
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="123" /%}版本
{% /section %}
{% /doc-cell %}

{% doc-cell %}
阅读 [模型版本模式](/docs/models#model-versions) 了解更多详情。稳定： `gemini-embedding-2`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="calendar_month" /%}最新更新
{% /section %}
{% /doc-cell %}

{% doc-cell %}
四月 2026
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="paid" /%}价格
{% /section %}
{% /doc-cell %}

{% doc-cell %}
[价格](/docs/pricing#gemini-embedding-2)
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}
{% /tab %}

{% tab title="Gemini Embedding" %}
{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
属性
{% /doc-cell %}

{% doc-cell %}
说明
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="id_card" /%}模型代码
{% /section %}
{% /doc-cell %}

{% doc-cell %}
**Gemini API**
`gemini-embedding-001`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="save" /%}支持的数据类型
{% /section %}
{% /doc-cell %}

{% doc-cell %}
**输入**
文本 **输出**
文本嵌入
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="token_auto" /%}token 限制[[*]](/docs/tokens)
{% /section %}
{% /doc-cell %}

{% doc-cell %}
**输入token限制**
2,048 **输出尺寸**
灵活，支持：128 - 3072, 推荐：768, 1536, 3072
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="123" /%}版本
{% /section %}
{% /doc-cell %}

{% doc-cell %}
阅读 [模型版本模式](/docs/models#model-versions) 了解更多详情。稳定： `gemini-embedding-001`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="calendar_month" /%}最新更新
{% /section %}
{% /doc-cell %}

{% doc-cell %}
六月 2025
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
{% section class="model-property" %}
{% icon name="paid" /%}价格
{% /section %}
{% /doc-cell %}

{% doc-cell %}
[价格](/docs/pricing#gemini-embedding)
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}
{% /tab %}
{% /tabs %}

对于已弃用的嵌入模型，请访问 [弃用](/docs/deprecations) 页面

## 从 gemini-embedding-001 迁移  {% #migration %}

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

除了不兼容性之外，这两个模型之间还存在其他一些显着差异：

* **任务类型规范：** 与 `gemini-embedding-001`，您可以使用指定任务类型 `task_type` 参数（例如， `SEMANTIC_SIMILARITY`, `RETRIEVAL_DOCUMENT`）。与 `gemini-embedding-2`, 的 `task_type`
  不支持参数。相反，您应该直接在纯文本任务的提示中包含任务说明。参见 [带有嵌入的任务类型 2](/docs/embeddings#task-types-embeddings-2) 有关如何针对不同用例设置提示格式的详细信息。

* **嵌入聚合：** `gemini-embedding-001` 为输入列表中的每个字符串生成单独的嵌入。相比之下， `gemini-embedding-2` 当在一个请求中直接提供多个输入（如文本和图像）时，会生成单个聚合嵌入。要为各个输入生成单独的嵌入，请将每个输入包装在 `Content` 对象，或使用 [Batch API](/docs/batch-api#batch-embedding)。参见 [嵌入聚合](/docs/embeddings#embedding-aggregation) 了解更多信息。

* **标准化：** 如果你使用 `output_dimensionality` 请求尺寸小于 3072 的嵌入， `gemini-embedding-2` 自动标准化这些截断的嵌入。与 `gemini-embedding-001`，需要对3072.以外的维度进行手动归一化参见 [确保较小尺寸的质量](/docs/embeddings#quality-for-smaller-dimensions)
  了解详情。

## 批量嵌入  {% #batch-embedding %}

如果延迟不是问题，请尝试使用 Gemini 嵌入模型 [Batch API](/docs/batch-api#batch-embedding)。这样可以以默认嵌入价格的 50% 实现更高的吞吐量。查找有关如何开始使用的示例 [Batch API食谱](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb).

## 负责任的使用通知  {% #responsible-use-notice %}

与创建新内容的生成式 AI 模型不同，Gemini Embedding 模型仅旨在将输入数据的格式转换为数字表示形式。虽然 Google 负责提供嵌入模型，将输入数据的格式转换为所请求的数字格式，但用户对其输入的数据和生成的嵌入负有全部责任。通过使用 Gemini Embedding 模型，您确认您对上传的任何内容拥有必要的权利。请勿生成侵犯他人知识产权或隐私权的内容。您对本服务的使用须遵守我们的 [禁止使用政策](https://policies.google.com/terms/generative-ai/use-policy) 和 [谷歌的服务条款](/docs/terms).

## 开始使用嵌入进行构建  {% #start-building %}

查看 [嵌入快速入门笔记本](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Embeddings.ipynb)
探索模型功能并了解如何自定义和可视化您的嵌入。
