Embeddings.ipynb 教程:从入门到精通

本教程面向有编程基础的开发者,系统讲解 Gemini API 嵌入模型的使用。涵盖文本、图像、音频、视频和 PDF 的多模态嵌入,以及批量嵌入、维度截断等高级功能。通过句子相似度分析和 RAG 检索示例,深入解析嵌入原理、task_type 的作用及实际应用。同时提供环境配置、代码解析、常见错误排查和生产优化建议,帮助开发者快速掌握嵌入技术并应用于实际项目。

技术背景

嵌入(Embedding)是将非结构化数据(如文本、图像、音频)转换为高维向量表示的技术,旨在捕捉数据的语义信息。在 AI 工程中,嵌入是构建语义搜索、推荐系统、异常检测、RAG(检索增强生成)等应用的基础。传统的关键词匹配无法理解语义,而嵌入通过向量空间中的距离度量(如余弦相似度)实现语义级别的相似性比较。Gemini API 提供先进的嵌入模型,特别是 gemini-embedding-2 支持多模态输入,统一了不同模态的表示空间,解决了跨模态检索和理解的难题。本教程旨在帮助开发者快速上手 Gemini 嵌入 API,理解其原理并应用于实际场景。

核心原理

嵌入模型将输入数据(文本、图像等)映射到高维向量空间,使得语义相近的输入在向量空间中距离更近。Gemini 嵌入模型基于 Transformer 架构,通过大规模预训练学习到丰富的语义表示。对于多模态输入,模型将不同模态的数据编码到统一的嵌入空间,实现跨模态的语义对齐。文本嵌入默认输出 3072 维向量,可通过 output_dimensionality 参数截断以降低维度。task_type 参数(仅 gemini-embedding-001)允许针对特定任务(如检索、分类)优化嵌入,提高下游任务性能。gemini-embedding-2 则通过提示指令实现类似效果。

架构分析

本教程的架构设计围绕 Gemini API 客户端展开。首先初始化 genai.Client,然后通过 client.models.embed_content 方法调用嵌入模型。该方法接受模型 ID、内容列表和配置参数(如 output_dimensionality、task_type)。对于多模态输入,使用 types.Part.from_bytes 或 types.Content 封装数据。聚合嵌入通过将多个输入直接放入 contents 列表实现,分离嵌入则通过 Content 对象包装。在 RAG 示例中,文档嵌入使用 RETRIEVAL_DOCUMENT 任务类型,查询嵌入使用 RETRIEVAL_QUERY,通过点积计算相似度并检索最相关文档,最后用生成模型生成答案。整个流程体现了嵌入在检索增强生成中的核心作用。

完整实战教程

##### 版权所有 2026 Google LLC.

# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Gemini API:开始使用 Gemini 嵌入模型

<a target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Embeddings.ipynb">

</a>

嵌入是捕捉不同输入之间关系的数值表示。文本嵌入通过将文本转换为浮点数数组(称为向量)来实现这一点。这些向量的主要目的是封装文本的语义含义。向量的维度,即嵌入数组的长度,可能相当大,一段文本有时由具有数百个维度的向量表示。

Gemini API 生成最先进的文本嵌入。嵌入是表示单词、句子或段落含义的浮点数列表。您可以在许多下游应用中使用嵌入,例如文档搜索。

本笔记本提供了快速代码示例,向您展示如何开始生成嵌入。

注意: 本笔记本使用 Interactions API,这是与 Gemini 模型交互的最新方式。正在寻找 generateContent 版本?请查看 归档分支。

目录

  1. 设置: 安装 SDK 并设置你的 API 密钥。
  2. 嵌入内容: 为单个或多个输入生成文本嵌入。
  3. 多模态嵌入: 为图像、音频、视频和 PDF 生成嵌入。
  4. 设置嵌入维度: 探索如何降低嵌入的维度。
  5. 嵌入实践: 使用余弦相似度和热图可视化进行句子相似度分析。
  6. 使用 task_type: 了解如何将 task_type 用于检索增强生成(RAG)等各类应用。

<a id="setup"></a>

设置

安装 SDK

从 PyPI 安装 SDK。

%pip install -q -U "google-genai>=2.9.0"  # Minimum version 1.73 for latest embedding behavior # 2.0 is needed to use the interactions API

