跳到主要内容

OpenAI 聊天

Deepseek 3.2 中英对照 OpenAI OpenAI Chat

Spring AI 支持来自OpenAI公司的多种人工智能语言模型,该公司是ChatGPT的幕后推手。凭借其行业领先的文本生成模型和嵌入技术,OpenAI在激发人们对AI驱动文本生成的兴趣方面发挥了关键作用。

前提条件

您需要通过OpenAI创建一个API来访问ChatGPT模型。

请在OpenAI 注册页面创建账户,并在API Keys 页面生成令牌。

Spring AI 项目定义了一个名为 spring.ai.openai.api-key 的配置属性,您应将其设置为从 openai.com 获取的 API Key 的值。

您可以在 application.properties 文件中设置此配置属性:

spring.ai.openai.api-key=<your-openai-api-key>

为了在处理API密钥等敏感信息时增强安全性,你可以使用Spring表达式语言(SpEL)来引用自定义环境变量:

# In application.yml
spring:
ai:
openai:
api-key: ${OPENAI_API_KEY}
# In your environment or .env file
export OPENAI_API_KEY=<your-openai-api-key>

您也可以在应用程序代码中以编程方式设置此配置:

// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("OPENAI_API_KEY");

添加仓库和BOM

Spring AI 构件发布于 Maven Central 和 Spring Snapshot 仓库。请参考 构件仓库 部分,将这些仓库添加到您的构建系统中。

为了协助依赖管理,Spring AI 提供了一个物料清单(BOM),以确保在整个项目中使用统一版本的 Spring AI。请参阅依赖管理章节,将 Spring AI BOM 添加到您的构建系统中。

自动配置

备注

Spring AI 自动配置、启动器模块的构件名称发生了重大变化。请查阅 升级说明 了解更多信息。

Spring AI 为 OpenAI 聊天客户端提供了 Spring Boot 自动配置。要启用此功能,请将以下依赖项添加到您项目的 Maven pom.xml 或 Gradle build.gradle 构建文件中:

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

:::提示
请参考依赖管理章节,将 Spring AI BOM 添加到你的构建文件中。
:::

聊天属性

重试属性

前缀 spring.ai.retry 用作配置 OpenAI 聊天模型重试机制的属性前缀。

属性描述默认值
spring.ai.retry.max-attempts最大重试次数10
spring.ai.retry.backoff.initial-interval指数退避策略的初始休眠时长2 秒
spring.ai.retry.backoff.multiplier退避间隔乘数5
spring.ai.retry.backoff.max-interval最大退避时长3 分钟
spring.ai.retry.on-client-errors如果为 false,对于 4xx 客户端错误码,将抛出 NonTransientAiException 且不尝试重试false
spring.ai.retry.exclude-on-http-codes不应触发重试的 HTTP 状态码列表(例如,抛出 NonTransientAiException)。
spring.ai.retry.on-http-codes应触发重试的 HTTP 状态码列表(例如,抛出 TransientAiException)。

连接属性

前缀 spring.ai.openai 作为属性前缀,用于连接到 OpenAI。

属性描述默认值
spring.ai.openai.base-url连接到的 URLapi.openai.com
spring.ai.openai.api-keyAPI 密钥-
spring.ai.openai.organization-id可选,可以为 API 请求指定使用哪个组织。-
spring.ai.openai.project-id可选,可以为 API 请求指定使用哪个项目。-
提示

对于属于多个组织(或通过其遗留用户 API 密钥访问其项目)的用户,您可以选择性地指定某个 API 请求使用哪个组织和项目。这些 API 请求所产生的使用量将计入指定组织和项目的用量。

User-Agent 标头

Spring AI 会自动向 OpenAI 发送所有请求时附带一个 User-Agent: spring-ai 请求头。这有助于 OpenAI 识别来自 Spring AI 的请求,以便进行分析和支持。该请求头是自动发送的,Spring AI 用户无需进行任何配置。

如果您是构建OpenAI兼容服务的API提供商,可以通过读取服务器接收请求中的User-Agent HTTP标头来追踪Spring AI的使用情况。

配置属性

备注

聊天自动配置的启用与禁用现在通过顶层属性进行配置,属性前缀为 spring.ai.model.chat

启用方式:spring.ai.model.chat=openai(默认已启用)

禁用方式:spring.ai.model.chat=none(或任何不匹配 openai 的值)

此项变更是为了支持配置多个模型。

