OpenAI SDK チャット (正式)

Spring AI supports OpenAI’s language models through the OpenAI Java SDK, providing a robust and officially-maintained integration with OpenAI’s services including Microsoft Foundry and GitHub Models.

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

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 Chat Client. 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 (Azure OpenAI) Properties

The OpenAI SDK implementation provides native support for Microsoft Foundry (Azure OpenAI) 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.

チャットモデルのプロパティ

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

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

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

使用する OpenAI チャットモデルの名前。gpt-5-minigpt-4ogpt-4o-minigpt-4-turboo1o3-mini などのモデルを選択できます。詳細については、モデル (英語) ページを参照してください。

gpt-5-mini

spring.ai.openai-sdk.chat.options.temperature

生成される補完の明らかな創造性を制御するために使用するサンプリング温度。値が高いほど出力はよりランダムになり、値が低いほど結果はより集中的かつ決定論的になります。これら 2 つの設定の相互作用を予測することは難しいため、同じ補完リクエストに対して temperature と top_p を変更することはお勧めしません。

1.0

spring.ai.openai-sdk.chat.options.frequency-penalty

-2.0 から 2.0 までの数値。正の値を指定すると、これまでのテキスト内の既存の頻度に基づいて新しいトークンにペナルティが課され、モデルが同じ行をそのまま繰り返す可能性が低くなります。

0.0

spring.ai.openai-sdk.chat.options.logit-bias

指定したトークンが補完に表示される可能性を変更します。

-

spring.ai.openai-sdk.chat.options.logprobs

Whether to return log probabilities of the output tokens.

false

spring.ai.openai-sdk.chat.options.top-logprobs

An integer between 0 and 5 specifying the number of most likely tokens to return at each token position. Requires logprobs to be true.

-

spring.ai.openai-sdk.chat.options.max-tokens

The maximum number of tokens to generate. 非推論モデルに使用する (e.g., gpt-4o, gpt-3.5-turbo). 推論モデルでは使用できません (e.g., o1, o3, o4-mini series). maxCompletionTokens とは相互排他的

-

spring.ai.openai-sdk.chat.options.max-completion-tokens

An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens. 推論モデルに必要 (e.g., o1, o3, o4-mini series). 非推論モデルでは使用できません . maxTokens とは相互排他的

-

spring.ai.openai-sdk.chat.options.n

How many chat completion choices to generate for each input message.

1

spring.ai.openai-sdk.chat.options.output-modalities

List of output modalities. Can include "text" and "audio".

-

spring.ai.openai-sdk.chat.options.output-audio

Parameters for audio output. Use AudioParameters with voice (ALLOY, ASH, BALLAD, CORAL, ECHO, FABLE, ONYX, NOVA, SAGE, SHIMMER) and format (MP3, FLAC, OPUS, PCM16, WAV, AAC).

-

spring.ai.openai-sdk.chat.options.presence-penalty

Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far.

0.0

spring.ai.openai-sdk.chat.options.response-format.type

Response format type: TEXTJSON_OBJECT, or JSON_SCHEMA.

TEXT

spring.ai.openai-sdk.chat.options.response-format.json-schema

JSON schema for structured outputs when type is JSON_SCHEMA.

-

spring.ai.openai-sdk.chat.options.seed

If specified, the system will make a best effort to sample deterministically for reproducible results.

-

spring.ai.openai-sdk.chat.options.stop

API がさらなるトークンの生成を停止する最大 4 つのシーケンス。

-

spring.ai.openai-sdk.chat.options.top-p

An alternative to sampling with temperature, called nucleus sampling.

-

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

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

-

spring.ai.openai-sdk.chat.options.parallel-tool-calls

Whether to enable parallel function calling during tool use.

true

spring.ai.openai-sdk.chat.options.reasoning-effort

Constrains effort on reasoning for reasoning models: lowmedium, or high.

-

spring.ai.openai-sdk.chat.options.verbosity

Controls the verbosity of the model’s response.

-

spring.ai.openai-sdk.chat.options.store

Whether to store the output of this chat completion request for use in OpenAI’s model distillation or evals products.

