跳到主要内容

OpenAI

备注

これは OpenAI 連携のドキュメントです。OpenAI REST API のカスタム Java 実装を使い、Quarkus(Quarkus REST クライアント)および Spring(Spring の RestClient)で最もよく動作します。

Quarkus を使っている場合は、 Quarkus LangChain4j ドキュメント を参照してください。

LangChain4j はチャットモデル用に 3 種類の OpenAI 連携を提供しており、本ドキュメントは #1 です:

  • OpenAI は OpenAI REST API のカスタム Java 実装を使い、Quarkus(Quarkus REST クライアント)と Spring(Spring RestClient)で最もよく動作します。
  • OpenAI Official SDK は公式 OpenAI Java SDK を使います。
  • Azure OpenAI は Microsoft の Azure SDK を使い、高度な Azure 認証を含む Microsoft Java スタックを使う場合に最適です。

OpenAI ドキュメント​

Maven依存関係​

Plain Java​

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai</artifactId>
<version>1.23.0</version>
</dependency>

Spring Boot​

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-spring-boot4-starter</artifactId>
<version>1.23.0-beta33</version>
</dependency>
备注

この starter には Spring Boot 4 が必要です。Spring Boot 3 では、代わりに langchain4j-open-ai-spring-boot-starter を使用してください。 詳細は Spring Boot 統合を参照してください。

API キー​

OpenAI モデルを使うには API キーが必要です。 こちら で作成できます。

OpenAiChatModel の作成​

Plain Java​

ChatModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.build();


// You can also specify default chat request parameters using ChatRequestParameters or OpenAiChatRequestParameters
ChatModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.defaultRequestParameters(OpenAiChatRequestParameters.builder()
.modelName("gpt-4o-mini")
.build())
.build();

指定したデフォルトパラメータで OpenAiChatModel のインスタンスが作成されます。

Spring Boot​

application.properties に追加:

# Mandatory properties:
langchain4j.open-ai.chat-model.api-key=${OPENAI_API_KEY}
langchain4j.open-ai.chat-model.model-name=gpt-4o-mini

# Optional properties:
langchain4j.open-ai.chat-model.base-url=...
langchain4j.open-ai.chat-model.custom-headers=...
langchain4j.open-ai.chat-model.frequency-penalty=...
langchain4j.open-ai.chat-model.log-requests=...
langchain4j.open-ai.chat-model.log-responses=...
langchain4j.open-ai.chat-model.logit-bias=...
langchain4j.open-ai.chat-model.max-retries=...
langchain4j.open-ai.chat-model.max-completion-tokens=...
langchain4j.open-ai.chat-model.max-tokens=...
langchain4j.open-ai.chat-model.metadata=...
langchain4j.open-ai.chat-model.organization-id=...
langchain4j.open-ai.chat-model.parallel-tool-calls=...
langchain4j.open-ai.chat-model.presence-penalty=...
langchain4j.open-ai.chat-model.project-id=...
langchain4j.open-ai.chat-model.reasoning-effort=...
langchain4j.open-ai.chat-model.response-format=...
langchain4j.open-ai.chat-model.return-thinking=...
langchain4j.open-ai.chat-model.seed=...
langchain4j.open-ai.chat-model.service-tier=...
langchain4j.open-ai.chat-model.stop=...
langchain4j.open-ai.chat-model.store=...
langchain4j.open-ai.chat-model.strict-schema=...
langchain4j.open-ai.chat-model.strict-tools=...
langchain4j.open-ai.chat-model.supported-capabilities=...
langchain4j.open-ai.chat-model.temperature=...
langchain4j.open-ai.chat-model.timeout=...
langchain4j.open-ai.chat-model.top-p=
langchain4j.open-ai.chat-model.user=...

# Optional Property: Custom Parameters (user-defined key=value)
langchain4j.open-ai.chat-model.custom-parameters.<key>=<value>

上記パラメータの多くは こちら で説明されています。

この設定により OpenAiChatModel bean が作成され、 AI Service で使うか、必要な場所にオートワイヤできます。例:

@RestController
class ChatModelController {

ChatModel chatModel;

ChatModelController(ChatModel chatModel) {
this.chatModel = chatModel;
}

@GetMapping("/model")
public String model(@RequestParam(value = "message", defaultValue = "Hello") String message) {
return chatModel.chat(message);
}
}

