app.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /**
  2. * RAG管道测试可视化工具
  3. * 用于展示RAG链路各环节输入输出数据流转
  4. */
  5. // API配置
  6. const API_BASE = 'http://localhost:8765';
  7. // 全局数据存储
  8. let pipelineData = null;
  9. let currentSelectedStep = null;
  10. let serverConnected = false;
  11. // DOM元素引用
  12. const uploadArea = document.getElementById('uploadArea');
  13. const fileInput = document.getElementById('fileInput');
  14. const pipelineOverview = document.getElementById('pipelineOverview');
  15. const pipelineFlow = document.getElementById('pipelineFlow');
  16. const detailPanel = document.getElementById('detailPanel');
  17. const stagesDetail = document.getElementById('stagesDetail');
  18. const flowContainer = document.getElementById('flowContainer');
  19. const stagesAccordion = document.getElementById('stagesAccordion');
  20. // 阶段配置映射
  21. const stageConfig = {
  22. '1_query_extract': {
  23. icon: '🔍',
  24. title: '查询提取',
  25. description: '从输入内容中提取查询对'
  26. },
  27. '2_entity_enhance_retrieval': {
  28. icon: '🎯',
  29. title: '实体增强检索',
  30. description: '实体召回 + BFP召回'
  31. },
  32. '3_parent_doc_enhancement': {
  33. icon: '📚',
  34. title: '父文档增强',
  35. description: '使用父文档增强检索结果'
  36. },
  37. '4_extract_first_result': {
  38. icon: '✂️',
  39. title: '结果提取',
  40. description: '提取最终检索结果'
  41. },
  42. '1_rag_retrieval': {
  43. icon: '🔄',
  44. title: 'RAG检索',
  45. description: '完整RAG检索流程'
  46. },
  47. '2_parameter_compliance_check': {
  48. icon: '✅',
  49. title: '参数合规检查',
  50. description: 'LLM审查参数合规性'
  51. }
  52. };
  53. // 初始化事件监听
  54. document.addEventListener('DOMContentLoaded', () => {
  55. initUploadEvents();
  56. initTabEvents();
  57. checkServerStatus();
  58. // 定时检查服务状态
  59. setInterval(checkServerStatus, 10000);
  60. });
  61. /**
  62. * 检查服务器状态
  63. */
  64. function checkServerStatus() {
  65. fetch(`${API_BASE}/api/health`)
  66. .then(response => response.json())
  67. .then(data => {
  68. serverConnected = true;
  69. updateServerStatus(true, data.milvus_ready);
  70. })
  71. .catch(() => {
  72. serverConnected = false;
  73. updateServerStatus(false, false);
  74. });
  75. }
  76. /**
  77. * 更新服务器状态显示
  78. */
  79. function updateServerStatus(connected, milvusReady) {
  80. const statusEl = document.getElementById('serverStatus');
  81. const dot = statusEl.querySelector('.status-dot');
  82. const text = statusEl.querySelector('.status-text');
  83. dot.className = 'status-dot ' + (connected ? (milvusReady ? 'online' : 'warning') : 'offline');
  84. if (connected) {
  85. text.textContent = milvusReady ? '服务已连接 (Milvus就绪)' : '服务已连接 (Milvus未就绪)';
  86. } else {
  87. text.textContent = '服务未连接 - 请启动 rag_pipeline_server.py';
  88. }
  89. document.getElementById('runRagBtn').disabled = !connected;
  90. }
  91. /**
  92. * 执行RAG检索
  93. */
  94. function runRAG() {
  95. const content = document.getElementById('ragInput').value.trim();
  96. if (!content) {
  97. alert('请输入测试文本');
  98. return;
  99. }
  100. if (!serverConnected) {
  101. alert('服务未连接,请先启动 rag_pipeline_server.py');
  102. return;
  103. }
  104. // 显示加载状态
  105. document.getElementById('loadingOverlay').style.display = 'flex';
  106. document.getElementById('runRagBtn').disabled = true;
  107. fetch(`${API_BASE}/api/rag`, {
  108. method: 'POST',
  109. headers: { 'Content-Type': 'application/json' },
  110. body: JSON.stringify({ content: content })
  111. })
  112. .then(response => {
  113. if (!response.ok) throw new Error(`请求失败: ${response.status}`);
  114. return response.json();
  115. })
  116. .then(data => {
  117. pipelineData = data;
  118. renderPipeline(data);
  119. document.getElementById('loadingOverlay').style.display = 'none';
  120. document.getElementById('runRagBtn').disabled = false;
  121. })
  122. .catch(err => {
  123. alert(`RAG执行失败: ${err.message}`);
  124. document.getElementById('loadingOverlay').style.display = 'none';
  125. document.getElementById('runRagBtn').disabled = false;
  126. });
  127. }
  128. /**
  129. * 初始化上传事件
  130. */
  131. function initUploadEvents() {
  132. uploadArea.addEventListener('click', () => fileInput.click());
  133. uploadArea.addEventListener('dragover', (e) => {
  134. e.preventDefault();
  135. uploadArea.classList.add('dragover');
  136. });
  137. uploadArea.addEventListener('dragleave', () => {
  138. uploadArea.classList.remove('dragover');
  139. });
  140. uploadArea.addEventListener('drop', (e) => {
  141. e.preventDefault();
  142. uploadArea.classList.remove('dragover');
  143. const file = e.dataTransfer.files[0];
  144. if (file) handleFile(file);
  145. });
  146. fileInput.addEventListener('change', (e) => {
  147. const file = e.target.files[0];
  148. if (file) handleFile(file);
  149. });
  150. }
  151. /**
  152. * 初始化标签页事件
  153. */
  154. function initTabEvents() {
  155. document.querySelectorAll('.tab-btn').forEach(btn => {
  156. btn.addEventListener('click', () => {
  157. const tabId = btn.dataset.tab;
  158. switchTab(tabId);
  159. });
  160. });
  161. }
  162. /**
  163. * 切换标签页
  164. */
  165. function switchTab(tabId) {
  166. document.querySelectorAll('.tab-btn').forEach(btn => {
  167. btn.classList.toggle('active', btn.dataset.tab === tabId);
  168. });
  169. document.querySelectorAll('.tab-pane').forEach(pane => {
  170. pane.classList.toggle('active', pane.id === tabId + 'Pane');
  171. });
  172. }
  173. /**
  174. * 处理上传的文件
  175. */
  176. function handleFile(file) {
  177. if (!file.name.endsWith('.json')) {
  178. alert('请上传JSON文件');
  179. return;
  180. }
  181. const reader = new FileReader();
  182. reader.onload = (e) => {
  183. try {
  184. const data = JSON.parse(e.target.result);
  185. pipelineData = data;
  186. renderPipeline(data);
  187. } catch (err) {
  188. alert('JSON解析失败: ' + err.message);
  189. }
  190. };
  191. reader.readAsText(file);
  192. }
  193. /**
  194. * 默认数据文件路径
  195. */
  196. const DEFAULT_DATA_PATH = '../../../temp/entity_bfp_recall/rag_pipeline_data.json';
  197. /**
  198. * 加载默认数据文件
  199. */
  200. function loadSampleData() {
  201. // 优先从服务器API加载
  202. if (serverConnected) {
  203. fetch(`${API_BASE}/api/data`)
  204. .then(response => {
  205. if (!response.ok) throw new Error('数据不存在');
  206. return response.json();
  207. })
  208. .then(data => {
  209. pipelineData = data;
  210. renderPipeline(data);
  211. })
  212. .catch(() => {
  213. // 服务器没有数据,尝试本地文件
  214. loadFromPath(DEFAULT_DATA_PATH);
  215. });
  216. } else {
  217. loadFromPath(DEFAULT_DATA_PATH);
  218. }
  219. }
  220. /**
  221. * 从指定路径加载JSON数据
  222. */
  223. function loadFromPath(path) {
  224. fetch(path)
  225. .then(response => {
  226. if (!response.ok) {
  227. throw new Error(`文件加载失败: ${response.status} ${response.statusText}`);
  228. }
  229. return response.json();
  230. })
  231. .then(data => {
  232. pipelineData = data;
  233. renderPipeline(data);
  234. })
  235. .catch(err => {
  236. alert(`加载数据失败: ${err.message}\n\n请确保已运行 test_rag_pipeline.py 生成数据文件,或手动上传JSON文件。`);
  237. console.error('加载数据失败:', err);
  238. });
  239. }
  240. /**
  241. * 清空数据
  242. */
  243. function clearData() {
  244. pipelineData = null;
  245. currentSelectedStep = null;
  246. document.getElementById('ragInput').value = '';
  247. pipelineOverview.style.display = 'none';
  248. pipelineFlow.style.display = 'none';
  249. detailPanel.style.display = 'none';
  250. stagesDetail.style.display = 'none';
  251. flowContainer.innerHTML = '';
  252. stagesAccordion.innerHTML = '';
  253. }
  254. /**
  255. * 渲染管道数据
  256. */
  257. function renderPipeline(data) {
  258. renderOverview(data);
  259. renderFlowChart(data);
  260. renderStagesDetail(data);
  261. pipelineOverview.style.display = 'block';
  262. pipelineFlow.style.display = 'block';
  263. stagesDetail.style.display = 'block';
  264. }
  265. /**
  266. * 渲染概览信息
  267. */
  268. function renderOverview(data) {
  269. const steps = data.steps || {};
  270. const stepCount = Object.keys(steps).length;
  271. document.getElementById('stageCount').textContent = stepCount + ' 个';
  272. // 显示总执行时间
  273. if (data.total_execution_time) {
  274. document.getElementById('totalTime').textContent = data.total_execution_time + ' 秒';
  275. } else {
  276. document.getElementById('totalTime').textContent = formatTimestamp(data.timestamp);
  277. }
  278. const hasError = data.error || (data.final_result && data.final_result.retrieval_status === 'no_results');
  279. document.getElementById('execStatus').textContent = hasError ? '异常' : '成功';
  280. document.getElementById('execStatus').style.color = hasError ? '#ff5555' : '#00ff88';
  281. }
  282. /**
  283. * 渲染流程图
  284. */
  285. function renderFlowChart(data) {
  286. flowContainer.innerHTML = '';
  287. const steps = data.steps || {};
  288. Object.entries(steps).forEach(([stepKey, stepData], index) => {
  289. const config = stageConfig[stepKey] || {
  290. icon: '📦',
  291. title: stepData.name || stepKey,
  292. description: ''
  293. };
  294. const node = document.createElement('div');
  295. node.className = 'flow-node';
  296. node.dataset.step = stepKey;
  297. const inputCount = stepData.input ? Object.keys(stepData.input).length : 0;
  298. const outputCount = stepData.output ? Object.keys(stepData.output).length : 0;
  299. const execTime = stepData.execution_time ? `${stepData.execution_time}s` : '-';
  300. node.innerHTML = `
  301. <div class="node-header">
  302. <span class="node-icon">${config.icon}</span>
  303. <span class="node-title">${stepData.name || config.title}</span>
  304. <span class="node-step">Step ${index + 1}</span>
  305. </div>
  306. <div class="node-stats">
  307. <div class="node-stat">
  308. <span>输入字段</span>
  309. <span class="node-stat-value">${inputCount}</span>
  310. </div>
  311. <div class="node-stat">
  312. <span>输出字段</span>
  313. <span class="node-stat-value">${outputCount}</span>
  314. </div>
  315. </div>
  316. <div class="node-time">⏱️ ${execTime}</div>
  317. `;
  318. node.addEventListener('click', () => selectStep(stepKey, stepData));
  319. flowContainer.appendChild(node);
  320. });
  321. }
  322. /**
  323. * 选择步骤显示详情
  324. */
  325. function selectStep(stepKey, stepData) {
  326. currentSelectedStep = stepKey;
  327. // 更新节点选中状态
  328. document.querySelectorAll('.flow-node').forEach(node => {
  329. node.classList.toggle('active', node.dataset.step === stepKey);
  330. });
  331. // 显示详情面板
  332. detailPanel.style.display = 'block';
  333. // 渲染输入输出数据
  334. document.getElementById('inputViewer').innerHTML = formatJson(stepData.input || {});
  335. document.getElementById('outputViewer').innerHTML = formatJson(stepData.output || {});
  336. document.getElementById('rawViewer').innerHTML = formatJson(stepData);
  337. // 滚动到详情面板
  338. detailPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
  339. }
  340. /**
  341. * 渲染各阶段详情
  342. */
  343. function renderStagesDetail(data) {
  344. stagesAccordion.innerHTML = '';
  345. const steps = data.steps || {};
  346. Object.entries(steps).forEach(([stepKey, stepData], index) => {
  347. const config = stageConfig[stepKey] || {
  348. icon: '📦',
  349. title: stepKey,
  350. description: ''
  351. };
  352. const item = document.createElement('div');
  353. item.className = 'accordion-item';
  354. item.innerHTML = `
  355. <div class="accordion-header" onclick="toggleAccordion(this)">
  356. <div class="accordion-title">
  357. <span>${config.icon}</span>
  358. <span>Step ${index + 1}: ${config.title}</span>
  359. </div>
  360. <span class="accordion-icon">▼</span>
  361. </div>
  362. <div class="accordion-content">
  363. ${renderStepContent(stepKey, stepData)}
  364. </div>
  365. `;
  366. stagesAccordion.appendChild(item);
  367. });
  368. }
  369. /**
  370. * 渲染步骤内容
  371. */
  372. function renderStepContent(stepKey, stepData) {
  373. let html = `
  374. <div class="data-flow">
  375. <div class="data-section input">
  376. <h4>输入数据</h4>
  377. <pre class="json-viewer">${formatJson(stepData.input || {})}</pre>
  378. </div>
  379. <div class="data-section output">
  380. <h4>输出数据</h4>
  381. <pre class="json-viewer">${formatJson(stepData.output || {})}</pre>
  382. </div>
  383. </div>
  384. `;
  385. // 如果有子步骤(如实体增强检索的process_details)
  386. if (stepData.output && stepData.output.process_details) {
  387. html += `<div class="sub-steps"><h4>🔬 子步骤详情</h4>`;
  388. stepData.output.process_details.forEach((detail, idx) => {
  389. html += `
  390. <div class="sub-step">
  391. <div class="sub-step-header">查询对 ${detail.index || idx + 1}</div>
  392. <div class="data-flow">
  393. <div class="data-section input">
  394. <h4>输入</h4>
  395. <pre class="json-viewer">${formatJson(detail.input || {})}</pre>
  396. </div>
  397. <div class="data-section output">
  398. <h4>子步骤</h4>
  399. <pre class="json-viewer">${formatJson(detail.steps || {})}</pre>
  400. </div>
  401. </div>
  402. </div>
  403. `;
  404. });
  405. html += `</div>`;
  406. }
  407. return html;
  408. }
  409. /**
  410. * 切换手风琴
  411. */
  412. function toggleAccordion(header) {
  413. const content = header.nextElementSibling;
  414. const isActive = header.classList.contains('active');
  415. // 关闭所有
  416. document.querySelectorAll('.accordion-header').forEach(h => h.classList.remove('active'));
  417. document.querySelectorAll('.accordion-content').forEach(c => c.classList.remove('active'));
  418. // 如果之前不是激活状态,则打开当前
  419. if (!isActive) {
  420. header.classList.add('active');
  421. content.classList.add('active');
  422. }
  423. }
  424. /**
  425. * 格式化JSON为带语法高亮的HTML
  426. */
  427. function formatJson(obj) {
  428. const json = JSON.stringify(obj, null, 2);
  429. return syntaxHighlight(json);
  430. }
  431. /**
  432. * JSON语法高亮
  433. */
  434. function syntaxHighlight(json) {
  435. json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  436. return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
  437. let cls = 'json-number';
  438. if (/^"/.test(match)) {
  439. if (/:$/.test(match)) {
  440. cls = 'json-key';
  441. } else {
  442. cls = 'json-string';
  443. }
  444. } else if (/true|false/.test(match)) {
  445. cls = 'json-boolean';
  446. } else if (/null/.test(match)) {
  447. cls = 'json-null';
  448. }
  449. return '<span class="' + cls + '">' + match + '</span>';
  450. });
  451. }
  452. /**
  453. * 格式化时间戳
  454. */
  455. function formatTimestamp(timestamp) {
  456. if (!timestamp) return '-';
  457. const date = new Date(timestamp * 1000);
  458. return date.toLocaleString('zh-CN');
  459. }