跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
JavaAIjava算法

Spring AI 框架入门与实战指南

Spring AI 是 Spring 生态中集成大模型能力的框架。涵盖环境搭建、DeepSeek 集成、ChatClient 与 ChatModel 使用、函数调用、Ollama 本地部署、阿里云 DashScope 接入,以及图像、语音模型和 RAG 检索增强生成的实战示例。通过具体代码演示,帮助开发者快速掌握在 Java 应用中构建 AI 功能的方法。

锁机制发布于 2026/4/5更新于 2026/9/1259 浏览
Spring AI 框架入门与实战指南

Spring AI 简介

在人工智能飞速发展的今天,AI 已成为各行各业的基础设施。作为主流的 Java 应用开发框架,Spring 社区紧跟潮流推出了 Spring AI 框架。

1.1 Spring AI 是什么

1.1.1 官方定位

Spring AI 是一个面向 AI 工程领域的应用程序框架。它的核心目标是将 Spring 生态系统的设计原则(如可移植性、模块化)应用到 AI 领域,促进使用 POJO 作为构建块。

简单来说,它提供了开发 AI 大模型应用所需的基本抽象模型,拥有多种实现方式。开发者只需少量代码改动即可轻松替换底层组件,旨在简化 AI 大模型应用的开发工作。

1.1.2 版本说明

目前 Spring AI 主要提供预览版 (PRE)、快照版 (SNAPSHOT) 和正式版 (GA)。

  • SNAPSHOT:持续更新的快照版本。
  • PRE:预览版,主要用于测试和找 Bug。
  • GA:正式发布版本,稳定性高,推荐使用。

1.2 主要功能

  • 多模型支持:兼容 OpenAI、DeepSeek、Microsoft、Ollama、Amazon、Google HuggingFace 等主流供应商。
  • 多模态能力:支持聊天、文本到图像、文本到声音等模型类型。
  • 向量数据库集成:支持 Azure Vector Search、Chroma、Milvus、Redis 等主流 Embedding 模型和向量库。
  • 函数调用:原生支持 Function Calling 功能。
  • 自动配置:基于 Spring Boot 的自动配置,便于快速启动和管理。

2. Spring AI 快速入门

2.1 准备工作

2.1.1 关于 DeepSeek

DeepSeek 是由深度求索开发的 AI 大模型,基于 Transformer 架构,擅长处理复杂文档解析、逻辑推理及编程任务。其特点是成本低、性能强,且 API 定价具有竞争力。

对于 Java 应用,我们可以借助 Spring AI 轻松集成 DeepSeek。

2.1.2 获取 API Key

  1. 访问 DeepSeek 官网,进入 API 开放平台并注册登录。
  2. 创建 API Key。
  3. 根据需求完成实名认证及充值。
  4. 参考接口文档进行后续开发。

注:Spring AI 的 openai starter 本质上是通过 RestTemplate 发送请求,因此可以复用该 Starter 对接 DeepSeek 接口。

2.2 创建 SpringBoot 工程

在 IDEA 中创建一个 SpringBoot 项目(父模块 springAiProject),并新建子模块 springai_hello。注意 Spring AI 对 JDK 版本的要求(建议 JDK 17+)。

2.2.1 引入依赖

在父模块的 pom.xml 中添加公共依赖管理:

<properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17
    1.0.0-M5


    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.ai
        spring-ai-openai-spring-boot-starter
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    
        org.projectlombok
        lombok
        1.18.30
    


    
        
            org.springframework.ai
            spring-ai-bom
            ${spring-ai.version}
            pom
            import
        
    

</maven.compiler.target>
<spring-ai.version>
</spring-ai.version>
</properties>
<dependencies>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
</dependency>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
</dependency>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
<scope>
</scope>
</dependency>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
<version>
</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>
</groupId>
<artifactId>
</artifactId>
<version>
</version>
<type>
</type>
<scope>
</scope>
</dependency>
</dependencies>
</dependencyManagement>

2.2.2 配置文件

在子模块的 application.properties 中配置连接信息:

server.port=8899
spring.application.name=spring-ai-deepseek-demo
# DeepSeek 的 Api key
spring.ai.openai.api-key=sk-****************
spring.ai.openai.base-url=https://api.deepseek.com
spring.ai.openai.chat.options.model=deepseek-chat
spring.ai.openai.chat.options.temperature=0.7

其中 temperature 控制生成文本的多样性。值越高越随机,值越低越确定。

2.2.3 启动类

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

2.2.4 编写 Controller

