OpenAI SDK 埋め込み (正式)

Spring AI は、OpenAI Java SDK を通じて OpenAI のテキスト埋め込みモデルをサポートし、Microsoft Foundry や GitHub モデルなどの OpenAI のサービスとの堅牢かつ公式にメンテナンスされた統合を提供します。

この実装は OpenAI の公式 OpenAI Java SDK [GitHub] (英語) を使用しています。Spring の代替 AI 実装については、OpenAI 埋め込みを参照してください。

OpenAI のテキスト埋め込みは、テキスト文字列の関連性を測定します。埋め込みは浮動小数点数のベクトル(リスト)です。2 つのベクトル間の距離は、それらの関連性を測定します。距離が小さいほど関連性が高く、距離が大きいほど関連性が低いことを示します。

The OpenAI SDK module automatically detects the service provider (OpenAI, Microsoft Foundry, or GitHub Models) based on the base URL you provide.

認証

Authentication is done using a base URL and an API Key. The implementation provides flexible configuration options through Spring Boot properties or environment variables.

OpenAI の使用

If you are using OpenAI directly, create an account at OpenAI サインアップページ (英語) and generate an API key on the API キーページ (英語)

The base URL doesn’t need to be set as it defaults to api.openai.com/v1 (英語) :

spring.ai.openai-sdk.api-key=<your-openai-api-key>
# base-url is optional, defaults to https://api.openai.com/v1

Or using environment variables:

export OPENAI_API_KEY=<your-openai-api-key>
# OPENAI_BASE_URL is optional, defaults to https://api.openai.com/v1

Using Microsoft Foundry

Microsoft Foundry is automatically detected when using a Microsoft Foundry URL. You can configure it using properties:

spring.ai.openai-sdk.base-url=https://<your-deployment-url>.openai.azure.com
spring.ai.openai-sdk.api-key=<your-api-key>
spring.ai.openai-sdk.microsoft-deployment-name=<your-deployment-name>

Or using environment variables:

export OPENAI_BASE_URL=https://<your-deployment-url>.openai.azure.com
export OPENAI_API_KEY=<your-api-key>

Passwordless Authentication (Recommended for Azure):

Microsoft Foundry supports passwordless authentication without providing an API key, which is more secure when running on Azure.

To enable passwordless authentication, add the com.azure:azure-identity dependency:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
</dependency>

Then configure without an API key:

spring.ai.openai-sdk.base-url=https://<your-deployment-url>.openai.azure.com
spring.ai.openai-sdk.microsoft-deployment-name=<your-deployment-name>
# No api-key needed - will use Azure credentials from environment

Using GitHub Models

GitHub Models is automatically detected when using the GitHub Models base URL. You’ll need to create a GitHub Personal Access Token (PAT) with the models:read scope.

spring.ai.openai-sdk.base-url=https://models.inference.ai.azure.com
spring.ai.openai-sdk.api-key=github_pat_XXXXXXXXXXX

Or using environment variables:

export OPENAI_BASE_URL=https://models.inference.ai.azure.com
export OPENAI_API_KEY=github_pat_XXXXXXXXXXX
For enhanced security when handling sensitive information like API keys, you can use Spring Expression Language (SpEL) in your properties:
spring.ai.openai-sdk.api-key=${OPENAI_API_KEY}

リポジトリと BOM の追加

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

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

自動構成

Spring AI provides Spring Boot auto-configuration for the OpenAI SDK Embedding Model. To enable it add the following dependency to your project’s Maven pom.xml or Gradle build.gradle build files:

  • Maven

  • Gradle

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

プロパティの構成

接続プロパティ

The prefix spring.ai.openai-sdk is used as the property prefix that lets you configure the OpenAI SDK client.

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

spring.ai.openai-sdk.base-url

The URL to connect to. Auto-detects from OPENAI_BASE_URL environment variable if not set.

api.openai.com/v1 (英語)

spring.ai.openai-sdk.api-key

The API Key. Auto-detects from OPENAI_API_KEY environment variable if not set.

-

spring.ai.openai-sdk.organization-id

Optionally specify which organization to use for API requests.

-

spring.ai.openai-sdk.timeout

Request timeout duration.

-

spring.ai.openai-sdk.max-retries

Maximum number of retry attempts for failed requests.

-

spring.ai.openai-sdk.proxy

Proxy settings for OpenAI client (Java Proxy object).

-

spring.ai.openai-sdk.custom-headers

Custom HTTP headers to include in requests. Map of header name to header value.

-

Microsoft Foundry Properties

The OpenAI SDK implementation provides native support for Microsoft Foundry with automatic configuration:

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

spring.ai.openai-sdk.microsoft-foundry

Enable Microsoft Foundry mode. Auto-detected if base URL contains openai.azure.comcognitiveservices.azure.com, or .openai.microsoftFoundry.com.

false

spring.ai.openai-sdk.microsoft-deployment-name

Microsoft Foundry deployment name. If not specified, the model name will be used. Also accessible via alias deployment-name.

-

spring.ai.openai-sdk.microsoft-foundry-service-version

Microsoft Foundry API service version.

-

spring.ai.openai-sdk.credential

Credential object for passwordless authentication (requires com.azure:azure-identity dependency).

-

Microsoft Foundry supports passwordless authentication. Add the com.azure:azure-identity dependency and the implementation will automatically attempt to use Azure credentials from the environment when no API key is provided.

GitHub Models Properties

Native support for GitHub Models is available:

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

spring.ai.openai-sdk.github-models

