OpenAI Embeddings
Spring AI 支持 OpenAI 的文本 embeddings 模型。 OpenAI 的文本 embeddings 测量文本字符串的相关性。 embedding 是浮点数(列表)的向量。两个向量之间的距离衡量它们的相关性。小距离表示高相关性,大距离表示低相关性。
先决条件
您需要创建一个 API 来访问 OpenAI embeddings 模型。
在 https://platform.openai.com/signup[OpenAI 注册页面] 创建账户,并在 https://platform.openai.com/account/api-keys[API Keys 页面] 生成 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");
添加仓库和 BOM
Spring AI 工件发布在 Maven Central 和 Spring Snapshot 仓库中。 请参阅 Artifact Repositories 部分,将这些仓库添加到您的构建系统。
为了帮助依赖管理,Spring AI 提供了一个 BOM(物料清单),以确保在整个项目中使用一致版本的 Spring AI。请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建系统。
自动配置
[注意]
Spring AI 自动配置、starter 模块的工件名称发生了重大变化。 请参阅 https://docs.spring.io/spring-ai/reference/upgrade-notes.html[升级说明] 了解更多信息。
Spring AI 为 OpenAI Embedding Model 提供 Spring Boot 自动配置。
要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
或添加到您的 Gradle build.gradle 构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
提示:请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建文件。