package com.atguigu.ai.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ChatDeepSeekController {

    @Resource
    private OpenAiChatModel chatModel;

    @GetMapping("/ai/generate")
    public String generate(@RequestParam(value = "message", defaultValue = "hello") String message) {
        String response = this.chatModel.call(message);
        System.out.println("response: " + response);
        return response;
    }
}

2.2.5 测试

访问 localhost:8899/ai/generate?message=你好,等待片刻即可收到模型响应。

3. Spring AI 的聊天模型

3.1 概述

Spring AI 的聊天模型 API 为开发者提供了便捷通道,能够无缝集成强大的 AI 驱动聊天功能。它基于预训练语言模型,依据用户输入生成自然流畅的回复,设计理念强调简单易用与高度可移植性。

3.2 ChatClient 接口

ChatClient 是定义与聊天服务交互客户端的接口,用于创建对象、设置规范及发起请求。

提示:以下示例需新建子模块 springai_chat,端口修改为 8890。

3.2.1 简单对话

需求

用户输入消息,通过封装方法向 AI 模型发送请求,以字符串形式返回响应。

实现
package com.atguigu.ai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ChatController {

    private final ChatClient chatClient;

    // 通过构造器注入 ChatClient
    public ChatController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @GetMapping("/chat")
    public String chat(@RequestParam(value = "message", defaultValue = "你是谁") String message) {
        // prompt: 提示词
        return this.chatClient.prompt()
                .user(message)
                .call()
                .content();
    }
}
总结

ChatClient 提供了灵活的构建和配置能力。通过 ChatClient.Builder 定制行为,使用 prompt() 设置规范,最后通过 call() 发起请求。

3.2.2 角色预设

我们可以通过配置默认的系统角色来设定 AI 的人设。

配置默认角色
package com.atguigu.ai.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AIConfig {

    @Bean
    public ChatClient chatClient(ChatClient.Builder builder) {
        return builder.defaultSystem("你是一名资深 Java 开发专家,精通技术原理,名字叫 TechExpert。").build();
    }
}
Controller 实现
package com.atguigu.ai.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
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;

@RestController
@RequestMapping("/ai")
public class ChatAIController {

    @Resource
    private ChatClient chatClient;

    @GetMapping("/chat")
    public String chat(@RequestParam(value = "message") String message) {
        return chatClient.prompt().user(message).call().content();
    }
}

3.2.3 流式响应

非流式输出 (call) 需要等待模型生成完整结果;流式输出 (stream) 则逐个字符输出,能显著提升用户体验,尤其是在模型推理较慢时。

实现流式响应
@GetMapping(value = "/chat/stream", produces = "text/html;charset=UTF-8")
public Flux<String> chatStream(@RequestParam(value = "message") String message) {
    return chatClient.prompt().user(message).stream().content();
}

在浏览器或支持 SSE 的工具中访问该接口,即可看到文字逐字输出的效果。

3.3 ChatModel 接口

3.3.1 概述

ChatModel 定义了与 AI 模型交互的基本方法,继承自 Model<Prompt, ChatResponse>。虽然它提供了简化的 call(String) 方法,但在实际应用中,更常见的是使用 call(Prompt) 方法以获取更详细的 ChatResponse。

3.3.2 简单对话

package com.atguigu.ai.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
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;

@RestController
@RequestMapping("/model")
public class ChatModelController {

    @Resource
    private ChatModel chatModel;

    @GetMapping("/chatModel01")
    public String chatModel01(@RequestParam("message") String message) {
        return chatModel.call(message);
    }

    @GetMapping("/chatModel02")
    public String chatModel02(@RequestParam("message") String message) {
        ChatResponse call = chatModel.call(new Prompt(
                message,
                OpenAiChatOptions.builder()
                        .model("deepseek-chat")
                        .temperature(0.8)
                        .build()
        ));
        return call.getResult().getOutput().getContent();
    }
}

3.3.3 提示词模板

Prompt 是引导模型生成特定输出的关键。Spring AI 提供了 Prompt Template 抽象,允许在运行时动态替换占位符。

@GetMapping("/prompt")
public String prompt(@RequestParam("name") String name, @RequestParam("voice") String voice) {
    String userText = "给我推荐北京的至少三种美食";
    UserMessage userMessage = new UserMessage(userText);

    String systemText = "你是一个美食咨询助手,你的名字是{name},你应该用你的名字和{voice}的饮食习惯回复用户的请求。";
    SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
    Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));

    Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
    List<Generation> results = chatModel.call(prompt).getResults();
    return results.stream().map(x -> x.getOutput().getContent()).collect(Collectors.joining(""));
}

