workflow_visualization.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. '''
  4. 知识获取工作流可视化
  5. 1. 读取知识获取工作流详细过程数据文件(参考 .cache/9f510b2a8348/execution_record.json)
  6. 2. 文件路径可设置,每个文件表示一个输入信息执行过程,可能有多个。多个文件路径硬编码在代码中,用list表示
  7. 3. 将知识获取工作流用html页面展示出来
  8. 4. HTML 文件输出路径在当前目录下,文件名称为 workflow_visualization_datetime.html
  9. '''
  10. import json
  11. import os
  12. from datetime import datetime
  13. from pathlib import Path
  14. # 硬编码的文件路径列表(相对于项目根目录)
  15. DATA_FILE_PATHS = [
  16. "../.cache/dd8dd68ebf0c/execution_record.json",
  17. "../.cache/70a208f70a7e/execution_record.json",
  18. "../.cache/996e626b9c85/execution_record.json",
  19. # 可以在这里添加更多文件路径
  20. ]
  21. def load_data_files(file_paths):
  22. """读取并解析JSON文件"""
  23. data_list = []
  24. script_dir = Path(__file__).parent
  25. for file_path in file_paths:
  26. # 将相对路径转换为绝对路径
  27. abs_path = (script_dir / file_path).resolve()
  28. if not abs_path.exists():
  29. print(f"警告: 文件不存在: {abs_path}")
  30. continue
  31. try:
  32. with open(abs_path, 'r', encoding='utf-8') as f:
  33. data = json.load(f)
  34. data_list.append(data)
  35. except (json.JSONDecodeError, IOError) as e:
  36. print(f"错误: 读取文件失败 {abs_path}: {e}")
  37. return data_list
  38. def parse_workflow_data(data):
  39. """解析工作流数据,提取关键信息"""
  40. workflow = {
  41. 'input': {},
  42. 'steps': [],
  43. 'output': {}
  44. }
  45. # 提取输入信息
  46. if 'input' in data:
  47. workflow['input'] = {
  48. 'question': data['input'].get('question', ''),
  49. 'post_info': data['input'].get('post_info', ''),
  50. 'persona_info': data['input'].get('persona_info', '')
  51. }
  52. # 提取执行流程(新格式:execution 直接包含各步骤,不再有 modules.function_knowledge)
  53. if 'execution' in data:
  54. execution = data['execution']
  55. # 步骤1: 生成query
  56. if 'generate_query' in execution:
  57. generate_query = execution['generate_query']
  58. workflow['steps'].append({
  59. 'step': 'generate_query',
  60. 'name': '生成查询',
  61. 'query': generate_query.get('query', '') or generate_query.get('response', ''),
  62. 'prompt': generate_query.get('prompt', '')
  63. })
  64. # 步骤2: 选择工具
  65. if 'select_tool' in execution:
  66. select_tool = execution['select_tool']
  67. response = select_tool.get('response', {})
  68. workflow['steps'].append({
  69. 'step': 'select_tool',
  70. 'name': '选择工具',
  71. 'prompt': select_tool.get('prompt', ''),
  72. 'tool_name': response.get('工具名', '') if isinstance(response, dict) else '',
  73. 'tool_id': response.get('工具调用ID', '') if isinstance(response, dict) else '',
  74. 'tool_usage': response.get('使用方法', '') if isinstance(response, dict) else ''
  75. })
  76. # 判断是否选择了工具(如果 response 为空字典或没有工具信息,则没有选择到工具)
  77. has_tool = False
  78. if 'select_tool' in execution:
  79. select_tool = execution['select_tool']
  80. response = select_tool.get('response', {})
  81. if isinstance(response, dict) and response.get('工具名'):
  82. has_tool = True
  83. # 如果选择了工具,执行工具调用流程
  84. if has_tool:
  85. # 步骤3: 提取参数
  86. if 'extract_params' in execution:
  87. extract_params = execution['extract_params']
  88. workflow['steps'].append({
  89. 'step': 'extract_params',
  90. 'name': '提取参数',
  91. 'prompt': extract_params.get('prompt', ''),
  92. 'params': extract_params.get('params', {})
  93. })
  94. # 步骤4: 执行工具(新格式:tool_call 替代 execute_tool)
  95. if 'tool_call' in execution:
  96. tool_call = execution['tool_call']
  97. # 优先使用 result,如果没有则使用 response
  98. result = tool_call.get('result', '')
  99. if not result and tool_call.get('response'):
  100. # 如果 response 是字典,尝试提取其中的 result
  101. response = tool_call.get('response', {})
  102. if isinstance(response, dict):
  103. result = response.get('result', response)
  104. else:
  105. result = response
  106. workflow['steps'].append({
  107. 'step': 'execute_tool',
  108. 'name': '执行工具',
  109. 'response': result or tool_call.get('response', '')
  110. })
  111. # 如果没有选择到工具,进行知识搜索流程
  112. else:
  113. if 'knowledge_search' in execution:
  114. knowledge_search = execution['knowledge_search']
  115. # 步骤3: LLM搜索(大模型+search 渠道的搜索过程)
  116. if 'llm_search' in knowledge_search:
  117. llm_search = knowledge_search['llm_search']
  118. search_results = llm_search.get('search_results', [])
  119. workflow['steps'].append({
  120. 'step': 'llm_search',
  121. 'name': 'LLM搜索',
  122. 'search_results': search_results
  123. })
  124. # 步骤4: 多渠道搜索结果整合
  125. if 'multi_search_merge' in knowledge_search:
  126. multi_search_merge = knowledge_search['multi_search_merge']
  127. workflow['steps'].append({
  128. 'step': 'multi_search_merge',
  129. 'name': '多渠道搜索结果整合',
  130. 'prompt': multi_search_merge.get('prompt', ''),
  131. 'response': multi_search_merge.get('response', ''),
  132. 'sources_count': multi_search_merge.get('sources_count', 0),
  133. 'valid_sources_count': multi_search_merge.get('valid_sources_count', 0)
  134. })
  135. # 提取输出信息
  136. if 'output' in data:
  137. workflow['output'] = {
  138. 'result': data['output'].get('result', '')
  139. }
  140. return workflow
  141. def escape_html(text):
  142. """转义HTML特殊字符"""
  143. if not isinstance(text, str):
  144. text = str(text)
  145. return (text.replace('&', '&')
  146. .replace('<', '&lt;')
  147. .replace('>', '&gt;')
  148. .replace('"', '&quot;')
  149. .replace("'", '&#39;'))
  150. def format_json_for_display(obj):
  151. """格式化JSON对象用于显示"""
  152. if isinstance(obj, dict):
  153. return json.dumps(obj, ensure_ascii=False, indent=2)
  154. elif isinstance(obj, str):
  155. try:
  156. parsed = json.loads(obj)
  157. return json.dumps(parsed, ensure_ascii=False, indent=2)
  158. except (json.JSONDecodeError, ValueError):
  159. return obj
  160. return str(obj)
  161. def generate_html(workflows):
  162. """生成HTML页面"""
  163. html = '''<!DOCTYPE html>
  164. <html lang="zh-CN">
  165. <head>
  166. <meta charset="UTF-8">
  167. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  168. <title>知识获取工作流可视化</title>
  169. <style>
  170. * {
  171. margin: 0;
  172. padding: 0;
  173. box-sizing: border-box;
  174. }
  175. body {
  176. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  177. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  178. color: #333;
  179. line-height: 1.6;
  180. min-height: 100vh;
  181. }
  182. .container {
  183. max-width: 1400px;
  184. margin: 0 auto;
  185. padding: 30px 20px;
  186. }
  187. h1 {
  188. text-align: center;
  189. color: white;
  190. margin-bottom: 40px;
  191. font-size: 32px;
  192. font-weight: 600;
  193. text-shadow: 0 2px 10px rgba(0,0,0,0.2);
  194. letter-spacing: 1px;
  195. }
  196. .tabs {
  197. display: flex;
  198. background: white;
  199. border-radius: 12px 12px 0 0;
  200. box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  201. overflow-x: auto;
  202. padding: 5px;
  203. }
  204. .tab {
  205. padding: 16px 28px;
  206. cursor: pointer;
  207. border: none;
  208. background: transparent;
  209. color: #666;
  210. font-size: 14px;
  211. transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  212. white-space: nowrap;
  213. border-radius: 8px;
  214. margin: 0 4px;
  215. position: relative;
  216. font-weight: 500;
  217. }
  218. .tab:hover {
  219. background: #f0f0f0;
  220. color: #333;
  221. }
  222. .tab.active {
  223. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  224. color: white;
  225. box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  226. }
  227. .tab-content {
  228. display: none;
  229. background: white;
  230. padding: 40px;
  231. border-radius: 0 0 12px 12px;
  232. box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  233. margin-bottom: 20px;
  234. animation: fadeIn 0.3s ease-in;
  235. }
  236. @keyframes fadeIn {
  237. from { opacity: 0; transform: translateY(10px); }
  238. to { opacity: 1; transform: translateY(0); }
  239. }
  240. .tab-content.active {
  241. display: block;
  242. }
  243. .input-section {
  244. background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  245. padding: 28px;
  246. border-radius: 12px;
  247. margin-bottom: 35px;
  248. box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  249. border: 1px solid rgba(255,255,255,0.5);
  250. }
  251. .input-section h3 {
  252. color: #2c3e50;
  253. margin-bottom: 20px;
  254. font-size: 20px;
  255. font-weight: 600;
  256. display: flex;
  257. align-items: center;
  258. gap: 10px;
  259. }
  260. .input-section h3::before {
  261. content: '📋';
  262. font-size: 24px;
  263. }
  264. .input-item {
  265. margin-bottom: 16px;
  266. padding: 12px;
  267. background: rgba(255,255,255,0.7);
  268. border-radius: 8px;
  269. transition: all 0.3s;
  270. }
  271. .input-item:hover {
  272. background: rgba(255,255,255,0.9);
  273. transform: translateX(5px);
  274. }
  275. .input-item strong {
  276. color: #495057;
  277. display: inline-block;
  278. width: 110px;
  279. font-weight: 600;
  280. }
  281. .input-item .placeholder {
  282. color: #999;
  283. font-style: italic;
  284. }
  285. .workflow {
  286. position: relative;
  287. }
  288. .workflow-step {
  289. background: white;
  290. border: 2px solid #e0e0e0;
  291. border-radius: 12px;
  292. margin-bottom: 25px;
  293. transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  294. overflow: hidden;
  295. box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  296. }
  297. .workflow-step.active {
  298. border-color: #667eea;
  299. box-shadow: 0 8px 24px rgba(102, 126, 234, 0.25);
  300. transform: translateY(-2px);
  301. }
  302. .step-header {
  303. padding: 20px 24px;
  304. background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  305. cursor: pointer;
  306. display: flex;
  307. justify-content: space-between;
  308. align-items: center;
  309. user-select: none;
  310. transition: all 0.3s;
  311. }
  312. .step-header:hover {
  313. background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
  314. }
  315. .workflow-step.active .step-header {
  316. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  317. color: white;
  318. }
  319. .workflow-step.active .step-name {
  320. color: white;
  321. }
  322. .workflow-step.active .step-toggle {
  323. color: white;
  324. }
  325. .step-title {
  326. display: flex;
  327. align-items: center;
  328. gap: 15px;
  329. }
  330. .step-number {
  331. display: inline-flex;
  332. align-items: center;
  333. justify-content: center;
  334. width: 36px;
  335. height: 36px;
  336. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  337. color: white;
  338. border-radius: 50%;
  339. font-size: 16px;
  340. font-weight: bold;
  341. box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  342. }
  343. .workflow-step.active .step-number {
  344. background: white;
  345. color: #667eea;
  346. box-shadow: 0 4px 12px rgba(255,255,255,0.3);
  347. }
  348. .step-name {
  349. font-size: 18px;
  350. font-weight: 600;
  351. color: #2c3e50;
  352. }
  353. .step-toggle {
  354. color: #6c757d;
  355. font-size: 20px;
  356. transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  357. }
  358. .step-toggle.expanded {
  359. transform: rotate(180deg);
  360. }
  361. .step-content {
  362. padding: 0 20px;
  363. max-height: 0;
  364. overflow: hidden;
  365. transition: max-height 0.3s ease-out, padding 0.3s;
  366. }
  367. .step-content.expanded {
  368. max-height: 5000px;
  369. padding: 20px;
  370. }
  371. .step-detail {
  372. margin-bottom: 20px;
  373. }
  374. .step-detail-label {
  375. font-weight: 600;
  376. color: #495057;
  377. margin-bottom: 10px;
  378. display: block;
  379. font-size: 14px;
  380. text-transform: uppercase;
  381. letter-spacing: 0.5px;
  382. }
  383. .step-detail-content {
  384. background: #f8f9fa;
  385. padding: 16px;
  386. border-radius: 8px;
  387. border-left: 4px solid #667eea;
  388. font-size: 14px;
  389. line-height: 1.8;
  390. white-space: pre-wrap;
  391. word-wrap: break-word;
  392. max-height: 400px;
  393. overflow-y: auto;
  394. box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  395. }
  396. .json-content {
  397. font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
  398. background: #1e1e1e;
  399. color: #d4d4d4;
  400. padding: 20px;
  401. border-radius: 8px;
  402. overflow-x: auto;
  403. border-left: 4px solid #667eea;
  404. box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  405. }
  406. .prompt-toggle-btn {
  407. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  408. color: white;
  409. border: none;
  410. padding: 10px 20px;
  411. border-radius: 6px;
  412. cursor: pointer;
  413. font-size: 13px;
  414. font-weight: 500;
  415. margin-top: 15px;
  416. transition: all 0.3s;
  417. box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  418. }
  419. .prompt-toggle-btn:hover {
  420. transform: translateY(-2px);
  421. box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  422. }
  423. .prompt-content {
  424. display: none;
  425. margin-top: 15px;
  426. padding: 16px;
  427. background: #fff3cd;
  428. border-radius: 8px;
  429. border-left: 4px solid #ffc107;
  430. font-size: 13px;
  431. line-height: 1.8;
  432. white-space: pre-wrap;
  433. word-wrap: break-word;
  434. max-height: 500px;
  435. overflow-y: auto;
  436. }
  437. .prompt-content.show {
  438. display: block;
  439. animation: slideDown 0.3s ease-out;
  440. }
  441. @keyframes slideDown {
  442. from {
  443. opacity: 0;
  444. max-height: 0;
  445. }
  446. to {
  447. opacity: 1;
  448. max-height: 500px;
  449. }
  450. }
  451. .output-section {
  452. background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
  453. padding: 28px;
  454. border-radius: 12px;
  455. margin-top: 35px;
  456. border-left: 4px solid #0ea5e9;
  457. box-shadow: 0 4px 15px rgba(14, 165, 233, 0.2);
  458. }
  459. .output-section h3 {
  460. color: #0369a1;
  461. margin-bottom: 20px;
  462. font-size: 20px;
  463. font-weight: 600;
  464. display: flex;
  465. align-items: center;
  466. gap: 10px;
  467. }
  468. .output-section h3::before {
  469. content: '✨';
  470. font-size: 24px;
  471. }
  472. .arrow {
  473. text-align: center;
  474. color: #667eea;
  475. font-size: 32px;
  476. margin: -15px 0;
  477. position: relative;
  478. z-index: 1;
  479. filter: drop-shadow(0 2px 4px rgba(102, 126, 234, 0.3));
  480. }
  481. .arrow::before {
  482. content: '↓';
  483. }
  484. @media (max-width: 768px) {
  485. .container {
  486. padding: 10px;
  487. }
  488. .tab {
  489. padding: 12px 15px;
  490. font-size: 13px;
  491. }
  492. .tab-content {
  493. padding: 20px;
  494. }
  495. }
  496. </style>
  497. </head>
  498. <body>
  499. <div class="container">
  500. <h1>知识获取工作流可视化</h1>
  501. <div class="tabs" id="tabs">
  502. '''
  503. # 生成Tab标签
  504. for i, workflow in enumerate(workflows):
  505. question = workflow['input'].get('question', f'问题 {i+1}')
  506. active_class = 'active' if i == 0 else ''
  507. html += f' <button class="tab {active_class}" onclick="switchTab({i})">{escape_html(question)}</button>\n'
  508. html += ' </div>\n'
  509. # 生成Tab内容
  510. for i, workflow in enumerate(workflows):
  511. active_class = 'active' if i == 0 else ''
  512. html += f' <div class="tab-content {active_class}" id="tab-{i}">\n'
  513. # 输入信息
  514. html += ' <div class="input-section">\n'
  515. html += ' <h3>输入信息</h3>\n'
  516. html += f' <div class="input-item"><strong>问题:</strong> {escape_html(workflow["input"].get("question", ""))}</div>\n'
  517. post_info = workflow['input'].get('post_info', '')
  518. post_info_display = escape_html(post_info) if post_info else '<span class="placeholder">(无)</span>'
  519. html += f' <div class="input-item"><strong>帖子信息:</strong> {post_info_display}</div>\n'
  520. persona_info = workflow['input'].get('persona_info', '')
  521. persona_info_display = escape_html(persona_info) if persona_info else '<span class="placeholder">(无)</span>'
  522. html += f' <div class="input-item"><strong>人设信息:</strong> {persona_info_display}</div>\n'
  523. html += ' </div>\n'
  524. # 工作流程
  525. html += ' <div class="workflow">\n'
  526. for j, step in enumerate(workflow['steps']):
  527. step_id = f"step-{i}-{j}"
  528. html += f' <div class="workflow-step" id="{step_id}">\n'
  529. html += ' <div class="step-header" onclick="toggleStep(\'' + step_id + '\')">\n'
  530. html += ' <div class="step-title">\n'
  531. html += f' <span class="step-number">{j+1}</span>\n'
  532. html += f' <span class="step-name">{escape_html(step["name"])}</span>\n'
  533. html += ' </div>\n'
  534. html += ' <span class="step-toggle">▼</span>\n'
  535. html += ' </div>\n'
  536. html += ' <div class="step-content" id="content-' + step_id + '">\n'
  537. # 根据步骤类型显示不同内容(prompt放在最后,默认隐藏)
  538. prompt_id = f"prompt-{step_id}"
  539. if step['step'] == 'generate_query':
  540. if step.get('query'):
  541. html += ' <div class="step-detail">\n'
  542. html += ' <span class="step-detail-label">生成的Query:</span>\n'
  543. html += f' <div class="step-detail-content">{escape_html(step["query"])}</div>\n'
  544. html += ' </div>\n'
  545. elif step['step'] == 'select_tool':
  546. # 判断是否选择了工具
  547. if step.get('tool_name'):
  548. html += ' <div class="step-detail">\n'
  549. html += ' <span class="step-detail-label">工具名称:</span>\n'
  550. html += f' <div class="step-detail-content">{escape_html(step["tool_name"])}</div>\n'
  551. html += ' </div>\n'
  552. if step.get('tool_id'):
  553. html += ' <div class="step-detail">\n'
  554. html += ' <span class="step-detail-label">工具调用ID:</span>\n'
  555. html += f' <div class="step-detail-content">{escape_html(step["tool_id"])}</div>\n'
  556. html += ' </div>\n'
  557. if step.get('tool_usage'):
  558. html += ' <div class="step-detail">\n'
  559. html += ' <span class="step-detail-label">使用方法:</span>\n'
  560. html += f' <div class="step-detail-content">{escape_html(step["tool_usage"])}</div>\n'
  561. html += ' </div>\n'
  562. else:
  563. # 无工具选择时显示提示
  564. html += ' <div class="step-detail">\n'
  565. html += ' <span class="step-detail-label">选择结果:</span>\n'
  566. html += ' <div class="step-detail-content" style="color: #dc3545; font-weight: 500;">无匹配工具</div>\n'
  567. html += ' </div>\n'
  568. elif step['step'] == 'extract_params':
  569. if step.get('params'):
  570. html += ' <div class="step-detail">\n'
  571. html += ' <span class="step-detail-label">提取的参数:</span>\n'
  572. params_str = format_json_for_display(step['params'])
  573. html += f' <div class="step-detail-content json-content">{escape_html(params_str)}</div>\n'
  574. html += ' </div>\n'
  575. elif step['step'] == 'execute_tool':
  576. if step.get('response'):
  577. html += ' <div class="step-detail">\n'
  578. html += ' <span class="step-detail-label">执行结果:</span>\n'
  579. response_str = format_json_for_display(step['response'])
  580. html += f' <div class="step-detail-content json-content">{escape_html(response_str)}</div>\n'
  581. html += ' </div>\n'
  582. elif step['step'] == 'llm_search':
  583. search_results = step.get('search_results', [])
  584. if search_results:
  585. html += ' <div class="step-detail">\n'
  586. html += ' <span class="step-detail-label">搜索结果:</span>\n'
  587. for idx, result in enumerate(search_results, 1):
  588. query = result.get('query', '')
  589. content = result.get('content', '')
  590. html += ' <div style="margin-bottom: 15px; padding: 12px; background: #f0f8ff; border-radius: 6px; border-left: 3px solid #4a90e2;">\n'
  591. html += f' <div style="font-weight: 600; color: #2c3e50; margin-bottom: 8px;">查询 {idx}: {escape_html(query)}</div>\n'
  592. html += f' <div style="color: #555; line-height: 1.6; white-space: pre-wrap;">{escape_html(content)}</div>\n'
  593. html += ' </div>\n'
  594. html += ' </div>\n'
  595. elif step['step'] == 'multi_search_merge':
  596. if step.get('sources_count') is not None:
  597. html += ' <div class="step-detail">\n'
  598. html += ' <span class="step-detail-label">来源统计:</span>\n'
  599. html += f' <div class="step-detail-content">总来源数: {step.get("sources_count", 0)}, 有效来源数: {step.get("valid_sources_count", 0)}</div>\n'
  600. html += ' </div>\n'
  601. if step.get('response'):
  602. html += ' <div class="step-detail">\n'
  603. html += ' <span class="step-detail-label">整合结果:</span>\n'
  604. response_str = format_json_for_display(step['response'])
  605. html += f' <div class="step-detail-content">{escape_html(response_str)}</div>\n'
  606. html += ' </div>\n'
  607. # Prompt放在最后,默认隐藏
  608. if step.get('prompt'):
  609. html += f' <button class="prompt-toggle-btn" onclick="togglePrompt(\'{prompt_id}\')">显示 Prompt</button>\n'
  610. html += f' <div class="prompt-content" id="{prompt_id}">{escape_html(step["prompt"])}</div>\n'
  611. html += ' </div>\n'
  612. html += ' </div>\n'
  613. # 添加箭头(除了最后一步)
  614. if j < len(workflow['steps']) - 1:
  615. html += ' <div class="arrow"></div>\n'
  616. html += ' </div>\n'
  617. # 输出信息
  618. if workflow['output'].get('result'):
  619. html += ' <div class="output-section">\n'
  620. html += ' <h3>最终输出</h3>\n'
  621. result_str = format_json_for_display(workflow['output']['result'])
  622. html += f' <div class="step-detail-content json-content">{escape_html(result_str)}</div>\n'
  623. html += ' </div>\n'
  624. html += ' </div>\n'
  625. html += ''' </div>
  626. <script>
  627. function switchTab(index) {
  628. // 隐藏所有tab内容
  629. const contents = document.querySelectorAll('.tab-content');
  630. contents.forEach(content => content.classList.remove('active'));
  631. // 移除所有tab的active状态
  632. const tabs = document.querySelectorAll('.tab');
  633. tabs.forEach(tab => tab.classList.remove('active'));
  634. // 显示选中的tab内容
  635. document.getElementById('tab-' + index).classList.add('active');
  636. tabs[index].classList.add('active');
  637. }
  638. function toggleStep(stepId) {
  639. const step = document.getElementById(stepId);
  640. const content = document.getElementById('content-' + stepId);
  641. const toggle = step.querySelector('.step-toggle');
  642. if (content.classList.contains('expanded')) {
  643. content.classList.remove('expanded');
  644. toggle.classList.remove('expanded');
  645. step.classList.remove('active');
  646. } else {
  647. content.classList.add('expanded');
  648. toggle.classList.add('expanded');
  649. step.classList.add('active');
  650. }
  651. }
  652. function togglePrompt(promptId) {
  653. const promptContent = document.getElementById(promptId);
  654. const btn = promptContent.previousElementSibling;
  655. if (promptContent.classList.contains('show')) {
  656. promptContent.classList.remove('show');
  657. btn.textContent = '显示 Prompt';
  658. } else {
  659. promptContent.classList.add('show');
  660. btn.textContent = '隐藏 Prompt';
  661. }
  662. }
  663. // 页面加载时高亮第一个步骤
  664. window.addEventListener('load', function() {
  665. const firstSteps = document.querySelectorAll('.workflow-step');
  666. firstSteps.forEach((step, index) => {
  667. if (index === 0 || index % (firstSteps.length / document.querySelectorAll('.tab-content').length) === 0) {
  668. step.classList.add('active');
  669. const content = step.querySelector('.step-content');
  670. const toggle = step.querySelector('.step-toggle');
  671. if (content) {
  672. content.classList.add('expanded');
  673. toggle.classList.add('expanded');
  674. }
  675. }
  676. });
  677. });
  678. </script>
  679. </body>
  680. </html>'''
  681. return html
  682. def main():
  683. """主函数"""
  684. # 获取当前脚本所在目录
  685. script_dir = Path(__file__).parent
  686. os.chdir(script_dir)
  687. # 读取数据文件
  688. print("正在读取数据文件...")
  689. data_list = load_data_files(DATA_FILE_PATHS)
  690. if not data_list:
  691. print("错误: 没有成功读取任何数据文件")
  692. return
  693. print(f"成功读取 {len(data_list)} 个数据文件")
  694. # 解析工作流数据
  695. print("正在解析工作流数据...")
  696. workflows = [parse_workflow_data(data) for data in data_list]
  697. # 生成HTML
  698. print("正在生成HTML页面...")
  699. html = generate_html(workflows)
  700. # 保存HTML文件
  701. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  702. output_filename = f"workflow_visualization_{timestamp}.html"
  703. with open(output_filename, 'w', encoding='utf-8') as f:
  704. f.write(html)
  705. print(f"HTML页面已生成: {output_filename}")
  706. print(f"文件路径: {os.path.abspath(output_filename)}")
  707. if __name__ == '__main__':
  708. main()