前缀 spring.ai.openai.chat 是用于配置 OpenAI 聊天模型实现的属性前缀。

属性描述默认
spring.ai.openai.chat.enabled (已移除且不再有效)启用 OpenAI 聊天模型。
spring.ai.model.chat启用 OpenAI 聊天模型。openai
spring.ai.openai.chat.base-url用于 spring.ai.openai.base-url 属性的可选覆盖,以提供聊天专用的 URL。-
spring.ai.openai.chat.completions-path附加到基础 URL 的路径。/v1/chat/completions
spring.ai.openai.chat.api-keyspring.ai.openai.api-key 的可选覆盖,用于提供聊天专用的 API 密钥。-
spring.ai.openai.chat.organization-id可选地,您可以指定在 API 请求中使用哪个组织。-
spring.ai.openai.chat.project-id可选地,您可以为 API 请求指定使用的项目。-
spring.ai.openai.chat.options.model使用的 OpenAI 聊天模型名称。您可以选择以下模型:gpt-4ogpt-4o-minigpt-4-turbogpt-3.5-turbo 等。更多信息请参见 模型 页面。gpt-4o-mini
spring.ai.openai.chat.options.temperature采样温度,用于控制生成内容的表面创造力。温度值越高,输出结果越随机;温度值越低,结果越集中且具有确定性。不建议在同一补全请求中同时修改 temperaturetop_p 参数,因为这两个设置的交互作用难以预测。0.8
spring.ai.openai.chat.options.frequencyPenalty取值范围在 -2.0 到 2.0 之间。正值会根据新 token 在当前文本中已出现的频率对其进行惩罚,从而降低模型逐字重复相同文本的可能性。0.0f
spring.ai.openai.chat.options.logitBias修改指定标记在完成文本中出现的可能性。-
spring.ai.openai.chat.options.maxTokens聊天补全中生成的最大令牌数。输入令牌和生成令牌的总长度受模型上下文长度限制。适用于非推理模型(例如 gpt-4o、gpt-3.5-turbo)。不能与推理模型同时使用(例如 o1、o3、o4-mini 系列)。与 maxCompletionTokens 互斥——同时设置两者将导致 API 错误。-
spring.ai.openai.chat.options.maxCompletionTokens一个补全任务所能生成的令牌数量的上限,包括可见输出令牌和推理令牌。推理模型必需(例如 o1、o3、o4-mini 系列)。不能用于非推理模型(例如 gpt-4o、gpt-3.5-turbo)。与 maxTokens 互斥 - 同时设置两者将导致 API 错误。-
spring.ai.openai.chat.options.n为每条输入消息生成多少个聊天完成选项。请注意,您将根据所有选项中生成的令牌数量计费。将 n 保持为 1 以最小化成本。1
spring.ai.openai.chat.options.store是否存储此次聊天补全请求的输出,以供我们的模型使用false
spring.ai.openai.chat.options.metadata开发者定义的标签和值,用于在聊天完成仪表板中筛选完成情况空地图
spring.ai.openai.chat.options.output-modalities你希望模型为此请求生成的输出类型。大多数模型能够生成文本,这是默认类型。gpt-4o-audio-preview 模型也可用于生成音频。若要求该模型同时生成文本和音频响应,可使用:text, audio。不支持流式传输。-
spring.ai.openai.chat.options.output-audio音频生成的音频参数。当通过 output-modalities: audio 请求音频输出时需要此参数。需要 gpt-4o-audio-preview 模型,且不支持流式补全。-
spring.ai.openai.chat.options.presencePenalty取值范围在 -2.0 到 2.0 之间。正值会根据新标记是否已在当前文本中出现来对其进行惩罚,从而增加模型讨论新话题的可能性。-
spring.ai.openai.chat.options.responseFormat.type兼容 GPT-4oGPT-4o miniGPT-4 Turbo 以及所有版本新于 gpt-3.5-turbo-1106GPT-3.5 Turbo 模型。JSON_OBJECT 类型启用 JSON 模式,确保模型生成的消息是有效的 JSON。JSON_SCHEMA 类型启用结构化输出,确保模型将匹配你提供的 JSON 模式。JSON_SCHEMA 类型还需要设置 responseFormat.schema 属性。-
spring.ai.openai.chat.options.responseFormat.name响应格式模式名称。仅适用于 responseFormat.type=JSON_SCHEMAcustom_schema
spring.ai.openai.chat.options.responseFormat.schema响应格式 JSON 模式。仅适用于 responseFormat.type=JSON_SCHEMA-
spring.ai.openai.chat.options.responseFormat.strict响应格式 JSON 模式严格性。仅适用于 responseFormat.type=JSON_SCHEMA-
spring.ai.openai.chat.options.seed此功能处于测试阶段。如果指定了种子,我们的系统将尽力进行确定性采样,从而使得使用相同种子和参数的重复请求应返回相同的结果。-
spring.ai.openai.chat.options.stop最多 4 个序列,API 将在此停止生成更多令牌。-
spring.ai.openai.chat.options.topP另一种替代温度采样的方法是核采样,其中模型会考虑具有 top_p 概率质量的标记结果。因此,0.1 意味着只考虑构成前 10% 概率质量的标记。我们通常建议调整此参数或 temperature,但不要同时调整两者。-
spring.ai.openai.chat.options.tools模型可调用的工具列表。目前仅支持函数作为工具。使用此功能来提供模型可以生成 JSON 输入的函数列表。-
spring.ai.openai.chat.options.toolChoice控制模型调用哪个(如果有的话)函数。none 表示模型不会调用函数,而是生成一条消息。auto 表示模型可以在生成消息或调用函数之间进行选择。通过 {"type": "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该函数。当没有函数存在时,默认值为 none。如果有函数存在,则默认值为 auto-
spring.ai.openai.chat.options.user代表您的最终用户的唯一标识符,可帮助 OpenAI 监控和检测滥用行为。-
spring.ai.openai.chat.options.stream-usage(仅限流式传输)设置为添加一个包含整个请求的令牌使用统计数据的额外块。该块的 choices 字段为空数组,其他所有块也将包含一个 usage 字段,但值为 null
spring.ai.openai.chat.options.parallel-tool-calls是否在工具使用时启用并行函数调用true
spring.ai.openai.chat.options.prompt-cache-key一个由OpenAI使用的缓存键,用于优化相似请求的缓存命中率。它可以改善延迟并降低成本。为缓存目的,它取代了已弃用的 user 字段。了解更多-
spring.ai.openai.chat.options.safety-identifier一个稳定的标识符,用于帮助 OpenAI 检测违反使用政策的用户。应为一个哈希值(例如,哈希化的用户名或电子邮件)。取代已弃用的 user 字段,用于安全追踪。了解更多-
spring.ai.openai.chat.options.http-headers可选的 HTTP 头部信息,用于添加到聊天补全请求中。若要覆盖 api-key,您需要使用 Authorization 头部键,并且必须在键值前加上 Bearer 前缀。-
spring.ai.openai.chat.options.tool-names工具列表,以其名称标识,用于在单个提示请求中启用函数调用。这些名称的工具必须存在于 ToolCallback 注册表中。-
spring.ai.openai.chat.options.tool-callbacks要注册到聊天模型中的工具回调函数。-
spring.ai.openai.chat.options.internal-tool-execution-enabled如果为 false,Spring AI 将不会在内部处理工具调用,而是将其代理给客户端。此时客户端需负责处理工具调用,将其分发给适当的函数并返回结果。如果为 true(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型。true
spring.ai.openai.chat.options.service-tier指定用于处理请求的服务处理类型-
spring.ai.openai.chat.options.extra-body包含在请求中的额外参数。接受任意键值对,这些键值对会被扁平化到JSON请求的顶层。此功能适用于支持超出标准OpenAI API参数的OpenAI兼容服务器(如vLLM、Ollama等)。官方的OpenAI API会忽略未知参数。详见在OpenAI兼容服务器中使用额外参数-
备注

在使用 GPT-5 系列模型,例如 gpt-5gpt-5-minigpt-5-nano 时,不支持 temperature 参数。这些模型针对推理任务进行了优化,不使用温度参数。指定温度值会导致错误。相比之下,像 gpt-5-chat 这样的对话模型确实支持 temperature 参数。

备注

你可以为 ChatModelEmbeddingModel 的实现覆盖通用的 spring.ai.openai.base-urlspring.ai.openai.api-key 配置。如果设置了 spring.ai.openai.chat.base-urlspring.ai.openai.chat.api-key 属性,它们将优先于通用属性。如果你想为不同的模型和不同的模型端点使用不同的 OpenAI 账户,这会非常有用。

提示

所有以 spring.ai.openai.chat.options 为前缀的属性,都可以通过在 Prompt 调用中添加特定于请求的运行时选项在运行时进行覆盖。

Token Limit Parameters: Model-Specific Usage

OpenAI提供了两个互斥的参数来控制令牌生成的上限:

参数使用场景兼容模型
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.",
OpenAiChatOptions.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: ...",
OpenAiChatOptions.builder()
.model("o1-preview")
.maxCompletionTokens(1000) // Use maxCompletionTokens for reasoning models
.build()
));

