-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathreport_agent.py
More file actions
2588 lines (2149 loc) · 97.9 KB
/
report_agent.py
File metadata and controls
2588 lines (2149 loc) · 97.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Report Agent服务
使用LangChain + Zep实现ReACT模式的模拟报告生成
功能:
1. 根据模拟需求和Zep图谱信息生成报告
2. 先规划目录结构,然后分段生成
3. 每段采用ReACT多轮思考与反思模式
4. 支持与用户对话,在对话中自主调用检索工具
"""
import os
import json
import time
import re
from typing import Dict, Any, List, Optional, Callable
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from ..config import Config
from ..utils.llm_client import LLMClient
from ..utils.logger import get_logger
from .zep_tools import (
ZepToolsService,
SearchResult,
InsightForgeResult,
PanoramaResult,
InterviewResult
)
logger = get_logger('mirofish.report_agent')
class ReportLogger:
"""
Report Agent 详细日志记录器
在报告文件夹中生成 agent_log.jsonl 文件,记录每一步详细动作。
每行是一个完整的 JSON 对象,包含时间戳、动作类型、详细内容等。
"""
def __init__(self, report_id: str):
"""
初始化日志记录器
Args:
report_id: 报告ID,用于确定日志文件路径
"""
self.report_id = report_id
self.log_file_path = os.path.join(
Config.UPLOAD_FOLDER, 'reports', report_id, 'agent_log.jsonl'
)
self.start_time = datetime.now()
self._ensure_log_file()
def _ensure_log_file(self):
"""确保日志文件所在目录存在"""
log_dir = os.path.dirname(self.log_file_path)
os.makedirs(log_dir, exist_ok=True)
def _get_elapsed_time(self) -> float:
"""获取从开始到现在的耗时(秒)"""
return (datetime.now() - self.start_time).total_seconds()
def log(
self,
action: str,
stage: str,
details: Dict[str, Any],
section_title: str = None,
section_index: int = None
):
"""
记录一条日志
Args:
action: 动作类型,如 'start', 'tool_call', 'llm_response', 'section_complete' 等
stage: 当前阶段,如 'planning', 'generating', 'completed'
details: 详细内容字典,不截断
section_title: 当前章节标题(可选)
section_index: 当前章节索引(可选)
"""
log_entry = {
"timestamp": datetime.now().isoformat(),
"elapsed_seconds": round(self._get_elapsed_time(), 2),
"report_id": self.report_id,
"action": action,
"stage": stage,
"section_title": section_title,
"section_index": section_index,
"details": details
}
# 追加写入 JSONL 文件
with open(self.log_file_path, 'a', encoding='utf-8') as f:
f.write(json.dumps(log_entry, ensure_ascii=False) + '\n')
def log_start(self, simulation_id: str, graph_id: str, simulation_requirement: str):
"""记录报告生成开始"""
self.log(
action="report_start",
stage="pending",
details={
"simulation_id": simulation_id,
"graph_id": graph_id,
"simulation_requirement": simulation_requirement,
"message": "报告生成任务开始"
}
)
def log_planning_start(self):
"""记录大纲规划开始"""
self.log(
action="planning_start",
stage="planning",
details={"message": "开始规划报告大纲"}
)
def log_planning_context(self, context: Dict[str, Any]):
"""记录规划时获取的上下文信息"""
self.log(
action="planning_context",
stage="planning",
details={
"message": "获取模拟上下文信息",
"context": context
}
)
def log_planning_complete(self, outline_dict: Dict[str, Any]):
"""记录大纲规划完成"""
self.log(
action="planning_complete",
stage="planning",
details={
"message": "大纲规划完成",
"outline": outline_dict
}
)
def log_section_start(self, section_title: str, section_index: int):
"""记录章节生成开始"""
self.log(
action="section_start",
stage="generating",
section_title=section_title,
section_index=section_index,
details={"message": f"开始生成章节: {section_title}"}
)
def log_react_thought(self, section_title: str, section_index: int, iteration: int, thought: str):
"""记录 ReACT 思考过程"""
self.log(
action="react_thought",
stage="generating",
section_title=section_title,
section_index=section_index,
details={
"iteration": iteration,
"thought": thought,
"message": f"ReACT 第{iteration}轮思考"
}
)
def log_tool_call(
self,
section_title: str,
section_index: int,
tool_name: str,
parameters: Dict[str, Any],
iteration: int
):
"""记录工具调用"""
self.log(
action="tool_call",
stage="generating",
section_title=section_title,
section_index=section_index,
details={
"iteration": iteration,
"tool_name": tool_name,
"parameters": parameters,
"message": f"调用工具: {tool_name}"
}
)
def log_tool_result(
self,
section_title: str,
section_index: int,
tool_name: str,
result: str,
iteration: int
):
"""记录工具调用结果(完整内容,不截断)"""
self.log(
action="tool_result",
stage="generating",
section_title=section_title,
section_index=section_index,
details={
"iteration": iteration,
"tool_name": tool_name,
"result": result, # 完整结果,不截断
"result_length": len(result),
"message": f"工具 {tool_name} 返回结果"
}
)
def log_llm_response(
self,
section_title: str,
section_index: int,
response: str,
iteration: int,
has_tool_calls: bool,
has_final_answer: bool
):
"""记录 LLM 响应(完整内容,不截断)"""
self.log(
action="llm_response",
stage="generating",
section_title=section_title,
section_index=section_index,
details={
"iteration": iteration,
"response": response, # 完整响应,不截断
"response_length": len(response),
"has_tool_calls": has_tool_calls,
"has_final_answer": has_final_answer,
"message": f"LLM 响应 (工具调用: {has_tool_calls}, 最终答案: {has_final_answer})"
}
)
def log_section_content(
self,
section_title: str,
section_index: int,
content: str,
tool_calls_count: int
):
"""记录章节内容生成完成(仅记录内容,不代表整个章节完成)"""
self.log(
action="section_content",
stage="generating",
section_title=section_title,
section_index=section_index,
details={
"content": content, # 完整内容,不截断
"content_length": len(content),
"tool_calls_count": tool_calls_count,
"message": f"章节 {section_title} 内容生成完成"
}
)
def log_section_full_complete(
self,
section_title: str,
section_index: int,
full_content: str
):
"""
记录章节生成完成
前端应监听此日志来判断一个章节是否真正完成,并获取完整内容
"""
self.log(
action="section_complete",
stage="generating",
section_title=section_title,
section_index=section_index,
details={
"content": full_content,
"content_length": len(full_content),
"message": f"章节 {section_title} 生成完成"
}
)
def log_report_complete(self, total_sections: int, total_time_seconds: float):
"""记录报告生成完成"""
self.log(
action="report_complete",
stage="completed",
details={
"total_sections": total_sections,
"total_time_seconds": round(total_time_seconds, 2),
"message": "报告生成完成"
}
)
def log_error(self, error_message: str, stage: str, section_title: str = None):
"""记录错误"""
self.log(
action="error",
stage=stage,
section_title=section_title,
section_index=None,
details={
"error": error_message,
"message": f"发生错误: {error_message}"
}
)
class ReportConsoleLogger:
"""
Report Agent 控制台日志记录器
将控制台风格的日志(INFO、WARNING等)写入报告文件夹中的 console_log.txt 文件。
这些日志与 agent_log.jsonl 不同,是纯文本格式的控制台输出。
"""
def __init__(self, report_id: str):
"""
初始化控制台日志记录器
Args:
report_id: 报告ID,用于确定日志文件路径
"""
self.report_id = report_id
self.log_file_path = os.path.join(
Config.UPLOAD_FOLDER, 'reports', report_id, 'console_log.txt'
)
self._ensure_log_file()
self._file_handler = None
self._setup_file_handler()
def _ensure_log_file(self):
"""确保日志文件所在目录存在"""
log_dir = os.path.dirname(self.log_file_path)
os.makedirs(log_dir, exist_ok=True)
def _setup_file_handler(self):
"""设置文件处理器,将日志同时写入文件"""
import logging
# 创建文件处理器
self._file_handler = logging.FileHandler(
self.log_file_path,
mode='a',
encoding='utf-8'
)
self._file_handler.setLevel(logging.INFO)
# 使用与控制台相同的简洁格式
formatter = logging.Formatter(
'[%(asctime)s] %(levelname)s: %(message)s',
datefmt='%H:%M:%S'
)
self._file_handler.setFormatter(formatter)
# 添加到 report_agent 相关的 logger
loggers_to_attach = [
'mirofish.report_agent',
'mirofish.zep_tools',
]
for logger_name in loggers_to_attach:
target_logger = logging.getLogger(logger_name)
# 避免重复添加
if self._file_handler not in target_logger.handlers:
target_logger.addHandler(self._file_handler)
def close(self):
"""关闭文件处理器并从 logger 中移除"""
import logging
if self._file_handler:
loggers_to_detach = [
'mirofish.report_agent',
'mirofish.zep_tools',
]
for logger_name in loggers_to_detach:
target_logger = logging.getLogger(logger_name)
if self._file_handler in target_logger.handlers:
target_logger.removeHandler(self._file_handler)
self._file_handler.close()
self._file_handler = None
def __del__(self):
"""析构时确保关闭文件处理器"""
self.close()
class ReportStatus(str, Enum):
"""报告状态"""
PENDING = "pending"
PLANNING = "planning"
GENERATING = "generating"
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class ReportSection:
"""报告章节"""
title: str
content: str = ""
def to_dict(self) -> Dict[str, Any]:
return {
"title": self.title,
"content": self.content
}
def to_markdown(self, level: int = 2) -> str:
"""转换为Markdown格式"""
md = f"{'#' * level} {self.title}\n\n"
if self.content:
md += f"{self.content}\n\n"
return md
@dataclass
class ReportOutline:
"""报告大纲"""
title: str
summary: str
sections: List[ReportSection]
def to_dict(self) -> Dict[str, Any]:
return {
"title": self.title,
"summary": self.summary,
"sections": [s.to_dict() for s in self.sections]
}
def to_markdown(self) -> str:
"""转换为Markdown格式"""
md = f"# {self.title}\n\n"
md += f"> {self.summary}\n\n"
for section in self.sections:
md += section.to_markdown()
return md
@dataclass
class Report:
"""完整报告"""
report_id: str
simulation_id: str
graph_id: str
simulation_requirement: str
status: ReportStatus
outline: Optional[ReportOutline] = None
markdown_content: str = ""
created_at: str = ""
completed_at: str = ""
error: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
return {
"report_id": self.report_id,
"simulation_id": self.simulation_id,
"graph_id": self.graph_id,
"simulation_requirement": self.simulation_requirement,
"status": self.status.value,
"outline": self.outline.to_dict() if self.outline else None,
"markdown_content": self.markdown_content,
"created_at": self.created_at,
"completed_at": self.completed_at,
"error": self.error
}
# ═══════════════════════════════════════════════════════════════
# Prompt 模板常量
# ═══════════════════════════════════════════════════════════════
# ── 工具描述 ──
TOOL_DESC_INSIGHT_FORGE = """\
【深度洞察检索 - 强大的检索工具】
这是我们强大的检索函数,专为深度分析设计。它会:
1. 自动将你的问题分解为多个子问题
2. 从多个维度检索模拟图谱中的信息
3. 整合语义搜索、实体分析、关系链追踪的结果
4. 返回最全面、最深度的检索内容
【使用场景】
- 需要深入分析某个话题
- 需要了解事件的多个方面
- 需要获取支撑报告章节的丰富素材
【返回内容】
- 相关事实原文(可直接引用)
- 核心实体洞察
- 关系链分析"""
TOOL_DESC_PANORAMA_SEARCH = """\
【广度搜索 - 获取全貌视图】
这个工具用于获取模拟结果的完整全貌,特别适合了解事件演变过程。它会:
1. 获取所有相关节点和关系
2. 区分当前有效的事实和历史/过期的事实
3. 帮助你了解舆情是如何演变的
【使用场景】
- 需要了解事件的完整发展脉络
- 需要对比不同阶段的舆情变化
- 需要获取全面的实体和关系信息
【返回内容】
- 当前有效事实(模拟最新结果)
- 历史/过期事实(演变记录)
- 所有涉及的实体"""
TOOL_DESC_QUICK_SEARCH = """\
【简单搜索 - 快速检索】
轻量级的快速检索工具,适合简单、直接的信息查询。
【使用场景】
- 需要快速查找某个具体信息
- 需要验证某个事实
- 简单的信息检索
【返回内容】
- 与查询最相关的事实列表"""
TOOL_DESC_INTERVIEW_AGENTS = """\
【深度采访 - 真实Agent采访(双平台)】
调用OASIS模拟环境的采访API,对正在运行的模拟Agent进行真实采访!
这不是LLM模拟,而是调用真实的采访接口获取模拟Agent的原始回答。
默认在Twitter和Reddit两个平台同时采访,获取更全面的观点。
功能流程:
1. 自动读取人设文件,了解所有模拟Agent
2. 智能选择与采访主题最相关的Agent(如学生、媒体、官方等)
3. 自动生成采访问题
4. 调用 /api/simulation/interview/batch 接口在双平台进行真实采访
5. 整合所有采访结果,提供多视角分析
【使用场景】
- 需要从不同角色视角了解事件看法(学生怎么看?媒体怎么看?官方怎么说?)
- 需要收集多方意见和立场
- 需要获取模拟Agent的真实回答(来自OASIS模拟环境)
- 想让报告更生动,包含"采访实录"
【返回内容】
- 被采访Agent的身份信息
- 各Agent在Twitter和Reddit两个平台的采访回答
- 关键引言(可直接引用)
- 采访摘要和观点对比
【重要】需要OASIS模拟环境正在运行才能使用此功能!"""
# ── 大纲规划 prompt ──
PLAN_SYSTEM_PROMPT = """\
你是一个「未来预测报告」的撰写专家,拥有对模拟世界的「上帝视角」——你可以洞察模拟中每一位Agent的行为、言论和互动。
【核心理念】
我们构建了一个模拟世界,并向其中注入了特定的「模拟需求」作为变量。模拟世界的演化结果,就是对未来可能发生情况的预测。你正在观察的不是"实验数据",而是"未来的预演"。
【你的任务】
撰写一份「未来预测报告」,回答:
1. 在我们设定的条件下,未来发生了什么?
2. 各类Agent(人群)是如何反应和行动?
3. 这个模拟揭示了哪些值得关注的未来趋势和风险?
【报告定位】
- ✅ 这是一份基于模拟的未来预测报告,揭示"如果这样,未来会怎样"
- ✅ 聚焦于预测结果:事件走向、群体反应、涌现现象、潜在风险
- ✅ 模拟世界中的Agent言行就是对未来人群行为的预测
- ❌ 不是对现实世界现状的分析
- ❌ 不是泛泛而谈的舆情综述
【章节数量限制】
- 最少2个章节,最多5个章节
- 不需要子章节,每个章节直接撰写完整内容
- 内容要精炼,聚焦于核心预测发现
- 章节结构由你根据预测结果自主设计
请输出JSON格式的报告大纲,格式如下:
{
"title": "报告标题",
"summary": "报告摘要(一句话概括核心预测发现)",
"sections": [
{
"title": "章节标题",
"description": "章节内容描述"
}
]
}
注意:sections数组最少2个,最多5个元素!"""
# 语言指令(根据 report_language 动态追加到各 prompt)
LANGUAGE_INSTRUCTION_ZH = "\n\n【语言要求】报告标题、摘要、章节标题和内容描述必须全部使用中文撰写。"
LANGUAGE_INSTRUCTION_EN = "\n\n【Language requirement】You MUST write the report title, summary, section titles and all content in English only. Think and respond in English."
PLAN_USER_PROMPT_TEMPLATE = """\
【预测场景设定】
我们向模拟世界注入的变量(模拟需求):{simulation_requirement}
【模拟世界规模】
- 参与模拟的实体数量: {total_nodes}
- 实体间产生的关系数量: {total_edges}
- 实体类型分布: {entity_types}
- 活跃Agent数量: {total_entities}
【模拟预测到的部分未来事实样本】
{related_facts_json}
请以「上帝视角」审视这个未来预演:
1. 在我们设定的条件下,未来呈现出了什么样的状态?
2. 各类人群(Agent)是如何反应和行动的?
3. 这个模拟揭示了哪些值得关注的未来趋势?
根据预测结果,设计最合适的报告章节结构。
【再次提醒】报告章节数量:最少2个,最多5个,内容要精炼聚焦于核心预测发现。"""
# ── 章节生成 prompt ──
SECTION_SYSTEM_PROMPT_TEMPLATE = """\
你是一个「未来预测报告」的撰写专家,正在撰写报告的一个章节。
报告标题: {report_title}
报告摘要: {report_summary}
预测场景(模拟需求): {simulation_requirement}
当前要撰写的章节: {section_title}
═══════════════════════════════════════════════════════════════
【核心理念】
═══════════════════════════════════════════════════════════════
模拟世界是对未来的预演。我们向模拟世界注入了特定条件(模拟需求),
模拟中Agent的行为和互动,就是对未来人群行为的预测。
你的任务是:
- 揭示在设定条件下,未来发生了什么
- 预测各类人群(Agent)是如何反应和行动的
- 发现值得关注的未来趋势、风险和机会
❌ 不要写成对现实世界现状的分析
✅ 要聚焦于"未来会怎样"——模拟结果就是预测的未来
═══════════════════════════════════════════════════════════════
【最重要的规则 - 必须遵守】
═══════════════════════════════════════════════════════════════
1. 【必须调用工具观察模拟世界】
- 你正在以「上帝视角」观察未来的预演
- 所有内容必须来自模拟世界中发生的事件和Agent言行
- 禁止使用你自己的知识来编写报告内容
- 每个章节至少调用3次工具(最多5次)来观察模拟的世界,它代表了未来
2. 【必须引用Agent的原始言行】
- Agent的发言和行为是对未来人群行为的预测
- 在报告中使用引用格式展示这些预测,例如:
> "某类人群会表示:原文内容..."
- 这些引用是模拟预测的核心证据
3. 【语言一致性 - 引用内容必须翻译为报告语言】
- 工具返回的内容可能包含英文或中英文混杂的表述
- {language_consistency_rule}
- 翻译时保持原意不变,确保表述自然通顺
- 这一规则同时适用于正文和引用块(> 格式)中的内容
4. 【忠实呈现预测结果】
- 报告内容必须反映模拟世界中的代表未来的模拟结果
- 不要添加模拟中不存在的信息
- 如果某方面信息不足,如实说明
═══════════════════════════════════════════════════════════════
【⚠️ 格式规范 - 极其重要!】
═══════════════════════════════════════════════════════════════
【一个章节 = 最小内容单位】
- 每个章节是报告的最小分块单位
- ❌ 禁止在章节内使用任何 Markdown 标题(#、##、###、#### 等)
- ❌ 禁止在内容开头添加章节主标题
- ✅ 章节标题由系统自动添加,你只需撰写纯正文内容
- ✅ 使用**粗体**、段落分隔、引用、列表来组织内容,但不要用标题
【正确示例】
```
本章节分析了事件的舆论传播态势。通过对模拟数据的深入分析,我们发现...
**首发引爆阶段**
微博作为舆情的第一现场,承担了信息首发的核心功能:
> "微博贡献了68%的首发声量..."
**情绪放大阶段**
抖音平台进一步放大了事件影响力:
- 视觉冲击力强
- 情绪共鸣度高
```
【错误示例】
```
## 执行摘要 ← 错误!不要添加任何标题
### 一、首发阶段 ← 错误!不要用###分小节
#### 1.1 详细分析 ← 错误!不要用####细分
本章节分析了...
```
═══════════════════════════════════════════════════════════════
【可用检索工具】(每章节调用3-5次)
═══════════════════════════════════════════════════════════════
{tools_description}
【工具使用建议 - 请混合使用不同工具,不要只用一种】
- insight_forge: 深度洞察分析,自动分解问题并多维度检索事实和关系
- panorama_search: 广角全景搜索,了解事件全貌、时间线和演变过程
- quick_search: 快速验证某个具体信息点
- interview_agents: 采访模拟Agent,获取不同角色的第一人称观点和真实反应
═══════════════════════════════════════════════════════════════
【工作流程】
═══════════════════════════════════════════════════════════════
每次回复你只能做以下两件事之一(不可同时做):
选项A - 调用工具:
输出你的思考,然后用以下格式调用一个工具:
<tool_call>
{{"name": "工具名称", "parameters": {{"参数名": "参数值"}}}}
</tool_call>
系统会执行工具并把结果返回给你。你不需要也不能自己编写工具返回结果。
选项B - 输出最终内容:
当你已通过工具获取了足够信息,以 "Final Answer:" 开头输出章节内容。
⚠️ 严格禁止:
- 禁止在一次回复中同时包含工具调用和 Final Answer
- 禁止自己编造工具返回结果(Observation),所有工具结果由系统注入
- 每次回复最多调用一个工具
═══════════════════════════════════════════════════════════════
【章节内容要求】
═══════════════════════════════════════════════════════════════
1. 内容必须基于工具检索到的模拟数据
2. 大量引用原文来展示模拟效果
3. 使用Markdown格式(但禁止使用标题):
- 使用 **粗体文字** 标记重点(代替子标题)
- 使用列表(-或1.2.3.)组织要点
- 使用空行分隔不同段落
- ❌ 禁止使用 #、##、###、#### 等任何标题语法
4. 【引用格式规范 - 必须单独成段】
引用必须独立成段,前后各有一个空行,不能混在段落中:
✅ 正确格式:
```
校方的回应被认为缺乏实质内容。
> "校方的应对模式在瞬息万变的社交媒体环境中显得僵化和迟缓。"
这一评价反映了公众的普遍不满。
```
❌ 错误格式:
```
校方的回应被认为缺乏实质内容。> "校方的应对模式..." 这一评价反映了...
```
5. 保持与其他章节的逻辑连贯性
6. 【避免重复】仔细阅读下方已完成的章节内容,不要重复描述相同的信息
7. 【再次强调】不要添加任何标题!用**粗体**代替小节标题"""
SECTION_USER_PROMPT_TEMPLATE = """\
已完成的章节内容(请仔细阅读,避免重复):
{previous_content}
═══════════════════════════════════════════════════════════════
【当前任务】撰写章节: {section_title}
═══════════════════════════════════════════════════════════════
【重要提醒】
1. 仔细阅读上方已完成的章节,避免重复相同的内容!
2. 开始前必须先调用工具获取模拟数据
3. 请混合使用不同工具,不要只用一种
4. 报告内容必须来自检索结果,不要使用自己的知识
【⚠️ 格式警告 - 必须遵守】
- ❌ 不要写任何标题(#、##、###、####都不行)
- ❌ 不要写"{section_title}"作为开头
- ✅ 章节标题由系统自动添加
- ✅ 直接写正文,用**粗体**代替小节标题
请开始:
1. 首先思考(Thought)这个章节需要什么信息
2. 然后调用工具(Action)获取模拟数据
3. 收集足够信息后输出 Final Answer(纯正文,无任何标题)"""
# ── ReACT 循环内消息模板 ──
REACT_OBSERVATION_TEMPLATE = """\
Observation(检索结果):
═══ 工具 {tool_name} 返回 ═══
{result}
═══════════════════════════════════════════════════════════════
已调用工具 {tool_calls_count}/{max_tool_calls} 次(已用: {used_tools_str}){unused_hint}
- 如果信息充分:以 "Final Answer:" 开头输出章节内容(必须引用上述原文)
- 如果需要更多信息:调用一个工具继续检索
═══════════════════════════════════════════════════════════════"""
REACT_INSUFFICIENT_TOOLS_MSG = (
"【注意】你只调用了{tool_calls_count}次工具,至少需要{min_tool_calls}次。"
"请再调用工具获取更多模拟数据,然后再输出 Final Answer。{unused_hint}"
)
REACT_INSUFFICIENT_TOOLS_MSG_ALT = (
"当前只调用了 {tool_calls_count} 次工具,至少需要 {min_tool_calls} 次。"
"请调用工具获取模拟数据。{unused_hint}"
)
REACT_TOOL_LIMIT_MSG = (
"工具调用次数已达上限({tool_calls_count}/{max_tool_calls}),不能再调用工具。"
'请立即基于已获取的信息,以 "Final Answer:" 开头输出章节内容。'
)
REACT_UNUSED_TOOLS_HINT = "\n💡 你还没有使用过: {unused_list},建议尝试不同工具获取多角度信息"
REACT_FORCE_FINAL_MSG = "已达到工具调用限制,请直接输出 Final Answer: 并生成章节内容。"
# ── Chat prompt ──
CHAT_SYSTEM_PROMPT_TEMPLATE = """\
你是一个简洁高效的模拟预测助手。
【背景】
预测条件: {simulation_requirement}
【已生成的分析报告】
{report_content}
【规则】
1. 优先基于上述报告内容回答问题
2. 直接回答问题,避免冗长的思考论述
3. 仅在报告内容不足以回答时,才调用工具检索更多数据
4. 回答要简洁、清晰、有条理
【可用工具】(仅在需要时使用,最多调用1-2次)
{tools_description}
【工具调用格式】
<tool_call>
{{"name": "工具名称", "parameters": {{"参数名": "参数值"}}}}
</tool_call>
【回答风格】
- 简洁直接,不要长篇大论
- 使用 > 格式引用关键内容
- 优先给出结论,再解释原因
【语言】{chat_language_instruction}"""
CHAT_OBSERVATION_SUFFIX = "\n\n请简洁回答问题。"
# ═══════════════════════════════════════════════════════════════
# ReportAgent 主类
# ═══════════════════════════════════════════════════════════════
class ReportAgent:
"""
Report Agent - 模拟报告生成Agent
采用ReACT(Reasoning + Acting)模式:
1. 规划阶段:分析模拟需求,规划报告目录结构
2. 生成阶段:逐章节生成内容,每章节可多次调用工具获取信息
3. 反思阶段:检查内容完整性和准确性
"""
# 最大工具调用次数(每个章节)
MAX_TOOL_CALLS_PER_SECTION = 5
# 最大反思轮数
MAX_REFLECTION_ROUNDS = 3
# 对话中的最大工具调用次数
MAX_TOOL_CALLS_PER_CHAT = 2
def __init__(
self,
graph_id: str,
simulation_id: str,
simulation_requirement: str,
llm_client: Optional[LLMClient] = None,
zep_tools: Optional[ZepToolsService] = None,
report_language: str = 'zh'
):
"""
初始化Report Agent
Args:
graph_id: 图谱ID
simulation_id: 模拟ID
simulation_requirement: 模拟需求描述
llm_client: LLM客户端(可选)
zep_tools: Zep工具服务(可选)
report_language: 报告输出语言 'zh' 或 'en',LLM 将用该语言思考和生成
"""
self.graph_id = graph_id
self.simulation_id = simulation_id
self.simulation_requirement = simulation_requirement
self.report_language = report_language if report_language in ('zh', 'en') else 'zh'
self.llm = llm_client or LLMClient()
self.zep_tools = zep_tools or ZepToolsService()
# 工具定义
self.tools = self._define_tools()
# 日志记录器(在 generate_report 中初始化)
self.report_logger: Optional[ReportLogger] = None
# 控制台日志记录器(在 generate_report 中初始化)
self.console_logger: Optional[ReportConsoleLogger] = None
logger.info(f"ReportAgent 初始化完成: graph_id={graph_id}, simulation_id={simulation_id}")
def _define_tools(self) -> Dict[str, Dict[str, Any]]:
"""定义可用工具"""
return {
"insight_forge": {
"name": "insight_forge",
"description": TOOL_DESC_INSIGHT_FORGE,
"parameters": {
"query": "你想深入分析的问题或话题",
"report_context": "当前报告章节的上下文(可选,有助于生成更精准的子问题)"
}
},
"panorama_search": {
"name": "panorama_search",
"description": TOOL_DESC_PANORAMA_SEARCH,
"parameters": {
"query": "搜索查询,用于相关性排序",
"include_expired": "是否包含过期/历史内容(默认True)"
}
},
"quick_search": {
"name": "quick_search",
"description": TOOL_DESC_QUICK_SEARCH,
"parameters": {
"query": "搜索查询字符串",
"limit": "返回结果数量(可选,默认10)"
}
},
"interview_agents": {
"name": "interview_agents",
"description": TOOL_DESC_INTERVIEW_AGENTS,
"parameters": {
"interview_topic": "采访主题或需求描述(如:'了解学生对宿舍甲醛事件的看法')",
"max_agents": "最多采访的Agent数量(可选,默认5,最大10)"
}
}
}
def _execute_tool(self, tool_name: str, parameters: Dict[str, Any], report_context: str = "") -> str:
"""
执行工具调用
Args:
tool_name: 工具名称
parameters: 工具参数
report_context: 报告上下文(用于InsightForge)
Returns:
工具执行结果(文本格式)
"""
logger.info(f"执行工具: {tool_name}, 参数: {parameters}")
try:
if tool_name == "insight_forge":
query = parameters.get("query", "")
ctx = parameters.get("report_context", "") or report_context
result = self.zep_tools.insight_forge(
graph_id=self.graph_id,
query=query,
simulation_requirement=self.simulation_requirement,
report_context=ctx
)
return result.to_text()
elif tool_name == "panorama_search":
# 广度搜索 - 获取全貌
query = parameters.get("query", "")
include_expired = parameters.get("include_expired", True)
if isinstance(include_expired, str):
include_expired = include_expired.lower() in ['true', '1', 'yes']
result = self.zep_tools.panorama_search(
graph_id=self.graph_id,
query=query,
include_expired=include_expired
)
return result.to_text()