Gemini API 提供文本嵌入模型,用于为字词、短语、句子和代码生成嵌入。这些基础嵌入可支持高级 NLP 任务,例如语义搜索、分类和聚类,与基于关键字的方法相比,可提供更准确、更具上下文感知能力的结果。
构建检索增强生成 (RAG) 系统是嵌入的一种常见使用场景。嵌入在显著提升模型输出方面发挥着关键作用,可提高事实准确性、连贯性和上下文丰富度。它们可以高效地从知识库(由嵌入表示)中检索相关信息,然后将这些信息作为输入提示中的附加背景信息传递给语言模型,引导语言模型生成更明智、更准确的回答。
对于企业级应用和高容量工作负载,我们建议在 Vertex AI 上使用嵌入模型。
生成嵌入
使用 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 "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-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 "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model": "models/gemini-embedding-001",
"content": [
{"parts": [{"text": "What is the meaning of life?"}]},
{"parts": [{"text": "What is the purpose of existence?"}]},
{"parts": [{"text": "How do I bake a cake?"}]}
]
}'
指定任务类型以提升性能
您可以将嵌入用于从分类到文档搜索的各种任务。指定正确的任务类型有助于针对预期关系优化嵌入,从而最大限度地提高准确性和效率。如需查看支持的任务类型的完整列表,请参阅支持的任务类型表格。
以下示例展示了如何使用 SEMANTIC_SIMILARITY
来检查文本字符串在含义上的相似程度。
Python
from google import genai
from google.genai import types
import numpy as np
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 = [
np.array(e.values) for e in client.models.embed_content(
model="gemini-embedding-001",
contents=texts,
config=types.EmbedContentConfig(task_type="SEMANTIC_SIMILARITY")).embeddings
]
# Calculate cosine similarity. Higher scores = greater semantic similarity.
embeddings_matrix = np.array(result)
similarity_matrix = cosine_similarity(embeddings_matrix)
for i, text1 in enumerate(texts):
for j in range(i + 1, len(texts)):
text2 = texts[j]
similarity = similarity_matrix[i, j]
print(f"Similarity between '{text1}' and '{text2}': {similarity:.4f}")
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 -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"contents": [
{"parts": [{"text": "What is the meaning of life?"}]},
{"parts": [{"text": "What is the purpose of existence?"}]},
{"parts": [{"text": "How do I bake a cake?"}]}
],
"embedding_config": {
"task_type": "SEMANTIC_SIMILARITY"
}
}'
以下内容展示了此代码段的输出示例:
Similarity between 'What is the meaning of life?' and 'What is the purpose of existence?': 0.9481
Similarity between 'What is the meaning of life?' and 'How do I bake a cake?': 0.7471
Similarity between 'What is the purpose of existence?' and 'How do I bake a cake?': 0.7371
支持的任务类型
任务类型 | 说明 | 示例 |
---|---|---|
SEMANTIC_SIMILARITY | 经过优化以评估文本相似度的嵌入。 | 推荐系统、重复内容检测 |
分类 | 经过优化的嵌入,可根据预设标签对文本进行分类。 | 情感分析、垃圾信息检测 |
聚类 | 经过优化的嵌入,可根据文本的相似性对文本进行聚类。 | 文档整理、市场调研、异常检测 |
RETRIEVAL_DOCUMENT | 针对文档搜索进行了优化的嵌入。 | 为搜索编制文章、图书或网页的索引。 |
RETRIEVAL_QUERY |
针对一般搜索查询进行了优化的嵌入。
使用 RETRIEVAL_QUERY 进行查询;使用 RETRIEVAL_DOCUMENT 表示要检索的文档。
|
自定义搜索 |
CODE_RETRIEVAL_QUERY |
经过优化的嵌入,可根据自然语言查询检索代码块。
使用 CODE_RETRIEVAL_QUERY 进行查询;使用 RETRIEVAL_DOCUMENT 检索代码块。
|
代码建议和搜索 |
QUESTION_ANSWERING |
问答系统中问题的嵌入,经过优化,可用于查找回答问题的文档。
使用 QUESTION_ANSWERING 提出问题;使用 RETRIEVAL_DOCUMENT 指定要检索的文档。
|
Chatbox |
FACT_VERIFICATION |
需要验证的陈述的嵌入,针对检索包含支持或反驳相应陈述的证据的文档进行了优化。
使用 FACT_VERIFICATION 表示目标文本;使用 RETRIEVAL_DOCUMENT 表示要检索的文档
|
自动化事实核查系统 |
控制嵌入大小
Gemini 嵌入模型 gemini-embedding-001
使用 Matryoshka Representation Learning (MRL) 技术进行训练,该技术可教导模型学习高维嵌入,这些嵌入具有初始段(或前缀),这些初始段也是相同数据的有用且更简单的版本。您可以选择使用完整的 3072 维嵌入,也可以将其截断为较小的尺寸,这样既不会损失质量,又能节省存储空间。为获得最佳质量,我们建议使用前 768 个和 1536 个。
通过使用 output_dimensionality
参数,用户可以控制输出嵌入向量的大小。选择较小的输出维度可以节省存储空间并提高下游应用的计算效率,同时在质量方面几乎没有损失。
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 "x-goog-api-key: YOUR_GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"contents": [
{"parts": [{"text": "What is the meaning of life?"}]}
],
"embedding_config": {
"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
使用场景
文本嵌入对于各种常见的 AI 应用场景至关重要,例如:
- 检索增强生成 (RAG):嵌入通过检索相关信息并将其纳入模型的情境中,来提高生成文本的质量。
信息检索:使用嵌入根据一段输入文本搜索语义相似的文本或文档。
异常值检测:比较嵌入群组有助于发现隐藏的趋势或离群点。
分类:根据文本内容自动对文本进行分类,例如情感分析或垃圾内容检测
聚类:了解关系的一种有效方法是创建嵌入的聚类和可视化图表。
存储嵌入
在将嵌入投入生产环境时,通常会使用矢量数据库来高效存储、索引和检索高维嵌入。Google Cloud 提供可用于此目的的托管数据服务,包括 BigQuery、AlloyDB 和 Cloud SQL。
以下教程展示了如何将其他第三方向量数据库与 Gemini Embedding 搭配使用。
嵌入模型
正式版模型
旧版模型
embedding-001
(将于 2025 年 8 月 14 日弃用)text-embedding-004
(将于 2026 年 1 月 14 日弃用)
使用嵌入
与创建新内容的生成式 AI 模型不同,Gemini Embedding 模型仅用于将输入数据的格式转换为数值表示形式。虽然 Google 负责提供一种嵌入模型,将输入数据的格式转换为所需的数值格式,但用户仍需对他们输入的数据和生成的嵌入内容承担全部责任。使用 Gemini 嵌入模型,即表示您确认自己拥有所上传内容的必要相关权利。请勿生成侵犯他人知识产权或隐私权的内容。使用此服务时,您必须遵守我们的《使用限制政策》和《Google 服务条款》。
开始使用嵌入模型进行构建
您可以查看嵌入快速入门笔记本,了解模型功能以及如何自定义和直观呈现嵌入。