Structured Outputs​

Structured Outputs 機能は ツール と レスポンス形式 の両方でサポートされます。

Structured Outputs の詳細は こちら。

ツール向け Structured Outputs​

ツール向けに Structured Outputs を有効にするには、モデル構築時に .strictTools(true) を設定します:

OpenAiChatModel.builder()
...
.strictTools(true)
.build(),

これにより、すべてのツールパラメータが自動的に必須(JSON スキーマの required)になり、 JSON スキーマ内の各 object に additionalProperties=false が設定されます。これは現在の OpenAI の制限によるものです。

レスポンス形式向け Structured Outputs​

AI Services 使用時にレスポンス形式向け Structured Outputs を有効にするには、 モデル構築時に .supportedCapabilities(RESPONSE_FORMAT_JSON_SCHEMA) と .strictJsonSchema(true) を設定します:

OpenAiChatModel.builder()
...
.supportedCapabilities(RESPONSE_FORMAT_JSON_SCHEMA)
.strictJsonSchema(true)
.build();

この場合、AI Service は指定された POJO から JSON スキーマを自動生成し、LLM に渡します。

Thinking / Reasoning​

この設定は DeepSeek 向けです。

OpenAiChatModel または OpenAiStreamingChatModel の構築時に returnThinking パラメータを有効にすると、 DeepSeek API レスポンスの reasoning_content フィールドが解析され、 AiMessage.thinking() 内に返されます。

OpenAiStreamingChatModel で returnThinking パラメータを有効にすると、 StreamingChatResponseHandler.onPartialThinking() と TokenStream.onPartialThinking() のコールバックが、DeepSeek API が reasoning_content をストリーミングする際に呼び出されます。

thinking の設定例:

ChatModel model = OpenAiChatModel.builder()
.baseUrl("https://api.deepseek.com/v1")
.apiKey(System.getenv("DEEPSEEK_API_KEY"))
.modelName("deepseek-reasoner")
.returnThinking(true)
.build();

OpenAiChatModel または OpenAiStreamingChatModel の構築時に sendThinking パラメータを有効にすると、 AiMessage.thinking() が DeepSeek API へのリクエストに送られます。 フィールド名は sendThinking(boolean, String) ビルダーメソッドで設定できます。 デフォルトでは reasoning_content フィールド名が使われます。

OpenAiStreamingChatModel の作成​

Plain Java​

StreamingChatModel model = OpenAiStreamingChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.build();

// You can also specify default chat request parameters using ChatRequestParameters or OpenAiChatRequestParameters
StreamingChatModel model = OpenAiStreamingChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.defaultRequestParameters(OpenAiChatRequestParameters.builder()
.modelName("gpt-4o-mini")
.build())
.build();

Spring Boot​

application.properties に追加:

# Mandatory properties:
langchain4j.open-ai.streaming-chat-model.api-key=${OPENAI_API_KEY}
langchain4j.open-ai.streaming-chat-model.model-name=gpt-4o-mini

# Optional properties:
langchain4j.open-ai.streaming-chat-model.base-url=...
langchain4j.open-ai.streaming-chat-model.custom-headers=...
langchain4j.open-ai.streaming-chat-model.frequency-penalty=...
langchain4j.open-ai.streaming-chat-model.log-requests=...
langchain4j.open-ai.streaming-chat-model.log-responses=...
langchain4j.open-ai.streaming-chat-model.logit-bias=...
langchain4j.open-ai.streaming-chat-model.max-retries=...
langchain4j.open-ai.streaming-chat-model.max-completion-tokens=...
langchain4j.open-ai.streaming-chat-model.max-tokens=...
langchain4j.open-ai.streaming-chat-model.metadata=...
langchain4j.open-ai.streaming-chat-model.organization-id=...
langchain4j.open-ai.streaming-chat-model.parallel-tool-calls=...
langchain4j.open-ai.streaming-chat-model.presence-penalty=...
langchain4j.open-ai.streaming-chat-model.project-id=...
langchain4j.open-ai.streaming-chat-model.reasoning-effort=...
langchain4j.open-ai.streaming-chat-model.response-format=...
langchain4j.open-ai.streaming-chat-model.return-thinking=...
langchain4j.open-ai.streaming-chat-model.seed=...
langchain4j.open-ai.streaming-chat-model.service-tier=...
langchain4j.open-ai.streaming-chat-model.stop=...
langchain4j.open-ai.streaming-chat-model.store=...
langchain4j.open-ai.streaming-chat-model.strict-schema=...
langchain4j.open-ai.streaming-chat-model.strict-tools=...
langchain4j.open-ai.streaming-chat-model.temperature=...
langchain4j.open-ai.streaming-chat-model.timeout=...
langchain4j.open-ai.streaming-chat-model.top-p=...
langchain4j.open-ai.streaming-chat-model.user=...

