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应用开发中提供帮助。