Spring Boot 集成硅基流动免费Qwen大模型实战——从零搭建支持多轮对话的网页应用 📅 2026/7/30 2:32:38 目录前言一、为什么选择硅基流动二、如何申请账号1、注册账号2、实名认证3、分配秘钥三、环境准备1、创建项目与引入依赖2、配置 application.yml3、定义数据模型3.1. 消息实体 ChatMessage3.2. 请求体 ChatRequest3.3. 响应体 ChatResponse四、封装调用服务1、控制器与多轮会话管理2、Thymeleaf 聊天页面3、运行与测试4、temperature 与 max_tokens 参数详解5、生产环境进阶建议五、总结前言大模型应用正快速走进日常开发但对很多同学来说『如何在一个普通 Spring Boot 项目里真正调通一个大模型接口』依然是第一步的门槛。本文以硅基流动SiliconFlow平台的免费模型 Qwen/Qwen2.5-7B-Instruct 为例手把手带你从零搭建一个支持多轮会话的网页对话应用所有代码均可直接复制运行。读完本文你将掌握如何用 Spring Boot 调用 OpenAI 兼容接口、如何设计多轮对话的上下文管理、以及如何用 Thymeleaf 快速做出可用的聊天界面。一、为什么选择硅基流动硅基流动是国内一家提供大模型推理 API 的云平台对开发者非常友好免费额度新用户注册即送额度Qwen2.5-7B-Instruct 等模型可免费试用适合学习与做 Demo如果只是想验证大模型的能力并不想直接部署一个大模型或者真的去购买千问的或最新Kimi的最新能力那么我们完全可以使用公开部署的免费模型OpenAI 兼容接口与 OpenAI 的 /v1/chat/completions 完全一致代码可直接复用迁移成本低模型丰富除 Qwen 系列外还提供 DeepSeek、GLM、Llama 等多种开源模型按需切换即可国内访问稳定无需科学上网延迟低文档与控制台均为中文。二、如何申请账号如果不想自己搭建本地大模型也不想只体验一种大模型那么完全可以使用硅基流动这种私有化了很多种常见大模型的网站平台助力你的AI应用。本节将来介绍一下如何注册申请账号以及申请key。1、注册账号硅基流动的网页地址如下硅基流动注册地址输入地址后在相应的页面中输入必要的信息完整注册即可。2、实名认证注册成功后在系统中需要进行实名认证界面如下按照网站的要求进行认证即可。3、分配秘钥与OpenAI一样要想在外部平台集成硅基流动中的模型也需要分配key然后在自己的应用程序中进行配置使用。管理界面如下输入信息描述之后点击新建就可以完成信key的创建一定要注意的是这里创建的key一定妥善保管不要泄露给第三方。经过以上的步骤后就可以进入下一步调用硅基流动中的大模型了。三、环境准备JDK 17 及以上本文基于 Java 17Maven 3.6 及以上一个硅基流动 API Key任意 IDEIntelliJ IDEA / Eclipse或者AI编辑器比如CodeBuddy或者Trae都可以。1、创建项目与引入依赖新建一个 Maven 项目只需要 Web、Thymeleaf 两个起步依赖即可。核心 pom.xml 如下?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version3.3.5/version relativePath/ /parent groupIdcom.example/groupId artifactIdsiliconflow-qwen-demo/artifactId version1.0.0/version namesiliconflow-qwen-demo/name descriptionSpring Boot Thymeleaf demo for SiliconFlow Qwen2.5-7B-Instruct chat/description properties java.version17/java.version /properties dependencies dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-thymeleaf/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-test/artifactId scopetest/scope /dependency /dependencies build plugins plugin groupIdorg.springframework.boot/groupId artifactIdspring-boot-maven-plugin/artifactId /plugin /plugins /build /project这里无需额外引入 OKHttp 或 OpenAI 的 SDK我们直接使用Spring 自带的 RestClient 已经足够好用。2、配置 application.yml接下来把模型名、接口地址和密钥放到配置文件中密钥建议用环境变量注入避免硬编码进代码仓库这里为了演示简单直接将密钥拷贝到配置文件中server: port: 8080 spring: application: name: siliconflow-qwen-demo thymeleaf: cache: false encoding: UTF-8 mode: HTML # 硅基流动配置 siliconflow: # 在 https://cloud.siliconflow.cn 注册后于“API密钥”页面生成 api: #key: 在此填入你的SiliconFlow_API_Key key: your_key url: https://api.siliconflow.cn/v1/chat/completions # 使用的模型 model: Qwen/Qwen2.5-7B-Instruct temperature: 0.7 max-tokens: 20483、定义数据模型硅基流动的请求/响应是标准的 OpenAI 格式我们先定义三个实体类。3.1. 消息实体 ChatMessagepublic class ChatMessage { private String role; // user / assistant / system private String content; // 省略构造方法、getter/setter }3.2. 请求体 ChatRequestpublic class ChatRequest { private String model; private ListChatMessage messages; private Double temperature; private Integer max_tokens; private Boolean stream; // 省略构造方法、getter/setter }3.3. 响应体 ChatResponsepublic class ChatResponse { private ListChoice choices; public static class Choice { private ChatMessage message; // getter/setter } // getter/setter }四、封装调用服务本节将重点介绍如何进行服务调用以及如何实现控制器和多轮会话的管理。核心逻辑把完整对话历史组装成请求POST 到硅基流动接口取回模型回复。其中 Value 注入的 temperature 和 maxTokens 即为采样参数。Service public class SiliconFlowService { private final RestClient restClient RestClient.create(); Value(${siliconflow.api.key}) private String apiKey; Value(${siliconflow.api.url}) private String apiUrl; Value(${siliconflow.model}) private String model; Value(${siliconflow.temperature:0.7}) private Double temperature; Value(${siliconflow.max-tokens:2048}) private Integer maxTokens; public String chat(ListChatMessage messages) { ChatRequest request new ChatRequest(model, messages, temperature, maxTokens, false); ChatResponse response restClient.post() .uri(apiUrl) .header(Authorization, Bearer apiKey) .header(Content-Type, application/json) .body(request) .retrieve() .body(ChatResponse.class); return response.getChoices().get(0).getMessage().getContent(); } }1、控制器与多轮会话管理多轮对话的关键是把『历史消息』保存下来。最简单稳妥的做法是用 HttpSession每个浏览器会话独立保存一份消息列表每次请求都带着完整历史发给模型模型便能『记住』上下文。RestController RequestMapping(/api) public class ChatController { private static final String HISTORY_KEY chatHistory; private static final String SYSTEM_PROMPT 你是一个有帮助的、友好的中文智能助手。; PostMapping(/chat) public ResponseEntityMapString, Object chat(RequestBody ChatInput input, HttpSession session) { ListChatMessage history getOrInitHistory(session); // 取出历史 history.add(new ChatMessage(user, input.message())); // 追加用户消息 String reply siliconFlowService.chat(history); // 调用模型 history.add(new ChatMessage(assistant, reply)); // 追加助手回复 return ResponseEntity.ok(Map.of(reply, reply)); } PostMapping(/reset) public ResponseEntityMapString, String reset(HttpSession session) { // 清空历史仅保留 system 提示词 session.setAttribute(HISTORY_KEY, List.of(new ChatMessage(system, SYSTEM_PROMPT))); return ResponseEntity.ok(Map.of(status, ok)); } }多轮原理一句话总结用户消息 → 进历史 → 调模型带全量历史→ 助手回复进历史 → 下一轮继续。会话历史在服务端前端无需关心。2、Thymeleaf 聊天页面页面用纯 JavaScript 通过 fetch 调用 /api/chat拿到回复后动态追加到对话区无需任何前端框架async function sendMessage() { const text inputEl.value.trim(); if (!text) return; appendMessage(user, text); inputEl.value ; const typing appendMessage(assistant, 正在思考...); const resp await fetch(/api/chat, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ message: text }) }); const data await resp.json(); typing.textContent data.reply; }完整的 HTML/CSS 已包含在示例工程中templates/chat.html含消息气泡样式、Enter 发送、清空会话按钮等。3、运行与测试方式一编辑 application.yml 填入真实 API Key方式二推荐用环境变量覆盖避免密钥入库 —— Windows(PowerShell): $env:SILICONFLOW_API_KEY你的Key启动mvn spring-boot:run浏览器打开 http://localhost:8080 即可多轮对话完整演示录屏如下SpringBoot集成硅基流动Qwen2.5-7B大模型4、temperature 与 max_tokens 参数详解这两个是调用大模型时最高频、也最影响效果的两个参数结合本项目代码重点说明参数控制什么调小效果调大效果temperature输出随机性/创造性更确定、保守、可复现适合代码/事实问答更发散、有创意、易出错适合闲聊/写作max_tokens单次回复最大长度回答更短、可能被截断可输出更长、占更多资源补充说明temperature 常用区间 0~1.2本项目默认 0.7兼顾稳定与灵动max_tokens 是『输出』上限而非上下文总窗口Qwen2.5-7B 上下文约 32K长对话要预留输入余量硅基流动接口中 temperature 与 top_p 通常二选一调整不要同时大幅改动。5、生产环境进阶建议上下文截断当前示例把全量历史发给模型轮次多了会超出窗口。可按 token 预算保留最近 N 轮或摘要旧消息流式输出将 stream 设为 true用 SSE/WebFlux 逐字返回体验更接近官方聊天密钥安全密钥务必走环境变量或配置中心禁止提交到 Git容错与重试对接口超时、限流429增加重试与降级提示多用户隔离HttpSession 已按会话隔离集群部署需配合 Spring Session Redis。五、总结通过本文我们就已经实现用 Spring Boot Thymeleaf 完整跑通了硅基流动的免费 Qwen 模型并实现了服务端维护历史的多轮对话。核心只有三步定义 OpenAI 兼容的数据模型、用 RestClient 封装一次接口调用、用 HttpSession 保存多轮上下文。在此基础上流式输出、上下文管理、多模型切换都可以平滑扩展。行文仓促定有不足之处欢迎各位朋友在评论区批评指正不胜感激。