Builder Pattern Validation: The OpenAI ChatOptions 构建器自动采用“最后设置优先”的方法来强制实施互斥性:

// This will automatically clear maxTokens and use maxCompletionTokens
OpenAiChatOptions options = OpenAiChatOptions.builder()
.maxTokens(100) // Set first
.maxCompletionTokens(200) // This clears maxTokens and logs a warning
.build();

// Result: maxTokens = null, maxCompletionTokens = 200

运行时选项

OpenAiChatOptions.java 类提供了模型配置,例如使用的模型、温度、频率惩罚等。

启动时,可通过 OpenAiChatModel(api, options) 构造函数或 spring.ai.openai.chat.options.* 属性配置默认选项。

在运行时,你可以通过在 Prompt 调用中添加新的、特定于请求的选项来覆盖默认选项。例如,要针对特定请求覆盖默认模型和温度参数:

ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
OpenAiChatOptions.builder()
.model("gpt-4o")
.temperature(0.4)
.build()
));
提示

除了使用模型特定的 OpenAiChatOptions 之外,你也可以使用一个可移植的 ChatOptions 实例,该实例可通过 ChatOptions#builder() 创建。

函数调用

你可以向 OpenAiChatModel 注册自定义 Java 函数,并让 OpenAI 模型智能地选择输出一个包含参数的 JSON 对象,以调用一个或多个已注册的函数。这是一种将 LLM 能力与外部工具和 API 连接起来的强大技术。了解更多关于工具调用的信息。

