差点忘了还有spring ai这个包
之前经常看一些LLM的工具,类似于ollama,chatbox等等,这些都类似于是个独立工具,真的在代码里使用的话可能没那么方便
正好看了下spring有个spring-ai的包,可以来使用试下
首先我们要用比较新的jdk版本,比如jdk17,然后需要使用springboot比较新的版本,比如3.2.3,但是不建议使用最新稳定版,3.4.x,因为会有bug,别问我怎么知道的。
真的是折腾,
简单分享下吧
需要在pom中增加仓库定义1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<!-- 仓库定义 -->
<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>
然后增加依赖1
2
3
4
5
6
7
8
9
10
11<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0-M5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
引入主要的几个包1
2
3
4
5
6
7
8
9
10
11
12
13
14<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>
代码也很简单,但是不确定是api限流太严重还是啥,响应慢的离谱1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ChatController {
private final ChatClient chatClient;
public ChatController(ChatClient.Builder builder) {
this.chatClient = builder.defaultSystem("你是个资深服务端架构师").build();
}
public String demo( { String message)
message = "怎么学习java";
String response = chatClient.prompt()
.user(message)
.call().content();
return response;
}
}
对的,甚至把prompt写死了
这里经过了好几个包版本的调整
原先比较早的0.8的不支持接口的自定义路径,因为要用火山的接口,它的接口跟openai是不一样的,后面有个v3啥的
所以需要增加最下面一行1
2
3spring.ai.openai.base-url=https://ark.cn-beijing.volces.com/api/v3
spring.ai.openai.chat.options.model=deepseek-r1-250120
spring.ai.openai.chat.completions-path=/chat/completions
但是可以从上面的图里看出来,响应非常慢,简直不能忍