generated from salesforce/oss-template
-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathrun_research_concurrent.py
More file actions
1480 lines (1285 loc) · 55.8 KB
/
run_research_concurrent.py
File metadata and controls
1480 lines (1285 loc) · 55.8 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
#!/usr/bin/env python3
"""
Multi-threaded research script for benchmarking.
"""
import asyncio
import argparse
import os
import sys
import json
import time
from pathlib import Path
from dotenv import load_dotenv
from datetime import datetime
import threading
from typing import List, Dict, Optional, Tuple
import logging
from abc import ABC, abstractmethod
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler("research_concurrent.log"),
logging.StreamHandler(sys.stdout),
],
)
logger = logging.getLogger(__name__)
# Add the deep-research directory to the Python path
script_dir = Path(__file__).parent
deep_research_dir = script_dir.parent
sys.path.insert(0, str(deep_research_dir))
# Load environment variables
env_file_path = deep_research_dir / ".env"
logger.info(f"Loading environment from: {env_file_path}")
load_dotenv(dotenv_path=env_file_path)
# Import HTML-to-markdown converter
from src.graph import generate_markdown_report
STATS_LOCK = threading.Lock()
GLOBAL_STATS = {
"completed": 0,
"failed": 0,
"start_time": None,
"tasks_started": 0,
"tasks_in_progress": 0,
}
# ==================== Trajectory Recorder ====================
class ResearchTrajectoryRecorder:
"""Records structured research trajectory with OpenAI-format tool calls"""
def __init__(self):
self.query = ""
self.iterations = []
self.current_iteration = None
self.tool_call_counter = 0
self.previous_sources = set()
def start_iteration(self, iteration_number: int):
"""Start a new research iteration"""
self.current_iteration = {
"iteration": iteration_number,
"timestamp_start": datetime.now().isoformat(),
"tool_calls": [], # OpenAI format tool calls
"running_summary": "",
"num_sources": 0,
}
def end_iteration(self):
"""End the current iteration and save it"""
if self.current_iteration:
self.current_iteration["timestamp_end"] = datetime.now().isoformat()
self.iterations.append(self.current_iteration)
self.current_iteration = None
def add_tool_call(self, function_name: str, arguments: Dict, result: any):
"""Add a tool call in OpenAI format"""
if self.current_iteration:
self.tool_call_counter += 1
tool_call = {
"id": f"call_{self.tool_call_counter}",
"type": "function",
"function": {"name": function_name, "arguments": arguments},
"result": result,
"timestamp": datetime.now().isoformat(),
}
self.current_iteration["tool_calls"].append(tool_call)
def record_running_summary(self, summary):
"""Record the running summary after this iteration (with HTML converted to markdown)"""
if self.current_iteration:
# Handle case where summary might be a list (convert to string)
if isinstance(summary, list):
summary = "\n\n".join(str(s) for s in summary)
elif not isinstance(summary, str):
summary = str(summary)
# Convert HTML to clean markdown using the existing graph.py function
cleaned_summary = generate_markdown_report(summary)
self.current_iteration["running_summary"] = cleaned_summary
def record_sources(self, sources: List[str]):
"""Record number of NEW sources gathered in this iteration"""
if self.current_iteration:
current_sources = set(sources)
new_sources = current_sources - self.previous_sources
self.current_iteration["num_sources"] = len(new_sources)
self.previous_sources = current_sources
def get_summary(self, total_unique_sources: int = 0) -> Dict:
"""Get a summary of the trajectory"""
return {
"query": self.query,
"num_iterations": len(self.iterations),
"total_num_sources": total_unique_sources,
"iterations_summary": [
{
"iteration": it["iteration"],
"num_tool_calls": len(it.get("tool_calls", [])),
"num_sources": it.get("num_sources", 0),
}
for it in self.iterations
],
}
def to_dict(self, total_unique_sources: int = 0) -> Dict:
"""Convert trajectory to dictionary for JSON serialization"""
return {
"query": self.query,
"summary": self.get_summary(total_unique_sources),
"iterations": self.iterations,
}
# ==================== Benchmark Dataset Managers ====================
class BenchmarkDatasetManager(ABC):
"""Abstract base class for managing different benchmark datasets."""
@abstractmethod
def load_queries(
self,
file_path: str,
task_ids: Optional[List[int]] = None,
limit: Optional[int] = None,
) -> List[Dict]:
"""Load queries from the dataset file."""
pass
@abstractmethod
def get_query_field(self) -> str:
"""Return the field name that contains the query text."""
pass
@abstractmethod
def get_processing_config(self) -> Dict:
"""Return the configuration for processing this benchmark."""
pass
@abstractmethod
def format_result(self, task_data: Dict, result_data: Dict) -> Dict:
"""Format the result according to benchmark requirements."""
pass
@abstractmethod
def get_output_filename(self, task_id: str) -> str:
"""Get the output filename for a task result."""
pass
class DRBDatasetManager(BenchmarkDatasetManager):
"""Manager for Deep Research Benchmark (DRB) dataset."""
def load_queries(
self,
file_path: str,
task_ids: Optional[List[int]] = None,
limit: Optional[int] = None,
) -> List[Dict]:
"""Load queries from DRB JSONL file."""
queries = []
try:
with open(file_path, "r", encoding="utf-8") as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if line:
try:
query_data = json.loads(line)
queries.append(query_data)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON on line {line_num}: {e}")
logger.info(f"📋 Loaded {len(queries)} queries from {file_path}")
# Filter by task IDs if specified
if task_ids:
queries = [q for q in queries if q["id"] in task_ids]
logger.info(f"🎯 Filtered to {len(queries)} specific tasks: {task_ids}")
# Apply limit if specified
if limit:
queries = queries[:limit]
logger.info(f"🔢 Limited to first {len(queries)} tasks")
return queries
except FileNotFoundError:
logger.error(f"Query file not found: {file_path}")
raise
except Exception as e:
logger.error(f"Error loading queries: {e}")
raise
def get_query_field(self) -> str:
return "prompt"
def get_processing_config(self) -> Dict:
return {
"max_loops": 5,
"extra_effort": False,
"qa_mode": False,
"benchmark_mode": False,
}
def format_result(self, task_data: Dict, result_data: Dict) -> Dict:
"""Format result for DRB."""
return {
"id": result_data["id"],
"prompt": result_data["query"], # DRB uses "prompt" not "query"
"article": result_data["article"],
"metadata": {
"timing": result_data["timing"],
"debug_info": result_data["debug_info"],
"content_stats": result_data["content_stats"],
},
}
def get_output_filename(self, task_id: str) -> str:
return f"{task_id}.json"
class DeepConsultDatasetManager(BenchmarkDatasetManager):
"""Dataset manager for DeepConsult CSV dataset."""
def load_queries(
self,
file_path: str,
task_ids: Optional[List[int]] = None,
limit: Optional[int] = None,
) -> List[Dict]:
"""Load queries from CSV file."""
import csv
queries = []
try:
with open(file_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for i, row in enumerate(reader):
# Create query dict with index as ID
# Ensure query is a string
query = row["query"]
if isinstance(query, list):
query = " ".join(str(item) for item in query)
query_data = {"id": i, "index": i, "query": str(query).strip()}
queries.append(query_data)
logger.info(f"📋 Loaded {len(queries)} queries from {file_path}")
# Filter by task IDs if specified
if task_ids:
queries = [q for q in queries if q["id"] in task_ids]
logger.info(f"🎯 Filtered to {len(queries)} specific tasks: {task_ids}")
# Apply limit if specified
if limit:
queries = queries[:limit]
logger.info(f"🔢 Limited to first {len(queries)} tasks")
return queries
except FileNotFoundError:
logger.error(f"Query file not found: {file_path}")
raise
except Exception as e:
logger.error(f"Error loading queries: {e}")
raise
def get_query_field(self) -> str:
return "query"
def get_processing_config(self) -> Dict:
return {
"max_loops_default": 10, # Max 10 loops as requested
"benchmark_mode": False, # Regular mode as requested
"qa_mode": False,
"visualization_disabled": True,
}
def format_result(self, task_data: Dict, result_data: Dict) -> Dict:
"""Format result for DeepConsult - keep existing structure."""
return result_data
def get_output_filename(self, task_id: str) -> str:
return f"deepconsult_{task_id}.json"
class HealthBenchDatasetManager(BenchmarkDatasetManager):
"""Dataset manager for HealthBench evaluation."""
def load_queries(
self,
file_path: str,
task_ids: Optional[List[int]] = None,
limit: Optional[int] = None,
) -> List[Dict]:
"""Load queries from HealthBench JSON file (final_run_100 or final_run_1000)."""
queries = []
try:
logger.info(f"📋 Loading HealthBench data from {file_path}")
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
data = data
# data is a list of HealthBench examples
for example in data:
query_data = {
"id": example["id"], # UUID from HealthBench
"query": example["problem"], # Formatted problem string
"original_data": example, # Keep all original data for eval
}
queries.append(query_data)
logger.info(f"📋 Loaded {len(queries)} HealthBench queries")
# Filter by task IDs if specified (using string IDs for HealthBench)
if task_ids:
# Convert task_ids to strings for comparison
task_ids_str = [str(tid) for tid in task_ids]
queries = [q for q in queries if q["id"] in task_ids_str]
logger.info(f"🎯 Filtered to {len(queries)} specific tasks")
# Apply limit if specified
if limit:
queries = queries[:limit]
logger.info(f"🔢 Limited to first {len(queries)} tasks")
return queries
except FileNotFoundError:
logger.error(f"HealthBench file not found: {file_path}")
raise
except Exception as e:
logger.error(f"Error loading HealthBench data: {e}")
raise
def get_query_field(self) -> str:
return "query"
def get_processing_config(self) -> Dict:
return {
"max_loops": 5, # 3 loops for medical questions
"extra_effort": False,
"qa_mode": False,
"benchmark_mode": False, # Use benchmark mode for citations
}
def format_result(self, task_data: Dict, result_data: Dict) -> Dict:
"""Format result for HealthBench - preserve all data needed for DR Tulu eval."""
return {
"id": result_data["id"],
"query": result_data["query"],
"article": result_data["article"],
"original_data": task_data.get(
"original_data", {}
), # Preserve HealthBench metadata
"metadata": {
"timing": result_data["timing"],
"debug_info": result_data["debug_info"],
"content_stats": result_data["content_stats"],
},
}
def get_output_filename(self, task_id: str) -> str:
return f"{task_id}.json"
class HFDatasetManager(BenchmarkDatasetManager):
"""Dataset manager for HuggingFace datasets (e.g., LiveResearchBench)."""
def __init__(
self,
dataset_name: str,
query_column: str,
config_name: Optional[str] = None,
split: str = "test",
mode: str = "regular",
max_loops: int = 5,
provider: str = "google",
model: str = "gemini-2.5-pro",
):
"""
Initialize HuggingFace dataset manager.
Args:
dataset_name: HF dataset path (e.g., "Salesforce/LiveResearchBench")
query_column: Column name containing queries (e.g., "question_no_placeholder")
config_name: Optional config name for the dataset (e.g., "question_only")
split: Dataset split to load (default: "test")
mode: Processing mode - "regular", "qa", or "benchmark" (default: "regular")
max_loops: Maximum research loops (default: 5)
provider: LLM provider (default: "google")
model: LLM model name (default: "gemini-2.5-pro")
"""
self.dataset_name = dataset_name
self.query_column = query_column
self.config_name = config_name
self.split = split
self.mode = mode
self.max_loops = max_loops
self.provider = provider
self.model = model
def load_queries(
self,
file_path: str, # Not used for HF datasets, kept for interface compatibility
task_ids: Optional[List[int]] = None,
limit: Optional[int] = None,
) -> List[Dict]:
"""Load queries from HuggingFace dataset."""
try:
from datasets import load_dataset
logger.info(f"📥 Loading HuggingFace dataset: {self.dataset_name}")
if self.config_name:
logger.info(f" Config: {self.config_name}")
logger.info(f" Split: {self.split}")
logger.info(f" Query column: {self.query_column}")
# Load dataset
if self.config_name:
dataset = load_dataset(
self.dataset_name, self.config_name, split=self.split
)
else:
dataset = load_dataset(self.dataset_name, split=self.split)
queries = []
for i, example in enumerate(dataset):
# Get query from specified column
query = example.get(self.query_column, "")
if isinstance(query, list):
query = " ".join(str(item) for item in query)
elif not isinstance(query, str):
query = str(query)
query = query.strip()
if not query:
logger.warning(f"⚠️ Skipping empty query at index {i}")
continue
# Use qid field as ID if available (for LiveResearchBench), otherwise use index
qid = example.get("qid", i)
query_data = {"id": qid, "index": i, "query": query}
queries.append(query_data)
logger.info(f"📋 Loaded {len(queries)} queries from HuggingFace dataset")
# Filter by task IDs if specified
if task_ids:
queries = [q for q in queries if q["id"] in task_ids]
logger.info(f"🎯 Filtered to {len(queries)} specific tasks: {task_ids}")
# Apply limit if specified
if limit:
queries = queries[:limit]
logger.info(f"🔢 Limited to first {len(queries)} tasks")
return queries
except ImportError:
logger.error(
"❌ HuggingFace datasets library not installed. Run: pip install datasets"
)
raise
except Exception as e:
logger.error(f"❌ Error loading HuggingFace dataset: {e}")
raise
def get_query_field(self) -> str:
return "query"
def get_processing_config(self) -> Dict:
return {
"max_loops_default": self.max_loops,
"benchmark_mode": self.mode == "benchmark",
"qa_mode": self.mode == "qa",
"visualization_disabled": True,
}
def format_result(self, task_data: Dict, result_data: Dict) -> Dict:
"""Format result for HuggingFace dataset."""
return result_data
def get_output_filename(self, task_id: str) -> str:
# Use qid directly as filename (for LiveResearchBench compatibility)
return f"{task_id}.json"
# ==================== Task Execution ====================
async def run_single_research_task_with_trajectory(
task_data: Dict,
dataset_manager: BenchmarkDatasetManager,
output_dir: str,
provider: str = None,
model: str = None,
max_web_search_loops: int = 5,
extra_effort: bool = False,
minimum_effort: bool = False,
qa_mode: bool = False,
benchmark_mode: bool = False,
visualization_disabled: bool = True,
steering_enabled: bool = False,
parallel_search_enabled: bool = True,
parallel_search_max_concurrency: int = 4,
task_manager=None,
collect_trajectory: bool = False,
save_md: bool = False,
) -> Tuple[bool, Dict, str]:
"""
Run a single research task with optional trajectory capture.
Args:
collect_trajectory: If True, collect detailed trajectory data (disabled by default for benchmarks)
save_md: If True, save markdown report as .md file immediately after generation
Returns: (success: bool, result: Dict, error_message: str)
"""
task_id = task_data.get("id", task_data.get("index", "unknown"))
query_field = dataset_manager.get_query_field()
query = task_data[query_field]
# Ensure query is a string (handle cases where it might be a list)
if isinstance(query, list):
query = " ".join(str(item) for item in query)
elif not isinstance(query, str):
query = str(query)
# Preserve the original query
original_query = query
task_start_time = datetime.now()
if task_manager:
await task_manager.rate_limit()
log_msg = f"[Task {task_id}] Starting"
if collect_trajectory:
log_msg += " with trajectory capture"
logger.info(log_msg)
with STATS_LOCK:
GLOBAL_STATS["tasks_started"] += 1
GLOBAL_STATS["tasks_in_progress"] += 1
# Initialize trajectory recorder only if requested
recorder = None
if collect_trajectory:
recorder = ResearchTrajectoryRecorder()
recorder.query = original_query # Use original query for recorder
try:
from src.state import SummaryState
from src.graph import create_graph
if not provider:
provider = os.environ.get("LLM_PROVIDER", "openai")
if not model:
model = os.environ.get("LLM_MODEL", "o3-mini")
# Set environment variables (match working version)
os.environ["MAX_WEB_RESEARCH_LOOPS"] = str(max_web_search_loops)
os.environ["LLM_PROVIDER"] = provider
os.environ["LLM_MODEL"] = model
fresh_graph = create_graph()
if isinstance(dataset_manager, DeepConsultDatasetManager):
benchmark_type = "DEEPCONSULT"
elif isinstance(dataset_manager, HFDatasetManager):
benchmark_type = "LRB"
elif isinstance(dataset_manager, HealthBenchDatasetManager):
benchmark_type = "HEALTHBENCH"
elif isinstance(dataset_manager, DRBDatasetManager):
benchmark_type = "DRB"
else:
benchmark_type = "UNKNOWN"
run_ref = f"EVAL_{benchmark_type}_{task_id}"
graph_config = {
"configurable": {
"llm_provider": provider,
"llm_model": model,
"max_web_research_loops": max_web_search_loops,
"user_prompt": query,
"parallel_search_enabled": parallel_search_enabled,
"parallel_search_max_concurrency": parallel_search_max_concurrency,
},
"recursion_limit": 100,
"tags": [
f"provider:{provider}",
f"model:{model}",
f"loops:{max_web_search_loops}",
f"task_id:{task_id}",
f"benchmark:{benchmark_type}",
f"parallel:{parallel_search_enabled}",
f"parallel_max:{parallel_search_max_concurrency}",
"eval_trajectory",
],
"metadata": {
"run_ref": run_ref,
"query": query,
"provider": provider,
"model": model,
"max_loops": max_web_search_loops,
"benchmark": benchmark_type,
},
}
initial_state = SummaryState(
research_topic=query,
search_query=query,
running_summary="",
research_complete=False,
knowledge_gap="",
research_loop_count=0,
sources_gathered=[],
web_research_results=[],
search_results_empty=False,
selected_search_tool="general_search",
source_citations={},
subtopic_queries=[],
subtopics_metadata=[],
extra_effort=extra_effort,
minimum_effort=minimum_effort,
qa_mode=qa_mode,
benchmark_mode=benchmark_mode,
visualization_disabled=visualization_disabled,
llm_provider=provider,
llm_model=model,
uploaded_knowledge=None,
uploaded_files=[],
uploaded_images=[],
current_node=None,
previous_node=None,
steering_enabled=steering_enabled,
parallel_search_enabled=parallel_search_enabled,
parallel_search_max_concurrency=parallel_search_max_concurrency,
)
graph_start_time = datetime.now()
logger.info(f"[Task {task_id}] Starting graph execution...")
result = None
last_started_iteration = -1
previous_state = {}
# Stream through graph and capture trajectory (same as working version)
async for state_update in fresh_graph.astream(initial_state, graph_config):
# state_update is a dict with node name as key and state changes as value
for node_name, state_data in state_update.items():
# Skip if not actual state data
if not isinstance(state_data, dict):
continue
# Get current research loop count
current_loop = state_data.get("research_loop_count", 0)
# Start a new iteration if not already started for this loop
# (Don't end previous iteration here - let reflection node handle it)
if recorder and (
recorder.current_iteration is None
and current_loop != last_started_iteration
):
recorder.start_iteration(current_loop)
last_started_iteration = current_loop
logger.info(f"[Task {task_id}] Started iteration {current_loop}")
# Capture query decomposition from research_plan
research_plan = state_data.get("research_plan")
if research_plan and research_plan != previous_state.get(
"research_plan"
):
if recorder and recorder.current_iteration is not None:
# Use research_topic for initial query, search_query for follow-ups
query = state_data.get("search_query") or state_data.get(
"research_topic", ""
)
recorder.add_tool_call(
function_name="decompose_query",
arguments={
"query": query,
"knowledge_gap": state_data.get("knowledge_gap", ""),
},
result=research_plan,
)
logger.info(
f"[Task {task_id}] 🔧 Captured decompose_query tool call"
)
# Capture search tool calls from web_research_results
web_results = state_data.get("web_research_results", [])
prev_web_results = previous_state.get("web_research_results", [])
if web_results and len(web_results) > len(prev_web_results):
if recorder and recorder.current_iteration is not None:
# Capture only NEW search results
new_results = web_results[len(prev_web_results) :]
for result in new_results:
query = result.get("query", "")
tool_name = result.get("tool", "general_search")
sources = result.get("sources", [])
recorder.add_tool_call(
function_name=tool_name,
arguments={"query": query},
result={
"num_sources": len(sources),
"sources": sources,
},
)
logger.info(
f"[Task {task_id}] 🔧 Captured {len(new_results)} search tool calls"
)
# Capture generate_report (synthesis) when running_summary changes
running_summary = state_data.get("running_summary", "")
prev_running_summary = previous_state.get("running_summary", "")
if running_summary and running_summary != prev_running_summary:
if recorder and recorder.current_iteration is not None:
# Capture the synthesis step as a tool call
recorder.add_tool_call(
function_name="generate_report",
arguments={
"existing_summary_length": len(prev_running_summary),
"new_research_results": len(web_results),
"knowledge_gap": state_data.get("knowledge_gap", ""),
},
result={
"updated_summary_length": len(running_summary),
"num_sources_cited": len(
state_data.get("source_citations", {})
),
},
)
logger.info(
f"[Task {task_id}] 📝 Captured generate_report synthesis call"
)
# Also record in running_summary field
if recorder:
recorder.record_running_summary(running_summary)
# Capture finalize_report when final_summary is created
final_summary = state_data.get("final_summary", "")
prev_final_summary = previous_state.get("final_summary", "")
if final_summary and not prev_final_summary:
if recorder and recorder.current_iteration is not None:
# Capture the finalization step
recorder.add_tool_call(
function_name="finalize_report",
arguments={
"running_summary_length": len(running_summary),
"total_sources": len(
state_data.get("sources_gathered", [])
),
"has_visualizations": len(
state_data.get("visualizations", [])
)
> 0,
},
result={
"final_report_length": len(final_summary),
"formatted_sources": len(
state_data.get("source_citations", {})
),
},
)
logger.info(
f"[Task {task_id}] 📄 Captured finalize_report formatting call"
)
# Record sources when they change - compare actual content for accuracy
sources = state_data.get("sources_gathered", [])
previous_sources = previous_state.get("sources_gathered", [])
if sources:
# Convert to sets for accurate comparison (handles additions AND replacements)
current_sources_set = set(sources)
previous_sources_set = (
set(previous_sources) if previous_sources else set()
)
# Only record if the actual source content changed
if current_sources_set != previous_sources_set:
new_sources = current_sources_set - previous_sources_set
logger.info(
f"[Task {task_id}] Iter {current_loop}: "
f"🔎 Sources updated: +{len(new_sources)} new (total: {len(current_sources_set)})"
)
if recorder:
recorder.record_sources(sources)
else:
# Log when sources exist but haven't changed (for debugging)
logger.debug(
f"[Task {task_id}] Iter {current_loop}: "
f"Sources unchanged ({len(current_sources_set)} total)"
)
# Check for reflection completion (capture and end iteration)
if (
node_name == "reflect_on_research"
or node_name == "reflect_on_report"
or "reflect" in node_name.lower()
):
if recorder and recorder.current_iteration is not None:
research_complete = state_data.get("research_complete", False)
logger.info(f"[Task {task_id}] 🤔 Reflection completed")
logger.info(
f"[Task {task_id}] Research complete: {research_complete}"
)
# Capture reflection output as a tool call
reflection_result = {
"research_complete": research_complete,
"knowledge_gap": state_data.get("knowledge_gap", ""),
"follow_up_query": state_data.get("search_query", ""),
"section_gaps": state_data.get("section_gaps", {}),
"priority_section": state_data.get("priority_section", ""),
"evaluation_notes": state_data.get("evaluation_notes", ""),
"research_topic": state_data.get("research_topic", ""),
}
# Add todo_updates if present (from steering system)
if "todo_updates" in state_data:
reflection_result["todo_updates"] = state_data[
"todo_updates"
]
# Add reflection as tool call with empty arguments (OpenAI format)
recorder.add_tool_call(
function_name="reflect_on_report",
arguments={}, # Empty args as requested
result=reflection_result,
)
logger.info(
f"[Task {task_id}] ✅ Captured reflection tool call"
)
# Log iteration summary before ending
if recorder:
iter_num = recorder.current_iteration.get("iteration", "?")
iter_sources = recorder.current_iteration.get(
"num_sources", 0
)
iter_tools = len(
recorder.current_iteration.get("tool_calls", [])
)
logger.info(
f"[Task {task_id}] 🏁 Ending iteration {iter_num} (after reflection): "
f"{iter_tools} tool_calls, {iter_sources} new sources"
)
recorder.end_iteration()
# DON'T start the next iteration here - let the loop count change handle it
# Update previous state
previous_state = state_data.copy()
# Store final result
result = state_data
# End final iteration if still active
if recorder and recorder.current_iteration is not None:
recorder.end_iteration()
graph_end_time = datetime.now()
graph_duration = graph_end_time - graph_start_time
if not result:
raise Exception("Graph execution produced no final result")
logger.info(
f"[Task {task_id}] Graph completed in {graph_duration.total_seconds():.2f}s"
)
# Extract final content (match working version logic)
final_summary = result.get("running_summary", "No summary generated")
# Handle case where summary might be a list (convert to string)
if isinstance(final_summary, list):
final_summary = "\n\n".join(str(s) for s in final_summary)
elif not isinstance(final_summary, str):
final_summary = str(final_summary)
if qa_mode or benchmark_mode:
benchmark_result = result.get("benchmark_result", {})
final_content = (
benchmark_result.get("full_response", final_summary)
if benchmark_result
else final_summary
)
else:
markdown_report = result.get("markdown_report", "")
# Handle if markdown_report is also a list or other non-string type
if isinstance(markdown_report, list):
markdown_report = "\n\n".join(str(s) for s in markdown_report)
elif not isinstance(markdown_report, str):
markdown_report = str(markdown_report) if markdown_report else ""
if markdown_report and markdown_report.strip():
# Find the start of Executive Summary section and trim TOC
exec_summary_start = markdown_report.find("## Executive Summary\n")
if exec_summary_start >= 0:
final_content = markdown_report[exec_summary_start:]
logger.info(
f"[Task {task_id}] Using clean markdown report (from Executive Summary)"
)
else:
final_content = markdown_report
logger.info(
f"[Task {task_id}] Using complete markdown report (no Executive Summary found)"
)
else:
final_content = final_summary
logger.info(
f"[Task {task_id}] Using running summary (no markdown report available)"
)
task_end_time = datetime.now()
total_duration = task_end_time - task_start_time
# Calculate total unique sources
total_unique_sources = len(result.get("sources_gathered", []))
# Create result data
result_data = {
"id": task_id,
"query": original_query, # Use original query
"article": final_content,
"summary": final_summary,
"timing": {
"start_time": task_start_time.isoformat(),
"end_time": task_end_time.isoformat(),
"total_duration_seconds": total_duration.total_seconds(),
"graph_execution_seconds": graph_duration.total_seconds(),
},
"debug_info": {
"research_loops": result.get("research_loop_count", 0),
"sources_gathered": total_unique_sources,
"knowledge_gap": result.get("knowledge_gap", ""),
"selected_search_tool": result.get("selected_search_tool", "unknown"),
"research_complete": result.get("research_complete", False),
},
"content_stats": {
"final_content_length": len(final_content.split()),
"final_summary_length": len(final_summary.split()),
},
}
# Format and save result
formatted_result = dataset_manager.format_result(task_data, result_data)
output_filename = dataset_manager.get_output_filename(str(task_id))
output_file = os.path.join(output_dir, output_filename)
with open(output_file, "w", encoding="utf-8") as f:
json.dump(formatted_result, f, indent=2, ensure_ascii=False)
# Save markdown file if requested
if save_md:
md_filename = Path(output_filename).stem + ".md"
md_file = os.path.join(output_dir, md_filename)
with open(md_file, "w", encoding="utf-8") as f:
f.write(final_content)
logger.info(f"[Task {task_id}] Markdown saved to: {md_file}")
# Save trajectory
trajectory_data = {
"run_ref": run_ref,
"query": original_query, # Use original query for trajectory too
"final_report_markdown": final_content,
"start_time": task_start_time.isoformat(),
"end_time": task_end_time.isoformat(),
"duration_seconds": total_duration.total_seconds(),
"configuration": {
"provider": provider,
"model": model,
"max_loops": max_web_search_loops,