-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact_agent.py
More file actions
1511 lines (1302 loc) · 73.2 KB
/
react_agent.py
File metadata and controls
1511 lines (1302 loc) · 73.2 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
import json
import json5
import os
import sys
import re
import hashlib
import threading
from typing import Dict, Iterator, List, Literal, Optional, Tuple, Union
from qwen_agent.llm.schema import Message
from qwen_agent.utils.utils import build_text_completion_prompt
from openai import OpenAI, APIError, APIConnectionError, APITimeoutError
from transformers import AutoTokenizer
from datetime import datetime, date
from qwen_agent.agents.fncall_agent import FnCallAgent
from qwen_agent.llm import BaseChatModel
from qwen_agent.llm.schema import ASSISTANT, DEFAULT_SYSTEM_MESSAGE, Message
from qwen_agent.settings import MAX_LLM_CALL_PER_RUN
from qwen_agent.tools import BaseTool
from qwen_agent.utils.utils import format_as_text_message, merge_generate_cfgs
from prompt import *
import time
import asyncio
import copy
from pathlib import Path
current_dir = os.path.dirname(os.path.abspath(__file__))
# Also add the current directory so modules in this directory can be imported(such as tool_memory.py)
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
from tool_scholar import *
from tool_search import *
from tool_visit import *
from tool_memory import *
OBS_START = '<tool_response>'
OBS_END = '\n</tool_response>'
MAX_LLM_CALL_PER_RUN = int(os.getenv('MAX_LLM_CALL_PER_RUN', 100))
def is_python_tool_enabled():
enable_python = os.getenv("ENABLE_PYTHON_TOOL", "true").strip().lower()
return enable_python not in {"0", "false", "no", "off"}
PYTHON_TOOL_ENABLED = is_python_tool_enabled()
if PYTHON_TOOL_ENABLED:
try:
from tool_python import PythonInterpreter
except ImportError as exc:
raise RuntimeError(
"ENABLE_PYTHON_TOOL=true requires the optional Python tool dependencies. "
"Install sandbox_fusion or set ENABLE_PYTHON_TOOL=false."
) from exc
else:
PythonInterpreter = None
def is_scholar_tool_enabled():
enable_scholar = os.getenv("ENABLE_SCHOLAR_TOOL", "false").strip().lower()
return enable_scholar not in {"0", "false", "no", "off"}
SCHOLAR_TOOL_ENABLED = is_scholar_tool_enabled()
TOOL_CLASS = [Visit(), Search(), Memory()]
if SCHOLAR_TOOL_ENABLED:
TOOL_CLASS.append(Scholar())
if PYTHON_TOOL_ENABLED:
TOOL_CLASS.append(PythonInterpreter())
TOOL_MAP = {tool.name: tool for tool in TOOL_CLASS}
# Remove visit from TOOL_MAP when disabled to prevent execution even if a model emits it.
if os.environ.get("DISABLE_VISIT_TOOL", "").lower() in ("1", "true", "yes"):
TOOL_MAP.pop("visit", None)
import random
PYTHON_TOOL_PROMPT = """{"type": "function", "function": {"name": "PythonInterpreter", "description": "Executes Python code in a sandboxed environment. To use this tool, you must follow this format:\n1. The 'arguments' JSON object must be empty: {}.\n2. The Python code to be executed must be placed immediately after the JSON block, enclosed within <code> and </code> tags.\n\nIMPORTANT: Any output you want to see MUST be printed to standard output using the print() function.\n\nExample of a correct call:\n<tool_call>\n{\"name\": \"PythonInterpreter\", \"arguments\": {}}\n<code>\nimport numpy as np\n# Your code here\nprint(f\"The result is: {np.mean([1,2,3])}\")\n</code>\n</tool_call>", "parameters": {"type": "object", "properties": {}}}}
"""
def today_date():
return date.today().strftime("%Y-%m-%d")
def _visit_disabled_notice() -> str:
return """
# CRITICAL - visit tool is DISABLED in this run
- Do not call `visit`. Never emit a `<tool_call>` whose `"name"` is `"visit"`.
- The `visit` tool is not available; such calls fail and waste context.
- Gather new evidence using `search` only. If `condenser` appears in <tools> above, you may still call it for memory / state summarization.
- If `prev_state`, instructions, or your own plan mention visiting a URL, issue another `search` query instead.
"""
def _apply_visit_disabled_text_overrides(prompt: str) -> str:
replacements = [
(
"- Check `visited_sources` to avoid visiting URLs that have already been visited.",
"- Check `visited_sources` to avoid redoing work already reflected in state (there is no `visit` tool in this run).",
),
(
"You can use these directly in your answer without re-searching or re-visiting.",
"You can use these directly in your answer without re-running the same searches.",
),
(
'The `need` field specifies the exact next action (e.g., "visit <URL>" or "search <query>") to resolve the uncertainty.',
'The `need` field may suggest a next action; if it mentions visiting a URL, use an additional `search` query instead (`visit` is disabled).',
),
(
"IMPORTANT: Do NOT search for or visit information that is already in `prev_state`, unless it's insufficient to answer the user's question. Only in this case, you are encouraged to search for more information or even visit the same URL. Instead, use the information from `prev_state` directly, or follow the specific actions suggested in `information_state.uncertain.need` if more information is needed.",
"IMPORTANT: Do NOT search for information that is already in `prev_state`, unless it's insufficient to answer the user's question. Only in this case, issue additional `search` queries (`visit` is disabled). Use `prev_state` directly where possible, or follow `information_state.uncertain.need` but map any \"visit\" suggestion to `search`.",
),
(
"- The visit tool can ONLY open bm25://<docid> URLs from search results. External URLs (https://, http://) will fail.",
"- Visit is disabled in this run; rely on search snippets and metadata from the local index only.",
),
(
"- Do NOT attempt to visit Wikipedia, Google, or any other external website.",
"- Do not call `visit` for external sites or bm25 links; use search only.",
),
(
"- When search returns relevant documents, use visit to read their full content via the bm25:// links before drawing conclusions.",
"- When search returns relevant documents, base conclusions on returned snippets and scores; do not call `visit`.",
),
]
for old, new in replacements:
if old in prompt:
prompt = prompt.replace(old, new, 1)
return prompt
def build_system_prompt(enable_python_tool: bool) -> str:
prompt_name = os.getenv("SYSTEM_PROMPT_NAME", "").strip()
if prompt_name and prompt_name != "SYSTEM_PROMPT":
prompt = globals().get(prompt_name)
if prompt is None:
print(
f"[build_system_prompt] Warning: SYSTEM_PROMPT_NAME={prompt_name!r} "
"not found in prompt.py, falling back to SYSTEM_PROMPT"
)
prompt = SYSTEM_PROMPT
elif os.environ.get('BM25_INDEX_PATH', '') or os.environ.get('FAISS_INDEX_PATH', ''):
prompt = BROWSECOMP_PLUS_SYSTEM_PROMPT
else:
prompt = SYSTEM_PROMPT
if SCHOLAR_TOOL_ENABLED:
prompt = prompt.replace("</tools>", f"{SCHOLAR_TOOL_PROMPT}</tools>")
if enable_python_tool:
prompt = prompt.replace("</tools>", f"{PYTHON_TOOL_PROMPT}</tools>")
visit_disabled = os.environ.get("DISABLE_VISIT_TOOL", "").lower() in ("1", "true", "yes")
if visit_disabled:
prompt = re.sub(r'\{"type": "function", "function": \{"name": "visit".*?\}\}\n?', '', prompt)
if "</tools>" in prompt:
prompt = prompt.replace("</tools>", "</tools>" + _visit_disabled_notice(), 1)
prompt = _apply_visit_disabled_text_overrides(prompt)
return prompt
class MultiTurnReactAgent(FnCallAgent):
def __init__(self,
function_list: Optional[List[Union[str, Dict, BaseTool]]] = None,
llm: Optional[Union[Dict, BaseChatModel]] = None,
**kwargs):
self.llm_generate_cfg = llm["generate_cfg"]
self.llm_local_path = llm["model_path"]
self.python_tool_enabled = PYTHON_TOOL_ENABLED
self.scholar_tool_enabled = SCHOLAR_TOOL_ENABLED
self.function_list = function_list or []
# Base configuration (not modified concurrently)
memory_threshold_str = (
os.getenv('MEMORY_THRESHOLD')
or os.getenv('MEMORY_CONTEXT_THRESHOLD')
or os.getenv('MEMORY_TOKEN_THRESHOLD')
or '16000'
)
self.base_memory_context_threshold = int(memory_threshold_str)
print(f"Base memory threshold: {self.base_memory_context_threshold}")
print(f"Python tool enabled: {self.python_tool_enabled}")
print(f"Scholar tool enabled: {self.scholar_tool_enabled}")
self.memory_enabled = os.getenv('MEMORY_ENABLED', 'true').lower() == 'true'
self.memory_strategy = os.getenv('MEMORY_STRATEGY', 'condenser').strip().lower()
print(f"Memory strategy: {self.memory_strategy}")
# Base log directory(not modified concurrently)
self.base_log_dir = os.getenv('TASK_LOG_DIR', './task_logs')
Path(self.base_log_dir).mkdir(parents=True, exist_ok=True)
# ========== Key fix: use threading.local() to store thread-specific state ==========
# this gives each thread its own independent state and prevents interference
self._thread_local = threading.local()
# Cache tokenizer to avoid reloading every time
self._tokenizer = None
def _get_thread_state(self):
"""Get the current thread state, initializing it if needed"""
if not hasattr(self._thread_local, 'initialized'):
self._init_thread_state()
return self._thread_local
def _init_thread_state(self):
"""Initialize the current thread state"""
tl = self._thread_local
tl.initialized = True
tl.url_filter_stats = {
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
"total_cost": 0.0,
}
tl.memory_state = None # prev_state for memory tool
tl.memory_context_threshold = self.base_memory_context_threshold
tl.context_threshold_triggered = False
tl.condenser_processing = False
tl.condenser_call_count = 0
tl.original_messages_snapshots = []
tl.full_messages = [] # full message history; not compressed by condenser; used for trajectory_no_memory
tl.task_log_dir = None
tl.current_question = None
tl.current_filename = ""
tl.trajectory_update_count = 0
tl.model = None
tl.preferred_endpoint = None # (host, port) for endpoint affinity to utilize KV cache
tl.endpoint_failure_count = 0 # consecutive failure count for current endpoint
tl.user_prompt = None
def sanity_check_output(self, content):
return "<think>" in content and "</think>" in content
def _parse_memory_result(self, result: str) -> Optional[Dict]:
"""
Parse the result returned by the memory tool and extract the JSON state
Args:
result: string returned by the memory tool
Returns:
parsed state JSON, or None if parsing fails
"""
if not result or result.startswith("[Memory]"):
return None
try:
# Try parsing directly
new_state = json.loads(result)
return new_state
except json.JSONDecodeError:
# Try extracting JSON from a markdown code block
json_match = re.search(r'```(?:json)?\s*\n(.*?)\n```', result, re.DOTALL)
if json_match:
try:
new_state = json.loads(json_match.group(1))
return new_state
except json.JSONDecodeError:
pass
# Try to find the content from the first { to the last }
first_brace = result.find('{')
last_brace = result.rfind('}')
if first_brace != -1 and last_brace != -1:
try:
new_state = json.loads(result[first_brace:last_brace + 1])
return new_state
except json.JSONDecodeError:
pass
print(f"[Memory] Warning: Failed to parse JSON from memory tool response: {result[:200]}")
return None
def _save_memory_log(self, original_messages: List[Dict], compressed_messages: List[Dict],
state: Dict, trigger_reason: str, round_num: int):
"""
Save logs for memory operations(simplified version, keeping only necessary debug information)
Args:
original_messages: original messages before compression(actually seen by the model)
compressed_messages: messages after compression(new prev_state added and later messages removed)
state: generated state JSON
trigger_reason: trigger reason (CONTEXT_THRESHOLD, final, or timeout)
round_num: current round number
"""
try:
tl = self._get_thread_state()
tl.condenser_call_count += 1
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
# Save only one simplified log file with the necessary information(save it directly under the task directory)
log_data = {
"condenser_call_number": tl.condenser_call_count,
"timestamp": timestamp,
"datetime": datetime.now().isoformat(),
"round": round_num,
"trigger_reason": trigger_reason,
"state": state,
"original_message_count": len(original_messages),
"compressed_message_count": len(compressed_messages),
"messages_removed": len(original_messages) - len(compressed_messages)
}
log_file = os.path.join(tl.task_log_dir, f"condenser_call_{tl.condenser_call_count}_{timestamp}.json")
with open(log_file, 'w', encoding='utf-8') as f:
json.dump(log_data, f, ensure_ascii=False, indent=2)
print(f"[Memory] Log saved to: {log_file}")
except Exception as e:
print(f"[Memory] Warning: Failed to save memory log: {e}")
import traceback
traceback.print_exc()
def _remove_prev_state_from_messages(self, messages: List[Dict]) -> List[Dict]:
"""
Remove all prev_state sections from messages and return the original messages(without the memory mechanism)
Args:
messages: messages containing prev_state
Returns:
messages after removing prev_state
"""
cleaned_messages = copy.deepcopy(messages)
for msg in cleaned_messages:
if msg.get("role") == "user" and "content" in msg:
content = msg["content"]
# Find and remove the prev_state section
prev_state_start = content.find("====================\nRESEARCH STATE SUMMARY")
if prev_state_start != -1:
# Remove everything from prev_state to the end
msg["content"] = content[:prev_state_start].rstrip()
return cleaned_messages
def _normalize_tool_call(self, raw_tool_call: str) -> Tuple[Optional[str], Optional[Dict], Optional[str]]:
"""
Parse and normalize a tool_call payload.
Returns:
(tool_name, tool_args, error_message)
- On success: (normalized_name, normalized_args_dict, None)
- On failure: (None, None, "[Tool Error] ...")
"""
# Handle <code>...</code> tags for PythonInterpreter:
# Model may generate: {"name": "PythonInterpreter", "arguments": {}}\n<code>...\n</code>
extracted_code = None
json_part = raw_tool_call
code_match = re.search(r'<code>(.*?)</code>', raw_tool_call, re.DOTALL)
if code_match:
extracted_code = code_match.group(1).strip()
# Remove <code>...</code> from the string before JSON parsing
json_part = raw_tool_call[:code_match.start()].strip()
try:
tool_call = json.loads(json_part)
except Exception:
raw_tool_name = ["__invalid_tool_call_json__", raw_tool_call]
return (
None,
None,
f"[Tool Error] Invalid tool call format: name must be string, got {raw_tool_name!r}",
)
# Align with training-side parser:
# - dict: read {"name", "arguments"}
# - non-dict: pass through as tool_name with empty args
if isinstance(tool_call, dict):
raw_tool_name = tool_call.get("name", "")
raw_tool_args = tool_call.get("arguments", {})
else:
raw_tool_name = tool_call
raw_tool_args = {}
tool_name = raw_tool_name
if isinstance(tool_name, list):
if len(tool_name) == 1 and isinstance(tool_name[0], str):
tool_name = tool_name[0]
else:
return (
None,
None,
f"[Tool Error] Invalid tool call format: name must be string, got {raw_tool_name!r}",
)
if not isinstance(tool_name, str) or not tool_name.strip():
return (
None,
None,
f"[Tool Error] Invalid tool call format: name must be string, got {raw_tool_name!r}",
)
tool_name = tool_name.strip()
tool_args = raw_tool_args
if isinstance(tool_args, str):
try:
# Keep strict JSON parsing for stringified arguments to mirror training loop.
tool_args = json.loads(tool_args)
except json.JSONDecodeError:
return (
None,
None,
f"[Tool Error] Invalid tool arguments JSON for {tool_name}: {raw_tool_args!r}",
)
elif isinstance(tool_args, list):
if len(tool_args) == 1 and isinstance(tool_args[0], dict):
tool_args = tool_args[0]
else:
return (
None,
None,
f"[Tool Error] Invalid tool call format for {tool_name}: arguments must be object, got {raw_tool_args!r}",
)
elif tool_args is None:
tool_args = {}
if not isinstance(tool_args, dict):
return (
None,
None,
f"[Tool Error] Invalid tool call format for {tool_name}: arguments must be object, got {raw_tool_args!r}",
)
# Inject extracted <code> into tool_args for PythonInterpreter
if extracted_code and tool_name and tool_name.strip() == "PythonInterpreter":
tool_args["code"] = extracted_code
return tool_name, tool_args, None
def _save_trajectory_for_distillation(self, messages: List[Dict], state: Optional[Dict] = None,
trigger_reason: str = "unknown", round_num: int = 0,
is_final: bool = False,
no_memory_messages: Optional[List[Dict]] = None):
"""
Save the trajectory used for distillation training
Save the messages actually seen by the model (before updating prev_state), rather than the updated messages
This ensures distillation training uses the actual inputs processed by the model
Args:
messages: messages actually seen by the model (original messages before updating prev_state)
state: newly generated state JSON (used for distillation training; can be None for the final trajectory)
trigger_reason: trigger reason (CONTEXT_THRESHOLD, final, timeout, or token_limit)
round_num: current round number
is_final: whether this is the final trajectory
"""
try:
tl = self._get_thread_state()
if tl.current_question is None:
print("[Memory] Warning: current_question is None, skipping trajectory save")
return
if tl.task_log_dir is None:
print("[Memory] Warning: task_log_dir is None, skipping trajectory save")
return
if not is_final:
tl.trajectory_update_count += 1
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
# Build trajectory data(the version containing prev_state)
trajectory_data = {
"question": tl.current_question,
"is_final": is_final,
"condenser_update_id": tl.trajectory_update_count if not is_final else None,
"condenser_call_id": tl.condenser_call_count if not is_final else None,
"timestamp": timestamp,
"datetime": datetime.now().isoformat(),
"round": round_num,
"trigger_reason": trigger_reason,
"prev_state": state, # Newly generated prev_state (used for distillation training); may be None for the final trajectory
"messages": copy.deepcopy(messages), # Messages actually seen by the model (original messages before updating prev_state)
"message_count": len(messages),
"token_count": self.count_tokens(messages) if hasattr(self, 'count_tokens') else None
}
# Save to a JSONL file(append mode for later training use)
trajectory_file = os.path.join(tl.task_log_dir, "trajectories.jsonl")
with open(trajectory_file, 'a', encoding='utf-8') as f:
f.write(json.dumps(trajectory_data, ensure_ascii=False) + "\n")
should_save_no_memory = is_final or no_memory_messages is not None
if should_save_no_memory:
if no_memory_messages is not None:
messages_no_memory = copy.deepcopy(no_memory_messages)
else:
full_msgs = tl.full_messages if tl.full_messages else messages
messages_no_memory = self._remove_prev_state_from_messages(full_msgs)
trajectory_data_no_memory = {
"question": tl.current_question,
"is_final": is_final,
"condenser_update_id": tl.trajectory_update_count if not is_final else None,
"condenser_call_id": tl.condenser_call_count if not is_final else None,
"timestamp": timestamp,
"datetime": datetime.now().isoformat(),
"round": round_num,
"trigger_reason": trigger_reason,
"prev_state": None, # Without the memory mechanism, prev_state is None
"messages": messages_no_memory, # Full conversation history with prev_state removed
"message_count": len(messages_no_memory),
"token_count": self.count_tokens(messages_no_memory) if hasattr(self, 'count_tokens') else None
}
trajectory_file_no_memory = os.path.join(tl.task_log_dir, "trajectories_no_memory.jsonl")
with open(trajectory_file_no_memory, 'a', encoding='utf-8') as f:
f.write(json.dumps(trajectory_data_no_memory, ensure_ascii=False) + "\n")
if is_final:
print(f"[Memory] Final trajectory saved for distillation (round {round_num}, trigger: {trigger_reason})")
else:
print(f"[Memory] Trajectory saved for distillation (update #{tl.trajectory_update_count}, round {round_num}, trigger: {trigger_reason})")
except Exception as e:
print(f"[Memory] Warning: Failed to save trajectory: {e}")
import traceback
traceback.print_exc()
def _update_first_user_message_with_state(self, messages: List[Dict], state: Dict,
original_messages: List[Dict] = None,
trigger_reason: str = "unknown",
round_num: int = 0):
"""
Update the first user message by appending prev_state and the prompt at the end
and delete all later interaction messages (user and assistant), because this information has already been summarized into prev_state
Args:
messages: message list(will be modified)
state: state JSON to add
original_messages: original messages before compression(used for logging)
trigger_reason: trigger reason(used for logging)
round_num: current round number(used for logging)
"""
# Save a snapshot of the messages before compression(used for logging)
if original_messages is None:
original_messages = copy.deepcopy(messages)
# Find the first user message(usually messages[1], since messages[0] is the system message)
first_user_idx = None
for i, msg in enumerate(messages):
if msg.get("role") == "user":
first_user_idx = i
break
if first_user_idx is None:
print("[Memory] Warning: No user message found to update")
return
# Save the raw content of the first user message (with any previously added prev_state removed)
first_user_content = messages[first_user_idx]["content"]
# If prev_state was added previously, remove it first
if "RESEARCH STATE SUMMARY (prev_state)" in first_user_content:
# Find the prev_state section and remove it
prev_state_start = first_user_content.find("====================\nRESEARCH STATE SUMMARY")
if prev_state_start != -1:
first_user_content = first_user_content[:prev_state_start].rstrip()
# Decide how many messages to keep based on the trigger type(before adding prev_state)
# This lets us compute the token count after deletion first
# CONTEXT_THRESHOLD when triggered, delete all subsequent messages(keep only the system prompt and the first user message)
messages_to_keep = first_user_idx + 1
removed_count = len(messages) - messages_to_keep
if removed_count > 0:
messages[:] = messages[:messages_to_keep]
print(f"[Memory] {trigger_reason}: Removed {removed_count} subsequent messages (summarized in prev_state)")
else:
print(f"[Memory] {trigger_reason}: No messages to remove")
# Compute the token count after deleting messages(before prev_state is added)
token_count_after_deletion = self.count_tokens(messages)
# Format state as a JSON string
state_json = json.dumps(state, ensure_ascii=False, indent=2)
# Add prev_state and the prompt
state_section = f"""
====================
RESEARCH STATE SUMMARY (prev_state)
====================
The following is a compressed summary of your research progress so far. Use this to:
- Avoid repeating searches you've already done (check search_queries)
- Reference information you've already verified (check information_state.trusted)
- Build upon previous findings rather than starting from scratch
{state_json}
IMPORTANT: This state summary is maintained automatically. You can reference it to avoid redundant work and build upon previous research findings.
"""
# Add the full prev_state
messages[first_user_idx]["content"] = first_user_content + state_section
# Compute the token count after adding prev_state
token_count_with_state = self.count_tokens(messages)
print(f"[Memory] Added prev_state to first user message (tokens: {token_count_after_deletion} -> {token_count_with_state})")
# Save a snapshot of the messages after compression
compressed_messages = copy.deepcopy(messages)
# Save logs
self._save_memory_log(original_messages, compressed_messages, state, trigger_reason, round_num)
# Save the trajectory used for distillation training (messages actually seen by the model, i.e. original_messages before the update)
# Note:This saves the messages seen by the model before calling condenser, including the old prev_state(if any)
self._save_trajectory_for_distillation(original_messages, state, trigger_reason, round_num)
def _discard_all_memory_context(self, messages: List[Dict],
original_messages: List[Dict] = None,
trigger_reason: str = "CONTEXT_THRESHOLD_DISCARD_ALL",
round_num: int = 0):
"""
Drop the current context and keep only the system prompt plus the first user message.
Any existing prev_state is removed, so the next round restarts without injected memory.
"""
if original_messages is None:
original_messages = copy.deepcopy(messages)
tl = self._get_thread_state()
tl.memory_state = None
first_user_idx = None
for i, msg in enumerate(messages):
if msg.get("role") == "user":
first_user_idx = i
break
if first_user_idx is None:
print("[Memory] Warning: No user message found to reset")
return
first_user_content = messages[first_user_idx]["content"]
if "RESEARCH STATE SUMMARY (prev_state)" in first_user_content:
prev_state_start = first_user_content.find("====================\nRESEARCH STATE SUMMARY")
if prev_state_start != -1:
first_user_content = first_user_content[:prev_state_start].rstrip()
messages[first_user_idx]["content"] = first_user_content
messages_to_keep = first_user_idx + 1
removed_count = len(messages) - messages_to_keep
if removed_count > 0:
messages[:] = messages[:messages_to_keep]
print(f"[Memory] {trigger_reason}: Removed {removed_count} subsequent messages and cleared prev_state")
else:
print(f"[Memory] {trigger_reason}: No messages to remove")
compressed_messages = copy.deepcopy(messages)
discard_state = {
"strategy": "discard_all",
"discarded": True,
"threshold": self.base_memory_context_threshold,
}
self._save_memory_log(original_messages, compressed_messages, discard_state, trigger_reason, round_num)
self._save_trajectory_for_distillation(
original_messages,
None,
trigger_reason,
round_num,
no_memory_messages=copy.deepcopy(tl.full_messages if tl.full_messages else original_messages),
)
def _hide_old_tool_results(self, messages: List[Dict],
original_messages: List[Dict] = None,
trigger_reason: str = "CONTEXT_THRESHOLD_HIDE_TOOL_RESULT",
round_num: int = 0):
"""
Retain the reasoning chain but prune bulky tool results.
Keep:
- system message(s)
- the first user message
- all assistant messages (think + tool calls)
- only the most recent tool_response user message
Drop:
- older tool_response user messages
"""
if original_messages is None:
original_messages = copy.deepcopy(messages)
first_user_idx = None
tool_response_indices = []
for i, msg in enumerate(messages):
role = msg.get("role")
content = msg.get("content", "")
if role == "user" and first_user_idx is None:
first_user_idx = i
if role == "user" and isinstance(content, str) and content.startswith(OBS_START) and content.rstrip().endswith("</tool_response>"):
tool_response_indices.append(i)
if first_user_idx is None:
print("[Memory] Warning: No user message found to prune")
return
latest_tool_response_idx = tool_response_indices[-1] if tool_response_indices else None
first_user_msg = copy.deepcopy(messages[first_user_idx])
first_user_content = first_user_msg.get("content", "")
if "RESEARCH STATE SUMMARY (prev_state)" in first_user_content:
prev_state_start = first_user_content.find("====================\nRESEARCH STATE SUMMARY")
if prev_state_start != -1:
first_user_msg["content"] = first_user_content[:prev_state_start].rstrip()
pruned_messages = []
removed_tool_results = 0
for i, msg in enumerate(messages):
if i == first_user_idx:
pruned_messages.append(first_user_msg)
continue
role = msg.get("role")
content = msg.get("content", "")
if role == "user" and isinstance(content, str) and content.startswith(OBS_START) and content.rstrip().endswith("</tool_response>"):
if i == latest_tool_response_idx:
pruned_messages.append(copy.deepcopy(msg))
else:
removed_tool_results += 1
continue
pruned_messages.append(copy.deepcopy(msg))
old_message_count = len(messages)
messages[:] = pruned_messages
new_message_count = len(messages)
print(
f"[Memory] {trigger_reason}: removed {removed_tool_results} old tool result messages "
f"({old_message_count} -> {new_message_count} messages)"
)
compressed_messages = copy.deepcopy(messages)
hide_state = {
"strategy": "hide_tool_result",
"removed_tool_results": removed_tool_results,
"kept_latest_tool_result": latest_tool_response_idx is not None,
"threshold": self.base_memory_context_threshold,
}
self._save_memory_log(original_messages, compressed_messages, hide_state, trigger_reason, round_num)
self._save_trajectory_for_distillation(
original_messages,
None,
trigger_reason,
round_num,
no_memory_messages=compressed_messages,
)
def _call_condenser_directly(self, messages: List[Dict], round_num: int = 0) -> Optional[Dict]:
"""
Directly call the condenser tool to update the state summary
Args:
messages: current message list (used to extract events)
round_num: current round number(used for logging)
Returns:
updated state JSON, or None if the update fails
"""
try:
tl = self._get_thread_state()
# Prevent duplicate calls:If processing is already in progress, return directly
if tl.condenser_processing:
print("[Memory] Warning: Condenser is already processing, skipping duplicate call")
return tl.memory_state
# Mark as processing
tl.condenser_processing = True
# Save a copy of the original messages(used for logging)
original_messages = copy.deepcopy(messages)
# Prepare events(extracting them from messages while excluding the system prompt)
events = []
for msg in messages:
role = msg.get("role", "")
if role in ["user", "assistant"]:
events.append({
"role": role,
"content": msg.get("content", "")
})
# Call the condenser tool
condenser_tool = TOOL_MAP.get("condenser")
if not condenser_tool:
print("[Memory] Warning: Condenser tool not found in TOOL_MAP")
return None
params = {
"events": events,
"prev_state": tl.memory_state
}
print(f"[Memory] Directly calling condenser tool (CONTEXT_THRESHOLD trigger)")
result = condenser_tool.call(params)
# Print the raw summary output
print(f"[Memory] Condenser output (raw):")
print("=" * 80)
# If the output is too long, show only the first 2000 characters
if len(result) > 2000:
print(result[:2000])
print(f"... [truncated, total length: {len(result)} chars]")
else:
print(result)
print("=" * 80)
# Parse the returned JSON state
new_state = self._parse_memory_result(result)
if new_state:
tl.memory_state = new_state
print(f"[Memory] State updated successfully from direct condenser call")
# Print the parsed state JSON
print(f"[Memory] Parsed state JSON:")
print(json.dumps(new_state, ensure_ascii=False, indent=2))
# Update the first user message, add prev_state, and save logs
self._update_first_user_message_with_state(
messages, new_state,
original_messages=original_messages,
trigger_reason="CONTEXT_THRESHOLD",
round_num=round_num
)
# Reset the processing flag
tl.condenser_processing = False
return new_state
else:
print(f"[Memory] Warning: Failed to parse state from condenser result")
# Reset the processing flag
tl.condenser_processing = False
return None
except Exception as e:
print(f"[Memory] Error calling condenser tool directly: {e}")
import traceback
traceback.print_exc()
# Reset the processing flag
tl = self._get_thread_state()
tl.condenser_processing = False
return None
def _strip_wrapping_quotes(self, value: str) -> str:
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
return value[1:-1].strip()
return value
def _load_server_endpoints(self) -> Tuple[List[str], List[int], str]:
"""Reload endpoint configuration on every call to support runtime hot-swapping.
Priority:SERVER_ENDPOINTS_FILE file > environment variables HOSTNAME_LIST / PORTS.
Changes to server_endpoints.conf take effect without restarting the process.
"""
hostname_list = os.getenv('HOSTNAME_LIST', 'localhost')
port_list = os.getenv('PORTS', '6000,6001,6002,6003')
endpoint_source = "env"
config_file = os.getenv('SERVER_ENDPOINTS_FILE', '').strip()
if config_file:
config_path = Path(config_file).expanduser()
if config_path.is_file():
try:
for raw_line in config_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = self._strip_wrapping_quotes(value)
if key == "HOSTNAME_LIST" and value:
hostname_list = value
elif key == "PORTS" and value:
port_list = value
endpoint_source = f"file:{config_path}"
except Exception as e:
print(f"Warning: failed to read endpoint config {config_path}: {e}. Falling back to env values.")
else:
print(f"Warning: SERVER_ENDPOINTS_FILE not found: {config_path}. Falling back to env values.")
hosts = [h.strip() for h in hostname_list.split(',') if h.strip()]
if not hosts:
hosts = ['localhost']
ports: List[int] = []
invalid_ports: List[str] = []
for raw_port in port_list.split(','):
raw_port = raw_port.strip()
if not raw_port:
continue
try:
ports.append(int(raw_port))
except ValueError:
invalid_ports.append(raw_port)
if invalid_ports:
print(f"Warning: invalid ports ignored: {', '.join(invalid_ports)}")
if not ports:
ports = [6000, 6001, 6002, 6003]
return hosts, ports, endpoint_source
def _select_endpoint(self, available_endpoints: List[Tuple[str, int]]) -> Tuple[str, int]:
"""Select endpoint with affinity to utilize KV cache.
- First call: randomly select and bind an endpoint
- Subsequent calls: reuse the bound endpoint if still available
- If bound endpoint is removed (hot-swap): re-select from available endpoints
"""
tl = self._get_thread_state()
if tl.preferred_endpoint and tl.preferred_endpoint in available_endpoints:
return tl.preferred_endpoint
selected = random.choice(available_endpoints)
tl.preferred_endpoint = selected
tl.endpoint_failure_count = 0
return selected
def _failover_endpoint(self, current_endpoint: Tuple[str, int],
all_endpoints: List[Tuple[str, int]],
hosts: List[str], ports: List[int]) -> Optional[Tuple[str, int]]:
"""Select a new endpoint for failover.
Priority:
1. Try a different host first (to avoid host-level failures)
2. If no other hosts, try a different port on the same host
3. If no alternatives, return None
"""
current_host, current_port = current_endpoint
other_host_endpoints = [ep for ep in all_endpoints
if ep[0] != current_host and ep != current_endpoint]
if other_host_endpoints:
return random.choice(other_host_endpoints)
same_host_other_ports = [ep for ep in all_endpoints
if ep[0] == current_host and ep[1] != current_port]
if same_host_other_ports:
return random.choice(same_host_other_ports)
return None
def call_server(self, msgs, max_tries=10):
openai_api_key = "EMPTY"
FAILOVER_THRESHOLD = 2 # Switch endpoint after 2 consecutive failures
tl = self._get_thread_state()
base_sleep_time = 1
for attempt in range(max_tries):
# Reload endpoint configuration on each attempt to support runtime hot-swapping
hosts, ports, endpoint_source = self._load_server_endpoints()
all_endpoints = [(host, port) for host in hosts for port in ports]
# Use endpoint affinity to utilize KV cache
selected_host, selected_port = self._select_endpoint(all_endpoints)
openai_api_base = f"http://{selected_host}:{selected_port}/v1"
print(f"--- Attempting to call the service, try {attempt + 1}/{max_tries} ---")
print(f"--- Endpoint source: {endpoint_source} (hosts={hosts}, ports={ports}) ---")
print(f"--- Using endpoint: {selected_host}:{selected_port} (preferred={tl.preferred_endpoint}, f_count={tl.endpoint_failure_count}) ---")
call_failed = False
try:
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
timeout=600.0,
)
max_tokens = int(os.getenv('LLM_MAX_TOKENS', '10000'))
chat_response = client.chat.completions.create(
model=tl.model,
messages=msgs,
stop=["\n<tool_response>", "<tool_response>"],
temperature=self.llm_generate_cfg.get('temperature', 0.6),
top_p=self.llm_generate_cfg.get('top_p', 0.95),
logprobs=True,
max_tokens=max_tokens,
presence_penalty=self.llm_generate_cfg.get('presence_penalty', 1.1)
)
content = chat_response.choices[0].message.content
# OpenRouter provides API calling. If you want to use OpenRouter, you need to uncomment line 89 - 90.
# reasoning_content = "<think>\n" + chat_response.choices[0].message.reasoning.strip() + "\n</think>"
# content = reasoning_content + content
if content and content.strip():
print(f"--- Service call successful, received a valid response from {selected_host}:{selected_port} ---")
tl.endpoint_failure_count = 0
return content.strip()
else:
print(f"Warning: Attempt {attempt + 1} received an empty response from {selected_host}:{selected_port}.")
call_failed = True
except (APIError, APIConnectionError, APITimeoutError) as e:
print(f"Error: Attempt {attempt + 1} failed with an API or network error on {selected_host}:{selected_port}: {e}")
call_failed = True
except Exception as e:
print(f"Error: Attempt {attempt + 1} failed with an unexpected error on {selected_host}:{selected_port}: {e}")