watsonx.ai 嵌入
通过 Watsonx.ai,您可以运行各种大型语言模型(LLMs)并从中生成嵌入。Spring AI 支持使用 WatsonxAiEmbeddingModel 来处理 Watsonx.ai 的文本嵌入。
嵌入(embedding)是一个由浮点数组成的向量(列表)。两个向量之间的距离衡量了它们之间的相关性。较小的距离表示高度相关,而较大的距离表示低相关性。
先决条件
首先,您需要拥有一个 watsonx.ai 的 SaaS 实例(以及一个 IBM Cloud 帐户)。
请参考 免费试用 免费体验 watsonx.ai。
更多信息可以在这里找到。
添加仓库和 BOM
Spring AI 构件已发布在 Maven Central 和 Spring Snapshot 仓库中。请参阅 Repositories 部分,将这些仓库添加到您的构建系统中。
为了帮助进行依赖管理,Spring AI 提供了一个 BOM(物料清单),以确保在整个项目中使用的 Spring AI 版本一致。请参考 依赖管理 部分,将 Spring AI BOM 添加到您的构建系统中。
自动配置
Spring AI 提供了对 Watsonx.ai 嵌入模型的 Spring Boot 自动配置。要启用它,请将以下依赖项添加到 Maven 的 pom.xml 文件中:
<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-watsonx-ai-spring-boot-starter</artifactId>
</dependency>
或者到你的 Gradle build.gradle 构建文件中。
dependencies {
    implementation 'org.springframework.ai:spring-ai-watsonx-ai-spring-boot-starter'
}
请参考 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。
spring.ai.watsonx.embedding.options.* 属性用于配置所有嵌入请求所使用的默认选项。
嵌入属性
前缀 spring.ai.watsonx.ai 用作属性前缀,允许你连接到 watsonx.ai。
| 属性 | 描述 | 默认值 | 
|---|---|---|
| spring.ai.watsonx.ai.base-url | 连接的 URL | us-south.ml.cloud.ibm.com | 
| spring.ai.watsonx.ai.embedding-endpoint | 文本端点 | ml/v1/text/embeddings?version=2023-05-29 | 
| spring.ai.watsonx.ai.project-id | 项目 ID | - | 
| spring.ai.watsonx.ai.iam-token | IBM Cloud 账户 IAM 令牌 | - | 
spring.ai.watsonx.embedding.options 前缀是用于配置 Watsonx.ai 的 EmbeddingModel 实现的属性前缀。
| 属性 | 描述 | 默认值 | 
|---|---|---|
| spring.ai.watsonx.ai.embedding.enabled | 启用 Watsonx.ai 嵌入模型 | true | 
| spring.ai.watsonx.ai.embedding.options.model | 使用的嵌入模型 | ibm/slate-30m-english-rtrvr | 
运行时选项
WatsonxAiEmbeddingOptions.java 提供了 Watsonx.ai 的配置选项,例如要使用的模型。
默认选项也可以通过 spring.ai.watsonx.embedding.options 属性进行配置。
EmbeddingResponse embeddingResponse = embeddingModel.call(
    new EmbeddingRequest(List.of("Hello World", "World is big and salvation is near"),
        WatsonxAiEmbeddingOptions.create()
            .withModel("Different-Embedding-Model-Deployment-Name"))
);
示例控制器
这将创建一个 EmbeddingModel 实现,你可以将其注入到你的类中。以下是一个使用 EmbeddingModel 实现的简单 @Controller 类示例。
@RestController
public class EmbeddingController {
    private final EmbeddingModel embeddingModel;
    @Autowired
    public EmbeddingController(EmbeddingModel embeddingModel) {
        this.embeddingModel = embeddingModel;
    }
    @GetMapping("/ai/embedding")
    public ResponseEntity<Embedding> embedding(@RequestParam String text) {
        EmbeddingResponse response = this.embeddingModel.embedForResponse(List.of(text));
        return ResponseEntity.ok(response.getResult());
    }
}