1. 模型 API KEY 准备

首先需要在以下平台去获取一个API KEY

  • IFLY (讯飞星火)

平台 lite 模型可以无限次调用,学习很好用 (๑•̀ㅂ•́)و✧ 也有其他的模型可供调用

  • 阿里云百炼平台

多个模型有免费额度

  • 硅基流动

有免费模型


2. 项目构建

  1. 创建一个新的工程

  2. 首先需要引入Maven依赖

xml
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter</artifactId>  
    <version>3.4.5</version>  
</dependency>
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId>  
    <version>3.4.5</version>  
</dependency>
<!--使用阿里百炼模型时引用-->
<dependency>  
    <groupId>com.alibaba.cloud.ai</groupId>  
    <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>  
    <version>1.0.0.2</version>  
</dependency>
<!--使用其他服务商模型时引用-->
<dependency>  
    <groupId>org.springframework.ai</groupId>  
    <artifactId>spring-ai-starter-model-openai</artifactId>
    <version>1.0.0</version>   
</dependency>
  1. 如果依赖引入失败,可能是仓库问题,参考以下配置
xml
    <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>
        <repository>
            <id>sonatype</id>
            <name>OSS Sonatype</name>
            <url>https://oss.sonatype.org/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>aliyunmaven</id>
            <name>aliyun</name>
            <url>https://maven.aliyun.com/repository/public</url>
        </repository>
    </repositories>

3. 开发

3.1. 阿里百炼

  1. 正确引入依赖
  2. 创建启动类
java
@SpringBootApplication  
public class AlibabaApplication {  
    public static void main(String[] args) {  
        SpringApplication.run(AlibabaApplication.class, args);  
    }  
}
  1. 创建配置文件 application.yml
yaml
server:  
  port: 10002  
  
spring:  
  application:  
    name: alibaba-chat-demo  
  ai:  
    dashscope:  
      api-key: ${API_KEY} # 配置在阿里百炼平台获取到的API KEY
  1. 创建 controller
java
@RestController
@RequestMapping("alibaba/chat-client")
public class AlibabaChatClientController {

    private static final String DEFAULT_PROMPT = "你好,介绍下你自己!";

    private final ChatClient alibabaChatClient;
    private final ChatModel chatModel;

    public AlibabaChatClientController(ChatModel chatModel) {
        this.chatModel = chatModel;

        // 构造时,可以设置 ChatClient 的参数
        // {@link org.springframework.ai.chat.client.ChatClient};
        this.alibabaChatClient = ChatClient.builder(chatModel)
                // 实现 Chat Memory 的 Advisor
                // 在使用 Chat Memory 时,需要指定对话 ID,以便 Spring AI 处理上下文。
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build()
                )
                // 实现 Logger 的 Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withTopP(0.7)
                                .build()
                )
                .build();
    }

    // 也可以使用如下的方式注入 ChatClient
    // public IFlyChatClientController(ChatClient.Builder chatClientBuilder) {
    //
    //  	this.alibabaChatClient = chatClientBuilder.build();
    // }

    /**
     * ChatClient 简单调用
     */
    @GetMapping("/simple/chat")
    public String simpleChat() {

        return alibabaChatClient.prompt(DEFAULT_PROMPT).call().content();
    }

    /**
     * ChatClient 流式调用
     */
    @GetMapping("/stream/chat")
    public Flux<String> streamChat() {

        return alibabaChatClient.prompt(DEFAULT_PROMPT).stream().content();
    }

    /**
     * ChatClient 流式响应
     */
    @GetMapping(value = "/stream/response")
    public Flux<ServerSentEvent<String>> simpleChat(@RequestParam("message") String message) {
        try {
            return alibabaChatClient.prompt()
                    .user(message)
                    .stream()
                    .content()
                    .map(content -> ServerSentEvent.<String>builder()
                            .data(content)
                            .build());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return Flux.just(ServerSentEvent.<String>builder().data("错误").build());
    }
}
  1. 启动测试

Tips:

阿里百炼平台也支持 openai 格式,但直接使用 spring-ai-alibaba 会更加方便。


3.2. 类openai,使用IFly

  1. 正确引入依赖
  2. 创建启动类
java
@SpringBootApplication  
public class IFlyApplication {  
    public static void main(String[] args) {  
        SpringApplication.run(IFlyApplication.class, args);  
    }  
}
  1. 创建配置文件 application.yml
yaml
  1. 创建 controller
java
@RestController
@RequestMapping("iFly/chat-client")
public class IFlyChatClientController {

    private static final String DEFAULT_PROMPT = "你好,介绍下你自己!";

    private final ChatClient iFlyOpenAiChatClient;
    private final ChatModel chatModel;

    public IFlyChatClientController(ChatModel chatModel) {
        this.chatModel = chatModel;

        // 构造时,可以设置 ChatClient 的参数
        // {@link org.springframework.ai.chat.client.ChatClient};
        this.iFlyOpenAiChatClient = ChatClient.builder(chatModel)
                // 实现 Chat Memory 的 Advisor
                // 在使用 Chat Memory 时,需要指定对话 ID,以便 Spring AI 处理上下文。
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build()
                )
                // 实现 Logger 的 Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        OpenAiChatOptions.builder()
                                .topP(0.7)
                                .build()
                )
                .build();
    }

    // 也可以使用如下的方式注入 ChatClient
    // public IFlyChatClientController(ChatClient.Builder chatClientBuilder) {
    //
    //  	this.iFlyOpenAiChatClient = chatClientBuilder.build();
    // }

    /**
     * ChatClient 简单调用
     */
    @GetMapping("/simple/chat")
    public String simpleChat() {

        return iFlyOpenAiChatClient.prompt(DEFAULT_PROMPT).call().content();
    }

    /**
     * ChatClient 流式调用
     */
    @GetMapping("/stream/chat")
    public Flux<String> streamChat(HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        return iFlyOpenAiChatClient.prompt(DEFAULT_PROMPT).stream().content();
    }

    /**
     * ChatClient 流式响应
     */
    @GetMapping(value = "/stream/response")
    public Flux<ServerSentEvent<String>> simpleChat(@RequestParam("message") String message) {
        return iFlyOpenAiChatClient.prompt()
                .user(message)
                .stream()
                .content()
                .map(content -> ServerSentEvent.<String>builder()
                        .data(content)
                        .build());
    }
}

详细代码可见: https://github.com/jizuiba/spring-ai-demo