当前位置: 首页 > 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.dtcms.com/a/307333.html

相关文章:

  • 力扣46:全排列
  • k8s-master03加入集群失败解决方法之一
  • Table-Render:基于 JSON Schema 的高性能 React 动态表格渲染器
  • 【达梦MPP(不带主备)集群搭建】
  • 【Linux我做主】进程优先级
  • Linux的库制作与原理
  • e签宝CEO金宏洲受邀出席WAIC世界人工智能大会
  • 对比学习:原理演进、技术突破与跨领域应用全景
  • 【Java23种设计模式】:模板方法模式
  • Java设计模式之《命令模式》
  • SQL理解——INNER JOIN
  • 机器人行业工商注册企业基本信息数据(1958-2023年)
  • MySQL转PostgreSQL迁移实战:从语法错误到完美兼容
  • AWS云安全审计终极实战指南:构建自动化安全防线
  • Golang 调试技巧:在 Goland 中查看 Beego 控制器接收的前端字段参数
  • Sort Merge Join为什么是Spark中最优的join
  • C语言指针(三):数组传参本质、冒泡排序与二级指针详解
  • C++异常处理的成本:理解与优化
  • 超宽带测距+测角+无线通信一体化模组:智能门锁、智能遥控器、AR头戴、智能穿戴
  • yolo目标检测基础知识
  • AWS高级解决方案架构师黄海波:GenAI 时代非结构化数据处理的实践与趋势洞察
  • 【最近公共祖先】ST表法
  • 从渠道渗透到圈层渗透:开源链动2+1模式、AI智能名片与S2B2C商城小程序的协同创新路径研究
  • 联通元景万悟 开源,抢先体验!!!
  • 技术速递|GitHub Copilot for Eclipse 迈出重要一步
  • SpringAI:AI工程应用框架新选择
  • 转码刷 LeetCode 笔记[1]:3.无重复字符的最长子串(python)
  • 一对一交友小程序 / APP 系统架构分析
  • n8n为什么建议在数组的每个item中添加json键?
  • python的异步、并发开发