# Optional Property: Custom Parameters (user-defined key=value)
langchain4j.open-ai.streaming-chat-model.custom-parameters.<key>=<value>

OpenAiModerationModel の作成​

Plain Java​

ModerationModel model = OpenAiModerationModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("text-moderation-stable")
.build();

Spring Boot​

application.properties に追加:

# Mandatory properties:
langchain4j.open-ai.moderation-model.api-key=${OPENAI_API_KEY}
langchain4j.open-ai.moderation-model.model-name=text-moderation-stable

# Optional properties:
langchain4j.open-ai.moderation-model.base-url=...
langchain4j.open-ai.moderation-model.custom-headers=...
langchain4j.open-ai.moderation-model.log-requests=...
langchain4j.open-ai.moderation-model.log-responses=...
langchain4j.open-ai.moderation-model.max-retries=...
langchain4j.open-ai.moderation-model.organization-id=...
langchain4j.open-ai.moderation-model.project-id=...
langchain4j.open-ai.moderation-model.timeout=...

OpenAiTextToSpeechModel の作成​

OpenAiTextToSpeechModel は OpenAI Speech API 生成された音声を生バイトとして Audio オブジェクトに包んで返します。

サポートモデルは tts-1、tts-1-hd、gpt-4o-mini-tts、gpt-4o-mini-tts-2025-12-15 (OpenAiTextToSpeechModelName を参照)。デフォルトの声は alloy です。

Plain Java​

import dev.langchain4j.model.audio.TextToSpeechModel;
import dev.langchain4j.model.audio.TextToSpeechRequest;
import dev.langchain4j.model.audio.TextToSpeechResponse;
import dev.langchain4j.model.openai.OpenAiTextToSpeechModel;
import dev.langchain4j.model.openai.OpenAiTextToSpeechModelName;

TextToSpeechModel model = OpenAiTextToSpeechModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName(OpenAiTextToSpeechModelName.TTS_1)
.voice("alloy") // optional, defaults to "alloy"
.build();

// Convenience method (uses the model's default voice):
TextToSpeechResponse response = model.synthesize("Hello world!");

// Or with an explicit request (the voice here overrides the model default):
TextToSpeechRequest request = TextToSpeechRequest.builder()
.text("Hello world!")
.voice("nova")
.build();
TextToSpeechResponse response2 = model.synthesize(request);

byte[] audioBytes = response.audio().binaryData(); // e.g. write to an .mp3 file
String mimeType = response.audio().mimeType(); // e.g. "audio/mpeg"

入力テキストは 4096 文字を超えてはなりません(OpenAI Speech API の制限)。 長い入力は IllegalArgumentException になります。

OpenAiTextToSpeechModel の作成​

OpenAiTextToSpeechModel は OpenAI Speech API 生成された音声を生バイトとして Audio オブジェクトに包んで返します。

サポートモデルは tts-1、tts-1-hd、gpt-4o-mini-tts、gpt-4o-mini-tts-2025-12-15 (OpenAiTextToSpeechModelName を参照)。デフォルトの声は alloy です。

Plain Java​

import dev.langchain4j.model.audio.TextToSpeechModel;
import dev.langchain4j.model.audio.TextToSpeechRequest;
import dev.langchain4j.model.audio.TextToSpeechResponse;
import dev.langchain4j.model.openai.OpenAiTextToSpeechModel;
import dev.langchain4j.model.openai.OpenAiTextToSpeechModelName;

