SpringAI 对接大模型聊天接口实战 Demo

1. 业务场景

很多后端业务需要接入大模型能力:客服自动问答、文档摘要、智能提示、代码解释、工单内容润色。如果直接手写 HTTP 请求调用大模型接口,要自己处理鉴权、参数封装、异常重试、不同厂商接口差异。一旦切换模型服务商,大量接口代码要重写,维护成本很高。

SpringAI 把各类大模型聊天能力做了统一抽象,用一套 ChatClient 标准 API 对接,适合已有 SpringBoot 项目快速植入 AI 对话能力,不用重复造轮子,业务侧只关心"发提问、拿回答"。

2. 开发思路

整体流程:前端/调用方发送提问 → 后端 Controller 接收参数 → 交给 SpringAI 的 ChatClient 组装 Prompt → 底层模型适配器拼接请求、携带密钥转发到大模型接口 → 拿到返回内容返回给调用方。

调用者 → SpringBoot Controller → ChatClient(统一门面)→ 模型适配器(OpenAI 兼容)→ 大模型服务端

核心思路就是面向抽象编程:业务代码和具体模型厂商解耦。后续换别的兼容 OpenAI 协议的模型,大多只改配置,业务代码基本不动。

3. 实操实现

环境版本:

  • JDK:17(Spring AI 2.0 推荐)

  • SpringBoot:3.3.x

  • SpringAI:2.0.x,使用 OpenAI 兼容 starter,适配国内多数支持兼容协议的大模型

  • 构建工具:Maven

pom.xml 核心依赖:

bash 复制代码
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>2.0.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-openai</artifactId>
    </dependency>
</dependencies>

application.properties 配置(替换为自己的 key、地址、模型名):

bash 复制代码
# 大模型密钥
spring.ai.openai.api-key=sk-xxx
# 兼容接口地址
spring.ai.openai.base-url=https://xxx/v1
# 指定模型名称
spring.ai.openai.chat.options.model=xxx

启动类 + 聊天接口完整代码:

bash 复制代码
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class SpringAiChatDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringAiChatDemoApplication.class, args);
    }

    // 注入 ChatClient Builder,自动装配
    @Bean
    CommandLineRunner runner(ChatClient.Builder builder) {
        return args -> {
            ChatClient chatClient = builder.build();
            String res = chatClient.prompt("你好").call().content();
            System.out.println("模型预热测试:" + res);
        };
    }
}

@RestController
class ChatController {
    private final ChatClient chatClient;

    public ChatController(ChatClient.Builder builder) {
        // 设置默认系统提示词,定义模型角色
        this.chatClient = builder
                .defaultSystem("你是一名资深 Java 后端工程师,回答简洁专业")
                .build();
    }

    @GetMapping("/api/chat")
    public String chat(@RequestParam String msg) {
        // 组装用户提问,调用模型
        return chatClient.prompt()
                .user(msg)
                .call()
                .content();
    }
}

4. 测试验证

启动方式:直接运行启动类,等待项目启动,控制台会打印预热调用结果。调用示例:浏览器或者 curl 访问:

bash 复制代码
GET http://localhost:8080/api/chat?msg=解释一下SpringAI的ChatClient

预期结果:返回一段通顺、贴合系统提示词的文字回答。正常返回代表对接成功;返回空、报错则进入排查环节。

5. 踩坑排查

1. API Key 或者 base-url 配置错误原因:复制密钥带空格、地址不是厂商兼容接口地址。解决:去掉首尾空格,核对厂商文档的兼容接口路径。

2. 版本不匹配,自动装配失效原因:SpringBoot、JDK、SpringAI 版本组合不兼容。解决:JDK17 + SpringBoot3.3 + SpringAI2.0 配套使用。

3. 模型名称写错,服务商返回 400原因:配置的 model 名称在该平台不存在。解决:复制平台官方提供的模型标识填入配置。

6. 小结

这套方案优点:标准统一、接入快、切换模型改配置为主;缺点:依赖外部大模型服务,受网络、额度、接口限流影响。适合企业内部辅助问答、内容生成类轻量 AI 需求,不适合强离线、高保密场景。后续可以扩展流式输出、多轮对话记忆、RAG 知识库、工具调用等能力。

  • End -

◆ 点左上角关注 · 不迷路 ◆

每周分享 Java + AI 大模型实战干货点赞 + 在看,是持续更新的动力

相关推荐
极客先躯26 分钟前
智能体开发高级面试每日一题|2026-06-01|Agent 系统中 LLM 扮演什么角色?除了 LLM 还需要哪些非 LLM 组件?
ai·面试·llm·agent·每日一题·高级面试题·智能体开发
极客先躯1 小时前
智能体开发高级面试每日一题|2026-05-30|什么是 Agentic Workflow?它和纯 Agent 有什么区别?
人工智能·ai·agent·每日一题·高级面试·智能体开发·agenticworkflow
Smoothcloud润云2 小时前
写实向生图智能体的工程实践:数据集取向、参数配置与两个纪实案例复现
服务器·数据库·人工智能·ai·ai编程·gpu算力
七牛云行业应用2 小时前
GLM-5.4 vs DeepSeek V4.1 Flash:同样 1M 上下文,API 价格与输出上限怎么选(2026 年 12 月)
人工智能·ai·开源·ai编程
MounRiver_Studio2 小时前
MRS Agent 开发实战(一):CH32V307 USB转8路串口方案
ide·ai·agent·risc-v
呆呆敲代码的小Y3 小时前
MiniMax M4 和 Gemini 4 Neon 的订阅额度对比
人工智能·ai·语言模型·agent
宿州派大星3 小时前
LangGraph + HITL 打造高可用智能客服:PDF知识库 + SQLite + 前后端分离(附源码)
ai·pdf·langgraph
Mirawork12 小时前
AI 低代码建站原理:从自然语言需求到在线应用,拆解 AI 生成网页的完整技术链路
人工智能·低代码·ai·ai编程
富贵儿99813 小时前
NL2SQL 实践手记 03:让模型决定下一步——把 Workflow 改造成 SQL Agent
数据库·python·sql·ai·自然语言处理·langchain