跳到主要内容

OpenAI 官方 SDK

备注

本文档介绍 OpenAI Official SDK 集成,它使用 官方 OpenAI Java SDK

LangChain4j 为使用聊天模型提供了 3 种不同的 OpenAI 集成,本文是其中的 #2:

  • OpenAI 使用 OpenAI REST API 的自定义 Java 实现,与 Quarkus(使用 Quarkus REST 客户端)和 Spring(使用 Spring 的 RestClient)配合最佳。
  • OpenAI Official SDK 使用官方 OpenAI Java SDK。
  • Azure OpenAI 使用 Microsoft 的 Azure SDK,在使用 Microsoft Java 技术栈(包括高级 Azure 认证机制)时效果最佳。

此集成的用例

此集成使用 OpenAI Java SDK GitHub 仓库,适用于可由以下来源提供的所有 OpenAI 模型:

  • OpenAI
  • Microsoft Foundry
  • GitHub Models

它也适用于支持 OpenAI API 的模型,例如 DeepSeek。

OpenAI 文档

Maven 依赖

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-official</artifactId>
<version>1.18.1-beta28</version>
</dependency>

配置模型

备注

此配置以及下一节关于其用法的内容,针对非流式模式(也称为“阻塞”或“同步”模式)。 流式模式在下方第 2 节详述:它允许与模型实时聊天,但使用更复杂。

要使用 OpenAI 模型,通常需要端点 URL、API 密钥和模型名称。这取决于模型的托管位置,此集成尝试 通过一些自动配置使其更简单:

通用配置

import com.openai.models.ChatModel;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openaiofficial.OpenAiOfficialChatModel;

import static com.openai.models.ChatModel.GPT_5_MINI;

// ....

ChatModel model = OpenAiOfficialChatModel.builder()
.baseUrl(System.getenv("OPENAI_BASE_URL"))
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName(GPT_5_MINI)
.build();

OpenAI 配置

OpenAI 的 baseUrlhttps://api.openai.com/v1)是默认值,因此可以省略:

ChatModel model = OpenAiOfficialChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName(GPT_5_MINI)
.build();

Azure OpenAI 配置

通用配置

对于 Azure OpenAI,必须设置 baseUrl;如果该 URL 以 openai.azure.com 结尾,将自动检测为 Azure OpenAI:

ChatModel model = OpenAiOfficialChatModel.builder()
.baseUrl(System.getenv("AZURE_OPENAI_ENDPOINT"))
.apiKey(System.getenv("AZURE_OPENAI_KEY"))
.modelName(GPT_5_MINI)
.build();

若要强制使用 Azure OpenAI,也可以使用 isAzure() 方法:

ChatModel model = OpenAiOfficialChatModel.builder()
.baseUrl(System.getenv("AZURE_OPENAI_ENDPOINT"))
.apiKey(System.getenv("AZURE_OPENAI_KEY"))
.isAzure(true)
.modelName(GPT_5_MINI)
.build();

无密码认证

您可以使用“无密码”认证访问 Azure OpenAI,由于无需管理 API 密钥,因此更安全。

为此,必须先将 Azure OpenAI 实例配置为支持托管身份,然后向此应用授予访问权限,例如:

# Enable system managed identity on the Azure OpenAI instance
az cognitiveservices account identity assign \
--name <your-openai-instance-name> \
--resource-group <your-resource-group>

# Get your logged-in identity
az ad signed-in-user show \
--query id -o tsv

# Give access to the Azure OpenAI instance
az role assignment create \
--role "Cognitive Services OpenAI User" \
--assignee <your-logged-identity-from-the-previous-command> \
--scope "/subscriptions/<your-subscription-id>/resourceGroups/<your-resource-group>"

然后,需要将 azure-identity 依赖添加到 Maven pom.xml

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

未配置 API 密钥时,LangChain4j 将自动对 Azure OpenAI 使用无密码认证。

GitHub Models 配置

对于 GitHub Models,可以使用默认 baseUrlhttps://models.inference.ai.azure.com):

ChatModel model = OpenAiOfficialChatModel.builder()
.baseUrl("https://models.inference.ai.azure.com")
.apiKey(System.getenv("GITHUB_TOKEN"))
.modelName(GPT_5_MINI)
.build();

或者使用 isGitHubModels() 方法强制使用 GitHub Models,它会自动设置 baseUrl

ChatModel model = OpenAiOfficialChatModel.builder()
.apiKey(System.getenv("GITHUB_TOKEN"))
.modelName(GPT_5_MINI)
.isGitHubModels(true)
.build();

由于 GitHub Models 通常使用 GITHUB_TOKEN 环境变量配置(在使用 GitHub Actions 或 GitHub Codespaces 时会自动填充),因此会被自动检测:

ChatModel model = OpenAiOfficialChatModel.builder()
.modelName(GPT_5_MINI)
.isGitHubModels(true)
.build();

最后这种配置更易用,也更安全,因为 GITHUB_TOKEN 环境变量不会暴露在代码或 GitHub 日志中。

使用模型

在上一节中,创建了实现 ChatModel 接口的 OpenAiOfficialChatModel 对象。

它既可由 AI Service 使用,也可在 Java 应用中直接使用。

在本例中,它作为 Spring Bean 自动注入:

@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) 功能同时支持 工具响应格式

有关结构化输出的更多信息见 此处