多模态

多模态性是指模型同时理解和处理来自多种来源信息的能力,这些来源包括文本、图像、音频以及其他数据格式。OpenAI支持文本、视觉和音频输入模态。

愿景

提供视觉多模态支持的 OpenAI 模型包括 gpt-4gpt-4ogpt-4o-mini。更多信息请参阅 Vision 指南。

OpenAI 的 用户消息 API 可以在消息中集成一个 base64 编码的图像列表或图像 URL。Spring AI 的 消息 接口通过引入 媒体 类型来支持多模态 AI 模型。该类型包含消息中媒体附件的数据和详细信息,使用 Spring 的 org.springframework.util.MimeType 和一个 org.springframework.core.io.Resource 来存储原始媒体数据。

以下是从 OpenAiChatModelIT.java 中摘录的代码示例,展示了使用 gpt-4o 模型将用户文本与图像进行融合的过程。

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

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

ChatResponse response = chatModel.call(new Prompt(this.userMessage,
OpenAiChatOptions.builder().model(OpenAiApi.ChatModel.GPT_4_O.getValue()).build()));
提示

从 2024 年 6 月 17 日开始,GPT_4_VISION_PREVIEW 将仅对已使用此模型的现有用户继续开放。如果您不是现有用户,请使用 GPT_4_O 或 GPT_4_TURBO 模型。更多详情请见此处

或使用 gpt-4o 模型的等效图片URL:

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

ChatResponse response = chatModel.call(new Prompt(this.userMessage,
OpenAiChatOptions.builder().model(OpenAiApi.ChatModel.GPT_4_O.getValue()).build()));

:::提示
您可以同时传递多张图片。
:::

该示例展示了模型以 multimodal.test.png 图像作为输入:

多模态测试图像

伴随文本消息"请解释你在图片中看到了什么?",并生成如下回应:

This is an image of a fruit bowl with a simple design. The bowl is made of metal with curved wire edges that
create an open structure, allowing the fruit to be visible from all angles. Inside the bowl, there are two
yellow bananas resting on top of what appears to be a red apple. The bananas are slightly overripe, as
indicated by the brown spots on their peels. The bowl has a metal ring at the top, likely to serve as a handle
for carrying. The bowl is placed on a flat surface with a neutral-colored background that provides a clear
view of the fruit inside.

音频

支持音频输入多模态的OpenAI模型包括 gpt-4o-audio-preview。更多信息请参阅 音频 指南。