4. Spring AI 的函数调用

4.1 概述

函数调用 (Function Calling) 允许大语言模型在生成回答时触发预定义的外部函数,从而实现动态数据获取或业务逻辑操作(如查询数据库、调用 API)。Spring AI 规范了函数定义和注册过程,并在请求前自动将函数注入到 Prompt 中。

核心流程:

  1. 定义函数:声明名称、描述及参数结构。
  2. 模型交互:发送函数信息与用户输入,模型决定是否调用。
  3. 执行函数:解析请求并执行业务逻辑。
  4. 返回结果:将执行结果反馈给模型生成最终回答。

4.2 实现步骤

提示:新建子模块 springai_function,端口修改为 8891。

4.2.1 创建自定义 Function

package com.atguigu.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;

import java.util.function.Function;

@Slf4j
@Configuration
public class CalculatorService {

    public record AddOperation(int a, int b) {}
    public record MulOperation(int m, int n) {}

    @Bean
    @Description("加法运算")
    public Function<AddOperation, Integer> addOperation() {
        return request -> {
            log.info("执行加法运算:{} + {} = {}", request.a, request.b, request.a + request.b);
            return request.a + request.b;
        };
    }

    @Bean
    @Description("乘法运算")
    public Function<MulOperation, Integer> mulOperation() {
        return request -> {
            log.info("执行乘法运算:{} * {} = {}", request.m, request.n, request.m * request.n);
            return request.m * request.n;
        };
    }
}

只需定义返回 java.util.Function 并用 @Bean 标注的方法,Spring AI 会自动包装适配。

4.2.2 编写 Controller

