このバージョンはまだ開発中であり、まだ安定しているとは考えられていません。最新のスナップショットバージョンについては、Spring AI 1.0.3 を使用してください。

Google GenAI テキスト埋め込み

Google GenAI Embeddings API (英語) は、Gemini 開発者 API または Vertex AI を介して、Google の埋め込みモデルを用いたテキスト埋め込み生成機能を提供します。このドキュメントでは、Google GenAI テキスト埋め込み API を用いてテキスト埋め込みを作成する方法について説明します。

Google GenAI テキスト埋め込み API は、密ベクトル表現を使用します。単語を数値に直接マッピングする傾向があるスパースベクトルとは異なり、密ベクトルはテキストの意味をより適切に表現するように設計されています。生成 AI で密ベクトル埋め込みを使用する利点は、単語や構文の直接的な一致を検索する代わりに、たとえ同じ言語を使用していなくても、クエリの意味に一致する文章をより適切に検索できることです。

現在、Google GenAI SDK はテキスト埋め込みのみをサポートしています。マルチモーダル埋め込みのサポートは保留中で、SDK で利用可能になった時点で追加される予定です。

この実装では、次の 2 つの認証モードが提供されます。

  • Gemini 開発者 API : API キーを使用して素早いプロトタイピングと開発を行う

  • Vertex AI : エンタープライズ機能を備えた本番環境の デプロイには Google クラウド認証情報を使用します

前提条件

次のいずれかの認証方法を選択します。

オプション 1: Gemini 開発者 API (API キー)

  • Google AI Studio (英語) から API キーを取得する

  • API キーを環境変数またはアプリケーションのプロパティとして設定します

オプション 2: Vertex AI (Google クラウド)

  • Install the gcloud CLI, appropriate for your OS.

  • 次のコマンドを実行して認証します。PROJECT_ID を Google Cloud プロジェクト ID に置き換え、ACCOUNT を Google Cloud ユーザー名に置き換えます。

gcloud config set project <PROJECT_ID> &&
gcloud auth application-default login <ACCOUNT>

リポジトリと BOM の追加

Spring AI アーティファクトは、Maven Central リポジトリと Spring スナップショットリポジトリに公開されています。これらのリポジトリをビルドシステムに追加するには、アーティファクトリポジトリセクションを参照してください。

依存関係の管理を支援するために、Spring AI は BOM (部品表) を提供し、一貫したバージョンの Spring AI がプロジェクト全体で使用されるようにします。Spring AI BOM をビルドシステムに追加するには、"依存関係管理" セクションを参照してください。

自動構成

Spring AI 自動構成、スターターモジュールのアーティファクト名に大きな変更がありました。詳細については、アップグレードノートを参照してください。

Spring AI は、Google GenAI 埋め込みモデル用の Spring Boot 自動構成を提供します。これを有効にするには、プロジェクトの Maven pom.xml ファイルに次の依存関係を追加します。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-google-genai-embedding</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに保存します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-google-genai-embedding'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

埋め込みプロパティ

接続プロパティ

The prefix spring.ai.google.genai.embedding is used as the property prefix that lets you connect to Google GenAI Embedding API.

The connection properties are shared with the Google GenAI Chat module. If you’re using both chat and embeddings, you only need to configure the connection once using either spring.ai.google.genai prefix (for chat) or spring.ai.google.genai.embedding prefix (for embeddings).

プロパティ 説明 デフォルト

spring.ai.google.genai.embedding.api-key

API key for Gemini Developer API. When provided, the client uses the Gemini Developer API instead of Vertex AI.

-

spring.ai.google.genai.embedding.project-id

Google クラウドプラットフォームプロジェクト ID (required for Vertex AI mode)

-

spring.ai.google.genai.embedding.location

Google Cloud region (required for Vertex AI mode)

-

spring.ai.google.genai.embedding.credentials-uri

URI to Google Cloud credentials. When provided it is used to create a GoogleCredentials instance for authentication.

-

埋め込み自動構成の有効化と無効化は、プレフィックス spring.ai.model.embedding を持つ最上位プロパティを介して構成されるようになりました。

