SpringAI调用硅基流动免费模型

一、引入Spring AI

新建一个Spring Boot的工程,在工程中引入Spring AI的依赖,Spring AI支持Ollma、类OpenAI的接口,这两个引入的pom不一样,这里示例中是使用的硅基流动的模型

<!-- Spring Boot版本要 2.x 或者 3.x以上--> 
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.6</version>
</parent>

<!-- Spring AI -->  
<properties>
	<spring-ai.version>1.0.0-M6</spring-ai.version>
</properties>

<dependency>  
    <groupId>org.springframework.ai</groupId>  
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>  
    <version>${spring-ai.version}</version>  
</dependency>

这里为了展示调用结果,同时引入Spring Boot Web相关依赖,使用restful方式调用

<!-- Spring Boot -->  
<properties>
	<spring-boot.version>3.4.0</spring-boot.version>
</properties>

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId>  
    <version>${spring-boot.version}</version>  
</dependency>

二、配置模型接口信息

这里使用的是硅基流动中Qwen/Qwen2.5-7B-Instruct模型,也可以其他的对话模型

server:  
  port: 9000  
  
spring:  
  ai:  
    openai:  
      api-key: ${密钥}  
      base-url: https://api.siliconflow.cn/  
      chat:  
        options:  
          model: Qwen/Qwen2.5-7B-Instruct  
        completions-path: /v1/chat/completions

三、使用Spring AI调用模型

编写控制器 OpenAiChatClientController 实现调用逻辑,可以设置默认的系统Prompt,定义模型的参数

package com.renne.ai.learn.chat.controller;  
  
import jakarta.servlet.http.HttpServletResponse;  
import org.springframework.ai.chat.client.ChatClient;  
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;  
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;  
import org.springframework.ai.chat.memory.InMemoryChatMemory;  
import org.springframework.ai.openai.OpenAiChatOptions;  
import org.springframework.http.MediaType;  
import org.springframework.http.codec.ServerSentEvent;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.RestController;  
import reactor.core.publisher.Flux;  
  
  
@RestController  
@RequestMapping("/openai/chat")  
public class OpenAiChatClientController {  
  
    private final ChatClient openAiChatClient;  
  
    private static final String DEFAULT_PROMPT = "你是一个聊天助手,请根据用户提问回答!";  
  
     public OpenAiChatClientController(ChatClient.Builder chatClientBuilder) {  
       this.openAiChatClient = chatClientBuilder  
             .defaultSystem(DEFAULT_PROMPT)  
              // 实现 Chat Memory 的 Advisor              // 在使用 Chat Memory 时,需要指定对话 ID,以便 Spring AI 处理上下文。  
              .defaultAdvisors(  
                    new MessageChatMemoryAdvisor(new InMemoryChatMemory())  
              )  
              // 实现 Logger 的 Advisor              
              .defaultAdvisors(  
                    new SimpleLoggerAdvisor()  
              )  
              // 设置 ChatClient 中 ChatModel 的 Options 参数  
              .defaultOptions(  
                    OpenAiChatOptions.builder()  
                          .topP(0.7)  
                          .build()  
              )  
             .build();  
     }  
  
    /**  
     * ChatClient 简单调用  
     */  
    @GetMapping("/simple/chat")  
    public String simpleChat(@RequestParam String message) {  
       return openAiChatClient  
             .prompt(message).call().content();  
    }  
    
	/**  
	 * ChatClient 简单调用  
	 * 默认使用 InMemoryChatMemory  
	 ** @param message 消息  
	 * @param chatId  会话ID  
	 */@GetMapping("/simple/chat")  
	public String simpleChat(@RequestParam String message, @RequestParam String chatId) {  
	    return openAiChatClient  
	          .prompt(message)  
	              .advisors(a -> a  
	                       .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId) // 设置聊天会话ID  
	                       .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)) // 设置聊天记录检索数量  
	          .call().content();  
	}
  
    /**  
     * ChatClient 流式调用  
     */  
    @GetMapping("/stream/chat")  
    public Flux<String> streamChat(@RequestParam String message,  
                            HttpServletResponse response) {  
  
       response.setCharacterEncoding("UTF-8");  
       return openAiChatClient.prompt(message).stream().content();  
    }  
  
    /**  
     * ChatClient 流式响应  
     */  
    @GetMapping(value = "/stream/response", produces = MediaType.TEXT_EVENT_STREAM_VALUE)  
    public Flux<ServerSentEvent<String>> streamChat(@RequestParam String message) {  
       return openAiChatClient.prompt()  
             .user(message)  
             .stream()  
             .content()  
             .map(content -> ServerSentEvent.<String>builder()  
                   .data(content)  
                   .build());  
    }  
  
}

使用InMemoryChatMemory聊天记录的存储,可以让模型记住对话记录,结合上下文去回答,chatId就是会话窗口的id,在这个id不变的情况下,它会自定义的去在总结100条对话记录,然后再回答你的问题

调用streamChat接口可以得到模型的返回值
在这里插入图片描述

### 解决 PP-OCRv4 出现的错误 当遇到 `WARNING: The pretrained params backbone.blocks2.0.dw_conv.lab.scale not in model` 这样的警告时,这通常意味着预训练模型中的某些参数未能匹配到当前配置下的模型结构中[^2]。 对于此问题的一个有效解决方案是采用特定配置文件来适配预训练权重。具体操作方法如下: 通过指定配置文件 `ch_PP-OCRv4_det_student.yml` 并利用已有的最佳精度预训练模型 (`best_accuracy`) 来启动训练过程可以绕过上述不兼容的问题。执行命令如下所示: ```bash python3 tools/train.py -c configs/det/ch_PP-OCRv4/ch_PP-OCRv4_det_student.yml ``` 该方案不仅解决了参数缺失带来的警告,还能够继续于高质量的预训练成果进行微调,从而提升最终检测效果。 关于蒸馏的概念,在机器学习领域内指的是将大型复杂网络(teacher 模型)的知识迁移到小型简单网络(student 模型)。这里 student 和 teacher 的关系是指两个不同规模或架构的神经网络之间的指导与被指导的关系;其中 teacher 已经经过充分训练并具有良好的性能,而 student 则试图模仿前者的行为模式以达到相似的效果但保持更高效的计算特性。 至于提到的 `Traceback` 错误信息部分,由于未提供具体的跟踪堆栈详情,难以给出针对性建议。不过一般而言,这类报错往往涉及代码逻辑错误或是环境配置不当等问题。为了更好地帮助定位和解决问题,推荐记录完整的异常日志,并仔细检查最近修改过的代码片段以及确认依赖库版本的一致性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值