package com.atguigu.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FunctionController {

    @Resource
    private ChatModel chatModel;

    @GetMapping(value = "/function", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public String ragJsonText(@RequestParam(value = "message") String message) {
        return ChatClient.builder(chatModel).build()
                .prompt()
                .system("""
                    您是算术计算器的代理。您能够支持加法运算、乘法运算等操作。
                    当用户询问数学计算时,您必须调用相应的函数来处理。
                    支持的函数:
                    - addOperation: 加法运算,需要两个数字参数
                    - mulOperation: 乘法运算,需要两个数字参数
                    请用中文回复,并在适当的时候调用函数。
                    """)
                .user(message)
                .functions("addOperation", "mulOperation")
                .call()
                .content();
    }
}

在 Prompt 中启用 functions("addOperation", "mulOperation") 告知 Client 使用这些函数。

4.2.3 测试

访问接口并输入 2 加 3 等于多少,观察日志确认函数是否被正确调用。

5. Spring AI 调用 Ollama

5.1 本地部署 Ollama

Ollama 是一个用于本地化部署和管理大型语言模型的工具,支持 LLaMA、Alpaca 等开源模型。

5.1.1 安装与配置

  1. 下载并安装 Ollama。
  2. 设置环境变量 OLLAMA_MODELS 指定模型存储路径。
  3. 重启电脑使配置生效。

5.1.2 拉取模型

根据硬件配置选择合适的模型版本。例如 Windows 下拉取 1.5B 版本:

ollama pull deepseek-r1:1.5b

5.1.3 启动服务

ollama run deepseek-r1:1.5b

默认监听 http://localhost:11434。

5.2 代码测试

5.2.1 依赖引入

新建子模块 springai_ollama,添加依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
    </dependency>
</dependencies>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <url>https://repo.spring.io/milestone</url>
    </repository>
</repositories>

5.2.2 配置与 Controller

server.port=8892
spring.application.name=spring-ai-ollama-demo
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=deepseek-r1:1.5b
spring.ai.ollama.chat.options.temperature=0.7
package com.atguigu.ai.ollama.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.ollama.OllamaChatModel;
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;

@RestController
@RequestMapping("/ollama")
public class SpringAiOllamaController {

    @Resource
    private OllamaChatModel ollamaChatModel;

    @GetMapping("/test")
    public String generate(@RequestParam(value = "message", defaultValue = "hello") String message) {
        String response = this.ollamaChatModel.call(message);
        System.out.println("response: " + response);
        return response;
    }
}

6. Spring AI Alibaba

6.1 概述

Spring AI Alibaba 是阿里云通义系列模型及服务在 Java 领域的最佳实践。它提供了 Model、Prompt、RAG、Tools 等必备能力,兼具低层次抽象(提示词模板、函数调用)和高层次抽象(智能体、对话记忆)。

6.2 快速入门

6.2.1 申请 API Key

访问阿里云百炼页面,开通'百炼大模型推理'服务,获取 API Key。

6.2.2 依赖与配置

新建子模块 springai_alibaba,引入 spring-ai-alibaba-starter 依赖,并排除默认的 OpenAI 自动配置以避免冲突。

spring.autoconfigure.exclude=org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration
spring.ai.dashscope.api-key=sk-*****cf

6.2.3 实现示例

package com.atguigu.controller;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringAiAlibabaController {

    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手,请根据用户提问回答!";
    private ChatClient dashScopeChatClient;

    public SpringAiAlibabaController(ChatClient.Builder chatClientBuilder) {
        this.dashScopeChatClient = chatClientBuilder
                .defaultSystem(DEFAULT_PROMPT)
                .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .defaultOptions(DashScopeChatOptions.builder().withTopP(0.7).build())
                .build();
    }

    @GetMapping("/simple/chat")
    public String simpleChat(@RequestParam("query") String query) {
        return dashScopeChatClient.prompt(query).call().content();
    }
}

7. Spring AI 的其他模型

7.1 图像模型

Spring AI 的 Image Model API 为与图像生成模型交互提供了简单接口,支持文生图功能。

7.1.1 核心类

  • ImageModel:图像模型接口。
  • ImagePrompt:封装输入消息和选项。
  • ImageResponse:持有生成结果。

7.1.2 生成图像示例

package com.atguigu.controller;

import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URI;

@RestController
public class ImageModelController {

    @Resource
    private DashScopeImageModel imageModel;

    @GetMapping("/generate-image")
    public void getImage(@RequestParam(value = "msg", defaultValue = "生成一只小猫") String msg, HttpServletResponse res) throws Exception {
        ImageResponse response = imageModel.call(new ImagePrompt(
                msg,
                DashScopeImageOptions.builder()
                        .withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
                        .withN(1)
                        .withHeight(1024)
                        .withWidth(1024)
                        .build()
        ));

        String imageUrl = response.getResult().getOutput().getUrl();
        InputStream in = URI.create(imageUrl).toURL().openStream();
        res.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
        res.getOutputStream().write(in.readAllBytes());
    }
}

7.2 语音模型

Text-to-Speech API 支持将文字内容转化为语音,可配置语速、音调等参数。

package com.atguigu.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;

@RestController
public class AudioModelController {

    @Resource
    private DashScopeSpeechSynthesisModel speechSynthesisModel;

    private static final String TEXT = "床前明月光,疑是地上霜。举头望明月,低头思故乡。";
    private static final String FILE_PATH = "E:\\testData\\tts";

    @GetMapping("/tts")
    public void tts() throws IOException {
        DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()
                .withSpeed(1.0)
                .withPitch(0.9)
                .withVolume(60)
                .build();

        SpeechSynthesisResponse response = speechSynthesisModel.call(new SpeechSynthesisPrompt(TEXT, options));
        File file = new File(FILE_PATH + "/output.mp3");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
            fos.write(byteBuffer.array());
        }
    }
}

8. Spring AI 实现 RAG

8.1 概述

8.1.1 向量化

向量数据库以数学向量形式存储数据,支持基于相似度的检索而非精准匹配。嵌入模型 (Embedding Model) 与向量数据库协同工作,构成语义搜索和 RAG 的技术基础。

8.1.2 RAG 概念

RAG (Retrieval-Augmented Generation,检索增强生成) 结合了检索系统和生成模型,利用外部知识库帮助大模型生成更准确、有依据的回答,有效解决知识局限性和幻觉问题。

工作流程:

  1. 用户输入问题。
  2. 问题向量化。
  3. 向量数据库检索相关片段。
  4. 构建上下文 Prompt。
  5. 调用 LLM 生成回答。

8.2 实现基本 RAG 流程

8.2.1 配置类

新建子模块 springai_rag,配置向量存储和 ChatClient。

package com.atguigu.ai.rag.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class RagConfig {

    @Bean
    ChatClient chatClient(ChatClient.Builder builder) {
        return builder.defaultSystem("你将作为一名 Java 开发语言的专家,对于用户的使用需求作出解答").build();
    }

    @Bean
    VectorStore vectorStore(@Qualifier("dashscopeEmbeddingModel") EmbeddingModel embeddingModel) {
        SimpleVectorStore simpleVectorStore = SimpleVectorStore.builder(embeddingModel).build();
        List<Document> documents = List.of(new Document(
                "产品说明:名称:Java 开发语言\n产品描述:Java 是一种面向对象开发语言。\n特性:\n1. 封装\n2. 继承\n3. 多态\n"
        ));
        simpleVectorStore.add(documents);
        return simpleVectorStore;
    }
}

