package com.custom.webui.controller;
|
|
import com.custom.webui.dto.req.MessageUpdateRequest;
|
import com.custom.webui.dto.resp.MessageDTO;
|
import com.custom.webui.dto.resp.Result;
|
import com.custom.webui.security.CurrentUser;
|
import com.custom.webui.exception.BusinessException;
|
import com.custom.webui.service.PendingAttachmentService;
|
import com.custom.webui.service.MessageService;
|
import jakarta.validation.Valid;
|
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.http.MediaType;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PutMapping;
|
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
|
import java.util.List;
|
|
/**
|
* 消息接口,包含 SSE 流式对话核心端点。
|
*
|
* <p><b>SSE 端点设计说明</b>
|
*
|
* <p>端点:{@code GET /api/chats/{chatId}/stream},{@code produces=text/event-stream}
|
*
|
* <p>两个不得不做的取舍,在此明确记录:
|
*
|
* <ol>
|
* <li><b>为什么是 GET 而不是 POST?</b>
|
* 浏览器原生 {@code EventSource} 只支持 GET,而文档要求用 EventSource 实现。
|
* 因此参数走 query string。用户输入较长时 URL 可能接近服务器限制
|
* (Tomcat 默认 8KB request line),所以前端应在发送前限制单条消息长度;
|
* 超长输入场景建议改用 fetch + ReadableStream 方案。</li>
|
*
|
* <li><b>token 为什么可以从 query 传?</b>
|
* EventSource 无法自定义请求头,拿不到 Authorization。
|
* {@link com.custom.webui.security.JwtAuthenticationFilter} 因此同时支持
|
* {@code ?token=} 形式。生产环境建议通过 nginx 关闭该路径的 query 日志、
|
* 强制 HTTPS,必要时改为「短时效一次性 ticket」换取连接。</li>
|
* </ol>
|
*
|
* <p><b>事件协议</b>(前端按 {@code event:} 名称分发):
|
* <pre>
|
* event: start data: {"type":"start","messageId":12,"userMessageId":11,...}
|
* event: delta data: {"type":"delta","messageId":12,"delta":"你","thinking":false}
|
* event: title data: {"type":"title","title":"关于消息树的设计"}
|
* event: done data: {"type":"done","messageId":12,"content":"完整文本","sources":[...]}
|
* event: error data: {"type":"error","error":"无法连接 LLM 服务..."}
|
* </pre>
|
*/
|
@Slf4j
|
@RestController
|
@RequestMapping("/api/chats")
|
@RequiredArgsConstructor
|
public class MessageController {
|
|
private final MessageService messageService;
|
private final PendingAttachmentService pendingAttachmentService;
|
|
/**
|
* query 里直接携带图片文字的字符上限。
|
*
|
* <p>取 1500:中文 URL 编码约 9 字节/字,1500 字 ≈ 13.5KB,
|
* 已经超过 Tomcat 默认 8KB 请求行上限 —— 所以实际能用的远小于此。
|
* 这个常量只用于「给一个比 Tomcat 更友好的错误提示」,
|
* 正常路径应当使用 imageTextId。
|
*/
|
private static final int MAX_INLINE_IMAGE_TEXT = 1500;
|
|
/**
|
* 获取会话的完整消息树。
|
*
|
* <p>返回根节点列表,每个节点内嵌 children,前端据此递归渲染并支持分支切换。
|
*/
|
@GetMapping("/{chatId}/messages")
|
public Result<List<MessageDTO>> messages(@PathVariable Long chatId) {
|
return Result.success(messageService.getMessageTree(CurrentUser.requireUserId(), chatId));
|
}
|
|
/**
|
* SSE 流式对话核心接口。
|
*
|
* <p>该方法<strong>立即返回</strong> SseEmitter,生成过程在专用线程池异步执行,
|
* 因此不会长时间占用 Tomcat 请求线程。
|
*
|
* @param chatId 会话 id
|
* @param content 用户输入(必填)
|
* @param parentId 父消息 id;不传则自动接在当前分支末尾。
|
* 编辑历史消息后重新生成时,传入被编辑消息的 id 即可产生新分支
|
* @param model 覆盖会话默认模型,可空
|
* @param useRag 是否启用知识库检索,默认 true
|
* @param imageText 随消息上传的图片经 OCR 提取的文字(前端先调 /api/files/ocr 得到)。
|
* 有值时作为「图片内容」注入 prompt 上下文。
|
* 之所以走 OCR 而不是直接传图:当前 Ollama 模型是纯文本模型,
|
* OCR 方案对所有模型通用。
|
* @param imageFileIds 图片在 upload_file 中的 id,写入消息 metadata 供前端展示原图
|
*/
|
@GetMapping(value = "/{chatId}/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
public SseEmitter stream(@PathVariable Long chatId,
|
@RequestParam("content") String content,
|
@RequestParam(value = "parentId", required = false) Long parentId,
|
@RequestParam(value = "model", required = false) String model,
|
@RequestParam(value = "useRag", defaultValue = "true") boolean useRag,
|
@RequestParam(value = "imageText", required = false) String imageText,
|
@RequestParam(value = "imageFileIds", required = false) List<Long> imageFileIds,
|
@RequestParam(value = "imageTextId", required = false) String imageTextId) {
|
|
Long userId = CurrentUser.requireUserId();
|
|
// 图片 OCR 文字优先通过暂存 id 取(见 PendingAttachmentService)。
|
// 为什么不直接放在 query 里:中文经 URL 编码后一字约 9 字节,
|
// 2000 字就是 18KB,超过 Tomcat 默认 8KB 的请求行上限,
|
// 会抛「Request header is too large」而前端只看到无正文的 400。
|
// imageText 参数仍保留,用于极短文本的兼容场景。
|
boolean fromStore = false;
|
if (imageTextId != null && !imageTextId.isBlank()) {
|
String stored = pendingAttachmentService.consume(userId, imageTextId);
|
if (stored != null) {
|
imageText = stored;
|
fromStore = true;
|
} else {
|
log.warn("附件文本 id 无效或已过期 id={},本轮将以无图片文字继续", imageTextId);
|
}
|
} else if (imageText != null && imageText.length() > MAX_INLINE_IMAGE_TEXT) {
|
// 兜底防呆:仅针对**直接塞进 query** 的长文本。
|
// 从暂存取回的文本长度不受限制 —— 那正是本接口存在的目的,
|
// 最终由 buildContext 的上下文预算统一裁剪。
|
// 这里提前拒绝是为了给出可操作的提示,而不是让它撞上
|
// Tomcat 的请求行上限(那样连应用日志都进不来)。
|
throw BusinessException.badRequest(
|
"图片识别文字过长(" + imageText.length() + " 字),请改用 POST /api/attachments/text "
|
+ "暂存后传 imageTextId,或直接使用 /api/files/ocr 上传图片");
|
}
|
if (fromStore) {
|
log.debug("图片文字来自暂存 id={},长度={}", imageTextId,
|
imageText == null ? 0 : imageText.length());
|
}
|
|
// 提前打印一条日志:SSE 请求在 access log 里表现为长时间挂起,有这行便于排查
|
log.info("SSE 对话请求 chatId={} userId={} contentLength={} parentId={} useRag={} 图片数={} 图片文字={}字",
|
chatId, CurrentUser.username(), content == null ? 0 : content.length(), parentId, useRag,
|
imageFileIds == null ? 0 : imageFileIds.size(),
|
imageText == null ? 0 : imageText.length());
|
|
return messageService.streamChat(
|
userId, chatId, content, parentId, model, useRag,
|
imageText, imageFileIds);
|
}
|
|
/** 编辑消息内容 */
|
@PutMapping("/{chatId}/messages/{messageId}")
|
public Result<MessageDTO> updateMessage(@PathVariable Long chatId,
|
@PathVariable Long messageId,
|
@Valid @RequestBody MessageUpdateRequest request) {
|
return Result.success(messageService.updateMessage(
|
CurrentUser.requireUserId(), chatId, messageId, request));
|
}
|
|
/** 删除消息及其全部子孙消息 */
|
@DeleteMapping("/{chatId}/messages/{messageId}")
|
public Result<Void> deleteMessage(@PathVariable Long chatId, @PathVariable Long messageId) {
|
messageService.deleteMessage(CurrentUser.requireUserId(), chatId, messageId);
|
return Result.success();
|
}
|
}
|