SpringAI入门
什么是Spring AI
Spring AI 项目旨在简化包含 AI 功能的应用程序的开发,避免不必要的复杂度。
Spring AI 干的事情,就是将应用程序(数据和API)与大模型连接起来。

搭建工程
创建 SpringBoot 项目。

在依赖选择中直接勾选需要的 AI 模型和向量数据库。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 继承 Spring Boot 父工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.5</version>
</parent>
<groupId>top.wwkq</groupId>
<artifactId>backend</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>
<spring-ai.version>1.1.0</spring-ai.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring AI BOM -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-deepseek</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.42</version>
</dependency>
</dependencies>
</project>
接着编写配置,参考官方文档:


server:
port: 8080 #端口
tomcat:
uri-encoding: UTF-8 #服务编码
spring:
application:
name: spring-ai-backend
ai:
deepseek: #openai配置
base-url: https://api.deepseek.com #api地址
api-key: ${OPENAI_API_KEY} #读取环境变量中的api key
chat:
options:
model: deepseek-chat #模型名称
普通聊天
参考官方文档中的示例代码编写

构造 ChatClient
ChatClient 是核心,负责与大模型交互,所以需要一个配置类。
package top.wwkq.config;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author 21129
*/
@Configuration
public class SpringAIConfig {
/**
* 创建并返回一个ChatClient的Spring Bean实例。
*
* @param builder 用于构建ChatClient实例的构建者对象
* @return 构建好的ChatClient实例
*/
@Bean
public ChatClient chatClient(ChatClient.Builder builder) {
return builder.build();
}
}
编写 ChatService