浅尝 Spring AI【使用超级简单~】

发布于:2025-07-13 ⋅ 阅读:(19) ⋅ 点赞:(0)

一直想要体验下 Spring AI,最近自己的一个工具有这个需求,所以这里准备使用下。其实使用起来超级简单。

1.IDEA 新建 Spring项目

1)这里可以根据自己的喜好选择 项目名、jdk版本等

image-20250711115133493

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

image-20250711115054272

2.项目代码与配置

项目目录文件结构:
在这里插入图片描述

1)配置 application.yml

这里我对接的是 硅基流动的api,然后选择的模型是 deepseek-ai/DeepSeek-V3。这些都可以自由选择,如果你之前没有注册使用过这种模型api提供商,可以先看下第三节。

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)配置客户端

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

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请求下

http://localhost:8080/ai/chat?prompt=Spring AI 怎么使用

在这里插入图片描述

3.硅基流动注册与使用

我的邀请注册链接:https://cloud.siliconflow.cn/i/19016f2p,注册完成后可以新建API密钥。

1)新建API密钥并复制粘贴到项目中

在这里插入图片描述

2)选择想要使用的模型

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

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到