跳到主要内容
Spring AI 入门实战:从环境配置到 RAG 应用构建 | 极客日志
Java AI java 算法
Spring AI 入门实战:从环境配置到 RAG 应用构建 综述由AI生成 Spring AI 是 Spring 官方推出的 AI 工程框架,旨在简化大模型应用在 Java 中的集成。涵盖从环境搭建、聊天模型调用(ChatClient/ChatModel)、函数调用、本地 Ollama 部署到阿里云 DashScope 的完整实践。重点解析了 RAG(检索增强生成)流程及综合案例(简历筛选助手),帮助开发者快速掌握 Spring AI 的核心能力与最佳实践。
Qiny01 发布于 2026/3/15 更新于 2026/4/26 3 浏览Spring AI 入门实战:从环境配置到 RAG 应用构建
在当今技术浪潮中,人工智能已成为行业标配。作为主流 Java 开发框架,Spring 社区紧跟趋势推出了 Spring AI 框架,旨在将 Spring 的设计原则应用于 AI 领域,简化大模型应用的开发工作。
1. Spring AI 简介
1.1 什么是 Spring AI
Spring AI 是一个面向 AI 工程的应用程序框架。它的核心目标是提供开发 AI 大模型应用所需的基本抽象模型,这些抽象拥有多种实现方式,使得开发者可以用很少的代码改动就能实现组件的轻松替换。简言之,它提供了一个友好的 API 和开发 AI 应用的抽象,让开发者能以极少的代码在不同 AI 模型间自由切换,充分契合 Spring 框架一贯秉持的模块化与可互换性原则。
目前 Spring AI 推出了预览版 (PRE)、快照版 (SNAPSHOT) 以及正式版 (GA)。推荐使用 GA 版本以保证稳定性,SNAPSHOT 版本则用于持续更新测试。
1.2 主要功能
多模型支持 :涵盖 OpenAI、DeepSeek、Microsoft、Ollama、Amazon、Google HuggingFace 等主流供应商。
多模态能力 :支持聊天、文本到图像、文本到声音等多种 AI 大模型类型。
向量数据库集成 :支持 Azure Vector Search、Chroma、Milvus、Neo4j、Redis、PineCone、PostgreSQL/PGVector 等。
函数调用 :内置 Function Calling 功能,允许模型触发外部函数。
数据工程 :为 ETL(数据抽取、转换和加载)提供框架支持。
自动配置 :支持 Spring Boot 自动配置,便于快速运行 AI 模型和管理向量库。
2. 快速入门:集成 DeepSeek
2.1 准备工作
DeepSeek 是一款由深度求索开发的 AI 大模型,基于 Transformer 架构,在中文理解与输出能力上表现优异,且具备极具竞争力的 API 定价。对于 Java 应用,我们可以借助 Spring AI 轻松集成。
首先需要在 DeepSeek 开放平台注册账号并创建 API Key。访问官网登录后,进入 API 开放平台即可获取密钥。接口文档地址为 https://api-docs.deepseek.com/zh-cn/。
2.2 创建 SpringBoot 工程
在 IDE 中创建一个 SpringBoot 项目(父模块 springAiProject),再创建一个名为 springai_hello 的子模块。注意 Spring AI 对 SpringBoot 和 JDK 版本有要求,建议使用 JDK 17 及以上。
引入依赖
在父模块的 pom.xml 中添加公共依赖管理:
<properties >
<maven.compiler.source > 17</maven.compiler.source >
<maven.compiler.target > 17</maven.compiler.target >
<spring-ai.version > 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
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 >
配置文件 在子模块的 application.properties 中配置服务端口及 DeepSeek 相关参数:
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 参数控制生成文本的多样性。值越高,文本越多样化但也可能更随机;值越低,结果越确定和一致。
编写代码 @SpringBootApplication
public class SpringAiHelloApplication {
public static void main (String[] args) {
SpringApplication.run(SpringAiHelloApplication.class, args);
}
}
package com.example.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;
}
}
启动服务后,访问 localhost:8899/ai/generate?message=你好 即可看到模型响应。
3. 聊天模型详解 Spring AI 提供了两种主要的聊天模型交互方式:ChatClient 和 ChatModel。
3.1 ChatClient 接口 ChatClient 是更高级的客户端接口,提供了构建和配置聊天对象的灵活性。它通过 prompt() 链式调用设置请求规范,最后通过 call() 或 stream() 发起请求。
简单对话 使用 ChatClient.Builder 注入客户端,并通过 user() 方法设置用户消息:
package com.example.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;
public ChatController (ChatClient.Builder chatClientBuilder) {
this .chatClient = chatClientBuilder.build();
}
@GetMapping("/chat")
public String chat (@RequestParam(value = "message", defaultValue = "你是谁") String message) {
return this .chatClient.prompt()
.user(message)
.call()
.content();
}
}
角色预设 可以通过配置 Bean 来设置默认的系统角色(System Prompt),这样无需在每个请求中重复指定:
package com.example.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 开发专家,精通 Spring 框架,名字叫 TechGuide。" ).build();
}
}
流式响应 为了提升用户体验,特别是在模型推理耗时较长时,可以使用流式输出 (stream)。非流式 (call) 需要等待全部生成完毕,而流式则逐个字符输出。
@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();
}
3.2 ChatModel 接口 ChatModel 是更底层的接口,定义了与 AI 模型交互的基本方法。虽然 ChatClient 底层也是基于 ChatModel,但在需要精细控制 Prompt 结构时,直接使用 ChatModel 更为合适。
package com.example.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();
}
}
提示词模板 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. 函数调用 (Function Calling) 函数调用允许大语言模型在生成回答时触发预定义的外部函数,从而实现动态数据获取或业务逻辑操作。流程包括:定义函数、模型交互、执行函数、返回结果。
4.1 自定义函数 只需定义一个返回 java.util.Function 并用 @Bean 标注的方法,Spring AI 会自动处理适配。
package com.example.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;
};
}
}
4.2 调用函数 在 Controller 中通过 functions() 方法告知 ChatClient 要使用的函数名称,并在 System Prompt 中明确指示模型何时调用。
package com.example.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: 乘法运算,需要两个数字参数
调用函数的条件:
1. 用户明确要求计算
2. 问题涉及加法或乘法
3. 能够从问题中提取出两个数字
请用中文回复,并在适当的时候调用函数。
""" )
.user(message)
.functions("addOperation" , "mulOperation" )
.call()
.content();
}
}
5. 本地部署:Ollama Ollama 是一个用于本地化部署和管理大型语言模型的工具,支持多种开源模型。结合 Spring AI,可以在本地低成本运行 AI 应用。
5.1 安装 Ollama
下载并安装 Ollama 客户端。
配置环境变量 OLLAMA_MODELS 指定模型存储路径。
重启电脑使配置生效。
拉取模型,例如:ollama pull deepseek-r1:1.5b。
启动服务:ollama run deepseek-r1:1.5b。
5.2 Spring AI 集成 添加 spring-ai-ollama-spring-boot-starter 依赖,并配置连接地址。
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.example.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 Spring AI Alibaba 是阿里云通义系列模型及服务在 Java AI 应用开发领域的最佳实践,提供了完整的开源配套,包括可观测、网关、消息队列等。
6.1 快速入门
申请阿里云 API Key(百炼平台)。
引入 spring-ai-alibaba-starter 依赖。
配置 application.properties,排除默认的 OpenAI 自动配置以避免冲突。
server.port=8893
spring.application.name=spring-ai-alibaba-demo
spring.ai.dashscope.api-key=sk-*****cf
spring.autoconfigure.exclude=org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration
6.2 代码示例 package com.example.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.client.advisor.SimpleLoggerAdvisor;
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. 其他模型能力
7.1 图像模型 Spring AI 的 Image Model API 抽象了'文生图'的交互过程。使用 DashScopeImageModel 可以直接生成图片。
package com.example.controller;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
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;
import java.net.URL;
@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(com.alibaba.cloud.ai.dashscope.api.DashScopeImageApi.DEFAULT_IMAGE_MODEL)
.withN(1 )
.withHeight(1024 )
.withWidth(1024 )
.build()));
String imageUrl = response.getResult().getOutput().getUrl();
URL url = URI.create(imageUrl).toURL();
InputStream in = url.openStream();
res.setHeader("Content-Type" , MediaType.IMAGE_PNG_VALUE);
res.getOutputStream().write(in.readAllBytes());
res.getOutputStream().flush();
}
}
7.2 语音模型 Text-to-Speech API 支持将文字内容转化为语音音频,可配置语速、音调、音量等参数。
package com.example.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 com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
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.io.IOException;
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. RAG (检索增强生成) RAG (Retrieval-Augmented Generation) 是一种结合了检索系统和生成模型的技术框架,旨在利用外部知识库帮助大模型生成更加准确、有依据的回答,解决知识局限性和幻觉问题。
8.1 工作流程
用户输入问题 。
问题向量化 :调用 Embedding 模型将问题转换为高维向量。
向量数据库检索 :在知识库中查找最相似的文档片段。
构建上下文 :将检索到的片段与系统提示词组合成最终 Prompt。
调用 LLM :模型基于上下文生成回答。
返回结果 。
8.2 实现步骤
配置向量存储 初始化 SimpleVectorStore,加载文档并转换为向量形式。
package com.example.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" +
"特性:\n" +
"1. 封装\n" +
"2. 继承\n" +
"3. 多态\n" ));
simpleVectorStore.add(documents);
return simpleVectorStore;
}
}
编写 Controller 使用 QuestionAnswerAdvisor 将向量存储关联到聊天请求中。
package com.example.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();
}
}
9. 综合案例:智能简历筛选 本案例构建一个招聘助手,结合 RAG 知识库和函数调用,分析候选人简历与岗位的匹配度。
9.1 环境搭建 创建子模块,配置与 Spring AI Alibaba 类似,端口设为 8896。
9.2 构建知识库 将候选人简历(txt 格式)放入资源目录,通过 TextReader 读取并切分,存入向量库。
package com.example.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 工具与角色设定 定义查询岗位的工具函数,并在 System Prompt 中设定助手的人设(专业、幽默、合规)。
9.4 实现 Agent 在 Controller 中串联人设、知识库检索和工具调用。
package com.example.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() : "" ;
String systemPrompt = """
角色与目标:你是一个招聘助手,会针对用户的问题,结合候选人经历,岗位匹配度等专业知识,给用户提供指导。
指导原则:你需要确保给出的建议合理科学,不会对候选人的表现有言论侮辱。
限制:在提供建议时,需要强调在个性建议方面用户仍然需要线下寻求专业咨询。
澄清:在与用户交互过程中,你需要明确回答用户关于招聘方面的问题,对于非招聘方面的问题,你的回应是'我只是一个招聘助手,不能回答这个问题哦'。
个性化:在回答时,你需要以专业可靠的预期回答,偶尔可以带点幽默感。调节气氛。
给你提供一个数据参考,并且给你调用岗位投递检索公户
请你跟进数据参考与工具返回结果回复用户的请求。
""" ;
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();
return results.stream().map(x -> x.getOutput().getContent()).collect(Collectors.joining());
}
}
通过以上步骤,我们完成了一个具备知识库检索和工具调用能力的智能 Agent 应用。开发者可以根据实际需求调整 Prompt 策略和向量库配置,构建更复杂的 AI 应用场景。
相关免费在线工具 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