进阶 ai.google.dev 2026-10-15 02:43:21 · 33 阅读

第11章 Gemini API Embeddings 嵌入技术详解:多模态模型与代码实践

Gemini 4 Argon 现已上线,欢迎体验。 首页 Gemini API 文档 Embeddings(嵌入) Gemini API 提供嵌入模型,用于生成文本、图像、视频及其他内容的嵌入向量。这些嵌入向量可用于语义搜索、分类、聚类等任务,相比基于关键词的方法,能提供更精准、更具上下文感知能力的结果。 最新模型 gemini-embedding-2 是 Gemini API 中首个多模态嵌入模型。它将文本、图像、视频、音频和文档映射到统一的嵌入空间,支持跨超过 100 种语言的跨模态搜索、分类和聚类。欲了解多模态嵌入的详细信息,请参阅“多模态嵌入”章节。若仅处理文本,gemini-embedding-001 模型仍可供使用。 构建检索增强生成(RAG)系统是 AI 产品的常见应用场景。嵌入在其中扮演关键角色,能显著提升模型输出的事实准确性、连贯性和上下文丰富度。如果你倾向于使用托管式 RAG 方案,我们推出了文件搜索(File Search)工具,使其更易于管理且更具成本效益。 生成嵌入 使用 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。

问题回答 任务: 问题回答 | 查询: {content} 标题: {title} | 文本: {content} 事实核查 任务: 事实核查 | 查询: {content} 标题: {title} | 文本: {content} 代码检索 任务: 代码检索 | 查询: {content} 标题: {title} | 文本: {content}

使用示例

Python# 为任务的查询生成嵌入。请在此处使用正确的任务:
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}"

# 为非对称检索任务的文档生成嵌入:
def prepare_document(content, title=None):
    if title is None:
        title = "none"
    return f"title: {title} | text: {content}"

单输入用例(对称格式)

在对称用例中,针对同一任务,查询和文档需使用相同的格式化结构。

用例 输入结构 分类 任务: 分类 | 查询: {content} 聚类 任务: 聚类 | 查询: {content} 语义相似度 任务: 语句相似度 | 查询: {content}

不要用它来做搜索或检索,它只适用于语义文本相似度(semantic textual similarity)。

使用示例

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}' 生成的 embedding,那么查询也必须使用同样的任务格式来生成 embedding。

Embeddings 1 支持的任务类型

对于 gemini-embedding-001,你可以在 embedContent 方法中指定 task_type。完整的任务类型列表见「支持的任务类型」表格。 下面的示例演示如何使用 SEMANTIC_SIMILARITY 来衡量几段文本在语义上的相似程度。 Pythonfrom 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) JavaScriptimport { 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(); Javaimport 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 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 embeddings = response.embeddings().get(); for (int i = 0; i < texts.size(); i++) { for (int j = i + 1; j < texts.size(); j++) { List v1 = embeddings.get(i).values().get(); List 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); } } Gopackage 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) } } } RESTcurl "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 支持的任务类型: Task type Description Examples SEMANTIC_SIMILARITY 用于评估文本相似度的 embedding。 推荐系统、重复内容检测 CLASSIFICATION 用于按预设标签对文本分类的 embedding。 情感分析、垃圾信息检测 CLUSTERING 用于按相似度对文本聚类的 embedding。 文档整理、市场调研、异常检测 RETRIEVAL_DOCUMENT 针对文档搜索优化的 embedding。 为文章、书籍或网页建立搜索索引。 RETRIEVAL_QUERY 针对通用搜索查询优化的 embedding。查询用 RETRIEVAL_QUERY,待检索文档用 RETRIEVAL_DOCUMENT。 自定义搜索 CODE_RETRIEVAL_QUERY 针对根据自然语言查询检索代码块优化的 embedding。查询用 CODE_RETRIEVAL_QUERY,待检索代码块用 RETRIEVAL_DOCUMENT。 代码建议与代码搜索 QUESTION_ANSWERING 用于问答系统中问题的 embedding,针对查找能回答该问题的文档做了优化。问题用 QUESTION_ANSWERING,待检索文档用 RETRIEVAL_DOCUMENT。 聊天机器人 FACT_VERIFICATION 用于待验证陈述的 embedding,针对检索包含支持或反驳该陈述的证据的文档做了优化。目标文本用 FACT_VERIFICATION,待检索文档用 RETRIEVAL_DOCUMENT。 自动事实核查系统