结构化输出 for Tools

要为工具启用结构化输出功能,在构建模型时设置 .strictTools(true)

OpenAiOfficialChatModel.builder()
// ...
.strictTools(true)
.build();

请注意,这会自动使所有工具参数成为必填(json schema 中的 required), 并为 json schema 中的每个 object 设置 additionalProperties=false。这是由于当前 OpenAI 的限制。

结构化输出 for Response Format

在使用 AI Services 时,若要为响应格式启用结构化输出功能, 在构建模型时设置 supportedCapabilities(Set.of(RESPONSE_FORMAT_JSON_SCHEMA)).strictJsonSchema(true)

import static dev.langchain4j.model.chat.Capability.RESPONSE_FORMAT_JSON_SCHEMA;

// ...

OpenAiChatModel.builder()
// ...
.supportedCapabilities(Set.of(RESPONSE_FORMAT_JSON_SCHEMA))
.strictJsonSchema(true)
.build();

在这种情况下,AI Service 将自动从给定的 POJO 生成 JSON schema 并传递给 LLM。

配置模型 for streaming

备注

在上面两节中,我们详细说明了如何为非流式模式(也称为“阻塞”或“同步”模式)配置模型。 本节针对流式模式,它允许与模型实时聊天,但使用起来更复杂。

这与非流式模式类似,但需要使用 OpenAiOfficialStreamingChatModel 类而不是 OpenAiOfficialChatModel

StreamingChatModel model = OpenAiOfficialStreamingChatModel.builder()
.baseUrl(System.getenv("OPENAI_BASE_URL"))
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName(GPT_5_MINI)
.build();

您也可以使用特定的 isAzure()isGitHubModels() 方法强制使用 Azure OpenAI 或 GitHub Models,详见非流式配置部分。

OpenAI Responses API

备注

此功能为实验性功能,可能在未来版本中发生变化。

OpenAI 的 Responses API/v1/responses)是 Chat Completions API 的替代方案。

创建 OpenAiOfficialResponsesChatModel

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

创建 OpenAiOfficialResponsesStreamingChatModel

StreamingChatModel model = OpenAiOfficialResponsesStreamingChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName(GPT_5_MINI)
.build();

您也可以使用 OpenAiOfficialResponsesChatRequestParameters 配置默认请求参数:

StreamingChatModel model = OpenAiOfficialResponsesStreamingChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.defaultRequestParameters(OpenAiOfficialResponsesChatRequestParameters.builder()
.modelName("gpt-4o-mini")
.previousResponseId("resp_abc123")
.reasoningEffort("medium")
.store(true)
.build())
.build();

OpenAiOfficialResponsesChatRequestParameters

OpenAiOfficialResponsesChatRequestParametersDefaultChatRequestParameters 基础上扩展了 Responses API 特有字段: previousResponseIdmaxToolCallsparallelToolCallstopLogprobstruncationincludeserviceTiersafetyIdentifierpromptCacheKeypromptCacheRetentionreasoningEffortreasoningSummarytextVerbositystreamIncludeObfuscationstorestrictToolsstrictJsonSchema

这些参数可在创建模型时通过构建器上的 defaultRequestParameters 配置为默认值, 也可通过 ChatRequest 按请求传递(按请求参数会覆盖默认值):

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

思考 / 推理

OpenAI 推理模型(例如 gpt-5.4gpt-5-mini)支持 推理摘要, 可公开模型内部推理的摘要。

要启用推理摘要,在构建器上(或通过 OpenAiOfficialResponsesChatRequestParameters)将 reasoningSummary 设为 Reasoning.Summary.AUTO。 您也可以使用 reasoningEffort 控制模型在推理上投入的力度。

ChatModel model = OpenAiOfficialResponsesChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5-mini")
.reasoningEffort(ReasoningEffort.LOW)
.reasoningSummary(Reasoning.Summary.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

当为 OpenAiOfficialResponsesStreamingChatModel 设置了 reasoningSummary 时, 随着推理摘要 token 被流式传输,会调用 StreamingChatResponseHandler.onPartialThinking() 回调:

StreamingChatModel model = OpenAiOfficialResponsesStreamingChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-5-mini")
.reasoningEffort(ReasoningEffort.LOW)
.reasoningSummary(Reasoning.Summary.AUTO)
.build();

AiMessage.thinking() 中的推理摘要仅供参考,无需在后续请求中发回——OpenAI 会在各轮之间丢弃它。 若要真正在各轮之间保留模型的推理状态(例如在工具调用之间),请改用下方所述的加密推理。

加密推理(在上下文中保留推理)

storefalse(默认)或您的组织启用了零数据保留时, 模型的推理上下文会在各轮之间丢失。 要保留它,可通过 include 参数请求 加密推理内容

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

include 包含 "reasoning.encrypted_content" 时,响应中的推理项 将包含一个不透明的加密 blob。它会自动存储在 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());

这对 OpenAiOfficialResponsesStreamingChatModel 同样适用。

OpenAiOfficialResponsesChatResponseMetadata

Responses API 的响应元数据在标准 ChatResponseMetadata 之外提供了额外字段:

OpenAiOfficialResponsesChatResponseMetadata metadata =
(OpenAiOfficialResponsesChatResponseMetadata) 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, OTHER)
metadata.tokenUsage(); // Returns OpenAiOfficialTokenUsage 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