To enable, spring.ai.model.embedding.text=google-genai (デフォルトで有効になっています)

無効にするには、spring.ai.model.embedding.text=none (or any value which doesn’t match google-genai)

この変更は、複数のモデルの構成を可能にするために行われます。

Text Embedding Properties

The prefix spring.ai.google.genai.embedding.text is the property prefix that lets you configure the embedding model implementation for Google GenAI Text Embedding.

プロパティ 説明 デフォルト

spring.ai.model.embedding.text

Enable Google GenAI Embedding API model.

google-genai

spring.ai.google.genai.embedding.text.options.model

The Google GenAI Text Embedding model (英語) to use. Supported models include text-embedding-004 and text-multilingual-embedding-002

text-embedding-004

spring.ai.google.genai.embedding.text.options.task-type

The intended downstream application to help the model produce better quality embeddings. Available task-types (英語) RETRIEVAL_QUERYRETRIEVAL_DOCUMENTSEMANTIC_SIMILARITYCLASSIFICATIONCLUSTERINGQUESTION_ANSWERINGFACT_VERIFICATION

RETRIEVAL_DOCUMENT

spring.ai.google.genai.embedding.text.options.title

オプションのタイトル。task_type=RETRIEVAL_DOCUMENT の場合にのみ有効です。

-

spring.ai.google.genai.embedding.text.options.dimensions

結果として得られる出力埋め込みの次元数。モデルバージョン 004 以降でサポートされます。このパラメーターを使用すると、たとえばストレージの最適化のために埋め込みサイズを縮小できます。

-

spring.ai.google.genai.embedding.text.options.auto-truncate

true に設定すると、入力テキストは切り捨てられます。false に設定すると、入力テキストがモデルでサポートされている最大長よりも長い場合にエラーが返されます。

true

サンプルコントローラー

新しい Spring Boot プロジェクトを作成し、spring-ai-starter-model-google-genai-embedding を pom (または gradle) の依存関係に追加します。

Add a application.properties file, under the src/main/resources directory, to enable and configure the Google GenAI embedding model:

Using Gemini Developer API (API キー)

spring.ai.google.genai.embedding.api-key=YOUR_API_KEY
spring.ai.google.genai.embedding.text.options.model=text-embedding-004

Vertex AI の使用

spring.ai.google.genai.embedding.project-id=YOUR_PROJECT_ID
spring.ai.google.genai.embedding.location=YOUR_PROJECT_LOCATION
spring.ai.google.genai.embedding.text.options.model=text-embedding-004

これにより、クラスに挿入できる GoogleGenAiTextEmbeddingModel 実装が作成されます。以下は、埋め込み生成に埋め込みモデルを使用する単純な @Controller クラスの例です。

@RestController
public class EmbeddingController {

    private final EmbeddingModel embeddingModel;

    @Autowired
    public EmbeddingController(EmbeddingModel embeddingModel) {
        this.embeddingModel = embeddingModel;
    }

    @GetMapping("/ai/embedding")
    public Map embed(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        EmbeddingResponse embeddingResponse = this.embeddingModel.embedForResponse(List.of(message));
        return Map.of("embedding", embeddingResponse);
    }
}

手動構成

GoogleGenAiTextEmbeddingModel [GitHub] (英語) は EmbeddingModel を実装します。

spring-ai-google-genai-embedding 依存関係をプロジェクトの Maven pom.xml ファイルに追加します。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-google-genai-embedding</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに保存します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-google-genai-embedding'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

Next, create a GoogleGenAiTextEmbeddingModel and use it for text embeddings:

Using API Key

GoogleGenAiEmbeddingConnectionDetails connectionDetails =
    GoogleGenAiEmbeddingConnectionDetails.builder()
        .apiKey(System.getenv("GOOGLE_API_KEY"))
        .build();

GoogleGenAiTextEmbeddingOptions options = GoogleGenAiTextEmbeddingOptions.builder()
    .model(GoogleGenAiTextEmbeddingOptions.DEFAULT_MODEL_NAME)
    .taskType(TaskType.RETRIEVAL_DOCUMENT)
    .build();