控制 embedding 维度

gemini-embedding-001 和 gemini-embedding-2 都采用 Matryoshka Representation Learning(MRL)技术训练。这种技术让模型学到的高维 embedding 具有一个特性:它的前缀部分本身就是同一数据更精简、依然可用的版本。 你可以通过 output_dimensionality 参数控制输出 embedding 向量的大小。选择较小的输出维度可以节省存储空间、提升下游应用的计算效率,而质量损失很小。这两个模型默认输出 3072 维的 embedding,但你可以直接截断到更小的尺寸而不损失质量。建议使用 768、1536 或 3072 维。 Pythonfrom 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}") JavaScriptimport { 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(); Javaimport 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); Gopackage 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) } RESTcurl -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 维 embedding 本身就是归一化的,而 Gemini Embedding 2 对截断后的维度(如 768、1536)也会自动归一化。这保证了语义相似度是基于向量方向而非模长计算的,开箱即用就能得到更准确的结果。 旧版模型:如果你使用的是 gemini-embedding-001,对非 3072 维的 embedding 需要手动归一化,方法如下: Pythonimport 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 下表列出了不同维度下常用的 embedding 基准测试 MTEB 的得分。值得注意的是,性能并不严格取决于 embedding 维度的大小,较低的维度也能取得与高维度相当的分数。
MRL Dimension MTEB Score (Gemini Embedding 001) 2048 68.16 1536 68.17 768 67.99 512 67.55 256 66.19 128 63.31

多模态 embedding

gemini-embedding-2 模型支持多模态输入,可以对图片、视频、音频和文档内容与文本一起生成 embedding。所有模态都会映射到同一个 embedding 空间,从而支持跨模态的搜索和比较。

支持的模态及限制

输入 token 总量上限为 8192。
Modality Specifications and limits Text 最多 8192 个 token。 Image 每次请求最多 6 张图片。支持格式:PNG、JPEG。 Audio 最长 180 秒。支持格式:MP3、WAV。 Video 最长 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', ), ] ) # 这会生成一个嵌入 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, }, }, ], }); // 这会生成一个嵌入 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); // 这会生成一个嵌入 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", ), ] ), ], ) # 这会生成两个嵌入 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, }, }], }, ], }); // 这会生成两个嵌入 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 contents = Arrays.asList( Content.fromParts(Part.fromText("task: classification | query: An image of a dog")), Content.fromParts(Part.fromBytes(imageBytes, "image/png"))); // 为每个 Content 对象生成分离的嵌入 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 页。为获得最佳质量,强烈建议使用每页 1 个 PDF。 以下示例展示如何使用 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: * ChromaDB 教程 * Qdrant 教程 * Weaviate 教程 * Pinecone 教程 模型版本 Gemini Embedding 2 * 模型代码:Gemini API 中为 gemini-embedding-2 * 支持的数据类型:输入为文本、图像、视频、音频、PDF;输出为文本嵌入 * Token 限制:输入限制 8,192;输出维度大小灵活,支持 128 - 3072,推荐 768、1536、3072 * 版本:稳定版为 gemini-embedding-2 * 最新更新:2026 年 4 月 Gemini Embedding * 模型代码:Gemini API 中为 gemini-embedding-001 * 支持的数据类型:输入为文本;输出为文本嵌入 * Token 限制:输入限制 2,048;输出维度大小灵活,支持 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 Embedding 模型配合 Batch API。这允许以默认嵌入价格的 50% 实现更高的吞吐量。Batch API 食谱中提供了入门示例。 负责任使用声明 与生成新内容的生成式 AI 模型不同,Gemini Embedding 模型仅旨在将输入数据的格式转换为数值表示。虽然 Google 负责提供能将输入数据格式转换为所请求数值格式的嵌入模型,但用户对其输入的数据和生成的嵌入承担全部责任。使用 Gemini Embedding 模型即表示您确认已拥有上传内容的必要权利。请勿生成侵犯他人知识产权或隐私权的内容。使用本服务须遵守我们的禁止使用政策和 Google 服务条款。 开始使用嵌入 请查看嵌入快速入门笔记本,以探索模型功能并学习如何定制和可视化嵌入。

评论 (0)