8.2.2 Controller

package com.atguigu.ai.rag.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rag")
public class RagController {

    @Resource
    private ChatClient dashScopeChatClient;

    @Resource
    private VectorStore vectorStore;

    @GetMapping(value = "/chat", produces = "text/plain; charset=UTF-8")
    public String generation(@RequestParam("userInput") String userInput) {
        return dashScopeChatClient.prompt()
                .user(userInput)
                .advisors(new QuestionAnswerAdvisor(vectorStore))
                .call()
                .content();
    }
}

通过 QuestionAnswerAdvisor 关联向量存储,模型将基于检索到的文档生成增强回答。

9. Spring AI 综合案例

本案例构建一个智能简历筛选助手,结合 RAG 知识库与工具调用,评估候选人匹配度。

9.1 环境搭建

新建子模块 springai_all,配置端口 8896。

9.2 创建 RAG 知识库

将候选人简历放入 resource 目录,通过配置类加载并切分文本存入向量库。

package com.atguigu.all.config;

import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class RagConfig {

    @Bean
    VectorStore vectorStore(@Qualifier("dashscopeEmbeddingModel") EmbeddingModel embeddingModel) {
        SimpleVectorStore simpleVectorStore = SimpleVectorStore.builder(embeddingModel).build();
        String filePath = "张三简历.txt";
        TextReader textReader = new TextReader(filePath);
        textReader.getCustomMetadata().put("filePath", filePath);
        List<Document> documents = textReader.get();

        TokenTextSplitter splitter = new TokenTextSplitter(1200, 350, 5, 100, true);
        splitter.apply(documents);

        simpleVectorStore.add(documents);
        return simpleVectorStore;
    }
}

9.3 创建工具类

定义查询岗位的工具函数。

package com.atguigu.all.function;

import java.util.function.Function;

public class RecruitServiceFunction implements Function<RecruitServiceFunction.Request, RecruitServiceFunction.Response> {

    @Override
    public Response apply(Request request) {
        String position = "未知";
        if (request.name.contains("张三")) {
            position = "算法工程师";
        }
        return new Response(position);
    }

    public record Request(String name) {}
    public record Response(String position) {}
}

9.4 编写人设与 Controller

设定招聘助手角色,串联知识库与工具。

package com.atguigu.ai.all.controller;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
public class ChatController {

    @Resource
    private ChatModel chatModel;

    @Resource
    private VectorStore vectorStore;

    @GetMapping("/ai/agent")
    public String agent(@RequestParam("query") String query) {
        // 检索知识库
        List<Document> documents = vectorStore.similaritySearch(query);
        String info = documents.size() > 0 ? documents.get(0).getContent() : "";

        // 构造系统 Prompt
        String systemPrompt = """
            角色与目标:你是一个招聘助手,会针对用户的问题,结合候选人经历,岗位匹配度等专业知识,给用户提供指导。
            指导原则:你需要确保给出的建议合理科学,不会对候选人的表现有言论侮辱。
            限制:在提供建议时,需要强调在个性建议方面用户仍然需要线下寻求专业咨询。
            澄清:在与用户交互过程中,你需要明确回答用户关于招聘方面的问题,对于非招聘方面的问题,你的回应是'我只是一个招聘助手,不能回答这个问题哦'。
            个性化:在回答时,你需要以专业可靠的预期回答,偶尔可以带点幽默感。调节气氛。
            给你提供一个数据参考,并且给你调用岗位投递检索公户 请你跟进数据参考与工具返回结果回复用户的请求。
            """;

        // 构造用户 Prompt
        String userPrompt = """
            给你提供一些数据参考:{info},请回答我的问题:{query}。
            请你跟进数据参考与工具返回结果回复用户的请求。
            """;

        SystemMessage systemMessage = new SystemMessage(systemPrompt);
        PromptTemplate promptTemplate = new PromptTemplate(userPrompt);
        Message userMessage = promptTemplate.createMessage(Map.of("info", info, "query", query));

        Prompt prompt = new Prompt(List.of(userMessage, systemMessage),
                DashScopeChatOptions.builder().withFunctions(Set.of("recruitServiceFunction")).build());

        List<Generation> results = chatModel.call(prompt).getResults();
        String content = results.stream().map(x -> x.getOutput().getContent()).collect(Collectors.joining());
        return content;
    }
}

