OpenAI Chat
Spring AI 支持来自 OpenAI 的各种 AI 语言模型,OpenAI 是 ChatGPT 背后的公司,通过创建行业领先的文本生成模型和 embeddings,在激发人们对 AI 驱动的文本生成的兴趣方面发挥了重要作用。
Prerequisites
您需要使用 OpenAI 创建 API 才能访问 ChatGPT 模型。
在 OpenAI signup page 创建账户,并在 API Keys page 生成 token。
Spring AI 项目定义了一个名为 spring.ai.openai.api-key 的配置属性,您应将其设置为从 openai.com 获得的 API Key 值。
您可以在 application.properties 文件中设置此配置属性:
spring.ai.openai.api-key=<your-openai-api-key>
为了在处理敏感信息(如 API keys)时增强安全性,您可以使用 Spring Expression Language (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");
Add Repositories and BOM
Spring AI artifacts 发布在 Maven Central 和 Spring Snapshot 仓库中。 请参阅 Artifact Repositories 部分,将这些仓库添加到您的构建系统中。
为了帮助进行依赖管理,Spring AI 提供了一个 BOM (bill of materials),以确保在整个项目中使用一致版本的 Spring AI。请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建系统中。
Auto-configuration
注意: Spring AI auto-configuration、starter modules 的 artifact 名称发生了重大变化。 请参阅 upgrade notes 了解更多信息。
Spring AI 为 OpenAI Chat Client 提供 Spring Boot auto-configuration。
要启用它,请将以下依赖项添加到项目的 Maven pom.xml 或 Gradle build.gradle 构建文件中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
提示: 请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建文件中。
Chat Properties
Retry Properties
前缀 spring.ai.retry 是用于配置 OpenAI chat model 的 retry 机制的属性前缀。
| Property | Description | Default |
|---|---|---|
| spring.ai.retry.max-attempts | 最大重试次数。 | 10 |
| spring.ai.retry.backoff.initial-interval | 指数退避策略的初始睡眠持续时间。 | 2 sec. |
| spring.ai.retry.backoff.multiplier | 退避间隔乘数。 | 5 |
| spring.ai.retry.backoff.max-interval | 最大退避持续时间。 | 3 min. |
| spring.ai.retry.on-client-errors | 如果为 false,抛出 NonTransientAiException,并且不对 4xx 客户端错误代码尝试重试 | false |
| spring.ai.retry.exclude-on-http-codes | 不应触发重试的 HTTP 状态代码列表(例如,抛出 NonTransientAiException)。 | empty |
| spring.ai.retry.on-http-codes | 应触发重试的 HTTP 状态代码列表(例如,抛出 TransientAiException)。 | empty |