OpenAI 的 用户消息 API 可以将一个 base64 编码的音频文件列表与消息结合。Spring AI 的 Message 接口通过引入 Media 类型来支持多模态 AI 模型。此类型包含了消息中媒体附件的数据和详细信息,并利用 Spring 的 org.springframework.util.MimeType 和一个用于原始媒体数据的 org.springframework.core.io.Resource。目前,OpenAI 仅支持以下媒体类型:audio/mp3audio/wav

以下是一个从OpenAiChatModelIT.java中摘录的代码示例,展示了如何使用gpt-4o-audio-preview模型将用户文本与音频文件进行融合。

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(List.of(userMessage),
OpenAiChatOptions.builder().model(OpenAiApi.ChatModel.GPT_4_O_AUDIO_PREVIEW).build()));
提示

您也可以传递多个音频文件。

音频输出

支持输入音频多模态功能的OpenAI模型包括 gpt-4o-audio-preview。更多信息请参阅音频指南。

OpenAI 的 Assistant Message API 可以在消息中包含一个 base64 编码的音频文件列表。Spring AI 的 Message 接口通过引入 Media 类型来支持多模态 AI 模型。该类型包含消息中媒体附件的数据和详细信息,使用 Spring 的 org.springframework.util.MimeTypeorg.springframework.core.io.Resource 来处理原始媒体数据。目前,OpenAI 仅支持以下音频类型:audio/mp3audio/wav

以下是一个代码示例,展示了使用 gpt-4o-audio-preview 模型时,如何处理用户文本和音频字节数组的响应:

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

ChatResponse response = chatModel.call(new Prompt(List.of(userMessage),
OpenAiChatOptions.builder()
.model(OpenAiApi.ChatModel.GPT_4_O_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

你必须在 OpenAiChatOptions 中指定 audio 模态才能生成音频输出。AudioParameters 类为音频输出提供了语音和音频格式。

结构化输出

OpenAI 提供定制化的 Structured Outputs API,确保您的模型生成的响应严格遵守您提供的 JSON Schema。除了现有的 Spring AI 模型无关的 结构化输出转换器 外,这些 API 还提供了更强的控制能力和更高的精确度。

备注

目前,OpenAI 支持 JSON Schema 语言的一个子集 格式。

配置

Spring AI 允许您通过使用 OpenAiChatOptions 构建器以编程方式或通过应用程序属性来配置响应格式。

使用聊天选项生成器

您可以通过 OpenAiChatOptions 构建器以编程方式设置响应格式,如下所示:

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",
OpenAiChatOptions.builder()
.model(ChatModel.GPT_4_O_MINI)
.responseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, this.jsonSchema))
.build());

ChatResponse response = this.openAiChatModel.call(this.prompt);
备注

请遵循 OpenAI 的 JSON Schema 语言子集 格式。

与 BeanOutputConverter 实用工具集成

您可以利用现有的 BeanOutputConverter 工具,从您的领域对象自动生成 JSON Schema,并将结构化响应转换为特定领域的实例:

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);

var jsonSchema = this.outputConverter.getJsonSchema();

Prompt prompt = new Prompt("how can I solve 8x + 7 = -23",
OpenAiChatOptions.builder()
.model(ChatModel.GPT_4_O_MINI)
.responseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, this.jsonSchema))
.build());

ChatResponse response = this.openAiChatModel.call(this.prompt);
String content = this.response.getResult().getOutput().getContent();

MathReasoning mathReasoning = this.outputConverter.convert(this.content);
备注

尽管这在 JSON Schema 中是可选的,但 OpenAI 强制要求所有字段必须为必填项,以确保结构化响应正常工作。Kotlin 反射会根据类型的可空性和参数的默认值推断属性是否为必填,因此在大多数用例中,不需要使用 @get:JsonProperty(required = true)@get:JsonProperty(value = "custom_name") 可用于自定义属性名称。请确保使用 @get: 语法在相关的 getter 上生成注解,参见相关文档

通过应用程序属性配置

或者,在使用OpenAI自动配置时,您可以通过以下应用程序属性来配置所需的响应格式:

spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.chat.options.model=gpt-4o-mini