TextToSpeechModel model = OpenAiTextToSpeechModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName(OpenAiTextToSpeechModelName.TTS_1)
.voice("alloy") // optional, defaults to "alloy"
.build();

// Convenience method (uses the model's default voice):
TextToSpeechResponse response = model.synthesize("Hello world!");

// Or with an explicit request (the voice here overrides the model default):
TextToSpeechRequest request = TextToSpeechRequest.builder()
.text("Hello world!")
.voice("nova")
.build();
TextToSpeechResponse response2 = model.synthesize(request);

byte[] audioBytes = response.audio().binaryData(); // e.g. write to an .mp3 file
String mimeType = response.audio().mimeType(); // e.g. "audio/mpeg"

入力テキストは 4096 文字を超えてはなりません(OpenAI Speech API の制限)。 長い入力は IllegalArgumentException になります。

OpenAiTokenCountEstimator の作成​

TokenCountEstimator tokenCountEstimator = new OpenAiTokenCountEstimator("gpt-4o-mini");

カスタムチャットリクエストパラメータの設定​

OpenAiChatModel と OpenAiStreamingChatModel を使うとき、 HTTP リクエストの JSON ボディ内のチャットリクエストにカスタムパラメータを設定できます。 ウェブ検索を有効にする例:

record ApproximateLocation(String city) {}
record UserLocation(String type, ApproximateLocation approximate) {}
record WebSearchOptions(UserLocation user_location) {}
WebSearchOptions webSearchOptions = new WebSearchOptions(new UserLocation("approximate", new ApproximateLocation("London")));
Map<String, Object> customParameters = Map.of("web_search_options", webSearchOptions);

ChatRequest chatRequest = ChatRequest.builder()
.messages(UserMessage.from("Where can I buy good coffee?"))
.parameters(OpenAiChatRequestParameters.builder()
.modelName("gpt-4o-mini-search-preview")
.customParameters(customParameters)
.build())
.build();

ChatModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.logRequests(true)
.build();

ChatResponse chatResponse = model.chat(chatRequest);

次のボディを持つ HTTP リクエストが生成されます:

{
"model" : "gpt-4o-mini-search-preview",
"messages" : [ {
"role" : "user",
"content" : "Where can I buy good coffee?"
} ],
"web_search_options" : {
"user_location" : {
"type" : "approximate",
"approximate" : {
"city" : "London"
}
}
}
}

あるいは、カスタムパラメータをネストした map 構造としても指定できます:

Map<String, Object> customParameters = Map.of(
"web_search_options", Map.of(
"user_location", Map.of(
"type", "approximate",
"approximate", Map.of("city", "London")
)
)
);

プロンプトキャッシュ(Prompt Caching)​

OpenAI は、長く繰り返されるプロンプトのプレフィックスをキャッシュし、キャッシュの読み取りを入力料金のごく一部で課金します。 以下の制御は、OpenAiChatModel/OpenAiStreamingChatModel(Chat Completions API)と OpenAiResponsesChatModel/OpenAiResponsesStreamingChatModel(Responses API)の両方で機能します。

プロンプトキャッシュの詳細はこちらを参照してください。

promptCacheKey​

promptCacheKey は任意の文字列で、ルーティングを誘導し、関連するリクエストがキャッシュエントリを保持するマシンに到達する可能性を高めます。リクエストを特定のマシンに固定するものではなく、キャッシュヒットを保証するものでもありません。

OpenAiChatModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5.6")
.promptCacheKey("satisfaction_judge_v1")
.build();

promptCacheOptions​

gpt-5.6 以降は、ブレークポイントでキャッシュされたプレフィックスを完全一致で照合し、より短いマークされていないプレフィックスにはフォールバックしません。promptCacheOptions は、ブレークポイントの発生元を制御します:

  • implicit - OpenAI が、最新の対象メッセージの末尾にブレークポイントを置きます。
  • explicit - 設定したブレークポイントのみが使用されます。ブレークポイントがない場合、何もキャッシュされません。
OpenAiChatModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5.6")
.promptCacheOptions(OpenAiPromptCacheOptions.builder()
.mode(OpenAiPromptCacheOptions.MODE_EXPLICIT)
.ttl(OpenAiPromptCacheOptions.TTL_30M)
.build())
.build();