false

spring.ai.openai-sdk.chat.options.metadata

Developer-defined tags and values used for filtering completions in the dashboard.

-

spring.ai.openai-sdk.chat.options.service-tier

Specifies the latency tier to use: autodefaultflex, or priority.

-

spring.ai.openai-sdk.chat.options.stream-options.include-usage

Whether to include usage statistics in streaming responses.

false

spring.ai.openai-sdk.chat.options.stream-options.include-obfuscation

Whether to include obfuscation in streaming responses.

false

spring.ai.openai-sdk.chat.options.tool-choice

モデルによって呼び出される関数(ある場合)を制御します。

-

spring.ai.openai-sdk.chat.options.internal-tool-execution-enabled

If false, Spring AI will proxy tool calls to the client for manual handling. If true (default), Spring AI handles function calls internally.

true

gpt-5gpt-5-minigpt-5-nano などの GPT-5 モデルを使用する場合、temperature パラメーターはサポートされません。これらのモデルは推論に最適化されており、温度は使用しません。温度値を指定するとエラーが発生します。一方、gpt-5-chat などの会話型モデルは temperature パラメーターをサポートしています。

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

トークン制限パラメーター: モデル固有の使用箇所

OpenAI は、トークン生成制限を制御するための相互に排他的な 2 つのパラメーターを提供します。

パラメーター ユースケース 対応モデル

maxTokens

非推論モデル

gpt-4o、gpt-4o-mini、gpt-4-turbo、gpt-3.5-turbo

maxCompletionTokens

推論モデル

o1、o1-mini、o1-preview、o3、o4-mini シリーズ

これらのパラメーターは相互に排他的です。両方を設定すると、OpenAI から API エラーが発生します。

使用例

非推論モデル(gpt-4o、gpt-3.5-turbo)の場合:

ChatResponse response = chatModel.call(
    new Prompt(
        "Explain quantum computing in simple terms.",
        OpenAiSdkChatOptions.builder()
            .model("gpt-4o")
            .maxTokens(150)  // Use maxTokens for non-reasoning models
        .build()
    ));

推論モデル(o1、o3 シリーズ)の場合:

ChatResponse response = chatModel.call(
    new Prompt(
        "Solve this complex math problem step by step: ...",
        OpenAiSdkChatOptions.builder()
            .model("o1-preview")
            .maxCompletionTokens(1000)  // Use maxCompletionTokens for reasoning models
        .build()
    ));

ランタイムオプション

OpenAiSdkChatOptions.java [GitHub] (英語) クラスは、使用するモデル、温度、周波数ペナルティなどのモデル構成を提供します。

起動時に、OpenAiSdkChatModel(options) コンストラクターまたは spring.ai.openai-sdk.chat.options.* プロパティを使用してデフォルトのオプションを構成できます。

実行時に、Prompt 呼び出しに新しいリクエスト固有のオプションを追加することで、デフォルトのオプションをオーバーライドできます。例: 特定のリクエストのデフォルトのモデルと温度をオーバーライドするには、次のようにします。

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        OpenAiSdkChatOptions.builder()
            .model("gpt-4o")
            .temperature(0.4)
        .build()
    ));
モデル固有の OpenAiSdkChatOptions [GitHub] (英語) に加えて、ChatOptions#builder() [GitHub] (英語) で作成されたポータブル ChatOptions [GitHub] (英語) インスタンスを使用することもできます。

ツール呼び出し

You can register custom Java functions or methods with the OpenAiSdkChatModel and have the OpenAI model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions/tools. This is a powerful technique to connect the LLM capabilities with external tools and API. Read more about ツール呼び出し

使用例:

var chatOptions = OpenAiSdkChatOptions.builder()
    .toolCallbacks(List.of(
        FunctionToolCallback.builder("getCurrentWeather", new WeatherService())
            .description("Get the weather in location")
            .inputType(WeatherService.Request.class)
            .build()))
    .build();

ChatResponse response = chatModel.call(
    new Prompt("What's the weather like in San Francisco?", chatOptions));

マルチモーダル

