今天正在路上刷手机,突然看到群里有人发了一个链接,内容是Spring Cloud Alibaba AI 的使用,spring cloud AI的使用,于是就想着玩一玩试试,难度不大,就是有些文档的坑,这里做一个记录,后续会继续更新这个系列的,毕竟AI时代,我们springer也得搭一下顺风车。
一、文档阅读
我们看到文档其实描述了他的能力如下图,但是我们这里只尝试一下文生文的能力,其实说人话就是对话。
二、快速开始
我们基于文档描述开始搭建这个环境。
1、基于文档搭建环境
- 1、 引入依赖
我们按照文档的内容引入如下依赖。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2023.0.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-ai</artifactId>
</dependency>
</dependencies>
- 2、在 application.yml 配置文件中加入以下配置:
这个API-KEY需要你通过阿里云去获取,具体操作步骤:获取通义千问api-key
spring:
cloud:
ai:
tongyi:
chat:
options:
# Replace the following key with a valid API-KEY.
api-key: sk-a3d73b1709bf4a178c28ed7c8b3b5axx
- 3、编写聊天服务实现类,由 Spring AI 自动注入 ChatClient、StreamingChatClient,ChatClient 屏蔽底层通义大模型交互细节。
@Service
public class TongYiSimpleServiceImpl extends AbstractTongYiServiceImpl {
private final ChatClient chatClient;
private final StreamingChatClient streamingChatClient;
@Autowired
public TongYiSimpleServiceImpl(ChatClient chatClient, StreamingChatClient streamingChatClient) {
this.chatClient = chatClient;
this.streamingChatClient = streamingChatClient;
}
}
提供具体聊天逻辑实现
@Service
public class TongYiSimpleServiceImpl extends AbstractTongYiServiceImpl {
// ......
@Override
public String completion(String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return chatClient.call(prompt).getResult().getOutput().getContent();
}
@Override
public Map<String, String> streamCompletion(String message) {
StringBuilder fullContent = new StringBuilder();
streamingChatClient.stream(new Prompt(message))
.flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults()))
.map(content -> content.getOutput().getContent())
.doOnNext(fullContent::append)
.last()
.map(lastContent -> Map.of(message, fullContent.toString()))
.block();
log.info(fullContent.toString());
return Map.of(message, fullContent.toString());
}
}
编写 Spring 入口类并启动应用
@SpringBootApplication
public class TongYiApplication {
public static void main(String[] args) {
SpringApplication.run(TongYiApplication.class);
}
}
2、踩坑
2.1、maven导入失败
我在按照如上环境搭建好之后,reload maven发现报错。
从阿里云的maven镜像库里面拉不下来这些依赖。我用的maven库如下:
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
既然踩了坑,那就去文档找吧,估计不止我一个人踩坑。翻了一下找到了一个阿里cloud答疑问题的网址。spring cloud alibaba答疑区
最后翻到了一个这个spring ai maven无法引入问题解决
我们就按照他这个加一个maven的仓库配置,
<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