OpenAiPromptCacheOptions.implicit() と OpenAiPromptCacheOptions.explicit() は、モードのみを設定するオプションの省略形です。

promptCacheOptions.ttl は promptCacheRetention(gpt-5.6 より古いモデルに適用)より優先されます。 OpenAI は、両方を含むリクエストを拒否します。

promptCacheBreakpoint​

SystemMessage、UserMessage、ToolExecutionResultMessage はそれぞれ、プロンプトキャッシュのブレークポイントとしてマークできます。プロンプトキャッシュはプレフィックスベースであるため、ブレークポイントはマークされたメッセージの最後のコンテンツブロックに適用され、そのメッセージまでのすべてがキャッシュされるプレフィックスになります。

OpenAiPromptCacheBreakpoint.mark() は、元のメッセージには手を加えず、マークされたコピーを返します:

SystemMessage systemMessage = OpenAiPromptCacheBreakpoint.mark(SystemMessage.from(SHARED_INSTRUCTIONS));

UserMessage userMessage = OpenAiPromptCacheBreakpoint.mark(UserMessage.from(LONG_DOCUMENT));

ToolExecutionResultMessage toolResult = OpenAiPromptCacheBreakpoint.mark(someToolExecutionResultMessage);

マークは実際にはメッセージの属性にすぎないため、手動で行うこともできます。たとえば、すでにメッセージを構築している場合などです:

SystemMessage systemMessage = SystemMessage.builder()
.text(SHARED_INSTRUCTIONS)
.attributes(Map.of(OpenAiPromptCacheBreakpoint.ATTRIBUTE_KEY,
OpenAiPromptCacheBreakpoint.MODE_EXPLICIT))
.build();

メッセージをマークすると、LangChain4j はそのメッセージの内容をコンテンツブロックのリストとして送信します。プレーンな文字列形式ではブレークポイントを持てないためです。

AiMessage はブレークポイントを持てません。アシスタントの出力ブロックは、OpenAI がブレークポイントを受け付けるブロックタイプに含まれないためです。AiMessage をマークしたり、explicit 以外のモードを使用したりすると、HTTP 400 を発生させる代わりに、即座に失敗します。

各リクエストは最大 4 回のキャッシュ書き込みをサポートし、そのうち 1 回は implicit モードで消費されます。

キャッシュのトークン数の読み取り​

OpenAiTokenUsage.InputTokensDetails は、プロンプトキャッシュから読み取られた入力トークン数と書き込まれた入力トークン数を報告します:

OpenAiTokenUsage tokenUsage = (OpenAiTokenUsage) chatResponse.tokenUsage();

tokenUsage.inputTokensDetails().cachedTokens(); // tokens read from the cache
tokenUsage.inputTokensDetails().cacheWriteTokens(); // tokens written to the cache

モデルプロバイダーが報告しなかった場合、cacheWriteTokens() は null を返します。これは、報告されたゼロとは区別されます。

生の HTTP レスポンスと Server-Sent Events(SSE)へのアクセス​

OpenAiChatModel 使用時、生の HTTP レスポンスにアクセスできます:

SuccessfulHttpResponse rawHttpResponse = ((OpenAiChatResponseMetadata) chatResponse.metadata()).rawHttpResponse();
System.out.println(rawHttpResponse.body());
System.out.println(rawHttpResponse.headers());
System.out.println(rawHttpResponse.statusCode());

OpenAiStreamingChatModel 使用時は、生の HTTP レスポンス(上記)と生の Server-Sent Events にアクセスできます:

List<ServerSentEvent> rawServerSentEvents = ((OpenAiChatResponseMetadata) chatResponse.metadata()).rawServerSentEvents();
System.out.println(rawServerSentEvents.get(0).data());
System.out.println(rawServerSentEvents.get(0).event());

HTTP クライアント​

Plain Java​

langchain4j-open-ai モジュール使用時、 デフォルトの HTTP クライアントは JDK の java.net.http.HttpClient です。

カスタマイズしたり、任意の他の HTTP クライアントを使ったりできます。 詳細は こちら。

Spring Boot​

langchain4j-open-ai-spring-boot4-starter/langchain4j-open-ai-spring-boot-starter Spring Boot starter を使用する場合、Spring の RestClient がデフォルトの HTTP クライアントとして使用されます。これは Spring Boot の HTTP クライアント設定で構成されます。詳細は Spring Boot 統合を参照してください。

