templateHtml.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. templateHtml.py - 生成 Trace 执行流程可视化 HTML
  5. 参考 visualize.py 的样式设计
  6. """
  7. import json
  8. import os
  9. from pathlib import Path
  10. def generate_trace_visualization_html(goal_list: list, msg_groups: dict, output_path: str = None):
  11. """
  12. 生成 Trace 可视化 HTML 文件
  13. Args:
  14. goal_list: 节点列表
  15. msg_groups: 节点消息分组
  16. output_path: 输出的 HTML 文件路径
  17. """
  18. if goal_list is None:
  19. goal_list = []
  20. if msg_groups is None:
  21. msg_groups = {}
  22. # 1.新建一个数组goal_list_new = goal_list
  23. goal_list_new = list(goal_list)
  24. # 2.查找msg_groups如果里面包含START,那么需要在goal_list_new添加一个对象
  25. if "START" in msg_groups:
  26. start_node = {
  27. "id": "START",
  28. "description": "START",
  29. "reason": None,
  30. "parent_id": None,
  31. "type": "start",
  32. "status": "completed",
  33. "summary": None,
  34. "sub_trace_ids": None,
  35. "agent_call_mode": None,
  36. "self_stats": None,
  37. "cumulative_stats": None,
  38. "created_at": None,
  39. "sub_trace_metadata": None
  40. }
  41. # 确保 START 节点在最前面或合适位置,这里直接 append
  42. # 如果需要它作为根节点被正确渲染,它应该在列表里即可
  43. goal_list_new.insert(0, start_node)
  44. # 读取 HTML 模板
  45. template_path = Path(__file__).parent / "trace_template.html"
  46. with open(template_path, "r", encoding="utf-8") as f:
  47. template_content = f.read()
  48. html_content = template_content.replace(
  49. '"__GOAL_LIST__"',
  50. json.dumps(goal_list_new, ensure_ascii=False)
  51. ).replace(
  52. '"__MSG_GROUPS__"',
  53. json.dumps(msg_groups, ensure_ascii=False)
  54. )
  55. # 确定输出路径
  56. if output_path is None:
  57. output_path = Path(__file__).parent / "trace_visualization.html"
  58. else:
  59. output_path = Path(output_path)
  60. mock_dir = Path(__file__).parent / "mock_data"
  61. mock_dir.mkdir(parents=True, exist_ok=True)
  62. with open(mock_dir / "goal_list.json", "w", encoding="utf-8") as f:
  63. json.dump(goal_list_new, f, ensure_ascii=False, indent=2)
  64. with open(mock_dir / "msg_groups.json", "w", encoding="utf-8") as f:
  65. json.dump(msg_groups, f, ensure_ascii=False, indent=2)
  66. # 写入 HTML 文件
  67. with open(output_path, 'w', encoding='utf-8') as f:
  68. f.write(html_content)
  69. print(f"可视化文件已生成: {output_path}")
  70. return output_path
  71. if __name__ == "__main__":
  72. generate_trace_visualization_html([], {})