spring.ai.openai.chat.options.response-format.type=JSON_SCHEMA
spring.ai.openai.chat.options.response-format.name=MySchemaName
spring.ai.openai.chat.options.response-format.schema={"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}
spring.ai.openai.chat.options.response-format.strict=true

示例控制器

创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-openai 添加到你的 pom(或 gradle)依赖中。

src/main/resources 目录下添加一个 application.properties 文件,以启用和配置 OpenAi 聊天模型:

spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.chat.options.model=gpt-4o
spring.ai.openai.chat.options.temperature=0.7

:::提示
api-key 替换为您的 OpenAI 凭证。
:::

这将创建一个 OpenAiChatModel 实现,你可以将其注入到你的类中。以下是一个使用该聊天模型进行文本生成的简单 @RestController 类示例。

@RestController
public class ChatController {

private final OpenAiChatModel chatModel;

@Autowired
public ChatController(OpenAiChatModel 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", this.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 this.chatModel.stream(prompt);
}
}

手动配置

OpenAiChatModel 实现了 ChatModelStreamingChatModel,并使用底层 OpenAiApi 客户端连接到 OpenAI 服务。

spring-ai-openai 依赖添加到项目的 Maven pom.xml 文件中:

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

或添加到您的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-openai'
}

:::提示
参考依赖管理章节,将Spring AI BOM添加到你的构建文件中。
:::

接下来,创建一个 OpenAiChatModel 并使用它进行文本生成:

var openAiApi = OpenAiApi.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.build();
var openAiChatOptions = OpenAiChatOptions.builder()
.model("gpt-3.5-turbo")
.temperature(0.4)
.maxTokens(200)
.build();
var chatModel = new OpenAiChatModel(this.openAiApi, this.openAiChatOptions);

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

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

OpenAiChatOptions 提供聊天请求的配置信息。OpenAiApi.BuilderOpenAiChatOptions.Builder 分别是用于 API 客户端和聊天配置的流畅选项构建器。

底层 OpenAiApi 客户端

OpenAiApi 为 OpenAI Chat API OpenAI Chat API 提供了一个轻量级的 Java 客户端。

下面的类图展示了 OpenAiApi 聊天接口及其构建模块:

OpenAiApi 聊天 API 流程图

以下是一个展示如何以编程方式使用 API 的简单代码片段:

OpenAiApi openAiApi = OpenAiApi.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.build();

ChatCompletionMessage chatCompletionMessage =
new ChatCompletionMessage("Hello world", Role.USER);

// Sync request
ResponseEntity<ChatCompletion> response = this.openAiApi.chatCompletionEntity(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), "gpt-3.5-turbo", 0.8, false));

// Streaming request
Flux<ChatCompletionChunk> streamResponse = this.openAiApi.chatCompletionStream(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), "gpt-3.5-turbo", 0.8, true));

如需更多信息,请参考 OpenAiApi.java 的 JavaDoc。

低级 API 示例

低级 OpenAiFileApi 客户端

OpenAiFileApi 为 OpenAI Files API 提供了一个轻量级的 Java 客户端,支持文件管理操作,例如上传、列出、检索、删除文件以及访问文件内容。OpenAI File API

以下是一个展示如何通过编程方式使用 API 的简单示例:

OpenAiFileApi openAiFileApi = OpenAiFileApi.builder()
.apiKey(new SimpleApiKey(System.getenv("OPENAI_API_KEY")))
.build();

// Upload a file
byte[] fileBytes = Files.readAllBytes(Paths.get("evals.jsonl"));
OpenAiFileApi.UploadFileRequest uploadRequest = OpenAiFileApi.UploadFileRequest.builder()
.file(fileBytes)
.fileName("evals-data.jsonl")
.purpose(OpenAiFileApi.Purpose.EVALS)
.build();
ResponseEntity<OpenAiFileApi.FileObject> uploadResponse = openAiFileApi.uploadFile(uploadRequest);

// List files
OpenAiFileApi.ListFileRequest listRequest = OpenAiFileApi.ListFileRequest.builder()
.purpose(OpenAiFileApi.Purpose.EVALS)
.build();
ResponseEntity<OpenAiFileApi.FileObjectResponse> listResponse = openAiFileApi.listFiles(listRequest);

// Retrieve file information
ResponseEntity<OpenAiFileApi.FileObject> fileInfo = openAiFileApi.retrieveFile("file-id");

// Delete a file
ResponseEntity<OpenAiFileApi.DeleteFileResponse> deleteResponse = openAiFileApi.deleteFile("file-id");

// Retrieve file content
ResponseEntity<String> fileContent = openAiFileApi.retrieveFileContent("file-id");

低级文件 API 示例

  • OpenAiFileApiIT.java 测试提供了一些关于如何使用轻量级文件 API 库的通用示例。

API Key 管理

Spring AI 通过 ApiKey 接口及其实现提供了灵活的 API 密钥管理功能。默认实现 SimpleApiKey 适用于大多数场景,但你也可以为更复杂的情况创建自定义实现。