マルチモーダル性とは、テキスト、イメージ、音声、その他のデータ形式を含むさまざまなソースからの情報を同時に理解して処理するモデルの機能を指します。

Vision

ビジョンマルチモーダルサポートを提供する OpenAI モデルには、gpt-4gpt-4ogpt-4o-mini が含まれます。詳細については、Vision (英語) ガイドを参照してください。

Spring AI’s メッセージ [GitHub] (英語) interface facilitates multimodal AI models by introducing the メディア [GitHub] (英語) type.

Below is a code example illustrating the fusion of user text with an image:

var imageResource = new ClassPathResource("/multimodal.test.png");

var userMessage = new UserMessage(
    "Explain what do you see on this picture?",
    List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageResource)));

ChatResponse response = chatModel.call(
    new Prompt(userMessage,
        OpenAiSdkChatOptions.builder()
            .model("gpt-4o")
            .build()));

Or using an image URL:

var userMessage = new UserMessage(
    "Explain what do you see on this picture?",
    List.of(Media.builder()
        .mimeType(MimeTypeUtils.IMAGE_PNG)
        .data(URI.create("https://docs.spring.io/spring-ai/reference/_images/multimodal.test.png"))
        .build()));

ChatResponse response = chatModel.call(new Prompt(userMessage));
複数のイメージを渡すこともできます。

音声

OpenAI models that offer audio input support include gpt-4o-audio-preview. Refer to the 音声 (英語) guide for more information.

Spring AI supports base64-encoded audio files with the message. Currently, OpenAI supports the following media types: audio/mp3 and audio/wav.

Example of audio input:

var audioResource = new ClassPathResource("speech1.mp3");

var userMessage = new UserMessage(
    "What is this recording about?",
    List.of(new Media(MimeTypeUtils.parseMimeType("audio/mp3"), audioResource)));

ChatResponse response = chatModel.call(
    new Prompt(userMessage,
        OpenAiSdkChatOptions.builder()
            .model("gpt-4o-audio-preview")
            .build()));

オーディオ出力

The gpt-4o-audio-preview model can generate audio responses.

Example of generating audio output:

var userMessage = new UserMessage("Tell me a joke about Spring Framework");

ChatResponse response = chatModel.call(
    new Prompt(userMessage,
        OpenAiSdkChatOptions.builder()
            .model("gpt-4o-audio-preview")
            .outputModalities(List.of("text", "audio"))
            .outputAudio(new AudioParameters(Voice.ALLOY, AudioResponseFormat.WAV))
            .build()));

String text = response.getResult().getOutput().getContent(); // audio transcript
byte[] waveAudio = response.getResult().getOutput().getMedia().get(0).getDataAsByteArray(); // audio data

構造化された出力

OpenAI provides custom 構造化された出力 (英語) API that ensure your model generates responses conforming strictly to your provided JSON Schema.

構成

You can set the response format programmatically with the OpenAiSdkChatOptions builder:

String jsonSchema = """
    {
        "type": "object",
        "properties": {
            "steps": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "explanation": { "type": "string" },
                        "output": { "type": "string" }
                    },
                    "required": ["explanation", "output"],
                    "additionalProperties": false
                }
            },
            "final_answer": { "type": "string" }
        },
        "required": ["steps", "final_answer"],
        "additionalProperties": false
    }
    """;

Prompt prompt = new Prompt(
    "how can I solve 8x + 7 = -23",
    OpenAiSdkChatOptions.builder()
        .model("gpt-4o-mini")
        .responseFormat(ResponseFormat.builder()
            .type(ResponseFormat.Type.JSON_SCHEMA)
            .jsonSchema(jsonSchema)
            .build())
        .build());

ChatResponse response = chatModel.call(prompt);

Integrating with BeanOutputConverter

You can leverage existing BeanOutputConverter utilities:

record MathReasoning(
    @JsonProperty(required = true, value = "steps") Steps steps,
    @JsonProperty(required = true, value = "final_answer") String finalAnswer) {

    record Steps(
        @JsonProperty(required = true, value = "items") Items[] items) {

        record Items(
            @JsonProperty(required = true, value = "explanation") String explanation,
            @JsonProperty(required = true, value = "output") String output) {
        }
    }
}

