workflow_visualization.py 34 KB

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