嵌入
Gemini API 提供嵌入模型来生成文本、图像、视频和其他内容的嵌入。这些生成的嵌入可以用于语义搜索、分类和聚类等任务,从而提供比基于关键字的方法更准确、上下文感知的结果。
最新型号, gemini-embedding-2,是 Gemini API 中的第一个多模态嵌入模型。它将文本、图像、视频、音频和文档映射到统一的嵌入空间,从而实现跨 100 语言的跨模式搜索、分类和聚类。请参阅 多模态嵌入部分 了解更多。对于纯文本用例, gemini-embedding-001 仍然可用。
构建检索增强生成 (RAG) 系统是人工智能产品的常见用例。嵌入在显着增强模型输出方面发挥着关键作用,提高了事实准确性、连贯性和上下文丰富性。如果您更喜欢使用托管 RAG 解决方案,我们构建了 文件搜索 工具,使 RAG 更易于管理且更具成本效益。
生成嵌入 #
使用 embedContent 生成文本嵌入的方法:
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)
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();
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));
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))
}
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?"
}]
}
}'
指定任务类型以提高性能 #
您可以使用嵌入来执行从分类到文档搜索的各种任务。指定正确的任务类型有助于优化预期关系的嵌入,从而最大限度地提高准确性和效率。
带有嵌入的任务类型 2 #
对于纯文本任务 gemini-embedding-2,我们强烈建议您在提示中添加任务说明。这可以通过使用正确的任务前缀格式化查询和文档来完成。
当生成一个 基于多模态输入的单嵌入,我们通常不建议在输入的文本部分前面添加任务指令。在某些情况下,它可以提高性能,但在其他情况下,它会降低性能。
下表显示了如何使用以下示例来格式化对称和非对称用例的查询和文档: gemini-embedding-2 模型。
检索用例(非对称格式)
在非对称用例中,将任务前缀添加到查询中,并应用要嵌入和检索的内容的文档结构。
使用案例 | 查询结构 | 文件结构 |
|---|---|---|
搜索查询 |
|
如果没有标题,则使用 |
问答 |
|
|
事实核查 |
|
|
代码检索 |
|
|
用法示例
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}"
// 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;
单输入用例(对称格式)
在对称用例中,对于同一任务,对查询和文档使用相同的格式。
使用案例 | 输入结构 |
|---|---|
分类 |
|
聚类 |
|
语义相似度 |
请勿将其用于搜索或检索。它旨在实现语义文本相似性。 |
用法示例
def prepare_query_and_document(content):
return f'task: classification | query: {content}'
// Generate embedding for query & document of your task.
String content = "This movie was fantastic!";
String formattedContent = "task: classification | query: " + content;
一致地使用该任务非常重要。例如,如果文档嵌入 f'task: classification | query: {content}',查询也应按照此任务格式嵌入。
带有嵌入的任务类型 1 #
对于 gemini-embedding-001,您可以指定 task_type 在 embedContent 方法。有关支持的任务类型的完整列表,请参阅 支持的任务类型 表。
以下示例展示了如何使用 SEMANTIC_SIMILARITY 检查文本字符串的含义有多相似。
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)
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();
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);
}
}
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)
}
}
}
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?"
}
]
}
}'
代码片段将显示运行时不同文本块之间的相似程度。
支持的任务类型 #
支持的任务类型 gemini-embedding-001:
SEMANTIC_SIMILARITY | 优化嵌入以评估文本相似性。 | 推荐系统、重复检测 |
|---|---|---|
CLASSIFICATION | 嵌入经过优化,可根据预设标签对文本进行分类。 | 情感分析、垃圾邮件检测 |
CLUSTERING | 嵌入优化为基于文本的相似性进行聚类。 | 文档组织、市场研究、异常检测 |
RETRIEVAL_DOCUMENT | 针对文档搜索优化的嵌入。 | 为文章、书籍或网页建立索引以供搜索。 |
RETRIEVAL_QUERY | 针对一般搜索查询优化的嵌入。使用 | 自定义搜索 |
CODE_RETRIEVAL_QUERY | 针对基于自然语言查询的代码块检索而优化的嵌入。使用 | 代码建议和搜索 |
QUESTION_ANSWERING | 在问答系统中嵌入问题,并针对查找回答问题的文档进行了优化。使用 | 聊天室 |
FACT_VERIFICATION | 需要验证的语句的嵌入,优化以检索包含支持或反驳该语句的证据的文档。使用 | 自动事实核查系统 |
控制嵌入大小 #
两者都 gemini-embedding-001 和 gemini-embedding-2 使用俄罗斯套娃表示学习(MRL)技术进行训练,该技术教导模型学习具有初始段(或前缀)的高维嵌入,这些初始段(或前缀)也是相同数据的有用、简单版本。
使用 output_dimensionality 参数来控制输出嵌入向量的大小。选择较小的输出维度可以节省存储空间并提高下游应用程序的计算效率,同时在质量方面几乎没有牺牲。默认情况下,两种模型都会输出 3072 维嵌入,但您可以将其截断为较小的尺寸,而不会损失质量以节省存储空间。我们建议使用 768, 1536, 或 3072 输出尺寸。
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}")
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();
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);
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)
}
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
}'
代码片段的示例输出:
Length of embedding: 768
确保较小尺寸的质量 #
虽然默认的 3072 维度嵌入始终标准化,但 Gemini Embedding 2 也会自动标准化截断的维度(例如,768, 1536)。这确保了通过向量方向而不是大小来计算语义相似度,从而提供更准确的开箱即用结果。
旧型号: 如果您正在使用 gemini-embedding-001,您必须手动标准化非 3072 尺寸,如下所示:
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
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
此代码片段的示例输出:
Normed embedding length: 768
Norm of normed embedding: 1.000000
下表显示了不同维度的 MTEB 分数(嵌入的常用基准)。值得注意的是,结果表明,性能并不严格与嵌入维度的大小相关,较低维度的得分与较高维度的得分相当。
2048 | 68.16 |
|---|---|
1536 | 68.17 |
768 | 67.99 |
512 | 67.55 |
256 | 66.19 |
128 | 63.31 |
多模态嵌入 #
该 gemini-embedding-2 模型支持多模态输入,允许您将图像、视频、音频和文档内容与文本一起嵌入。所有模态都映射到相同的嵌入空间,从而实现跨模态搜索和比较。
支持的方式和限制 #
总体最大输入 token 限制为 8192 token。
文本 | 最高支持 8,192 token。 |
|---|---|
图像 | 每个请求最多 6 图像。支持的格式:PNG、JPEG。 |
音频 | 最大持续时间为 180 秒。支持的格式:MP3、WAV。 |
视频 | 最大持续时间为 120 秒。支持的格式:MP4、MOV。支持的编解码器:H264、H265、AV1、VP9。 系统每个视频最多处理 32 帧:短视频(≤32s)以 1 fps 采样,而较长视频统一采样到 32 帧。视频文件中的音轨不会被处理。 |
文件(PDF) | 每个请求最多 1 文件,最多 6 页。 |
嵌入图像 #
以下示例展示了如何使用嵌入图像 gemini-embedding-2.
图像可以作为内联数据或通过上传的文件提供 Files API.
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)
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();
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));
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 参数:
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)
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();
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()));
}
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}"'"
}
}
]
}
}'
另一方面,如果您使用 Content 里面的物体 contents 参数,它返回单独的嵌入。此示例在一次嵌入调用中创建多个嵌入:
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)
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();
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()));
}
}
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.
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)
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();
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));
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.
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)
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();
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()));
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 页。为了获得最佳质量,我们强烈建议每个 PDF 使用 1 页面。
以下示例展示了如何使用嵌入 PDF gemini-embedding-2:
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)
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();
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));
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}"'"
}
}]
}
}'
使用案例 #
文本嵌入对于各种常见的人工智能用例至关重要,例如:
检索增强生成 (RAG): 嵌入通过检索相关信息并将其合并到模型上下文中来提高生成文本的质量。
信息检索: 给定一段输入文本,搜索语义最相似的文本或文档。
- 搜索重新排名:通过根据查询对初始结果进行语义评分,对最相关的项目进行优先级排序。
- 异常检测: 比较嵌入组可以帮助识别隐藏的趋势或异常值。
- 分类: 根据内容自动对文本进行分类,例如情绪分析或垃圾邮件检测
- 聚类: 通过创建嵌入的集群和可视化,有效掌握复杂的关系。
存储嵌入 #
当您将嵌入应用于生产时,通常会使用 矢量数据库 有效地存储、索引和检索高维嵌入。 Google Cloud 提供可用于此目的的托管数据服务,包括 Gemini Enterprise Agent Platform 矢量搜索 2.0, 大查询, 合金数据库, 和 云SQL.
以下教程展示了如何将其他第三方矢量数据库与 Gemini Embedding 一起使用。
型号版本 #
对于已弃用的嵌入模型,请访问 弃用 页面
从 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不支持参数。相反,您应该直接在纯文本任务的提示中包含任务说明。参见 带有嵌入的任务类型 2 有关如何针对不同用例设置提示格式的详细信息。嵌入聚合:
gemini-embedding-001为输入列表中的每个字符串生成单独的嵌入。相比之下,gemini-embedding-2当在一个请求中直接提供多个输入(如文本和图像)时,会生成单个聚合嵌入。要为各个输入生成单独的嵌入,请将每个输入包装在Content对象,或使用 Batch API。参见 嵌入聚合 了解更多信息。标准化: 如果你使用
output_dimensionality请求尺寸小于 3072 的嵌入,gemini-embedding-2自动标准化这些截断的嵌入。与gemini-embedding-001,需要对3072.以外的维度进行手动归一化参见 确保较小尺寸的质量 了解详情。
批量嵌入 #
如果延迟不是问题,请尝试使用 Gemini 嵌入模型 Batch API。这样可以以默认嵌入价格的 50% 实现更高的吞吐量。查找有关如何开始使用的示例 Batch API食谱.
负责任的使用通知 #
与创建新内容的生成式 AI 模型不同,Gemini Embedding 模型仅旨在将输入数据的格式转换为数字表示形式。虽然 Google 负责提供嵌入模型,将输入数据的格式转换为所请求的数字格式,但用户对其输入的数据和生成的嵌入负有全部责任。通过使用 Gemini Embedding 模型,您确认您对上传的任何内容拥有必要的权利。请勿生成侵犯他人知识产权或隐私权的内容。您对本服务的使用须遵守我们的 禁止使用政策 和 谷歌的服务条款.
开始使用嵌入进行构建 #
查看 嵌入快速入门笔记本 探索模型功能并了解如何自定义和可视化您的嵌入。