默认配置

默认情况下,Spring Boot 自动配置会使用 spring.ai.openai.api-key 属性来创建一个 API 密钥 bean:

spring.ai.openai.api-key=your-api-key-here

自定义API密钥配置

您可以使用构建器模式,通过自定义的 ApiKey 实现来创建 OpenAiApi 的自定义实例:

ApiKey customApiKey = new ApiKey() {
@Override
public String getValue() {
// Custom logic to retrieve API key
return "your-api-key-here";
}
};

OpenAiApi openAiApi = OpenAiApi.builder()
.apiKey(customApiKey)
.build();

// Create a chat model with the custom OpenAiApi instance
OpenAiChatModel chatModel = OpenAiChatModel.builder()
.openAiApi(openAiApi)
.build();
// Build the ChatClient using the custom chat model
ChatClient openAiChatClient = ChatClient.builder(chatModel).build();

当您需要以下操作时,这非常有用:

  • 从安全密钥存储中检索API密钥

  • 动态轮换API密钥

  • 实现自定义的API密钥选择逻辑

使用额外参数配合OpenAI兼容服务器

与 OpenAI API 兼容的推理服务器,如 vLLM、Ollama 等,除了支持 OpenAI 标准 API 定义的参数外,通常还支持额外的参数。例如,这些服务器可能会接受诸如 top_krepetition_penalty 或其他采样控制参数,而这些参数是官方 OpenAI API 所不支持的。

extraBody选项允许您向这些服务器传递任意参数。在extraBody中提供的任何键值对都将包含在JSON请求的顶层,使您在使用Spring AI的OpenAI客户端时能够利用服务器特定的功能。

:::重要
extraBody 参数仅适用于与 OpenAI 兼容的服务器,而非官方的 OpenAI API。虽然官方的 OpenAI API 会忽略未知参数,但此参数在其中并无作用。请务必查阅您所用服务器的具体文档,以确定其支持哪些参数。
:::

使用属性配置

你可以通过Spring Boot属性来配置额外的参数。位于spring.ai.openai.chat.options.extra-body下的每个属性都会成为请求中的一个顶级参数:

spring.ai.openai.base-url=http://localhost:8000/v1
spring.ai.openai.chat.options.model=meta-llama/Llama-3-8B-Instruct
spring.ai.openai.chat.options.temperature=0.7
spring.ai.openai.chat.options.extra-body.top_k=50
spring.ai.openai.chat.options.extra-body.repetition_penalty=1.1

此配置将生成类似如下的 JSON 请求:

{
"model": "meta-llama/Llama-3-8B-Instruct",
"temperature": 0.7,
"top_k": 50,
"repetition_penalty": 1.1,
"messages": [...]
}

通过 Builder 进行运行时配置

你也可以在运行时使用选项构建器指定额外的参数:

ChatResponse response = chatModel.call(
new Prompt(
"Tell me a creative story",
OpenAiChatOptions.builder()
.model("meta-llama/Llama-3-8B-Instruct")
.temperature(0.7)
.extraBody(Map.of(
"top_k", 50,
"repetition_penalty", 1.1,
"frequency_penalty", 0.5
))
.build()
));

示例:vLLM 服务器

在使用vLLM运行Llama模型时,你可能需要用到专为vLLM设计的采样参数:

spring.ai.openai.base-url=http://localhost:8000/v1
spring.ai.openai.chat.options.model=meta-llama/Llama-3-70B-Instruct
spring.ai.openai.chat.options.extra-body.top_k=40
spring.ai.openai.chat.options.extra-body.top_p=0.95
spring.ai.openai.chat.options.extra-body.repetition_penalty=1.05
spring.ai.openai.chat.options.extra-body.min_p=0.05

请参阅 vLLM 文档 以获取完整支持的采样参数列表。

示例:Ollama服务器

当通过OpenAI兼容端点使用Ollama时,可以传递Ollama特有的参数:

OpenAiChatOptions options = OpenAiChatOptions.builder()
.model("llama3.2")
.extraBody(Map.of(
"num_predict", 100,
"top_k", 40,
"repeat_penalty", 1.1
))
.build();

ChatResponse response = chatModel.call(new Prompt("Generate text", options));

请查阅 Ollama API 文档 以了解可用的参数。

备注