测试访问 localhost:8896/ai/agent?query=java 语言有哪些特性,系统将结合简历内容与工具返回结果给出专业回答。

目录

  1. Spring AI 简介
  2. 1.1 Spring AI 是什么
  3. 1.1.1 官方定位
  4. 1.1.2 版本说明
  5. 1.2 主要功能
  6. 2. Spring AI 快速入门
  7. 2.1 准备工作
  8. 2.1.1 关于 DeepSeek
  9. 2.1.2 获取 API Key
  10. 2.2 创建 SpringBoot 工程
  11. 2.2.1 引入依赖
  12. 2.2.2 配置文件
  13. DeepSeek 的 Api key
  14. 2.2.3 启动类
  15. 2.2.4 编写 Controller
  16. 2.2.5 测试
  17. 3. Spring AI 的聊天模型
  18. 3.1 概述
  19. 3.2 ChatClient 接口
  20. 3.2.1 简单对话
  21. 需求
  22. 实现
  23. 总结
  24. 3.2.2 角色预设
  25. 配置默认角色
  26. Controller 实现
  27. 3.2.3 流式响应
  28. 实现流式响应
  29. 3.3 ChatModel 接口
  30. 3.3.1 概述
  31. 3.3.2 简单对话
  32. 3.3.3 提示词模板
  33. 4. Spring AI 的函数调用
  34. 4.1 概述
  35. 4.2 实现步骤
  36. 4.2.1 创建自定义 Function
  37. 4.2.2 编写 Controller
  38. 4.2.3 测试
  39. 5. Spring AI 调用 Ollama
  40. 5.1 本地部署 Ollama
  41. 5.1.1 安装与配置
  42. 5.1.2 拉取模型
  43. 5.1.3 启动服务
  44. 5.2 代码测试
  45. 5.2.1 依赖引入
  46. 5.2.2 配置与 Controller
  47. 6. Spring AI Alibaba
  48. 6.1 概述
  49. 6.2 快速入门
  50. 6.2.1 申请 API Key
  51. 6.2.2 依赖与配置
  52. 6.2.3 实现示例
  53. 7. Spring AI 的其他模型
  54. 7.1 图像模型
  55. 7.1.1 核心类
  56. 7.1.2 生成图像示例
  57. 7.2 语音模型
  58. 8. Spring AI 实现 RAG
  59. 8.1 概述
  60. 8.1.1 向量化
  61. 8.1.2 RAG 概念
  62. 8.2 实现基本 RAG 流程
  63. 8.2.1 配置类
  64. 8.2.2 Controller
  65. 9. Spring AI 综合案例
  66. 9.1 环境搭建
  67. 9.2 创建 RAG 知识库
  68. 9.3 创建工具类
  69. 9.4 编写人设与 Controller

更多推荐文章

查看全部
  • Linux 进程间通信进阶:消息队列与信号量详解
  • 动态规划:子数组与子串问题实战
  • 编程学习如何保持兴趣与动力:方法与路线指南
  • LeetCode 二分查找算法入门与实战
  • 数据结构实战:选择排序详解与图解
  • 零基础转行网络安全:学习路径与职业前景分析
  • 小米 Miloco 本地部署与使用记录
  • 硕士论文盲审前降AI率:评委是否查看AIGC报告
  • Python 新手学习路线规划与基础语法指南
  • 通义万相 2.1 模型功能解析与部署指南
  • 解决 IDEA 中 java.lang.ExceptionInInitializerError TypeTag UNKNOWN 错误
  • RabbitMQ 分布式系统实战:从安装部署到 C++ 调用
  • 从 Gitee 到 GitHub 的迁移与自动同步实践
  • Python 爬虫接单指南:技术储备、合规风险与实战建议
  • Python 内置函数 enumerate() 详解与实战
  • 基于 Dify 低代码平台开发 AI 应用:从入门到生产部署
  • N8N 对接飞书多维表:数据增删改查实战
  • 2026 年 3 月 23 日人工智能产业动态
  • Java 程序员选型指南:Cursor、Claude Code 与 Kiro 深度对比
  • 2026 年高校论文 AI 率新规解读:哪些学校已明确 AIGC 检测要求

相关免费在线工具

  • Keycode 信息

    查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online

  • Escape 与 Native 编解码

    JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online

  • JavaScript / HTML 格式化

    使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online

  • JavaScript 压缩与混淆

    Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • RSA密钥对生成器

    生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online