Enable GitHub Models mode. Auto-detected if base URL contains models.github.ai or models.inference.ai.azure.com.

false

GitHub Models requires a Personal Access Token with the models:read scope. Set it via the OPENAI_API_KEY environment variable or the spring.ai.openai-sdk.api-key property.

Embedding Model Properties

The prefix spring.ai.openai-sdk.embedding is the property prefix for configuring the embedding model implementation:

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

spring.ai.openai-sdk.embedding.metadata-mode

ドキュメントコンテンツ抽出モード。

EMBED

spring.ai.openai-sdk.embedding.options.model

The model to use. You can select between models such as: text-embedding-ada-002text-embedding-3-smalltext-embedding-3-large. See the models (英語) page for more information.

text-embedding-ada-002

spring.ai.openai-sdk.embedding.options.user

エンドユーザーを表す一意の識別子。OpenAI が不正使用を監視および検出できます。

-

spring.ai.openai-sdk.embedding.options.dimensions

結果として得られる出力埋め込みの次元数。text-embedding-3 以降のモデルでのみサポートされます。

-

spring.ai.openai-sdk.embedding.options で始まるすべてのプロパティは、リクエスト固有のランタイムオプションを EmbeddingRequest 呼び出しに追加することによって実行時にオーバーライドできます。

ランタイムオプション

The OpenAiSdkEmbeddingOptions.java [GitHub] (英語) provides the OpenAI configurations, such as the model to use, dimensions, and user identifier.

デフォルトのオプションは、spring.ai.openai-sdk.embedding.options プロパティを使用して構成することもできます。

開始時に、OpenAiSdkEmbeddingModel コンストラクターを使用して、すべての埋め込みリクエストに使用されるデフォルトのオプションを設定します。実行時に、OpenAiSdkEmbeddingOptions インスタンスを EmbeddingRequest の一部として使用して、デフォルトのオプションをオーバーライドできます。

たとえば、特定のリクエストのデフォルトのモデル名をオーバーライドするには、次のようにします。

EmbeddingResponse embeddingResponse = embeddingModel.call(
    new EmbeddingRequest(List.of("Hello World", "World is big and salvation is near"),
        OpenAiSdkEmbeddingOptions.builder()
            .model("text-embedding-3-large")
            .dimensions(1024)
        .build()));
In addition to the model specific OpenAiSdkEmbeddingOptions [GitHub] (英語) you can use a portable EmbeddingOptions [GitHub] (英語) instance, created with the builder.

サンプルコントローラー

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

Add an application.properties file under the src/main/resources directory to configure the OpenAI SDK embedding model:

spring.ai.openai-sdk.api-key=YOUR_API_KEY
spring.ai.openai-sdk.embedding.options.model=text-embedding-ada-002
api-key を OpenAI の資格情報に置き換えます。

This will create an OpenAiSdkEmbeddingModel implementation that you can inject into your classes. Here is an example of a simple @RestController class that uses the embedding model.

@RestController
public class EmbeddingController {

    private final EmbeddingModel embeddingModel;

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

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

手動構成

The OpenAiSdkEmbeddingModel [GitHub] (英語) implements the EmbeddingModel and uses the official OpenAI Java SDK to connect to the OpenAI service.

If you are not using Spring Boot auto-configuration, you can manually configure the OpenAI SDK Embedding Model. For this add the spring-ai-openai-sdk dependency to your project’s Maven pom.xml file:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-sdk</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに次の内容を追加します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai-sdk'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。
The spring-ai-openai-sdk dependency provides access also to the OpenAiSdkChatModel and OpenAiSdkImageModel. For more information about the OpenAiSdkChatModel refer to the OpenAI SDK チャット section.

次に、OpenAiSdkEmbeddingModel インスタンスを作成し、それを使用して 2 つの入力テキスト間の類似性を計算します。

var embeddingOptions = OpenAiSdkEmbeddingOptions.builder()
    .model("text-embedding-ada-002")
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .build();

var embeddingModel = new OpenAiSdkEmbeddingModel(embeddingOptions);

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

OpenAiSdkEmbeddingOptions は、埋め込みリクエストの構成情報を提供します。オプションクラスは、オプションを簡単に作成できる builder() を提供します。

Microsoft Foundry Configuration

For Microsoft Foundry:

var embeddingOptions = OpenAiSdkEmbeddingOptions.builder()
    .baseUrl("https://your-resource.openai.azure.com")
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .deploymentName("text-embedding-ada-002")
    .azureOpenAIServiceVersion(AzureOpenAIServiceVersion.V2024_10_01_PREVIEW)
    .azure(true)  // Enables Microsoft Foundry mode
    .build();

var embeddingModel = new OpenAiSdkEmbeddingModel(embeddingOptions);
Microsoft Foundry supports passwordless authentication. Add the com.azure:azure-identity dependency to your project. If you don’t provide an API key, the implementation will automatically attempt to use Azure credentials from your environment.

GitHub Models Configuration

For GitHub Models:

var embeddingOptions = OpenAiSdkEmbeddingOptions.builder()
    .baseUrl("https://models.inference.ai.azure.com")
    .apiKey(System.getenv("GITHUB_TOKEN"))
    .model("text-embedding-3-large")
    .githubModels(true)
    .build();

var embeddingModel = new OpenAiSdkEmbeddingModel(embeddingOptions);

可観測性

The OpenAI SDK implementation supports Spring AI’s observability features through Micrometer. All embedding model operations are instrumented for monitoring and tracing.