SpringAI 基础使用
前言
Spring AI,听着名字就感觉很好使用,快速上手,虽然功能没有太完善,但是社区活跃度很高,可以看看源码,让我们一起成为贡献者吧。
Spring AI
新建SpringBoot工程,然后添加以下依赖:
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>3.2.1</version>
</parent>
<groupId>com.qjc</groupId>
<artifactId>spring-ai-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
  <maven.compiler.source>17</maven.compiler.source>
  <maven.compiler.target>17</maven.compiler.target>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-bom</artifactId>
      <version>0.8.1-SNAPSHOT</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
  </dependency>
</dependencies>
<repositories>
  <repository>
    <id>spring-milestones</id>
    <name>Spring Milestones</name>
    <url>https://repo.spring.io/milestone</url>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
  </repository>
  <repository>
    <id>spring-snapshots</id>
    <name>Spring Snapshots</name>
    <url>https://repo.spring.io/snapshot</url>
    <releases>
      <enabled>false</enabled>
    </releases>
  </repository>
</repositories>
需要注意的是:由于版本的不同,可能会引起很多的问题,因为底层的版本使用的webflux,需要对应,这是我碰到的问题。
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
 </dependency>
然后定义一个ChatController:
package com.qjc.demo.controller;
import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/***
 * @projectName spring-ai-demo
 * @packageName com.qjc.demo.controller
 * @author qjc
 * @description TODO
 * @Email qjc1024@aliyun.com
 * @date 2024-10-16 09:05
 **/
@RestController
public class ChatController {
    @Autowired
    private ChatClient chatClient;
    @GetMapping("/chat")
    public String generate(@RequestParam String message) {
        return chatClient.call(message);
    }
}
由于依赖了:
<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
该starter中间接依赖了:
<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-spring-boot-autoconfigure</artifactId>
  <version>0.8.1-SNAPSHOT</version>
  <scope>compile</scope>
</dependency>
而该依赖中针对各个大模型提供了一个对应的自动配置类,比如OpenAiAutoConfiguration,而在该自动配置类中定义了以下几个Bean:
- OpenAiChatClient:文字聊天客户端
- OpenAiEmbeddingClient:文本向量化客户端
- OpenAiImageClient:文生图客户端
- OpenAiAudioTranscriptionClient:语音转文字客户端
这些Bean在创建时就会构造底层连接OpenAi的客户端OpenAiApi对象,其中会用到以下几种配置:
- OpenAiConnectionProperties:连接配置
- OpenAiChatProperties:聊天配置
- OpenAiEmbeddingProperties:向量化配置
- OpenAiImageProperties:文生图配置
- OpenAiAudioTranscriptionProperties:语音转文字配置
连接OpenAi的地址就apiKey就在OpenAiConnectionProperties中,比如application.properties的配置为:
spring.ai.openai.base-url=http://localhost:3000
spring.ai.openai.api-key=sk-xxxxx
ChatClient
所以,当我们需要基于OpenAI来提问时,直接注入ChatClient或OpenAiChatClient就可以了:
@Autowired
private ChatClient chatClient;
然后就可以使用call()方法来进行提问了:
@GetMapping("/chat")
public String chat(@RequestParam String message) {
    return chatClient.call(message);
}

ImageClient
使用下文生图的API:
@Autowired
private ImageClient imageClient;
@GetMapping("/image")
public String image(@RequestParam String message) {
    ImagePrompt imagePrompt = new ImagePrompt(message);
    ImageResponse imageResponse = imageClient.call(imagePrompt);
    return imageResponse.getResult().getOutput().getUrl();
}

 访问该URL即可拿到对应图片。
OpenAiAudioTranscriptionClient
也可以使用语音转文字的API:
@Value("classpath:/abc.flac")
private Resource audioFile;
@Autowired
private OpenAiAudioTranscriptionClient audioTranscriptionClient;
@GetMapping("/audio")
public String audio() {
    AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile);
    AudioTranscriptionResponse response = audioTranscriptionClient.call(transcriptionRequest);
    return response.getResult().getOutput();
}
EmbeddingClient
也可以用来对文本进行向量化:
@Autowired
private EmbeddingClient embeddingClient;
@GetMapping("/embedding")
public List<Double> embedding(@RequestParam String message) {
    return embeddingClient.embed(message);
}

总结
SpringBoot的自动配置,基于自动配置,我们只需要直接依赖注入对应的Client就可以使用了,还是那么的善解人意,LangChain4j虽好但不是我的最爱,我更加的偏向Spring AI,因为使用简单,扩展方便,拥有强大的自动配置等,更适用于SpringBoot 让开发更加简洁。