设置你的 API 密钥

要运行以下单元格,你的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab 密钥中。如果你还没有 API 密钥,或者不确定如何创建 Colab 密钥,请参阅 [身份验证]

image](../quickstarts/Authentication.ipynb) 查看演练。

from google.colab import userdata

GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')

初始化 SDK 客户端

使用新的 SDK,现在你只需要用你的 API 密钥(如果使用 Vertex AI 则使用 OAuth)初始化一个客户端。模型现在在每次调用中设置。

from google import genai
from google.genai import types

client = genai.Client(api_key=GEMINI_API_KEY)

选择模型

选择本指南中要使用的模型。

最新模型 gemini-embedding-2 是 Gemini API 中首个多模态嵌入模型。它将文本、图像、视频、音频和 PDF 映射到统一的嵌入空间,支持跨 100 多种语言的跨模态搜索、分类和聚类。请参阅多模态嵌入部分了解更多信息。对于纯文本用例,gemini-embedding-001 仍然可用。

有关所有 Gemini 模型的完整概述,请查看文档。

MODEL_ID = "gemini-embedding-2" # @param ["gemini-embedding-2", "gemini-embedding-001"] {"allow-input":true, isTemplate: true}

<a id="embed_content"></a>

嵌入内容

调用 embed_content 方法并传入模型以生成文本嵌入。

text = ["Hello world"]
result = client.models.embed_content(model=MODEL_ID, contents=text)
[embedding] = result.embeddings

# Print just a part of the embedding to keep the output manageable
print(str(embedding.values)[:50], '... TRIMMED]')
print(len(embedding.values))  # The embeddings have 3072 dimensions by default

<a id="multimodal"></a>

多模态嵌入

gemini-embedding-2 支持以下格式:

总输入 token 数上限为 8192 个 token。

嵌入图片

以下示例展示了如何嵌入图片。图片可以作为内联数据提供,也可以通过 Files API 作为上传文件提供。

!wget -O jetpack.png https://storage.googleapis.com/generativeai-downloads/data/jetpack.png -q
with open('jetpack.png', 'rb') as f:
    image_bytes = f.read()

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

print(result.embeddings)

嵌入聚合

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

* 多个部分(聚合): 直接将多个输入添加到 contents 参数中,会为所有输入生成一个聚合嵌入。

* 多个 Content 对象(分离): 将每个输入包装在 Content 对象中,并在 contents 参数中传递它们,会为每个条目返回单独的嵌入。

* 帖子级表示: 对于包含多个媒体项目的复杂对象(如社交媒体帖子),考虑通过聚合单独的嵌入(例如,取平均值)来创建连贯的帖子级表示。

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

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

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

另一方面,如果你在 contents 参数中使用 Content 对象,它将返回单独的嵌入。

以下示例在一次嵌入调用中创建多个嵌入:

result = client.models.embed_content(
    model="gemini-embedding-2",
    contents=[
        types.Content(parts=[types.Part.from_text(text="The jetpack is cool")]),
        types.Content(
            parts=[
                types.Part.from_bytes(
                    data=image_bytes,
                    mime_type="image/jpeg",
                ),
            ]
        ),
    ],
)

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

嵌入音频

以下示例展示了如何嵌入音频文件。音频文件可以作为内联数据提供,也可以通过 Files API 上传的文件提供。

import urllib.request

URL = "https://www.gstatic.com/aistudio/starter-apps/multimodal-search/audio/trees.wav"
urllib.request.urlretrieve(URL, "trees.wav")
print("Downloaded: trees.wav")
with open('trees.wav', 'rb') as f:
    audio_bytes = f.read()

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

print(result.embeddings[0].values)

嵌入视频

以下示例展示了如何嵌入视频文件。视频文件可以作为内联数据提供,也可以通过 Files API 作为上传文件提供。

URL = "https://storage.googleapis.com/generativeai-downloads/gemini-cookbook/videos/unicorn.mp4"
!wget -q $URL -O unicorn.wav
with open('unicorn.wav', '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/wav',
      ),
    ]
)

print(result.embeddings[0].values)

嵌入 PDF

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

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

!wget -O handwriting_form.pdf https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/handwriting_form.pdf  -q
with open('handwriting_form.pdf', 'rb') as f:
    pdf_bytes = f.read()

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

