当前位置: 首页 > news >正文

SpringBoot+SpringAI打造智能对话机器人

基于Spring Boot和Spring AI的智能系统

在现代软件开发中,人工智能(AI)已经成为不可或缺的一部分。通过Spring Boot和Spring AI框架,开发者可以快速构建智能系统,实现自然语言处理、智能对话等功能。本文将介绍如何使用Spring Boot和Spring AI结合DeepSeek平台,创建一个具备自然语言处理能力的智能对话机器人。

环境准备

首先,需要准备以下环境:

  • JDK 17+

  • Maven或Gradle构建工具

  • Spring Boot 3.2+

  • DeepSeek API Key

项目创建

可以使用Spring Initializr快速创建一个Spring Boot项目,并添加Spring AI相关依赖。以下是pom.xml的配置示例:

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

在application.properties中添加DeepSeek API的配置:

spring.ai.openai.base-url=https://api.siliconflow.cn/spring.ai.openai.api-key=你的密钥spring.ai.openai.chat.options.model=deepseek-ai/DeepSeek-V3logging.level.org.springframework.ai.chat.client.advisor=DEBUG

核心实现

1. 人设设定

新建Config配置类,设置智能体的人设:

@Configurationclass Config {@BeanChatClient chatClient(ChatClient.Builder builder) {return builder.defaultSystem("你是一个智能机器人,你的名字叫Spring AI智能机器人").build();}}

2. 流式对话

新建ChatbotController类,实现流式对话功能:

@RestController@CrossOrigin("*")@Slf4jpublic class ChatbotController {private final ChatClient chatClient;public ChatbotController(ChatClient chatClient) {this.chatClient = chatClient;}@PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)public Flux<ServerSentEvent<String>> streamChat(@RequestBody ChatRequest request) {String userId = request.userId();return chatClient.prompt(request.message()).stream().content().map(content -> ServerSentEvent.builder(content).event("message").build()).concatWithValues(ServerSentEvent.builder("[DONE]").build()).onErrorResume(e -> Flux.just(ServerSentEvent.builder("Error: " +                     e.getMessage()).event("error").build()));}record ChatRequest(String userId, String message) {}}

3. 前端实现

前端使用Vite+Vue3+TS实现,以下是核心代码:

<script setup lang="ts">import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { fetchEventSource } from '@microsoft/fetch-event-source';const generateUserId = () => Math.random().toString(36).substr(2, 8);
const userId = ref('');
const messages = ref<Message[]>([]);
const inputMessage = ref('');
const isLoading = ref(false);
const controller = ref<AbortController>();
const messageContainer = ref<HTMLElement>();
const inputRef = ref<HTMLInputElement>();const scrollToBottom = () => {nextTick(() => {if (messageContainer.value && autoScroll) {messageContainer.value.scrollTop = messageContainer.value.scrollHeight;}});};const sendChatRequest = async (content: string, botMessage: Message) => {
controller.value = new AbortController();
await fetchEventSource('http://localhost:8080/chat/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream', 'X-Content-Lang': 'zh-CN' },
body: JSON.stringify({ message: content, userId: userId.value }),
signal: controller.value?.signal,
onopen: async response => {if (!response.ok) throw new Error(`HTTP error ${response.status}`);},onmessage: event => {if (event.data === '[DONE]') {botMessage.status = MessageStatus.Complete;return;}botMessage.content += event.data;
botMessage.timestamp = Date.now();
scrollToBottom();},onerror: err => {throw err;}});};const sendMessage = async () => {if (!inputMessage.value.trim() || isLoading.value) return;const userContent = inputMessage.value.trim();inputMessage.value = '';const userMessage = reactive<Message>({ id: `user-${Date.now()}`, content: userContent, isBot: false, timestamp: Date.now() });messages.value.push(userMessage);const botMessage = reactive<Message>({ id: `bot-${Date.now()}`, content: '', isBot: true, status: MessageStatus.Streaming, timestamp: Date.now() });messages.value.push(botMessage);isLoading.value = true;try {await sendChatRequest(userContent, botMessage);} catch (err) {botMessage.status = MessageStatus.Error;botMessage.content = err.message;} finally {isLoading.value = false;nextTick(() => inputRef.value?.focus());}};</script>

总结

通过本文的介绍,我们了解了如何使用Spring Boot和Spring AI结合DeepSeek平台,快速搭建一个具备自然语言处理能力的智能对话机器人。希望本文能为您在AI应用开发中提供帮助。

http://www.xdnf.cn/news/1218133.html

相关文章:

  • MySQL 8.0 OCP 1Z0-908 题目解析(38)
  • Kafka Streams窗口技术全解析:从理论到电商实时分析实战
  • TTS语音合成|GPT-SoVITS语音合成服务器部署,实现http访问
  • Linux多线程线程控制
  • 前端核心技术Node.js(五)——Mongodb、Mongoose和接口
  • 计算机网络学习(一、Cisco Packet Tracer软件安装)
  • 计算机网络学习--------三次握手与四次挥手
  • diffusion原理和代码延伸笔记1——扩散桥,GOUB,UniDB
  • 【计算机网络】5传输层
  • 网络与信息安全有哪些岗位:(4)应急响应工程师
  • 【网络安全】等级保护2.0解决方案
  • 物联网与AI深度融合,赋能企业多样化物联需求
  • Redis实战(4)-- BitMap结构与使用
  • 基于单片机智能油烟机设计/厨房排烟系统设计
  • 用Python绘制SM2国密算法椭圆曲线:一场数学与视觉的盛宴
  • XML 用途
  • MVS相机+YOLO检测方法
  • 基于N32G45x+RTT驱动框架的定时器外部计数
  • 前端js通过a标签直接预览pdf文件,弹出下载页面问题
  • .NET 10 中的新增功能系列文章3—— .NET MAUI 中的新增功能
  • 《Java 程序设计》第 18 章 - Java 网络编程
  • C++面试5题--6day
  • LLC电源原边MOS管DS增加RC吸收对ZVS的影响分析
  • 开发避坑短篇(11):Oracle DATE(7)到MySQL时间类型精度冲突解决方案
  • PHP 5.5 Action Management with Parameters (English Version)
  • 专业鼠标点击器,自定义间隔次数
  • 网站技术攻坚与Bug围剿手记
  • Spring Cloud『学习笔记』
  • [硬件电路-111]:滤波的分类:模拟滤波与数字滤波; 无源滤波与有源滤波;低通、带通、带阻、高通滤波;时域滤波与频域滤波;低价滤波与高阶滤波。
  • 《Java 程序设计》第 17 章 - 并发编程基础