Spaces:
Sleeping
Sleeping
Enhance report generation process with improved formatting and content management
Browse files- Introduced strict formatting guidelines for chapter content, prohibiting the use of Markdown headers and emphasizing the use of bold text for section titles.
- Implemented a new method to save chapters along with their subsections into a single file, streamlining the report structure.
- Added content cleaning functionality to remove duplicate titles and ensure proper formatting before saving.
- Enhanced the report assembly process to include post-processing for title management and improved readability.
- backend/app/services/report_agent.py +368 -47
- backend/app/services/zep_tools.py +36 -26
backend/app/services/report_agent.py
CHANGED
|
@@ -603,6 +603,11 @@ class ReportAgent:
|
|
| 603 |
logger.info(f"ReACT生成章节: {section.title}")
|
| 604 |
|
| 605 |
# 构建系统prompt - 优化后强调工具使用和引用原文
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 606 |
system_prompt = f"""你是一个专业的舆情分析报告撰写专家,正在撰写报告的一个章节。
|
| 607 |
|
| 608 |
报告标题: {outline.title}
|
|
@@ -632,6 +637,44 @@ class ReportAgent:
|
|
| 632 |
- 不要添加模拟中不存在的信息
|
| 633 |
- 如果某方面信息不足,如实说明
|
| 634 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 635 |
═══════════════════════════════════════════════════════════════
|
| 636 |
【可用检索工具】(建议每章节调用2-5次)
|
| 637 |
═══════════════════════════════════════════════════════════════
|
|
@@ -662,32 +705,65 @@ class ReportAgent:
|
|
| 662 |
|
| 663 |
1. 内容必须基于工具检索到的模拟数据
|
| 664 |
2. 大量引用原文来展示模拟效果
|
| 665 |
-
3. 使用Markdown格式:
|
| 666 |
-
- 使用
|
| 667 |
-
- 使用
|
| 668 |
-
- 使用
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
|
| 677 |
══════════════════════════════════════════════════════��════════
|
| 678 |
【当前任务】撰写章节: {section.title}
|
| 679 |
═══════════════════════════════════════════════════════════════
|
| 680 |
|
| 681 |
【重要提醒】
|
| 682 |
-
1.
|
| 683 |
-
2.
|
| 684 |
-
3.
|
| 685 |
4. 报告内容必须来自检索结果,不要使用自己的知识
|
| 686 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 687 |
请开始:
|
| 688 |
1. 首先思考(Thought)这个章节需要什么信息
|
| 689 |
2. 然后调用工具(Action)获取模拟数据
|
| 690 |
-
3. 收集足够信息后输出 Final Answer"""
|
| 691 |
|
| 692 |
messages = [
|
| 693 |
{"role": "system", "content": system_prompt},
|
|
@@ -921,7 +997,7 @@ class ReportAgent:
|
|
| 921 |
f"正在生成章节: {section.title} ({section_num}/{total_sections})"
|
| 922 |
)
|
| 923 |
|
| 924 |
-
# 生成章节内容
|
| 925 |
section_content = self._generate_section_react(
|
| 926 |
section=section,
|
| 927 |
outline=outline,
|
|
@@ -937,35 +1013,21 @@ class ReportAgent:
|
|
| 937 |
section.content = section_content
|
| 938 |
generated_sections.append(f"## {section.title}\n\n{section_content}")
|
| 939 |
|
| 940 |
-
#
|
| 941 |
-
|
| 942 |
-
completed_section_titles.append(section.title)
|
| 943 |
-
|
| 944 |
-
logger.info(f"章节已保存: {report_id}/section_{section_num:02d}.md")
|
| 945 |
-
|
| 946 |
-
# 更新进度
|
| 947 |
-
ReportManager.update_progress(
|
| 948 |
-
report_id, "generating",
|
| 949 |
-
base_progress + int(70 / total_sections),
|
| 950 |
-
f"章节 {section.title} 已完成",
|
| 951 |
-
current_section=None,
|
| 952 |
-
completed_sections=completed_section_titles
|
| 953 |
-
)
|
| 954 |
-
|
| 955 |
-
# 生成并保存子章节
|
| 956 |
for j, subsection in enumerate(section.subsections):
|
| 957 |
subsection_num = j + 1
|
| 958 |
|
| 959 |
if progress_callback:
|
| 960 |
progress_callback(
|
| 961 |
"generating",
|
| 962 |
-
base_progress + int(((j + 1) / len(section.subsections)) * 5),
|
| 963 |
f"正在生成子章节: {subsection.title}"
|
| 964 |
)
|
| 965 |
|
| 966 |
ReportManager.update_progress(
|
| 967 |
report_id, "generating",
|
| 968 |
-
base_progress + int(((j + 1) / len(section.subsections)) * 5),
|
| 969 |
f"正在生成子章节: {subsection.title}",
|
| 970 |
current_section=subsection.title,
|
| 971 |
completed_sections=completed_section_titles
|
|
@@ -979,15 +1041,27 @@ class ReportAgent:
|
|
| 979 |
)
|
| 980 |
subsection.content = subsection_content
|
| 981 |
generated_sections.append(f"### {subsection.title}\n\n{subsection_content}")
|
| 982 |
-
|
| 983 |
-
# 【关键】立即保存子章节到文件
|
| 984 |
-
ReportManager.save_section(
|
| 985 |
-
report_id, subsection_num, subsection,
|
| 986 |
-
is_subsection=True, parent_index=section_num
|
| 987 |
-
)
|
| 988 |
completed_section_titles.append(f" └─ {subsection.title}")
|
| 989 |
|
| 990 |
-
logger.info(f"子章节已
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 991 |
|
| 992 |
# 阶段3: 组装完整报告
|
| 993 |
if progress_callback:
|
|
@@ -1292,7 +1366,7 @@ class ReportManager:
|
|
| 1292 |
parent_index: int = None
|
| 1293 |
) -> str:
|
| 1294 |
"""
|
| 1295 |
-
保存单个章节
|
| 1296 |
|
| 1297 |
在每个章节生成完成后立即调用,实现分章节输出
|
| 1298 |
|
|
@@ -1316,10 +1390,11 @@ class ReportManager:
|
|
| 1316 |
level = "##"
|
| 1317 |
file_suffix = f"section_{section_index:02d}.md"
|
| 1318 |
|
| 1319 |
-
# 构建章节Markdown内容
|
|
|
|
| 1320 |
md_content = f"{level} {section.title}\n\n"
|
| 1321 |
-
if
|
| 1322 |
-
md_content += f"{
|
| 1323 |
|
| 1324 |
# 保存文件
|
| 1325 |
file_path = os.path.join(cls._get_report_folder(report_id), file_suffix)
|
|
@@ -1329,6 +1404,118 @@ class ReportManager:
|
|
| 1329 |
logger.info(f"章节已保存: {report_id}/{file_suffix}")
|
| 1330 |
return file_path
|
| 1331 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1332 |
@classmethod
|
| 1333 |
def update_progress(
|
| 1334 |
cls,
|
|
@@ -1408,7 +1595,7 @@ class ReportManager:
|
|
| 1408 |
"""
|
| 1409 |
组装完整报告
|
| 1410 |
|
| 1411 |
-
从已保存的章节文件组装完整报告
|
| 1412 |
"""
|
| 1413 |
folder = cls._get_report_folder(report_id)
|
| 1414 |
|
|
@@ -1417,11 +1604,17 @@ class ReportManager:
|
|
| 1417 |
md_content += f"> {outline.summary}\n\n"
|
| 1418 |
md_content += f"---\n\n"
|
| 1419 |
|
| 1420 |
-
# 按顺序读取所有章节文件
|
| 1421 |
sections = cls.get_generated_sections(report_id)
|
| 1422 |
for section_info in sections:
|
|
|
|
|
|
|
|
|
|
| 1423 |
md_content += section_info["content"]
|
| 1424 |
|
|
|
|
|
|
|
|
|
|
| 1425 |
# 保存完整报告
|
| 1426 |
full_path = cls._get_report_markdown_path(report_id)
|
| 1427 |
with open(full_path, 'w', encoding='utf-8') as f:
|
|
@@ -1430,6 +1623,134 @@ class ReportManager:
|
|
| 1430 |
logger.info(f"完整报告已组装: {report_id}")
|
| 1431 |
return md_content
|
| 1432 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1433 |
@classmethod
|
| 1434 |
def save_report(cls, report: Report) -> None:
|
| 1435 |
"""保存报告元信息和完整报告"""
|
|
|
|
| 603 |
logger.info(f"ReACT生成章节: {section.title}")
|
| 604 |
|
| 605 |
# 构建系统prompt - 优化后强调工具使用和引用原文
|
| 606 |
+
# 确定当前章节的标题级别
|
| 607 |
+
section_level = 2 # 默认为二级标题(##)
|
| 608 |
+
sub_heading_level = 3 # 子标题使用三级(###)
|
| 609 |
+
sub_sub_heading_level = 4 # 更小的子标题使用四级(####)
|
| 610 |
+
|
| 611 |
system_prompt = f"""你是一个专业的舆情分析报告撰写专家,正在撰写报告的一个章节。
|
| 612 |
|
| 613 |
报告标题: {outline.title}
|
|
|
|
| 637 |
- 不要添加模拟中不存在的信息
|
| 638 |
- 如果某方面信息不足,如实说明
|
| 639 |
|
| 640 |
+
═══════════════════════════════════════════════════════════════
|
| 641 |
+
【⚠️ 格式规范 - 极其重要!】
|
| 642 |
+
═══════════════════════════════════════════════════════════════
|
| 643 |
+
|
| 644 |
+
【一个章节 = 最小内容单位】
|
| 645 |
+
- 每个章节是报告的最小分块单位
|
| 646 |
+
- ❌ 禁止在章节内使用任何 Markdown 标题(#、##、###、#### 等)
|
| 647 |
+
- ❌ 禁止在内容开头添加章节主标题
|
| 648 |
+
- ✅ 章节标题由系统自动添加,你只需撰写纯正文内容
|
| 649 |
+
- ✅ 使用**粗体**、段落分隔、引用、列表来组织内容,但不要用标题
|
| 650 |
+
|
| 651 |
+
【正确示例】
|
| 652 |
+
```
|
| 653 |
+
本章节分析了事件的舆论传播态势。通过对模拟数据的深入分析,我们发现...
|
| 654 |
+
|
| 655 |
+
**首发引爆阶段**
|
| 656 |
+
|
| 657 |
+
微博作为舆情的第一现场,承担了信息首发的核心功能:
|
| 658 |
+
|
| 659 |
+
> "微博贡献了68%的首发声量..."
|
| 660 |
+
|
| 661 |
+
**情绪放大阶段**
|
| 662 |
+
|
| 663 |
+
抖音平台进一步放大了事件影响力:
|
| 664 |
+
|
| 665 |
+
- 视觉冲击力强
|
| 666 |
+
- 情绪共鸣度高
|
| 667 |
+
```
|
| 668 |
+
|
| 669 |
+
【错误示例】
|
| 670 |
+
```
|
| 671 |
+
## 执行摘要 ← 错误!不要添加任何标题
|
| 672 |
+
### 一、首发阶段 ← 错误!不要用###分小节
|
| 673 |
+
#### 1.1 详细分析 ← 错误!不要用####细分
|
| 674 |
+
|
| 675 |
+
本章节分析了...
|
| 676 |
+
```
|
| 677 |
+
|
| 678 |
═══════════════════════════════════════════════════════════════
|
| 679 |
【可用检索工具】(建议每章节调用2-5次)
|
| 680 |
═══════════════════════════════════════════════════════════════
|
|
|
|
| 705 |
|
| 706 |
1. 内容必须基于工具检索到的模拟数据
|
| 707 |
2. 大量引用原文来展示模拟效果
|
| 708 |
+
3. 使用Markdown格式(但禁止使用标题):
|
| 709 |
+
- 使用 **粗体文字** 标记重点(代替子标题)
|
| 710 |
+
- 使用列表(-或1.2.3.)组织要点
|
| 711 |
+
- 使用空行分隔不同段落
|
| 712 |
+
- ❌ 禁止使用 #、##、###、#### 等任何标题语法
|
| 713 |
+
4. 【引用格式规范 - 必须单独成段】
|
| 714 |
+
引用必须独立成段,前后各有一个空行,不能混在段落中:
|
| 715 |
+
|
| 716 |
+
✅ 正确格式:
|
| 717 |
+
```
|
| 718 |
+
校方的回应被认为缺乏实质内容。
|
| 719 |
+
|
| 720 |
+
> "校方的应对模式在瞬息万变的社交媒体环境中显得僵化和迟缓。"
|
| 721 |
+
|
| 722 |
+
这一评价反映了公众的普遍不满。
|
| 723 |
+
```
|
| 724 |
+
|
| 725 |
+
❌ 错误格式:
|
| 726 |
+
```
|
| 727 |
+
校方的回应被认为缺乏实质内容。> "校方的应对模式..." 这一评价反映了...
|
| 728 |
+
```
|
| 729 |
+
5. 保持与其他章节的逻辑连贯性
|
| 730 |
+
6. 【避免重复】仔细阅读下方已完成的章节内容,不要重复描述相同的信息
|
| 731 |
+
7. 【再次强调】不要添加任何标题!用**粗体**代替小节标题"""
|
| 732 |
+
|
| 733 |
+
# 构建用户prompt - 每个已完成章节各传入最大4000字
|
| 734 |
+
if previous_sections:
|
| 735 |
+
previous_parts = []
|
| 736 |
+
for sec in previous_sections:
|
| 737 |
+
# 每个章节最多4000字
|
| 738 |
+
truncated = sec[:4000] + "..." if len(sec) > 4000 else sec
|
| 739 |
+
previous_parts.append(truncated)
|
| 740 |
+
previous_content = "\n\n---\n\n".join(previous_parts)
|
| 741 |
+
else:
|
| 742 |
+
previous_content = "(这是第一个章节)"
|
| 743 |
+
|
| 744 |
+
user_prompt = f"""已完成的章节内容(请仔细阅读,避免重复):
|
| 745 |
+
{previous_content}
|
| 746 |
|
| 747 |
══════════════════════════════════════════════════════��════════
|
| 748 |
【当前任务】撰写章节: {section.title}
|
| 749 |
═══════════════════════════════════════════════════════════════
|
| 750 |
|
| 751 |
【重要提醒】
|
| 752 |
+
1. 仔细阅读上方已完成的章节,避免重复相同的内容!
|
| 753 |
+
2. 开始前必须先调用工具获取模拟数据
|
| 754 |
+
3. 推荐先使用 insight_forge 进行深度检索
|
| 755 |
4. 报告内容必须来自检索结果,不要使用自己的知识
|
| 756 |
|
| 757 |
+
【⚠️ 格式警告 - 必须遵守】
|
| 758 |
+
- ❌ 不要写任何标题(#、##、###、####都不行)
|
| 759 |
+
- ❌ 不要写"{section.title}"作为开头
|
| 760 |
+
- ✅ 章节标题由系统自动添加
|
| 761 |
+
- ✅ 直接写正文,用**粗体**代替小节标题
|
| 762 |
+
|
| 763 |
请开始:
|
| 764 |
1. 首先思考(Thought)这个章节需要什么信息
|
| 765 |
2. 然后调用工具(Action)获取模拟数据
|
| 766 |
+
3. 收集足够信息后输出 Final Answer(纯正文,无任何标题)"""
|
| 767 |
|
| 768 |
messages = [
|
| 769 |
{"role": "system", "content": system_prompt},
|
|
|
|
| 997 |
f"正在生成章节: {section.title} ({section_num}/{total_sections})"
|
| 998 |
)
|
| 999 |
|
| 1000 |
+
# 生成主章节内容
|
| 1001 |
section_content = self._generate_section_react(
|
| 1002 |
section=section,
|
| 1003 |
outline=outline,
|
|
|
|
| 1013 |
section.content = section_content
|
| 1014 |
generated_sections.append(f"## {section.title}\n\n{section_content}")
|
| 1015 |
|
| 1016 |
+
# 如果有子章节,也一并生成并合并到主章节中
|
| 1017 |
+
subsection_contents = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1018 |
for j, subsection in enumerate(section.subsections):
|
| 1019 |
subsection_num = j + 1
|
| 1020 |
|
| 1021 |
if progress_callback:
|
| 1022 |
progress_callback(
|
| 1023 |
"generating",
|
| 1024 |
+
base_progress + int(((j + 1) / max(len(section.subsections), 1)) * 5),
|
| 1025 |
f"正在生成子章节: {subsection.title}"
|
| 1026 |
)
|
| 1027 |
|
| 1028 |
ReportManager.update_progress(
|
| 1029 |
report_id, "generating",
|
| 1030 |
+
base_progress + int(((j + 1) / max(len(section.subsections), 1)) * 5),
|
| 1031 |
f"正在生成子章节: {subsection.title}",
|
| 1032 |
current_section=subsection.title,
|
| 1033 |
completed_sections=completed_section_titles
|
|
|
|
| 1041 |
)
|
| 1042 |
subsection.content = subsection_content
|
| 1043 |
generated_sections.append(f"### {subsection.title}\n\n{subsection_content}")
|
| 1044 |
+
subsection_contents.append((subsection.title, subsection_content))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1045 |
completed_section_titles.append(f" └─ {subsection.title}")
|
| 1046 |
|
| 1047 |
+
logger.info(f"子章节已生成: {subsection.title}")
|
| 1048 |
+
|
| 1049 |
+
# 【关键】将主章节和所有子章节合并保存到一个文件
|
| 1050 |
+
ReportManager.save_section_with_subsections(
|
| 1051 |
+
report_id, section_num, section, subsection_contents
|
| 1052 |
+
)
|
| 1053 |
+
completed_section_titles.append(section.title)
|
| 1054 |
+
|
| 1055 |
+
logger.info(f"��节已保存(包含{len(subsection_contents)}个子章节): {report_id}/section_{section_num:02d}.md")
|
| 1056 |
+
|
| 1057 |
+
# 更新进度
|
| 1058 |
+
ReportManager.update_progress(
|
| 1059 |
+
report_id, "generating",
|
| 1060 |
+
base_progress + int(70 / total_sections),
|
| 1061 |
+
f"章节 {section.title} 已完成",
|
| 1062 |
+
current_section=None,
|
| 1063 |
+
completed_sections=completed_section_titles
|
| 1064 |
+
)
|
| 1065 |
|
| 1066 |
# 阶段3: 组装完整报告
|
| 1067 |
if progress_callback:
|
|
|
|
| 1366 |
parent_index: int = None
|
| 1367 |
) -> str:
|
| 1368 |
"""
|
| 1369 |
+
保存单个章节(不推荐使用,建议使用 save_section_with_subsections)
|
| 1370 |
|
| 1371 |
在每个章节生成完成后立即调用,实现分章节输出
|
| 1372 |
|
|
|
|
| 1390 |
level = "##"
|
| 1391 |
file_suffix = f"section_{section_index:02d}.md"
|
| 1392 |
|
| 1393 |
+
# 构建章节Markdown内容 - 清理可能存在的重复标题
|
| 1394 |
+
cleaned_content = cls._clean_section_content(section.content, section.title)
|
| 1395 |
md_content = f"{level} {section.title}\n\n"
|
| 1396 |
+
if cleaned_content:
|
| 1397 |
+
md_content += f"{cleaned_content}\n\n"
|
| 1398 |
|
| 1399 |
# 保存文件
|
| 1400 |
file_path = os.path.join(cls._get_report_folder(report_id), file_suffix)
|
|
|
|
| 1404 |
logger.info(f"章节已保存: {report_id}/{file_suffix}")
|
| 1405 |
return file_path
|
| 1406 |
|
| 1407 |
+
@classmethod
|
| 1408 |
+
def save_section_with_subsections(
|
| 1409 |
+
cls,
|
| 1410 |
+
report_id: str,
|
| 1411 |
+
section_index: int,
|
| 1412 |
+
section: ReportSection,
|
| 1413 |
+
subsection_contents: List[tuple]
|
| 1414 |
+
) -> str:
|
| 1415 |
+
"""
|
| 1416 |
+
保存章节及其所有子章节到一个文件
|
| 1417 |
+
|
| 1418 |
+
Args:
|
| 1419 |
+
report_id: 报告ID
|
| 1420 |
+
section_index: 章节索引(从1开始)
|
| 1421 |
+
section: 主章节对象
|
| 1422 |
+
subsection_contents: 子章节列表 [(title, content), ...]
|
| 1423 |
+
|
| 1424 |
+
Returns:
|
| 1425 |
+
保存的文件路径
|
| 1426 |
+
"""
|
| 1427 |
+
cls._ensure_report_folder(report_id)
|
| 1428 |
+
|
| 1429 |
+
# 构建主章节Markdown内容
|
| 1430 |
+
cleaned_main_content = cls._clean_section_content(section.content, section.title)
|
| 1431 |
+
md_content = f"## {section.title}\n\n"
|
| 1432 |
+
if cleaned_main_content:
|
| 1433 |
+
md_content += f"{cleaned_main_content}\n\n"
|
| 1434 |
+
|
| 1435 |
+
# 添加所有子章节内容
|
| 1436 |
+
for sub_title, sub_content in subsection_contents:
|
| 1437 |
+
cleaned_sub_content = cls._clean_section_content(sub_content, sub_title)
|
| 1438 |
+
md_content += f"### {sub_title}\n\n"
|
| 1439 |
+
if cleaned_sub_content:
|
| 1440 |
+
md_content += f"{cleaned_sub_content}\n\n"
|
| 1441 |
+
|
| 1442 |
+
# 保存文件
|
| 1443 |
+
file_suffix = f"section_{section_index:02d}.md"
|
| 1444 |
+
file_path = os.path.join(cls._get_report_folder(report_id), file_suffix)
|
| 1445 |
+
with open(file_path, 'w', encoding='utf-8') as f:
|
| 1446 |
+
f.write(md_content)
|
| 1447 |
+
|
| 1448 |
+
logger.info(f"章节已保存(含{len(subsection_contents)}个子章节): {report_id}/{file_suffix}")
|
| 1449 |
+
return file_path
|
| 1450 |
+
|
| 1451 |
+
@classmethod
|
| 1452 |
+
def _clean_section_content(cls, content: str, section_title: str) -> str:
|
| 1453 |
+
"""
|
| 1454 |
+
清理章节内容
|
| 1455 |
+
|
| 1456 |
+
1. 移除内容开头与章节标题重复的Markdown标题行
|
| 1457 |
+
2. 将所有 ### 及以下级别的标题转换为粗体文本
|
| 1458 |
+
|
| 1459 |
+
Args:
|
| 1460 |
+
content: 原始内容
|
| 1461 |
+
section_title: 章节标题
|
| 1462 |
+
|
| 1463 |
+
Returns:
|
| 1464 |
+
清理后的内容
|
| 1465 |
+
"""
|
| 1466 |
+
import re
|
| 1467 |
+
|
| 1468 |
+
if not content:
|
| 1469 |
+
return content
|
| 1470 |
+
|
| 1471 |
+
content = content.strip()
|
| 1472 |
+
lines = content.split('\n')
|
| 1473 |
+
cleaned_lines = []
|
| 1474 |
+
skip_next_empty = False
|
| 1475 |
+
|
| 1476 |
+
for i, line in enumerate(lines):
|
| 1477 |
+
stripped = line.strip()
|
| 1478 |
+
|
| 1479 |
+
# 检查是否是Markdown标题行
|
| 1480 |
+
heading_match = re.match(r'^(#{1,6})\s+(.+)$', stripped)
|
| 1481 |
+
|
| 1482 |
+
if heading_match:
|
| 1483 |
+
level = len(heading_match.group(1))
|
| 1484 |
+
title_text = heading_match.group(2).strip()
|
| 1485 |
+
|
| 1486 |
+
# 检查是否是与章节标题重复的标题(跳过前5行内的重复)
|
| 1487 |
+
if i < 5:
|
| 1488 |
+
if title_text == section_title or title_text.replace(' ', '') == section_title.replace(' ', ''):
|
| 1489 |
+
skip_next_empty = True
|
| 1490 |
+
continue
|
| 1491 |
+
|
| 1492 |
+
# 将所有级别的标题(#, ##, ###, ####等)转换为粗体
|
| 1493 |
+
# 因为章节标题由系统添加,内容中不应有任何标题
|
| 1494 |
+
cleaned_lines.append(f"**{title_text}**")
|
| 1495 |
+
cleaned_lines.append("") # 添加空行
|
| 1496 |
+
continue
|
| 1497 |
+
|
| 1498 |
+
# 如果上一行是被跳过的标题,且当前行为空,也跳过
|
| 1499 |
+
if skip_next_empty and stripped == '':
|
| 1500 |
+
skip_next_empty = False
|
| 1501 |
+
continue
|
| 1502 |
+
|
| 1503 |
+
skip_next_empty = False
|
| 1504 |
+
cleaned_lines.append(line)
|
| 1505 |
+
|
| 1506 |
+
# 移除开头的空行
|
| 1507 |
+
while cleaned_lines and cleaned_lines[0].strip() == '':
|
| 1508 |
+
cleaned_lines.pop(0)
|
| 1509 |
+
|
| 1510 |
+
# 移除开头的分隔线
|
| 1511 |
+
while cleaned_lines and cleaned_lines[0].strip() in ['---', '***', '___']:
|
| 1512 |
+
cleaned_lines.pop(0)
|
| 1513 |
+
# 同时移除分隔线后的空行
|
| 1514 |
+
while cleaned_lines and cleaned_lines[0].strip() == '':
|
| 1515 |
+
cleaned_lines.pop(0)
|
| 1516 |
+
|
| 1517 |
+
return '\n'.join(cleaned_lines)
|
| 1518 |
+
|
| 1519 |
@classmethod
|
| 1520 |
def update_progress(
|
| 1521 |
cls,
|
|
|
|
| 1595 |
"""
|
| 1596 |
组装完整报告
|
| 1597 |
|
| 1598 |
+
从已保存的章节文件组装完整报告,并进行标题清理
|
| 1599 |
"""
|
| 1600 |
folder = cls._get_report_folder(report_id)
|
| 1601 |
|
|
|
|
| 1604 |
md_content += f"> {outline.summary}\n\n"
|
| 1605 |
md_content += f"---\n\n"
|
| 1606 |
|
| 1607 |
+
# 按顺序读取所有章节文件(只读取主章节文件,不读取子章节文件)
|
| 1608 |
sections = cls.get_generated_sections(report_id)
|
| 1609 |
for section_info in sections:
|
| 1610 |
+
# 跳过子章节文件(已合并到主章节中)
|
| 1611 |
+
if section_info.get("is_subsection", False):
|
| 1612 |
+
continue
|
| 1613 |
md_content += section_info["content"]
|
| 1614 |
|
| 1615 |
+
# 后处理:清理整个报告的标题问题
|
| 1616 |
+
md_content = cls._post_process_report(md_content, outline)
|
| 1617 |
+
|
| 1618 |
# 保存完整报告
|
| 1619 |
full_path = cls._get_report_markdown_path(report_id)
|
| 1620 |
with open(full_path, 'w', encoding='utf-8') as f:
|
|
|
|
| 1623 |
logger.info(f"完整报告已组装: {report_id}")
|
| 1624 |
return md_content
|
| 1625 |
|
| 1626 |
+
@classmethod
|
| 1627 |
+
def _post_process_report(cls, content: str, outline: ReportOutline) -> str:
|
| 1628 |
+
"""
|
| 1629 |
+
后处理报告内容
|
| 1630 |
+
|
| 1631 |
+
1. 移除重复的标题
|
| 1632 |
+
2. 保留报告主标题(#)和章节标题(##),移除其他级别的标题(###, ####等)
|
| 1633 |
+
3. 清理多余的空行和分隔线
|
| 1634 |
+
|
| 1635 |
+
Args:
|
| 1636 |
+
content: 原始报告内容
|
| 1637 |
+
outline: 报告大纲
|
| 1638 |
+
|
| 1639 |
+
Returns:
|
| 1640 |
+
处理后的内容
|
| 1641 |
+
"""
|
| 1642 |
+
import re
|
| 1643 |
+
|
| 1644 |
+
lines = content.split('\n')
|
| 1645 |
+
processed_lines = []
|
| 1646 |
+
prev_was_heading = False
|
| 1647 |
+
|
| 1648 |
+
# 收集大纲中的所有章节标题
|
| 1649 |
+
section_titles = set()
|
| 1650 |
+
for section in outline.sections:
|
| 1651 |
+
section_titles.add(section.title)
|
| 1652 |
+
for sub in section.subsections:
|
| 1653 |
+
section_titles.add(sub.title)
|
| 1654 |
+
|
| 1655 |
+
i = 0
|
| 1656 |
+
while i < len(lines):
|
| 1657 |
+
line = lines[i]
|
| 1658 |
+
stripped = line.strip()
|
| 1659 |
+
|
| 1660 |
+
# 检查是否是标题行
|
| 1661 |
+
heading_match = re.match(r'^(#{1,6})\s+(.+)$', stripped)
|
| 1662 |
+
|
| 1663 |
+
if heading_match:
|
| 1664 |
+
level = len(heading_match.group(1))
|
| 1665 |
+
title = heading_match.group(2).strip()
|
| 1666 |
+
|
| 1667 |
+
# 检查是否是重复标题(在连续5行内出现相同内容的标题)
|
| 1668 |
+
is_duplicate = False
|
| 1669 |
+
for j in range(max(0, len(processed_lines) - 5), len(processed_lines)):
|
| 1670 |
+
prev_line = processed_lines[j].strip()
|
| 1671 |
+
prev_match = re.match(r'^(#{1,6})\s+(.+)$', prev_line)
|
| 1672 |
+
if prev_match:
|
| 1673 |
+
prev_title = prev_match.group(2).strip()
|
| 1674 |
+
if prev_title == title:
|
| 1675 |
+
is_duplicate = True
|
| 1676 |
+
break
|
| 1677 |
+
|
| 1678 |
+
if is_duplicate:
|
| 1679 |
+
# 跳过重复标题及其后的空行
|
| 1680 |
+
i += 1
|
| 1681 |
+
while i < len(lines) and lines[i].strip() == '':
|
| 1682 |
+
i += 1
|
| 1683 |
+
continue
|
| 1684 |
+
|
| 1685 |
+
# 标题层级处理:
|
| 1686 |
+
# - # (level=1) 只保留报告主标题
|
| 1687 |
+
# - ## (level=2) 保留章节标题
|
| 1688 |
+
# - ### 及以下 (level>=3) 转换为粗体文本
|
| 1689 |
+
|
| 1690 |
+
if level == 1:
|
| 1691 |
+
if title == outline.title:
|
| 1692 |
+
# 保留报告主标题
|
| 1693 |
+
processed_lines.append(line)
|
| 1694 |
+
prev_was_heading = True
|
| 1695 |
+
elif title in section_titles:
|
| 1696 |
+
# 章节标题错误使用了#,修正为##
|
| 1697 |
+
processed_lines.append(f"## {title}")
|
| 1698 |
+
prev_was_heading = True
|
| 1699 |
+
else:
|
| 1700 |
+
# 其他一级标题转为粗体
|
| 1701 |
+
processed_lines.append(f"**{title}**")
|
| 1702 |
+
processed_lines.append("")
|
| 1703 |
+
prev_was_heading = False
|
| 1704 |
+
elif level == 2:
|
| 1705 |
+
if title in section_titles or title == outline.title:
|
| 1706 |
+
# 保留章节标题
|
| 1707 |
+
processed_lines.append(line)
|
| 1708 |
+
prev_was_heading = True
|
| 1709 |
+
else:
|
| 1710 |
+
# 非章节的二级标题转为粗体
|
| 1711 |
+
processed_lines.append(f"**{title}**")
|
| 1712 |
+
processed_lines.append("")
|
| 1713 |
+
prev_was_heading = False
|
| 1714 |
+
else:
|
| 1715 |
+
# ### 及以下级别的标题转换为粗体文本
|
| 1716 |
+
processed_lines.append(f"**{title}**")
|
| 1717 |
+
processed_lines.append("")
|
| 1718 |
+
prev_was_heading = False
|
| 1719 |
+
|
| 1720 |
+
i += 1
|
| 1721 |
+
continue
|
| 1722 |
+
|
| 1723 |
+
elif stripped == '---' and prev_was_heading:
|
| 1724 |
+
# 跳过标题后紧跟的分隔线
|
| 1725 |
+
i += 1
|
| 1726 |
+
continue
|
| 1727 |
+
|
| 1728 |
+
elif stripped == '' and prev_was_heading:
|
| 1729 |
+
# 标题后只保留一个空行
|
| 1730 |
+
if processed_lines and processed_lines[-1].strip() != '':
|
| 1731 |
+
processed_lines.append(line)
|
| 1732 |
+
prev_was_heading = False
|
| 1733 |
+
|
| 1734 |
+
else:
|
| 1735 |
+
processed_lines.append(line)
|
| 1736 |
+
prev_was_heading = False
|
| 1737 |
+
|
| 1738 |
+
i += 1
|
| 1739 |
+
|
| 1740 |
+
# 清理连续的多个空行(保留最多2个)
|
| 1741 |
+
result_lines = []
|
| 1742 |
+
empty_count = 0
|
| 1743 |
+
for line in processed_lines:
|
| 1744 |
+
if line.strip() == '':
|
| 1745 |
+
empty_count += 1
|
| 1746 |
+
if empty_count <= 2:
|
| 1747 |
+
result_lines.append(line)
|
| 1748 |
+
else:
|
| 1749 |
+
empty_count = 0
|
| 1750 |
+
result_lines.append(line)
|
| 1751 |
+
|
| 1752 |
+
return '\n'.join(result_lines)
|
| 1753 |
+
|
| 1754 |
@classmethod
|
| 1755 |
def save_report(cls, report: Report) -> None:
|
| 1756 |
"""保存报告元信息和完整报告"""
|
backend/app/services/zep_tools.py
CHANGED
|
@@ -1009,37 +1009,47 @@ class ZepToolsService:
|
|
| 1009 |
result.semantic_facts = all_facts
|
| 1010 |
result.total_facts = len(all_facts)
|
| 1011 |
|
| 1012 |
-
# Step 3: 提取相关实体
|
| 1013 |
-
all_nodes = self.get_all_nodes(graph_id)
|
| 1014 |
-
node_map = {n.uuid: n for n in all_nodes}
|
| 1015 |
-
|
| 1016 |
-
# 从边中提取涉及的实体
|
| 1017 |
entity_uuids = set()
|
| 1018 |
for edge_data in all_edges:
|
| 1019 |
if isinstance(edge_data, dict):
|
| 1020 |
-
|
| 1021 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1022 |
|
| 1023 |
-
# 获取实体详情
|
| 1024 |
entity_insights = []
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1043 |
|
| 1044 |
result.entity_insights = entity_insights
|
| 1045 |
result.total_entities = len(entity_insights)
|
|
|
|
| 1009 |
result.semantic_facts = all_facts
|
| 1010 |
result.total_facts = len(all_facts)
|
| 1011 |
|
| 1012 |
+
# Step 3: 从边中提取相关实体UUID,只获取这些实体的信息(不获取全部节点)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1013 |
entity_uuids = set()
|
| 1014 |
for edge_data in all_edges:
|
| 1015 |
if isinstance(edge_data, dict):
|
| 1016 |
+
source_uuid = edge_data.get('source_node_uuid', '')
|
| 1017 |
+
target_uuid = edge_data.get('target_node_uuid', '')
|
| 1018 |
+
if source_uuid:
|
| 1019 |
+
entity_uuids.add(source_uuid)
|
| 1020 |
+
if target_uuid:
|
| 1021 |
+
entity_uuids.add(target_uuid)
|
| 1022 |
|
| 1023 |
+
# 只获取相关实体的详情(限制数量,避免获取过多)
|
| 1024 |
entity_insights = []
|
| 1025 |
+
node_map = {} # 用于后续关系链构建
|
| 1026 |
+
|
| 1027 |
+
for uuid in list(entity_uuids)[:50]: # 最多30个实体
|
| 1028 |
+
if not uuid:
|
| 1029 |
+
continue
|
| 1030 |
+
try:
|
| 1031 |
+
# 单独获取每个相关节点的信息
|
| 1032 |
+
node = self.get_node_detail(uuid)
|
| 1033 |
+
if node:
|
| 1034 |
+
node_map[uuid] = node
|
| 1035 |
+
entity_type = next((l for l in node.labels if l not in ["Entity", "Node"]), "实体")
|
| 1036 |
+
|
| 1037 |
+
# 获取该实体相关的事实
|
| 1038 |
+
related_facts = [
|
| 1039 |
+
f for f in all_facts
|
| 1040 |
+
if node.name.lower() in f.lower()
|
| 1041 |
+
]
|
| 1042 |
+
|
| 1043 |
+
entity_insights.append({
|
| 1044 |
+
"uuid": node.uuid,
|
| 1045 |
+
"name": node.name,
|
| 1046 |
+
"type": entity_type,
|
| 1047 |
+
"summary": node.summary,
|
| 1048 |
+
"related_facts": related_facts[:5]
|
| 1049 |
+
})
|
| 1050 |
+
except Exception as e:
|
| 1051 |
+
logger.debug(f"获取节点 {uuid} 失败: {e}")
|
| 1052 |
+
continue
|
| 1053 |
|
| 1054 |
result.entity_insights = entity_insights
|
| 1055 |
result.total_entities = len(entity_insights)
|