print(result.embeddings)

批量嵌入内容

您可以通过一次 API 调用嵌入多个提示词的列表,以提高效率。

result = client.models.embed_content(
    model=MODEL_ID,
    contents=[
      'What is the meaning of life?',
      'How much wood would a woodchuck chuck?',
      'How does the brain work?'])

for embedding in result.embeddings:
    # Print just a part of the embedding to keep the output manageable
  print(str(embedding)[:50], '... TRIMMED]')

<a id="dimensionality"></a>

设置嵌入维度

嵌入模型也支持更低的嵌入维度。指定 output_dimensionality 来截断输出。

text=["Hello world"]
# Not truncated
result1 = client.models.embed_content(
    model=MODEL_ID,
    contents=text)


# Truncated
from google.genai import types

result2 = client.models.embed_content(
    model=MODEL_ID,
    contents=text,
    config=types.EmbedContentConfig(output_dimensionality=10))

[embedding1] = result1.embeddings
[embedding2] = result2.embeddings


(len(embedding1.values), len(embedding2.values))

<a id="practice"></a>

嵌入的实际应用——句子相似度分析

句子相似度分析利用嵌入模型将句子转换为数值向量,这些向量封装了句子的语义含义。这使得可以通过测量句子各自向量在高维空间中的距离或角度来比较句子——这样,含义相近的文本其向量也会更接近。

在本示例中,你将使用一个 Pandas 数据框来存储句子,并计算一个外部句子与它们的相似度。

import pandas as pd

text = [
    "I really enjoyed last night's movie",
    "The film featured a lot of acrobatic scenes yesterday",
    "I had fun writing my first program in Python",
    "a tremendous feeling of relief to finally get my Nodejs scripts to run without errors!",
    "Oh Romeo, Romeo, wherefore art thou Romeo?"
]

df = pd.DataFrame(text, columns=["text"])
df

现在,你将创建一个名为 embeddings 的新数据框列,使用嵌入模型为每个文本生成嵌入。

df["embeddings"] = df.apply(lambda x: client.models.embed_content(model=MODEL_ID, contents=(x['text'])).embeddings[0].values, axis=1)
df

使用余弦相似度分析文本示例的相似性

通过将文本转换为嵌入,您可以计算相似度分数。计算相似度分数的方法有很多,其中一种常见的技术是使用余弦相似度。

在上面的示例中,文本列中的两个句子涉及喜欢看电影,另外两个涉及喜欢编程。当对语义相关的句子进行两两比较时,余弦相似度分数应该更高(接近1.0),而在语义不同的句子之间,分数应该更低。

下面的DataFrame输出显示了嵌入之间的余弦相似度分数结果:

from sklearn.metrics.pairwise import cosine_similarity

cos_sim_array = cosine_similarity(list(df.embeddings.values))

# display as DataFrame
similarities = pd.DataFrame(cos_sim_array, index=text, columns=text)
similarities

为了更容易理解这一点,你可以使用热力图。自然,当文本完全相同时,相似度最高(得分为 1.0)。次高的得分出现在句子语义相似的情况下。最低的得分则出现在句子含义差异较大的情况下。

import seaborn as sns
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 6))
ax = sns.heatmap(similarities, annot=True, cmap="crest")
ax.xaxis.tick_top()
ax.set_xticklabels(text, rotation=90)
plt.show()

<a id="task_type"></a>

在不同场景下使用 task_type

重要提示: 以下部分涉及 gemini-embedding-001。对于 gemini-embedding-2,不支持 task_type 参数。相反,对于纯文本任务,您应该直接在提示中包含任务指令。有关如何为不同用例格式化提示的详细信息,请参阅 Embeddings 2 文档中的任务类型。

在生成嵌入时,尤其是对于检索增强生成(RAG)等复杂系统,一刀切的方法有时会导致结果质量较低。例如,像“天空为什么是蓝色的?”这样的问题和它的答案“阳光的散射导致蓝色”作为陈述具有不同的含义,而通用嵌入模型可能无法识别它们之间的强关联。为了解决这个问题,您可以在创建嵌入时指定 task_type。这会指示模型生成针对您的预期用例专门优化的向量,这可以显著提高性能,同时节省时间和成本。