カスタマイズしたり、任意の他の HTTP クライアントを使ったりできます。 詳細は こちら。

OpenAI Responses API​

备注

この機能は実験的であり、今後のリリースで変更される可能性があります。

OpenAI の Responses API(/v1/responses)は、Chat Completions API の代替です。

OpenAiResponsesChatModel の作成​

ChatModel model = OpenAiResponsesChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5.4")
.build();

OpenAiResponsesStreamingChatModel の作成​

StreamingChatModel model = OpenAiResponsesStreamingChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.build();

カスタム HTTP ヘッダー(Custom HTTP headers)​

OpenAI API が、追加の HTTP ヘッダーを要求する認証付きプロキシやゲートウェイ経由でアクセスされる場合、これらのヘッダーをビルダーで設定できます。これらは、すべてのリクエストとともに送信されます:

ChatModel model = OpenAiResponsesChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.customHeaders(Map.of("Proxy-Authorization", "Basic dXNlcjpwYXNz"))
.build();

ヘッダーの値が一定でない場合(たとえば、有効期限が切れて更新が必要な OAuth2 トークン)は、代わりに Supplier を指定できます。これは各リクエストの前に呼び出されます:

ChatModel model = OpenAiResponsesChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.customHeaders(() -> Map.of("Authorization", "Bearer " + tokenProvider.currentToken()))
.build();

カスタムヘッダーは最後に適用されるため、LangChain4j がデフォルトで設定するヘッダー(たとえば Authorization)を上書きするためにも使用できます。

OpenAiResponsesStreamingChatModel にも同様に適用されます。

OpenAiResponsesChatRequestParameters​

OpenAiResponsesChatRequestParameters は DefaultChatRequestParameters を拡張し、Responses API 固有のフィールドを持ちます: previousResponseId、maxToolCalls、parallelToolCalls、topLogprobs、truncation、include、 serviceTier、safetyIdentifier、promptCacheKey、promptCacheRetention、promptCacheOptions、 reasoningEffort、reasoningSummary、textVerbosity、streamIncludeObfuscation、store、strictTools、 strictJsonSchema。

これらのパラメータはモデル作成時にデフォルトとして設定でき(ビルダーの defaultRequestParameters)、 または ChatRequest 経由でリクエスト単位に渡せます(リクエスト単位がデフォルトを上書き):

ChatRequest chatRequest = ChatRequest.builder()
.messages(UserMessage.from("Hello"))
.parameters(OpenAiResponsesChatRequestParameters.builder()
.modelName("gpt-4o-mini")
.previousResponseId("resp_abc123")
.store(true)
.build())
.build();

組み込み/サーバーツールの設定​

OpenAI Responses API 連携は、serverTools 経由で OpenAI 組み込みツールをサポートします。

  • serverTools は、生の OpenAI 形式の組み込みツールに使います

web_search、file_search などの組み込みツールや、その他の OpenAI Responses API のツールオブジェクトを、追加の型付きラッパーを導入せずに送信したい場合は、serverTools を使用します:

ChatModel model = OpenAiResponsesChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5.4")
.serverTools(List.of(
Map.of(
"type", "web_search",
"filters", Map.of("allowed_domains", List.of("openai.com", "developers.openai.com")),
"user_location", Map.of(
"type", "approximate",
"country", "US")),
Map.of(
"type", "file_search",
"vector_store_ids", List.of("vs_abc123"),
"max_num_results", 3,
"filters", Map.of(
"type", "eq",
"key", "category",
"value", "blog"))))
.build();

リクエスト単位でも組み込みツールを設定できます:

ChatRequest chatRequest = ChatRequest.builder()
.messages(UserMessage.from("What's the weather in Berlin?"))
.parameters(OpenAiResponsesChatRequestParameters.builder()
.serverTools(List.of(Map.of("type", "web_search")))
.build())
.build();

ChatResponse response = model.chat(chatRequest);

serverTools はモデルビルダー上のデフォルト、または OpenAiResponsesChatRequestParameters 経由のリクエスト単位で設定できます。両方ある場合、リクエスト単位の値が優先され、 そのリクエストではモデルレベルの serverTools を置き換えます。