var outputConverter = new BeanOutputConverter<>(MathReasoning.class);
String jsonSchema = outputConverter.getJsonSchema();

Prompt prompt = new Prompt(
    "how can I solve 8x + 7 = -23",
    OpenAiSdkChatOptions.builder()
        .model("gpt-4o-mini")
        .responseFormat(ResponseFormat.builder()
            .type(ResponseFormat.Type.JSON_SCHEMA)
            .jsonSchema(jsonSchema)
            .build())
        .build());

ChatResponse response = chatModel.call(prompt);
MathReasoning mathReasoning = outputConverter.convert(
    response.getResult().getOutput().getContent());

サンプルコントローラー

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

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

spring.ai.openai-sdk.api-key=YOUR_API_KEY
spring.ai.openai-sdk.chat.options.model=gpt-5-mini
spring.ai.openai-sdk.chat.options.temperature=0.7
api-key を OpenAI の資格情報に置き換えます。

これにより、クラスに挿入できる OpenAiSdkChatModel 実装が作成されます。以下は、テキスト生成にチャットモデルを使用する単純な @RestController クラスの例です。

@RestController
public class ChatController {

    private final OpenAiSdkChatModel chatModel;

    @Autowired
    public ChatController(OpenAiSdkChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Map<String,String> generate(
            @RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
    public Flux<ChatResponse> generateStream(
            @RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return chatModel.stream(prompt);
    }
}

手動構成

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

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

<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 をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

次に、OpenAiSdkChatModel を作成し、テキスト生成に使用します。

var chatOptions = OpenAiSdkChatOptions.builder()
    .model("gpt-4o")
    .temperature(0.7)
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .build();

var chatModel = new OpenAiSdkChatModel(chatOptions);

ChatResponse response = chatModel.call(
    new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> response = chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

Microsoft Foundry Configuration

For Microsoft Foundry :

var chatOptions = OpenAiSdkChatOptions.builder()
    .baseUrl("https://your-resource.openai.azure.com")
    .apiKey(System.getenv("OPENAI_API_KEY"))
    .deploymentName("gpt-4")
    .azureOpenAIServiceVersion(AzureOpenAIServiceVersion.V2024_10_01_PREVIEW)
    .azure(true)  // Enables Microsoft Foundry mode
    .build();

var chatModel = new OpenAiSdkChatModel(chatOptions);
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 chatOptions = OpenAiSdkChatOptions.builder()
    .baseUrl("https://models.inference.ai.azure.com")
    .apiKey(System.getenv("GITHUB_TOKEN"))
    .model("gpt-4o")
    .githubModels(true)
    .build();

var chatModel = new OpenAiSdkChatModel(chatOptions);

Key Differences from Spring AI OpenAI

This implementation differs from the Spring AI OpenAI implementation in several ways:

アスペクト Official OpenAI SDKExisting OpenAI

HTTP クライアント

OkHttp (via official SDK)

Spring RestClient/WebClient

API Updates

Automatic via SDK updates

Manual maintenance

Azure サポート

Native with passwordless auth

Manual URL construction

GitHub モデル

ネイティブサポート

未サポート

Audio/Moderation

Not yet supported

Fully supported

Retry Logic

SDK-managed (exponential backoff)

Spring Retry (customizable)

依存関係

Official OpenAI SDK

Spring WebFlux

When to use OpenAI SDK:

  • You’re starting a new project

  • You primarily use Microsoft Foundry or GitHub Models

  • You want automatic API updates from OpenAI

  • You don’t need audio transcription or moderation features

  • You prefer official SDK support

When to use Spring AI OpenAI:

  • You have an existing project using it

  • You need audio transcription or moderation features

  • You require fine-grained HTTP control

  • You want native Spring reactive support

  • You need custom retry strategies

可観測性

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

制限

The following features are not yet supported in the OpenAI SDK implementation:

  • Audio speech generation (TTS)

  • Audio transcription

  • Moderation API

  • File API operations

These features are available in the Spring AI OpenAI implementation.