Embeddings

Gemini API 提供文本嵌入模型,用于为字词、短语、句子和代码生成嵌入。嵌入任务,例如语义搜索、分类和聚类,可提供比基于关键字的方法更准确、更贴合情境的结果。

构建检索增强生成 (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 检索文档。 聊天框
FACT_VERIFICATION 需要验证的陈述的嵌入内容,经过优化,可检索包含支持或反驳相应陈述的证据的文档。 使用 FACT_VERIFICATION 表示目标文本;使用 RETRIEVAL_DOCUMENT 表示要检索的文档 自动化事实核查系统

控制嵌入大小

Gemini 嵌入模型 gemini-embedding-001 使用 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 维度 MTEB 得分
2048 68.16
1536 68.17
768 67.99
512 67.55
256 66.19
128 63.31

使用场景

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

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

    文档搜索教程

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

    搜索重新排名教程

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

    异常值检测教程

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

    分类教程

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

    聚类可视化教程

存储嵌入

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

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

模型版本

属性 说明
模型代码

Gemini API

gemini-embedding-001

支持的数据类型

输入

文本

输出

文本嵌入

令牌限制[*]

输入 token 限制

2048

输出维度大小

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

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

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

批量嵌入

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

负责任的使用声明

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

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

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