serverTools はプロバイダ固有で、意図的に OpenAI のワイヤ形式を映すため、ネストしたツールフィールドは 通常の Map / List 値として渡してください。

Thinking / Reasoning​

OpenAI の推論モデル(例: gpt-5.4、gpt-5-mini)は、 reasoning summaries をサポートします。

推論サマリーを有効にするには、ビルダーで reasoningSummary を "auto" に設定します (または OpenAiResponsesChatRequestParameters 経由で)。 reasoningEffort でモデルが推論にどれだけ努力するかを制御することもできます。

ChatModel model = OpenAiResponsesChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5-mini")
.reasoningEffort("low")
.reasoningSummary("auto")
.build();

ChatResponse response = model.chat("What is the capital of Germany?");
response.aiMessage().text(); // "The capital of Germany is Berlin."
response.aiMessage().thinking(); // reasoning summary text

OpenAiResponsesStreamingChatModel に reasoningSummary が設定されている場合、推論サマリーのトークンがストリーミングされるのに合わせて StreamingChatResponseHandler.onPartialThinking() コールバックが呼び出されます:

StreamingChatModel model = OpenAiResponsesStreamingChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5-mini")
.reasoningEffort("low")
.reasoningSummary("auto")
.build();

AiMessage.thinking() の推論要約は情報提供用であり、後続リクエストに送り返す必要はありません—— OpenAI はターン間で破棄します。ツール呼び出しの間など、ターンをまたいでモデルの推論状態を実際に保持するには、 下記の暗号化推論を使います。

暗号化推論(コンテキスト内に推論を保持)​

store が false(デフォルト)の場合、または組織がゼロデータ保持の場合、 モデルの推論コンテキストはターン間で失われます。 これを保持するには、include パラメータで暗号化された推論コンテンツをリクエストします:

ChatModel model = OpenAiResponsesChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5-mini")
.reasoningEffort("medium")
.include(List.of("reasoning.encrypted_content"))
.build();

include に "reasoning.encrypted_content" が含まれると、レスポンスの推論アイテムに 不透明な暗号化ブロブが含まれます。これは自動的に AiMessage.attributes() の "encrypted_reasoning" キー配下に保存されます。

その AiMessage を後続リクエスト(例: ツール呼び出し後)に渡すと、 暗号化推論が自動的にリクエストに含まれ、 モデルが推論コンテキストを再開できます:

// Turn 1: model calls a tool
ChatResponse response1 = model.chat(ChatRequest.builder()
.messages(userMessage)
.parameters(ChatRequestParameters.builder()
.toolSpecifications(weatherTool)
.build())
.build());

AiMessage aiMessage1 = response1.aiMessage();
// aiMessage1.attribute("encrypted_reasoning", String.class) is not null

// Turn 2: send tool result back — encrypted reasoning is sent automatically
ChatResponse response2 = model.chat(ChatRequest.builder()
.messages(
userMessage,
aiMessage1, // contains encrypted reasoning in attributes
ToolExecutionResultMessage.from(aiMessage1.toolExecutionRequests().get(0), "sunny"))
.parameters(ChatRequestParameters.builder()
.toolSpecifications(weatherTool)
.build())
.build());

これは OpenAiResponsesStreamingChatModel でも同様に動作します。

OpenAiResponsesChatResponseMetadata​

Responses API のレスポンスメタデータは、標準の ChatResponseMetadata を超える追加フィールドを提供します:

OpenAiResponsesChatResponseMetadata metadata =
(OpenAiResponsesChatResponseMetadata) chatResponse.metadata();

metadata.id(); // Response ID (can be used as previousResponseId)
metadata.modelName(); // Model name used for the request
metadata.finishReason(); // Finish reason (STOP, LENGTH, TOOL_EXECUTION, CONTENT_FILTER, OTHER)
metadata.tokenUsage(); // Returns OpenAiTokenUsage with detailed token counts
metadata.createdAt(); // Timestamp when the response was created
metadata.completedAt(); // Timestamp when the response was completed
metadata.serviceTier(); // Service tier used for the request

// Raw HTTP access (same as Chat Completions API)
metadata.rawHttpResponse();
metadata.rawServerSentEvents();

例​