1. 引言
对于使用 Java 语言的 Spring 程序员来说,SpringAI 框架会是一个比 LangChain4j 更熟悉、也更有影响力的框架。SpringAI 是 Spring 社区推出的一个专门与大模型交互的框架,其基础功能和 LangChain4j 大致相同。不过目前阶段,SpringAI 框架的功能还远没有 LangChain4j 成熟,甚至它的 Maven 依赖都还没有发布到 Maven 中央仓库上,目前算是体验版。
本文将通过一个完整的 HelloWorld 项目,带大家体验 SpringAI 框架的核心功能,包括文本聊天、图片生成、文本向量化以及工具函数调用。
2. 环境准备与项目搭建
首先,我们需要创建一个 SpringBoot 工程。需要注意的是,目前 SpringAI 框架依赖的 SpringBoot 版本必须是 3.2.x 或 3.3.x。
2.1 添加 Maven 依赖
在 pom.xml 中引入 SpringAI 的 BOM 以及具体的 AI 平台接入包(以清华智谱 AI 为例):
<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>
<groupId>com.roy</groupId>
<artifactId>SpringAIDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringAIDemo</name>
<url>http://maven.apache.org</url>
<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>1.0.0-M3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.2.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!– 清华智谱AI接入包 –>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-zhipuai-spring-boot-starter</artifactId>
</dependency>
</dependencies>
<repositories>
<!– Spring Milestone 仓库 –>
<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>
<!– 阿里云镜像,用来下载SpringAI之外的依赖 –>
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
</project>
2.2 配置 API Key
在 application.properties 或 application.yml 中配置智谱 AI 的 API Key:
spring.ai.zhipuai.api-key=你的智谱AI_API_Key
3. ChatModel:文本聊天
SpringAI 的使用方式是非常简单的 SpringBoot 风格:下载依赖 -> 配置参数 -> 引入组件。
创建一个 Controller,注入 ChatModel 即可完成与智谱 AI 的聊天交互:
package com.roy.controller;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChatController {
@Resource
private ChatModel chatModel;
@RequestMapping("/chat")
public String chat(@RequestParam("message") String message) {
return chatModel.call(message);
}
}
启动服务,访问 http://localhost:8080/chat?message=你是谁 就能拿到 AI 的交互结果。
4. ImageModel:图片生成
SpringAI 同样支持图片生成功能。注入 ImageModel 组件,调用 call 方法即可:
package com.roy.controller;
import jakarta.annotation.Resource;
import org.springframework.ai.image.ImageModel;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ImageController {
@Resource
private ImageModel imageModel;
@GetMapping("/image")
public String image(@RequestParam("message") String message) {
ImageResponse response = imageModel.call(new ImagePrompt(message));
return response.getResult().getOutput().getUrl();
}
}
启动服务,访问测试端口,就能拿到一个图片地址,访问这个地址就能看到生成的图片。
5. EmbeddingModel:文本向量化
文本向量化是 RAG 应用的基础。SpringAI 通过 EmbeddingModel 组件轻松实现:
package com.roy.controller;
import jakarta.annotation.Resource;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmbeddingController {
@Resource
private EmbeddingModel embeddingModel;
@GetMapping("/embedding")
public float[] embedding(@RequestParam("message") String message) {
return embeddingModel.embed(message);
}
}
6. FunctionCall:工具函数
SpringAI 同样支持本地工具函数。有两种实现方式:基于 Spring 容器的 Bean 方式和基于 FunctionCallbackWrapper 的方式。
6.1 基于 Spring 容器的方式
首先,定义一个实现 Function 接口的 Bean,并通过 @Description 注解描述工具的作用:
package com.roy.tools;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.function.Function;
@Component
@Description("获得指定地点的当前时间")
public class DateFunction implements Function<DateFunction.Request, DateFunction.Response> {
public record Request(@Schema(description = "地点") String address) {}
public record Response(String date) {}
@Override
public Response apply(Request request) {
System.out.println(request.address);
return new Response(String.format("%s的当前时间是%s", request.address, LocalDateTime.now()));
}
}
然后在 Controller 中通过 ZhiPuAiChatOptions 指定要使用的工具函数:
@RequestMapping("/function")
public String function(@RequestParam("message") String message) {
Prompt prompt = new Prompt(message,
ZhiPuAiChatOptions.builder().withFunction("dateFunction").build());
Generation result = chatModel.call(prompt).getResult();
return null == result ? "" : result.getOutput().getContent();
}
6.2 基于 FunctionCallbackWrapper 的方式
这种方式可以摆脱 Spring 容器的限制,并且可以同时对提示词进行增强:
@RequestMapping("/function2")
public String function2(@RequestParam("message") String message) {
// 添加提示消息
SystemMessage systemMessage = new SystemMessage("请用中文回答");
UserMessage userMessage = new UserMessage(message);
// 构建工具集
FunctionCallbackWrapper<DateFunction.Request, DateFunction.Response> wrapper =
FunctionCallbackWrapper.builder(new DateFunction())
.withName("dateService")
.withDescription("获取指定地点的当前时间")
.build();
// 构建prompt
Prompt prompt = new Prompt(List.of(systemMessage, userMessage),
ZhiPuAiChatOptions.builder().withFunctionCallbacks(List.of(wrapper)).build());
Generation result = chatModel.call(prompt).getResult();
return null == result ? "" : result.getOutput().getContent();
}
访问测试接口,就可以让 AI 大模型结合这个工具获取某个城市当前的时间。
7. 总结
SpringAI 框架秉承了 Spring 一贯的风格:约定大于配置。应用层只需要记住几个重要的接口,未来对接其他 AI 大模型,基本上只要修改一下配置就可以了,应用层几乎可以不做任何改动。
当然,SpringAI 框架还在测试阶段,都还没有推出正式版本,所以目前 SpringAI 框架的功能整体还不如 LangChain4j 框架稳定。如果你真的想要用上 SpringAI,还需要持续关注一段时间。
另外,SpringAI 框架只是 AI 大模型的接入层,真正核心的还是 AI 大模型。而目前各个 AI 大模型的成熟度以及提供的功能都不尽相同,各种多模态功能也层出不穷。比如文字和声音互转、文字生视频、个性化智能体等各种功能场景,不同 AI 大模型的支持程度也不同,这也需要持续关注。