Gemini Embedding 1 模型支持多种任务类型,每种类型都针对特定目标量身定制。以下是可用类型及其应用的总体概述:

* SEMANTIC_SIMILARITY:当您的目标是评估两段文本在语义上的相似程度时,请使用此类型。

* RETRIEVAL_QUERY 和 RETRIEVAL_DOCUMENT:这些对于信息检索任务至关重要。对用户的搜索查询使用 RETRIEVAL_QUERY,对数据库中要搜索的文本使用 RETRIEVAL_DOCUMENT。这是构建有效语义搜索和 RAG 系统的基础。

* CLASSIFICATION:当您打算使用嵌入来训练一个将文本分类到一组预定义类别中的模型时,请选择此任务类型。

* CLUSTERING:如果您的目标是在没有预先存在的标签的情况下将相似的文本分组在一起,以识别隐藏的趋势或主题,则此任务类型将生成针对该目的优化的嵌入。

这个例子直观地展示了更复杂的 RAG 系统是如何工作的——比如你在构建一个 FAQ 系统时。你将:

首先,你将声明代表文档的信息,创建一个包含文档标题和内容的结构,并从中创建一个数据框。

contents01 = """
    Operating the Climate Control System Your Googlecar has a climate control system that allows you to adjust the temperature and airflow in the car.
    To operate the climate control system, use the buttons and knobs located on the center console.
    Temperature: The temperature knob controls the temperature inside the car.
    Turn the knob clockwise to increase the temperature or counterclockwise to decrease the temperature.
    Airflow: The airflow knob controls the amount of airflow inside the car.
    Turn the knob clockwise to increase the airflow or counterclockwise to decrease the airflow.
    Fan speed: The fan speed knob controls the speed of the fan.
    Turn the knob clockwise to increase the fan speed or counterclockwise to decrease the fan speed.
    Mode: The mode button allows you to select the desired mode.
    The available modes are: Auto: The car will automatically adjust the temperature and airflow to maintain a comfortable level.
    Cool: The car will blow cool air into the car.
    Heat: The car will blow warm air into the car.
    Defrost: The car will blow warm air onto the windshield to defrost it.
"""

contents02 = """
    Your Googlecar has a large touchscreen display that provides access to a variety of features, including navigation, entertainment, and climate control.
    To use the touchscreen display, simply touch the desired icon.
    For example, you can touch the "Navigation" icon to get directions to your destination or touch the "Music" icon to play your favorite songs.
"""

contents03 = """
    Shifting Gears Your Googlecar has an automatic transmission.
    To shift gears, simply move the shift lever to the desired position.
    Park: This position is used when you are parked. The wheels are locked and the car cannot move.
    Reverse: This position is used to back up.
    Neutral: This position is used when you are stopped at a light or in traffic.
    The car is not in gear and will not move unless you press the gas pedal.
    Drive: This position is used to drive forward.
    Low: This position is used for driving in snow or other slippery conditions.
"""

document01 = {
    "title": "Climate control system",
    "contents": " ".join(contents01.split())
}
document02 = {
    "title": "Touchscreen",
    "contents": " ".join(contents02.split())
}
document03 = {
    "title": "Shifting gears",
    "contents": " ".join(contents03.split())
}

documents = [document01, document02, document03]

docs_df = pd.DataFrame(documents)
docs_df.columns = ['title', 'contents']
docs_df

现在,你将使用(RETRIEVAL_DOCUMENT 任务类型)列在数据框中创建嵌入。