var embeddingModel = new GoogleGenAiTextEmbeddingModel(connectionDetails, options);

EmbeddingResponse embeddingResponse = embeddingModel
	.embedForResponse(List.of("Hello World", "World is big and salvation is near"));

Vertex AI の使用

GoogleGenAiEmbeddingConnectionDetails connectionDetails =
    GoogleGenAiEmbeddingConnectionDetails.builder()
        .projectId(System.getenv("GOOGLE_CLOUD_PROJECT"))
        .location(System.getenv("GOOGLE_CLOUD_LOCATION"))
        .build();

GoogleGenAiTextEmbeddingOptions options = GoogleGenAiTextEmbeddingOptions.builder()
    .model(GoogleGenAiTextEmbeddingOptions.DEFAULT_MODEL_NAME)
    .taskType(TaskType.RETRIEVAL_DOCUMENT)
    .build();

var embeddingModel = new GoogleGenAiTextEmbeddingModel(connectionDetails, options);

EmbeddingResponse embeddingResponse = embeddingModel
	.embedForResponse(List.of("Hello World", "World is big and salvation is near"));

Task Types

The Google GenAI embeddings API supports different task types to optimize embeddings for specific use cases:

  • RETRIEVAL_QUERY: Optimized for search queries in retrieval systems

  • RETRIEVAL_DOCUMENT: Optimized for documents in retrieval systems

  • SEMANTIC_SIMILARITY: Optimized for measuring semantic similarity between texts

  • CLASSIFICATION: Optimized for text classification tasks

  • CLUSTERING: Optimized for clustering similar texts

  • QUESTION_ANSWERING: Optimized for question-answering systems

  • FACT_VERIFICATION: Optimized for fact verification tasks

Example of using different task types:

// For indexing documents
GoogleGenAiTextEmbeddingOptions docOptions = GoogleGenAiTextEmbeddingOptions.builder()
    .model("text-embedding-004")
    .taskType(TaskType.RETRIEVAL_DOCUMENT)
    .title("Product Documentation")  // Optional title for documents
    .build();

// For search queries
GoogleGenAiTextEmbeddingOptions queryOptions = GoogleGenAiTextEmbeddingOptions.builder()
    .model("text-embedding-004")
    .taskType(TaskType.RETRIEVAL_QUERY)
    .build();

Dimension Reduction

For model version 004 and later, you can reduce the embedding dimensions for storage optimization:

GoogleGenAiTextEmbeddingOptions options = GoogleGenAiTextEmbeddingOptions.builder()
    .model("text-embedding-004")
    .dimensions(256)  // Reduce from default 768 to 256 dimensions
    .build();

Migration from Vertex AI Text Embeddings

If you’re currently using the Vertex AI Text Embeddings implementation (spring-ai-vertex-ai-embedding), you can migrate to Google GenAI with minimal changes:

Key Differences

  1. SDK : Google GenAI uses the new com.google.genai.Client instead of Vertex AI SDK

  2. 認証 : Supports both API key and Google Cloud credentials

  3. パッケージ名 : Classes are in org.springframework.ai.google.genai.text instead of org.springframework.ai.vertexai.embedding

  4. プロパティ接頭辞 spring.ai.vertex.ai.embedding の代わりに spring.ai.google.genai.embedding を使用する

  5. 接続詳細 VertexAiEmbeddingConnectionDetails の代わりに GoogleGenAiEmbeddingConnectionDetails を使用する

When to Use Google GenAI vs Vertex AI Text Embeddings

Use Google GenAI Embeddings when : - You want quick prototyping with API keys - You need the latest embedding features from the Developer API - You want flexibility to switch between API key and Vertex AI modes - You’re already using Google GenAI for chat

Use Vertex AI Text Embeddings when : - You have existing Vertex AI infrastructure - You need multimodal embeddings (currently only available in Vertex AI) - Your organization requires Google Cloud-only deployment