extraBody 参数接受任何 Map<String, Object>,允许你传递目标服务器支持的任何参数。Spring AI 不会验证这些参数——它们会被直接传递给服务器。此设计为处理各种 OpenAI 兼容实现提供了最大的灵活性。

推理模型中的推理内容

一些支持推理模型(如DeepSeek R1、配备推理解析器的vLLM)的OpenAI兼容服务器,会通过其API响应中的reasoning_content字段暴露模型的内部思维链。该字段包含模型为得出最终答案所使用的逐步推理过程。

Spring AI 将 JSON 响应中的这个字段映射到 AssistantMessage 元数据中的 reasoningContent 键。

important

关于 reasoning_content 可用性的重要区别:

  • OpenAI 兼容服务器 (DeepSeek, vLLM): 在 Chat Completions API 响应中暴露 reasoning_content

  • 官方 OpenAI 模型 (GPT-5, o1, o3): 在 Chat Completions API 响应中暴露推理文本 ❌

官方 OpenAI 推理模型在使用 Chat Completions API 时会隐藏思维链内容。它们仅在用量统计中暴露 reasoning_tokens 计数。要访问官方 OpenAI 模型的实际推理文本,必须使用 OpenAI 的 Responses API(这是一个单独的端点,本客户端目前不支持)。

回退行为: 当服务器未提供 reasoning_content 时(例如,官方的 OpenAI Chat Completions),reasoningContent 元数据字段将是一个空字符串。

访问推理内容

在使用兼容服务器时,您可以从响应元数据中访问推理内容。

直接使用 ChatModel:

// Configure to use DeepSeek R1 or vLLM with a reasoning model
ChatResponse response = chatModel.call(
new Prompt("Which number is larger: 9.11 or 9.8?")
);

// Get the assistant message
AssistantMessage message = response.getResult().getOutput();

// Access the reasoning content from metadata
String reasoning = message.getMetadata().get("reasoningContent");
if (reasoning != null && !reasoning.isEmpty()) {
System.out.println("Model's reasoning process:");
System.out.println(reasoning);
}

// The final answer is in the regular content
System.out.println("\nFinal answer:");
System.out.println(message.getContent());

使用 ChatClient:

ChatClient chatClient = ChatClient.create(chatModel);

String result = chatClient.prompt()
.user("Which number is larger: 9.11 or 9.8?")
.call()
.chatResponse()
.getResult()
.getOutput()
.getContent();

// To access reasoning content with ChatClient, retrieve the full response
ChatResponse response = chatClient.prompt()
.user("Which number is larger: 9.11 or 9.8?")
.call()
.chatResponse();

AssistantMessage message = response.getResult().getOutput();
String reasoning = message.getMetadata().get("reasoningContent");

流式推理内容

在使用流式响应时,推理内容会像常规消息内容一样跨数据块进行累积:

Flux<ChatResponse> responseFlux = chatModel.stream(
new Prompt("Solve this logic puzzle...")
);

StringBuilder reasoning = new StringBuilder();
StringBuilder answer = new StringBuilder();

responseFlux.subscribe(chunk -> {
AssistantMessage message = chunk.getResult().getOutput();

// Accumulate reasoning if present
String reasoningChunk = message.getMetadata().get("reasoningContent");
if (reasoningChunk != null) {
reasoning.append(reasoningChunk);
}

// Accumulate the final answer
if (message.getContent() != null) {
answer.append(message.getContent());
}
});

示例:DeepSeek R1

DeepSeek R1 是一种推理模型,会展示其内部推理过程:

spring.ai.openai.api-key=${DEEPSEEK_API_KEY}
spring.ai.openai.base-url=https://api.deepseek.com
spring.ai.openai.chat.options.model=deepseek-reasoner

当你向DeepSeek R1发出请求时,响应将同时包含推理内容(模型的思考过程)和最终答案。

更多关于推理模型的详细信息,请参阅 DeepSeek API 文档

示例:vLLM与推理解析器

vLLM 在配置推理解析器时支持推理模型:

vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B \
--enable-reasoning \
--reasoning-parser deepseek_r1
spring.ai.openai.base-url=http://localhost:8000/v1
spring.ai.openai.chat.options.model=deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B

请查阅 vLLM 推理输出文档 以了解支持的推理模型和解析器。

备注

reasoning_content 的可用性完全取决于您使用的推理服务器。并非所有与 OpenAI 兼容的服务器都会暴露推理内容,即使在使用具备推理能力的模型时也是如此。请务必查阅您服务器的 API 文档,以了解响应中可用的字段。