useInsightStream.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * 对象关系分析 · AI 研判流式状态机
  3. *
  4. * 为什么新写 hook 而不复用 `ai/store/chatStream.ts`:那个 store 是 defineStore **单例**,
  5. * `workspaceId / sessions / messages` 均为全局态,AI 数据分析页正在使用;
  6. * 抽屉里再驱动它会把两处消息流搅在一起。这里用独立组合式 hook 持状态,
  7. * 但**复用** `ai/api/sse` 的解析器与 `ai/utils/parseMessageContent` 的解析函数。
  8. *
  9. * 状态:idle → creating(建会话)→ streaming(首轮/追问)→ done
  10. * ↘ error(模型未配置 / 网络 / 超限 / 409 进行中)
  11. */
  12. import { computed, ref, type Ref } from 'vue';
  13. import * as insightApi from '../api';
  14. import type { InsightContextVO, InsightCreateParams, InsightMessageVO, InsightSessionVO } from '../types';
  15. import type { ContentBlock } from '@/ai/utils/scanner';
  16. import { isInsightPayload } from '@/ai/utils/scanner';
  17. import type { InsightPayload, ToolStep } from '@/ai/api/types';
  18. import { RESCAN_THROTTLE_MS } from '@/ai/utils/constants';
  19. import {
  20. normalizeToolPayloadText,
  21. parseThinkingFromMetadata,
  22. parseToolEvents,
  23. parseMessageBlocksIncremental,
  24. } from '@/ai/utils/parseMessageContent';
  25. /** 消息分页每页条数(与后端 message-page-size 默认值一致) */
  26. const MESSAGE_PAGE_SIZE = 20;
  27. /** 抽屉内的消息(含前端渲染态) */
  28. export interface InsightChatMessage extends InsightMessageVO {
  29. /** 仅存在于前端(未落库) */
  30. local?: boolean;
  31. /** 解析后的富内容块 */
  32. blocks?: ContentBlock[];
  33. /** 工具调用步骤(流式期间实时累积;历史消息点开「分析过程」时才拉) */
  34. toolSteps?: ToolStep[];
  35. /** 模型思考过程 */
  36. thinking?: string;
  37. thinkingActive?: boolean;
  38. /** 是否正在流式输出 */
  39. streaming?: boolean;
  40. /** 结构化产物(首轮 assistant 消息才有) */
  41. payload?: InsightPayload | null;
  42. /** trace 是否已按需拉取过 */
  43. traceLoaded?: boolean;
  44. }
  45. /** 本地临时消息 ID(负数,与后端雪花 ID 的字符串形态区分开) */
  46. let tempIdSeed = -1;
  47. function nextTempId() {
  48. return String(tempIdSeed--);
  49. }
  50. /** 从内容块里取出第一个合法的 insight 载荷(结构化产物的唯一来源) */
  51. function pickInsightPayload(blocks: ContentBlock[]): InsightPayload | null {
  52. for (const block of blocks) {
  53. if (block.kind === 'insight' && isInsightPayload(block.data)) return block.data as InsightPayload;
  54. }
  55. return null;
  56. }
  57. export function useInsightStream(caseId: Ref<string>) {
  58. /** 当前会话ID(字符串,禁止 Number 转换) */
  59. const sessionId = ref<string | null>(null);
  60. /** 当前会话(含上下文摘要) */
  61. const session = ref<InsightSessionVO | null>(null);
  62. /** 上下文摘要(ContextBar 用) */
  63. const context = ref<InsightContextVO | null>(null);
  64. /** 消息(按 seq 升序) */
  65. const messages = ref<InsightChatMessage[]>([]);
  66. const creating = ref(false);
  67. const streaming = ref(false);
  68. const loadingMessages = ref(false);
  69. const loadingMore = ref(false);
  70. const loadMoreFailed = ref(false);
  71. const error = ref('');
  72. /** 分页水位(page=1 是最新一页) */
  73. const page = ref(1);
  74. const pages = ref(1);
  75. const total = ref(0);
  76. let abortController: AbortController | null = null;
  77. let rescanTimer: ReturnType<typeof setTimeout> | null = null;
  78. /* ---------------------------------------------------------------- *
  79. * 派生状态
  80. * ---------------------------------------------------------------- */
  81. /** 首轮分析消息(报告区渲染它,不进追问对话流) */
  82. const reportMessage = computed<InsightChatMessage | null>(
  83. () => messages.value.find((m) => m.messageType === 'first_round') || null,
  84. );
  85. /** 追问对话(用户提问 + 模型回答) */
  86. const followupMessages = computed(() => messages.value.filter((m) => m.messageType !== 'first_round'));
  87. /**
  88. * 结构化产物。
  89. *
  90. * 流式过程中来自 `insight` 帧(先于 done 下发,卡片能提前渲染);
  91. * 刷新 / 打开历史会话时,由 hydrate 从正文的 ```insight 围栏解析得到
  92. * (列表接口刻意不下发 output_json,避免大字段进列表)。
  93. */
  94. const payload = computed<InsightPayload | null>(() => reportMessage.value?.payload ?? null);
  95. /* ---------------------------------------------------------------- *
  96. * 内部工具
  97. * ---------------------------------------------------------------- */
  98. function clearRescanTimer() {
  99. if (rescanTimer) {
  100. clearTimeout(rescanTimer);
  101. rescanTimer = null;
  102. }
  103. }
  104. /** 服务端消息 → 前端渲染态 */
  105. function hydrate(message: InsightMessageVO): InsightChatMessage {
  106. const blocks = parseMessageBlocksIncremental(undefined, message.content || '').blocks;
  107. return {
  108. ...message,
  109. blocks,
  110. toolSteps: [],
  111. thinking: parseThinkingFromMetadata(message.metadata),
  112. payload: pickInsightPayload(blocks),
  113. };
  114. }
  115. /** 拉第 N 页消息(ORDER BY seq DESC),reverse 后 unshift 到头部 */
  116. async function loadPage(target: number) {
  117. const id = sessionId.value;
  118. const cid = caseId.value;
  119. if (!id || !cid) return 0;
  120. const resp = await insightApi.listInsightMessages(id, cid, target, MESSAGE_PAGE_SIZE);
  121. const records = Array.isArray(resp?.records) ? resp.records : [];
  122. // 服务端给的是 seq 降序,前端列表要升序
  123. const ordered = [...records].reverse().map(hydrate);
  124. if (target === 1) {
  125. messages.value = ordered;
  126. } else {
  127. // 按 id 去重兜底:页码分页在消息持续追加时可能出现「同一条出现在两页」
  128. const seen = new Set(messages.value.map((m) => m.id));
  129. messages.value = [...ordered.filter((m) => !seen.has(m.id)), ...messages.value];
  130. }
  131. page.value = Number(resp?.current) || target;
  132. pages.value = Number(resp?.pages) || 1;
  133. total.value = Number(resp?.total) || 0;
  134. return ordered.length;
  135. }
  136. /** 上滑加载更早的消息(滚动位置补偿由列表组件负责) */
  137. async function loadMore() {
  138. if (loadingMore.value || loadingMessages.value) return 0;
  139. if (page.value >= pages.value) return 0;
  140. loadingMore.value = true;
  141. loadMoreFailed.value = false;
  142. try {
  143. return await loadPage(page.value + 1);
  144. } catch (e: any) {
  145. // 失败不回退 page、不重置列表,列表底部给「点击重试」
  146. loadMoreFailed.value = true;
  147. return 0;
  148. } finally {
  149. loadingMore.value = false;
  150. }
  151. }
  152. /** 按需拉取单条消息的执行明细(工具调用 + 思考过程) */
  153. async function ensureTrace(message: InsightChatMessage) {
  154. if (message.traceLoaded || message.local || !caseId.value) return;
  155. try {
  156. const trace = await insightApi.getInsightMessageTrace(message.id, caseId.value);
  157. message.toolSteps = parseToolEvents(trace?.toolEvents);
  158. const thinking = parseThinkingFromMetadata(trace?.metadata);
  159. if (thinking) message.thinking = thinking;
  160. message.traceLoaded = true;
  161. } catch {
  162. // 明细拉取失败不影响报告主体,保持原状即可
  163. message.traceLoaded = true;
  164. }
  165. }
  166. /**
  167. * 跑一轮流式。
  168. *
  169. * @param userText 追问内容;首轮传空串(服务端注入固定首轮指令)
  170. */
  171. async function runStream(userText: string) {
  172. const id = sessionId.value;
  173. const cid = caseId.value;
  174. if (!id || !cid) return;
  175. const firstRound = !userText;
  176. if (!firstRound) {
  177. messages.value = [
  178. ...messages.value,
  179. {
  180. id: nextTempId(),
  181. sessionId: id,
  182. seq: Number.MAX_SAFE_INTEGER - 1,
  183. role: 'user',
  184. content: userText,
  185. messageType: 'followup',
  186. local: true,
  187. createAt: new Date().toISOString(),
  188. } as InsightChatMessage,
  189. ];
  190. }
  191. const target: InsightChatMessage = {
  192. id: nextTempId(),
  193. sessionId: id,
  194. seq: Number.MAX_SAFE_INTEGER,
  195. role: 'assistant',
  196. content: '',
  197. messageType: firstRound ? 'first_round' : 'chat',
  198. local: true,
  199. streaming: true,
  200. blocks: [],
  201. toolSteps: [],
  202. createAt: new Date().toISOString(),
  203. };
  204. messages.value = [...messages.value, target];
  205. streaming.value = true;
  206. error.value = '';
  207. abortController = new AbortController();
  208. const rescan = () => {
  209. const res = parseMessageBlocksIncremental(target.blocks, target.content);
  210. target.blocks = res.blocks;
  211. // 围栏闭合后即可拿到结构化产物(不依赖 SSE 的 insight 帧)
  212. const fromBlocks = pickInsightPayload(res.blocks);
  213. if (fromBlocks) target.payload = fromBlocks;
  214. };
  215. const scheduleRescan = () => {
  216. if (rescanTimer) return;
  217. rescanTimer = setTimeout(() => {
  218. rescanTimer = null;
  219. rescan();
  220. }, RESCAN_THROTTLE_MS);
  221. };
  222. try {
  223. await insightApi.streamInsight(
  224. { sessionId: id, caseId: cid, message: firstRound ? undefined : userText },
  225. {
  226. onThinking: (data) => {
  227. if (data.phase === 'start') {
  228. if (target.thinking) target.thinking += '\n\n';
  229. target.thinkingActive = true;
  230. return;
  231. }
  232. if (data.phase === 'end') {
  233. target.thinkingActive = false;
  234. return;
  235. }
  236. const delta = data.data || '';
  237. if (!delta) return;
  238. target.thinking = (target.thinking || '') + delta;
  239. target.thinkingActive = true;
  240. },
  241. onToolCall: (data) => {
  242. target.toolSteps = [
  243. ...(target.toolSteps || []),
  244. { id: data.toolCallId, toolName: data.toolName, status: 'running' },
  245. ];
  246. },
  247. onToolInput: (data) => {
  248. const step = target.toolSteps?.find((s) => s.id === data.toolCallId);
  249. if (step) step.input = normalizeToolPayloadText(data.toolInput || '');
  250. },
  251. onToolResult: (data) => {
  252. const step = target.toolSteps?.find((s) => s.id === data.toolCallId);
  253. if (step) {
  254. step.result = normalizeToolPayloadText(data.toolResult || '');
  255. step.status = 'done';
  256. if (!step.toolName && data.toolName) step.toolName = data.toolName;
  257. }
  258. },
  259. onInsight: (data) => {
  260. if (isInsightPayload(data?.data)) target.payload = data.data as InsightPayload;
  261. },
  262. onToken: (data) => {
  263. target.content += data.data || '';
  264. scheduleRescan();
  265. },
  266. onError: (data) => {
  267. error.value = data.error || '请求失败';
  268. target.content = target.content || `⚠️ ${error.value}`;
  269. },
  270. onTransportError: (err) => {
  271. error.value = (err as Error)?.message || String(err);
  272. target.content = target.content || `⚠️ 网络异常:${error.value}`;
  273. },
  274. },
  275. abortController.signal,
  276. );
  277. } catch (err: any) {
  278. if (err?.name !== 'AbortError') {
  279. error.value = err?.message || '请求失败';
  280. target.content = target.content || `⚠️ ${error.value}`;
  281. } else {
  282. target.content = target.content || '(已停止生成)';
  283. }
  284. } finally {
  285. clearRescanTimer();
  286. rescan();
  287. target.streaming = false;
  288. target.thinkingActive = false;
  289. streaming.value = false;
  290. abortController = null;
  291. }
  292. }
  293. /* ---------------------------------------------------------------- *
  294. * 对外动作
  295. * ---------------------------------------------------------------- */
  296. /**
  297. * 新建会话并立刻开跑首轮分析(打开抽屉即分析,用户不用敲字)。
  298. *
  299. * @param buildParams 上下文组装函数(由 useInsightContext 提供)
  300. * @param topN 研判规模
  301. */
  302. async function start(buildParams: (caseId: string, topN: number) => InsightCreateParams, topN: number) {
  303. const cid = caseId.value;
  304. if (!cid || creating.value || streaming.value) return;
  305. creating.value = true;
  306. error.value = '';
  307. try {
  308. const created = await insightApi.createInsightSession(buildParams(cid, topN));
  309. sessionId.value = created.id;
  310. session.value = created;
  311. context.value = created.context || null;
  312. messages.value = [];
  313. page.value = 1;
  314. pages.value = 1;
  315. total.value = 0;
  316. await runStream('');
  317. } catch (e: any) {
  318. error.value = e?.message || '创建研判会话失败';
  319. throw e;
  320. } finally {
  321. creating.value = false;
  322. }
  323. }
  324. /** 打开历史会话 */
  325. async function openSession(id: string) {
  326. const cid = caseId.value;
  327. if (!cid) return;
  328. stop();
  329. loadingMessages.value = true;
  330. error.value = '';
  331. try {
  332. const detail = await insightApi.getInsightSession(id, cid);
  333. sessionId.value = detail.id;
  334. session.value = detail;
  335. context.value = detail.context || null;
  336. page.value = 1;
  337. pages.value = 1;
  338. await loadPage(1);
  339. } catch (e: any) {
  340. error.value = e?.message || '加载会话失败';
  341. } finally {
  342. loadingMessages.value = false;
  343. }
  344. }
  345. /** 追问(同一会话) */
  346. async function followup(text: string) {
  347. const content = (text || '').trim();
  348. if (!content || streaming.value || !sessionId.value) return;
  349. await runStream(content);
  350. }
  351. /** 中止当前流 */
  352. function stop() {
  353. clearRescanTimer();
  354. if (abortController) {
  355. abortController.abort();
  356. abortController = null;
  357. }
  358. streaming.value = false;
  359. const last = messages.value[messages.value.length - 1];
  360. if (last?.streaming) {
  361. last.streaming = false;
  362. last.thinkingActive = false;
  363. if (!last.content) last.content = '(已停止生成)';
  364. }
  365. }
  366. /** 重置(关闭抽屉 / 切换案件时调用,防泄漏) */
  367. function reset() {
  368. stop();
  369. sessionId.value = null;
  370. session.value = null;
  371. context.value = null;
  372. messages.value = [];
  373. page.value = 1;
  374. pages.value = 1;
  375. total.value = 0;
  376. loadingMore.value = false;
  377. loadMoreFailed.value = false;
  378. error.value = '';
  379. }
  380. /** 删除会话 */
  381. async function remove(id: string) {
  382. const cid = caseId.value;
  383. if (!cid) return;
  384. await insightApi.deleteInsightSession(id, cid);
  385. if (sessionId.value === id) reset();
  386. }
  387. return {
  388. // 状态
  389. sessionId,
  390. session,
  391. context,
  392. messages,
  393. reportMessage,
  394. followupMessages,
  395. payload,
  396. creating,
  397. streaming,
  398. loadingMessages,
  399. loadingMore,
  400. loadMoreFailed,
  401. error,
  402. page,
  403. pages,
  404. total,
  405. // 动作
  406. start,
  407. openSession,
  408. followup,
  409. stop,
  410. reset,
  411. remove,
  412. loadMore,
  413. ensureTrace,
  414. };
  415. }