Embeddings

Gemini API 支持多种嵌入模型,可为字词、短语、代码和句子生成嵌入。然后,生成的嵌入可用于语义搜索、文本分类、聚类等许多任务。

什么是嵌入?

嵌入是文本(或其他媒体格式)的数值表示法,可捕获输入之间的关系。文本嵌入的工作原理是将文本转换为浮点数数组(称为向量)。这些向量旨在捕获文本的含义。嵌入数组的长度称为向量的维度。一段文本可能由包含数百个维度的向量表示。

嵌入会捕获语义含义和上下文,这会导致具有相似含义的文本具有“更近”的嵌入。例如,“我带狗去看兽医”和“我带猫去看兽医”这两个句子的嵌入在矢量空间中彼此接近。

您可以使用嵌入来比较不同的文本,并了解它们之间的关系。例如,如果文本“cat”和“dog”的嵌入相近,则可以推断这两个词在含义或上下文方面相似。这支持各种常见 AI 应用场景

生成嵌入

使用 embedContent 方法生成文本嵌入:

from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")

result = client.models.embed_content(
        model="gemini-embedding-exp-03-07",
        contents="What is the meaning of life?")

print(result.embeddings)
import { GoogleGenAI } from "@google/genai";

async function main() {

    const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-exp-03-07',
        contents: 'What is the meaning of life?',
    });

    console.log(response.embeddings);
}

main();
ctx := context.Background()

client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

em := client.EmbeddingModel("gemini-embedding-exp-03-07")
res, err := em.EmbedContent(ctx, genai.Text("What is the meaning of life?"))

if err != nil {
    panic(err)
}
fmt.Println(res.Embedding.Values)
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-exp-03-07:embedContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model": "models/gemini-embedding-exp-03-07",
     "content": {
     "parts":[{
     "text": "What is the meaning of life?"}]}
    }'

您还可以将多个分块作为字符串列表传入,以便一次为多个分块生成嵌入。

任务类型

在构建检索增强生成 (RAG) 系统时,一种常见的设计是使用文本嵌入来执行相似性搜索。在某些情况下,这可能会导致质量下降,因为问题及其答案在语义上并不相似。例如,“为什么天空是蓝色的?”这一问题及其答案“阳光的散射会导致天空呈现蓝色”作为陈述的含义截然不同,这意味着 RAG 系统不会自动识别它们之间的关系。

借助任务类型,您可以为特定任务生成经过优化的嵌入,从而节省时间和费用并提升性能。

from google import genai
from google.genai import types

client = genai.Client(api_key="GEMINI_API_KEY")

result = client.models.embed_content(
        model="gemini-embedding-exp-03-07",
        contents="What is the meaning of life?",
        config=types.EmbedContentConfig(task_type="SEMANTIC_SIMILARITY")
)
print(result.embeddings)
import { GoogleGenAI } from "@google/genai";

async function main() {

    const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

    const response = await ai.models.embedContent({
        model: 'gemini-embedding-exp-03-07',
        contents: 'What is the meaning of life?',
        config: {
            taskType: "SEMANTIC_SIMILARITY",
        }
    });

    console.log(response.embeddings);
}

main();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-exp-03-07:embedContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model": "models/gemini-embedding-exp-03-07",
     "content": {
     "parts":[{
     "text": "What is the meaning of life?"}]},
     "taskType": "SEMANTIC_SIMILARITY"
    }'

支持的任务类型

任务类型 说明
SEMANTIC_SIMILARITY 用于生成经过优化以评估文本相似度的嵌入。
CLASSIFICATION 用于生成经过优化的嵌入,以便根据预设标签对文本进行分类。
CLUSTERING 用于生成经过优化的嵌入,以便根据文本的相似性对文本进行分组。
RETRIEVAL_DOCUMENTRETRIEVAL_QUERYQUESTION_ANSWERINGFACT_VERIFICATION 用于生成针对文档搜索或信息检索进行了优化的嵌入。
CODE_RETRIEVAL_QUERY 用于根据自然语言查询检索代码块,例如“对数组进行排序”或“反转链表”。代码块的嵌入是使用 RETRIEVAL_DOCUMENT 计算的。

使用场景

文本嵌入可用于各种常见的 AI 用例,例如:

嵌入模型

Gemini API 提供了三个用于生成文本嵌入的模型:

后续步骤

请参阅嵌入快速入门笔记本