Files
snails-ai-backend/snails-chat/src/main/java/com/hanserwei/chat/controller/AiChatController.java
Hanserwei 5ee2a0f11c refactor(chat):重构AI助手功能并集成文档读取能力
- 移除原有的手机号识别与消息发送逻辑
- 删除RabbitMQ和邮件相关配置及代码
- 引入PDF、HTML、JSON等多种文档读取器
- 集成向量存储与检索功能支持问答
- 更新Spring AI依赖并调整内存存储方式
- 添加新的工具类用于保存文档到向量库- 修改提示词模板去除强制附加句规则
- 调整Cassandra和PgVector相关配置项- 新增多种文件格式读取组件实现类
2025-10-31 20:48:28 +08:00

55 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.hanserwei.chat.controller;
import com.hanserwei.chat.model.dto.ChatMessageDTO;
import com.hanserwei.chat.model.vo.AIResponse;
import com.hanserwei.chat.reader.MyPdfReader;
import com.hanserwei.chat.utils.ConversationContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/ai")
public class AiChatController {
@Resource
private ChatClient dashScopeChatClient;
@Resource
private MyPdfReader myPdfReader;
@Resource
private VectorStore vectorStore;
@PostMapping(path = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<AIResponse> chatWithAi(@RequestBody ChatMessageDTO chatMessageDTO) {
log.info("会话ID{}", chatMessageDTO.getConversionId());
ConversationContext.setConversationId(chatMessageDTO.getConversionId());
return dashScopeChatClient.prompt()
.user(chatMessageDTO.getMessage())
.advisors(p -> p.param(ChatMemory.CONVERSATION_ID, chatMessageDTO.getConversionId()))
.stream()
.chatResponse()
.mapNotNull(chatResponse -> AIResponse.builder()
.v(chatResponse.getResult().getOutput().getText())
.build())
.contextWrite(ctx -> ConversationContext.withConversationId(chatMessageDTO.getConversionId()))
.doFinally(signalType -> ConversationContext.clear());
}
@GetMapping("/readpdf")
public String readPdf() {
List<Document> docsFromPdf = myPdfReader.getDocsFromPdf();
vectorStore.add(docsFromPdf);
return "ok!";
}
}