进阶 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}
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?"
}
]
}
}'
运行这些代码后,输出会展示各段文本之间的相似程度。
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。
自动事实核查系统
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
Modality
Specifications and limits
Text
最多 8192 个 token。
Image
每次请求最多 6 张图片。支持格式:PNG、JPEG。
Audio
最长 180 秒。支持格式:MP3、WAV。
Video
最长 120 秒。支持格式:MP4、MOV。支持的编解码器:H264、H265、AV1、VP9。
若未提供标题,请使用 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}