浅尝 Spring AI
一直想要体验下 Spring AI,最近自己的一个工具有这个需求,所以这里准备使用下。
1.IDEA 新建 Spring项目
1)这里可以根据自己的喜好选择 项目名、jdk版本等

2)这里选择 在ai中选择 openAI 即可。然后我另外选择了一个 Spring Web,因为我是需要对外提供API的。

2.项目代码与配置
项目目录文件结构:

1)配置 application.yml
这里我对接的是 硅基流动的api,然后选择的模型是 deepseek-ai/DeepSeek-V3。这些都可以自由选择,如果你之前没有注册使用过这种模型api提供商,可以先看下第三节。
1 2 3 4 5 6 7 8 9 10
| spring: application: name: x-ai ai: openai: api-key: sk-qoiiuryvclnaqbmhqqquyg*****vyrincprsfvirxafrr base-url: https://api.siliconflow.cn/ chat: options: model: deepseek-ai/DeepSeek-V3
|
2)配置客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package com.xr.xai.config;
import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.openai.OpenAiChatModel; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class CommonConfiguration { @Bean public ChatClient chatClient(OpenAiChatModel model){ return ChatClient .builder(model) .build(); } }
|
3)编写 ChatController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package com.xr.xai.controller;
import org.springframework.ai.chat.client.ChatClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux;
@RestController @RequestMapping("/ai") public class ChatController { @Autowired private ChatClient chatClient;
@RequestMapping(value = "/chat", produces = "text/html;charset=utf8") public Flux<String> chat(String prompt) { return chatClient.prompt() .user(prompt) .stream() .content(); }
}
|
完成以上,就可以编译运行了。怎么测试呢?
在浏览器上输入这个URL 或者 postman请求下
1
| http://localhost:8080/ai/chat?prompt=Spring AI 怎么使用
|

3.硅基流动注册与使用
我的邀请注册链接:https://cloud.siliconflow.cn/i/19016f2p,注册完成后可以新建API密钥。
1)新建API密钥并复制粘贴到项目中

2)选择想要使用的模型
可以使用的模型有很多,有些是低参数的是免费的,这里你想要使用什么,就把他的名字 复制粘贴到项目配置中。
