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 Embedding 模型即代表您確認自己有權使用所上傳的一切內容。請勿生成侵犯他人智慧財產或隱私權的內容。使用這項服務時,須遵守《使用限制政策》和《Google 服務條款》。
開始使用嵌入功能建構內容
請參閱嵌入快速入門筆記本,瞭解模型功能,以及如何自訂和顯示嵌入內容。