GEMINI_EMBEDDING_1_MODEL_ID = "gemini-embedding-001" #task type param only works with gemini-embedding-001
docs_df["embeddings"] = docs_df.apply(lambda x: client.models.embed_content(model=GEMINI_EMBEDDING_1_MODEL_ID, contents=(x['contents']), config=types.EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT")).embeddings[0].values, axis=1)
docs_df

现在你将创建一个函数来实现问题与数据框中的搜索之间的交互。

find_best_passage 函数不是搜索简单的关键词,而是搜索含义。

以下是当你提出问题时它执行步骤的详细分解:

import numpy as np

def find_best_passage(query: str, dataframe: pd.DataFrame, model: str) -> str:

    # 1. Create an embedding for the user's query.
    query_embedding = client.models.embed_content(
            model=model,
            contents=query,
            config=types.EmbedContentConfig(task_type="RETRIEVAL_QUERY")
    )

    # 2. Calculate the dot product to find the similarity between the query and all documents
    dot_products = np.dot(np.stack(dataframe.embeddings), query_embedding.embeddings[0].values)

    # 3. Find the index of the highest score and return the corresponding text.
    best_passage_index = np.argmax(dot_products)

    # 4. return the document contents more relevant to the question
    return dataframe.contents.iloc[best_passage_index]

例如,对于问题“如何让汽车冷却系统的风扇转速更强”,你会有以下段落作为最接近的答案:

question = "how to make the fan speed stronger on the car cooling system"

best_passage = find_best_passage(question, docs_df, GEMINI_EMBEDDING_1_MODEL_ID)
best_passage

现在,你可以使用第一步找到的最佳段落进行一次增强生成(RAG 流程的最后一步),但仍然可以为用户提供自定义答案,而不是直接粘贴大段文档内容。

from IPython.display import Markdown

final_answer_prompt = f"""
    Your Role: You are a friendly AI assistant. Your purpose is to explain information to users who are not experts.

    Your Task: Use the provided "Source Text" below to answer the user's question.

    Guidelines for your Response:

    Be Clear and Simple: Explain any complicated ideas in easy-to-understand terms. Avoid jargon.
    Be Friendly: Write in a warm, conversational, and approachable tone.
    Be Thorough: Construct a complete and detailed answer in full sentences, using all the relevant information from the source text.
    Stay on Topic: If the source text does not contain the answer, you must state that the information is not available in the provided material. Do not use outside knowledge.

    QUESTION: {question}
    PASSAGE: {best_passage}
"""

MODEL_ID = "gemini-3.7-flash"  # @param ["gemini-3.7-flash", "gemini-2.5-pro", "gemini-3.1-pro-preview"]

final_answer = client.interactions.create(
    model=MODEL_ID,
    input=final_answer_prompt,
)

Markdown(final_answer.steps[-1].content[0].text)

了解更多

请查看 Cookbook 中的这些示例,了解如何使用嵌入做更多事情:

嵌入在向量数据库中也有很多应用。请查看以下示例:

您可以在 ai.google.dev 上的嵌入指南中了解更多关于嵌入的一般信息。

常见问题

常见错误:1. API 密钥未设置或无效,导致认证失败。解决:确保在 Colab 中正确设置 GEMINI_API_KEY。2. 模型 ID 错误,如使用 gemini-embedding-2 时传入 task_type 参数,会报错。解决:gemini-embedding-2 不支持 task_type,应通过提示指令实现。3. 输入格式错误,如音频文件 mime_type 错误(示例中视频文件误命名为 .wav)。解决:确保 mime_type 与实际文件类型匹配。4. 维度截断时未使用 config 参数,导致输出维度不变。解决:使用 types.EmbedContentConfig(output_dimensionality=10)。5. 批量嵌入时 contents 列表元素类型不一致,导致错误。解决:统一使用字符串或 Part 对象。排查方法:检查 API 响应错误信息,使用 print 输出中间结果,逐步调试。

企业应用扩展

生产环境优化:1. 使用批量嵌入减少 API 调用次数,提高吞吐量。2. 对于大规模文档,预先计算并存储嵌入向量,使用向量数据库(如 Chroma、Qdrant)进行高效检索。3. 根据任务选择合适的 task_type 或提示指令,提升嵌入质量。4. 考虑使用 output_dimensionality 降低维度,减少存储和计算开销,但需权衡精度。5. 实现缓存机制,避免重复嵌入相同内容。6. 监控 API 使用量和延迟,必要时采用异步调用或并发控制。7. 对于多模态数据,注意输入大小限制(如图片数量、音频时长),合理分块处理。

总结

本教程面向有编程基础的开发者,系统讲解 Gemini API 嵌入模型的使用。涵盖文本、图像、音频、视频和 PDF 的多模态嵌入,以及批量嵌入、维度截断等高级功能。通过句子相似度分析和 RAG 检索示例,深入解析嵌入原理、task_type 的作用及实际应用。同时提供环境配置、代码解析、常见错误排查和生产优化建议,帮助开发者快速掌握嵌入技术并应用于实际项目。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部RAG 与知识库教程