Repository navigation
Expand file tree
/
Copy pathtree.py
More file actions
1789 lines (1570 loc) · 61.7 KB
/
Copy pathtree.py
File metadata and controls
1789 lines (1570 loc) · 61.7 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 asyncio
import heapq
import json
import os
import random
import re
import string
from collections import deque
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from general_prompt import (
BLOCKSWORLD_EXECUTABILITY_EXAMPLE,
EXECUTABILITY_CHECK_PROMPT,
GENERATE_AVAILABLE_ACTIONS_PROMPT,
GOAL_EXTRACTOR_PROMPT_ACP,
GOAL_EXTRACTOR_PROMPT_PLANBENCH,
INITIAL_STATE_EXTRACTOR_PROMPT_PLANBENCH,
PROGRESSION_PROMPT,
STATE_CHECK_PROMPT,
STATE_SCORE_PROMPT,
)
from utils import AsyncRequestSender, ContentExtraction, RequestSender, readPDDL
# Import the new heuristic computation system
try:
from heuristic_computer import clear_lora_model_cache as new_clear_lora_model_cache
from heuristic_computer import (
compute_heuristic_batch_with_lora as new_compute_heuristic_batch_with_lora,
)
from heuristic_computer import (
compute_heuristic_with_lora as new_compute_heuristic_with_lora,
)
HEURISTIC_SYSTEM_AVAILABLE = True
except ImportError as exc:
HEURISTIC_SYSTEM_AVAILABLE = False
new_compute_heuristic_batch_with_lora = None
HEURISTIC_IMPORT_ERROR = exc
def _load_pddl(filename: str) -> str:
"""尝试多个相对路径加载 PDDL 文件,全部失败则返回空字符串(不阻断启动)。"""
search_paths = [
f"../domain_pddl/{filename}",
f"./domain_pddl/{filename}",
f"domain_pddl/{filename}",
os.path.join(
os.path.dirname(os.path.abspath(__file__)), "domain_pddl", filename
),
]
for path in search_paths:
try:
content = readPDDL(path)
return content
except FileNotFoundError:
continue
print(f"[警告] 无法加载 PDDL 文件: {filename},已跳过。")
return ""
DOMAIN_DESCRIPTION_BLOCKSWORLD = _load_pddl("blocksworld.pddl")
DOMAIN_DESCRIPTION_LOGISTICS = _load_pddl("logistics.pddl")
DOMAIN_DESCRIPTION_DEPOT = _load_pddl("depots.pddl")
DOMAIN_MAP = {
"blocksworld": DOMAIN_DESCRIPTION_BLOCKSWORLD,
"logistics": DOMAIN_DESCRIPTION_LOGISTICS,
"depots": DOMAIN_DESCRIPTION_DEPOT,
"depot": DOMAIN_DESCRIPTION_DEPOT,
}
def _get_domain_description(domain: str) -> str:
"""根据领域名称返回对应的 PDDL 领域描述字符串。"""
return DOMAIN_MAP.get(domain.lower(), DOMAIN_DESCRIPTION_BLOCKSWORLD)
def normalize_state_for_search(state: str) -> str:
"""Normalize a controlled-NL state into an order-insensitive search key."""
predicates = re.split(r"[.,]|\band\b", state.strip().lower())
return "|".join(sorted(predicate.strip() for predicate in predicates if predicate.strip()))
def record_better_expansion(
closed_best_g: Dict[str, float], normalized_state: str, g_cost: float
) -> bool:
"""Record an expansion and allow reopening only when g strictly improves."""
previous = closed_best_g.get(normalized_state)
if previous is not None and previous <= g_cost:
return False
closed_best_g[normalized_state] = g_cost
return True
class Node:
"""
Description
-----------
Node of the tree, each node represents a state.
Parameters
----------
node_id : the ID of the node, which is a unique identifier for the node.
parent_id : the parent id of this node.
children_id : children of this node, corresponding to available_actions.
available_actions : list, each element is a list of [available_action, ...].
state : the state of the tree node.
action_taken : the last action taken from parent to this node.
history_actions : the actions taken from root to this node.
g_cost : the cost from root to this node.
h_cost : the cost from this node to goal, estimated by LLM.
status : whether this node is active or pruned.
flag : whether this state is the goal state.
pruned_reason : if pruned, the reason for pruning.
"""
def __init__(
self,
node_id: int,
parent_id: Optional[int] = None,
state: str = "",
query: str = "",
g_cost: float = 0.0,
h_cost: float = 0.0,
**kwargs,
):
self.node_id: int = node_id
self.parent_id: Optional[int] = parent_id
self.children_id: List[int] = []
self.generated_actions: List[str] = kwargs.get("generated_actions", [])
self.available_actions: Optional[List[List[Any]]] = kwargs.get(
"available_actions", []
)
self.state: str = state
self.state_score: float = kwargs.get("state_score", 5.0)
self.action_taken: Optional[List[str]] = kwargs.get("action_taken", [])
self.history_actions: List[str] = kwargs.get("history_actions", [])
self.query: str = query
self.g_cost: float = g_cost
self.h_cost: float = h_cost
self.flag: bool = False # True means this state is the goal state
self.status: bool = True # True (1) = active, False (0) = pruned
self.pruned_reason: Optional[str] = (
None # INFINITE_HEURISTIC_VALUE or DOMAIN_KNOWLEDGE_VIOLATION
)
@property
def f_cost(self) -> float:
"""count total cost f, f = g+h = actual cost + heuristic cost."""
h_val = self.h_cost if self.h_cost is not None else 0.0
return self.g_cost + h_val
def __lt__(self, other: "Node") -> bool:
"""compare nodes for priority queue (A* algorithm)."""
return self.f_cost < other.f_cost
def to_dict(self) -> Dict[str, Any]:
"""Convert node to dictionary for JSON serialization."""
return {
"node_id": self.node_id,
"parent_id": self.parent_id,
"children_id": self.children_id,
"generated_actions": self.generated_actions,
"available_actions": self.available_actions,
"state": self.state,
"state_score": self.state_score,
"action_taken": self.action_taken,
"history_actions": self.history_actions,
"query": self.query,
"g_cost": self.g_cost,
"h_cost": self.h_cost,
"f_cost": self.f_cost,
"flag": self.flag,
"status": self.status,
"pruned_reason": self.pruned_reason,
}
def extract_initial_state(raw_text: str, max_retries: int = 3, **kwargs) -> str:
"""
Extract initial state from raw text.
Parameters
----------
raw_text : str
Raw text containing initial state description
max_retries : int
Maximum number of retry attempts
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
str
Extracted initial state
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
prompt = (
f"{DOMAIN_DESCRIPTION_BLOCKSWORLD}\n"
f"[Initial State needed to be extracted]{raw_text}\n"
f"{INITIAL_STATE_EXTRACTOR_PROMPT_PLANBENCH}"
)
for attempt in range(max_retries):
response = RequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
# Check if extraction was successful
if not extracted.startswith("Extraction failed"):
return extracted
print(
f"[Warning] Initial state extraction failed (attempt {attempt + 1}/{max_retries}): {extracted}"
)
# All retries failed
print(f"[Error] Initial state extraction failed after {max_retries} attempts")
return extracted
def extract_goal(raw_text: str, max_retries: int = 3, **kwargs) -> str:
"""
Extract goal from raw text.
Parameters
----------
raw_text : str
Raw text containing goal description
max_retries : int
Maximum number of retry attempts
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
str
Extracted goal
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
prompt = (
f"[Raw text that needed to be extracted as goal]{raw_text}\n"
f"{GOAL_EXTRACTOR_PROMPT_PLANBENCH}\n"
)
for attempt in range(max_retries):
response = RequestSender(prompt, **LLM_params)
goal = ContentExtraction(response)
# Check if extraction was successful
if not goal.startswith("Extraction failed"):
return goal
print(
f"[Warning] Goal extraction failed (attempt {attempt + 1}/{max_retries}): {goal}"
)
# All retries failed
print(f"[Error] Goal extraction failed after {max_retries} attempts")
return goal
def check_goal_state(
state: str,
goal: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> bool:
"""
Check if the current state satisfies the goal.
Parameters
----------
state : str
Current state description
goal : str
Goal state description
max_retries : int
Maximum number of retry attempts
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
bool
True if state satisfies goal, False otherwise
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"[Current State]{state}\n"
f"[Goal State]{goal}\n"
f"{STATE_CHECK_PROMPT}\n"
)
for attempt in range(max_retries):
response = RequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
# Check if extraction was successful
if not extracted.startswith("Extraction failed"):
result = extracted.strip().lower()
return result == "true"
print(
f"[Warning] Goal check extraction failed (attempt {attempt + 1}/{max_retries}): {extracted}"
)
# All retries failed
print(f"[Error] Goal check extraction failed after {max_retries} attempts")
return False
def generate_available_actions(
state: str,
max_retries: int = 3,
last_action: str = None,
domain_description: str = None,
**kwargs,
) -> List[str]:
"""
Generate all available actions from the current state.
Parameters
----------
state : str
Current state description
max_retries : int
Maximum number of retry attempts
last_action : str, optional
The last action taken (to avoid generating inverse actions)
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
List[str]
List of available actions
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
# Build prompt with optional last action hint
last_action_str = last_action if last_action else "None"
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"[Current State]{state}\n"
f"[Last executed action]{last_action_str}\n"
f"{GENERATE_AVAILABLE_ACTIONS_PROMPT}\n"
)
for attempt in range(max_retries):
response = RequestSender(prompt, **LLM_params)
# Check if request failed
if not response.startswith("Request Failed"):
# Extract content from \box{...}
extracted = ContentExtraction(response)
# Debug: print raw response and extracted content
# print(f"[DEBUG] Raw LLM response (first 500 chars): {response[:500]}...")
# print(f"[DEBUG] Extracted content: {extracted}")
if extracted.startswith("Extraction failed"):
print(
f"[Warning] Action extraction failed (attempt {attempt + 1}/{max_retries}): {extracted}"
)
continue
# Split actions by period and clean them
actions = []
for action in extracted.split("."):
action = action.strip()
if action: # Only add non-empty actions
actions.append(action)
print(f"[DEBUG] Parsed actions: {actions}")
if not actions:
print(
f"[Warning] No actions parsed from extracted content (attempt {attempt + 1}/{max_retries})"
)
continue
return actions
print(
f"[Warning] Generate actions request failed (attempt {attempt + 1}/{max_retries}): {response}"
)
# All retries failed
print(f"[Error] Generate actions failed after {max_retries} attempts")
return []
def check_action_executability(
state: str,
action: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> bool:
"""
Check if an action is executable in the current state.
Parameters
----------
state : str
Current state description
action : str
Action to check
max_retries : int
Maximum number of retry attempts
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
bool
True if action is executable, False otherwise
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"{BLOCKSWORLD_EXECUTABILITY_EXAMPLE}\n"
f"[Current State]{state}\n"
f"[Action]{action}\n"
f"{EXECUTABILITY_CHECK_PROMPT}\n"
)
for attempt in range(max_retries):
response = RequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
# Check if extraction was successful
if not extracted.startswith("Extraction failed"):
is_executable = _parse_boxed_bool(extracted)
# print(
# f"[DEBUG] Executability check for '{action}': extracted='{extracted}', result={is_executable}"
# )
return is_executable
print(
f"[Warning] Executability check extraction failed (attempt {attempt + 1}/{max_retries}): {extracted}"
)
# print(f"[DEBUG] Raw response: {response[:300]}...")
# All retries failed
print(f"[Error] Executability check failed after {max_retries} attempts")
return False
async def async_check_action_executability(
state: str,
action: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> bool:
"""Async version of check_action_executability for concurrent execution."""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"{BLOCKSWORLD_EXECUTABILITY_EXAMPLE}\n"
f"[Current State]{state}\n"
f"[Action]{action}\n"
f"{EXECUTABILITY_CHECK_PROMPT}\n"
)
for attempt in range(max_retries):
response = await AsyncRequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
if not extracted.startswith("Extraction failed"):
return _parse_boxed_bool(extracted)
print(
f"[Warning] Async executability check failed (attempt {attempt + 1}/{max_retries})"
)
return False
async def async_take_action(
state: str,
action: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> str:
"""Async version of take_action for concurrent execution."""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
from general_prompt import PROGRESSION_EXAMPLE_PROMPT
prompt = (
f"{domain_desc}\n"
f"{PROGRESSION_EXAMPLE_PROMPT}\n"
f"[Current State]{state}\n"
f"[Action]{action}\n"
f"{PROGRESSION_PROMPT}\n"
)
for attempt in range(max_retries):
response = await AsyncRequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
if not extracted.startswith("Extraction failed"):
return extracted
print(
f"[Warning] Async state progression failed (attempt {attempt + 1}/{max_retries})"
)
return state # Return original state if all retries fail
async def async_check_goal_state(
state: str,
goal: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> bool:
"""Async version of check_goal_state for concurrent execution."""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"[Current State]{state}\n"
f"[Goal State]{goal}\n"
f"{STATE_CHECK_PROMPT}\n"
)
for attempt in range(max_retries):
response = await AsyncRequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
if not extracted.startswith("Extraction failed"):
return extracted.strip().lower() == "true"
print(f"[Warning] Async goal check failed (attempt {attempt + 1}/{max_retries})")
return False
def _parse_boxed_bool(extracted: str) -> bool:
"""Parse boxed boolean answers while tolerating light punctuation noise."""
normalized = extracted.strip().lower().strip(" \t\r\n.,;:!?")
return normalized == "true"
async def async_evaluate_state(
state: str,
goal: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> float:
"""Async version of evaluate_state for concurrent execution (used in ToT)."""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"[Current State]{state}\n"
f"[Goal State]{goal}\n"
f"{STATE_SCORE_PROMPT}\n"
)
for attempt in range(max_retries):
response = await AsyncRequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
if not extracted.startswith("Extraction failed"):
try:
score = float(extracted.strip())
return max(0.0, min(10.0, score))
except ValueError:
print(
f"[Warning] Could not parse score '{extracted}' (attempt {attempt + 1}/{max_retries})"
)
continue
print(f"[Warning] Async state evaluation failed (attempt {attempt + 1}/{max_retries})")
raise RuntimeError(
f"asynchronous state evaluation failed after {max_retries} attempts"
)
async def async_generate_available_actions(
state: str,
max_retries: int = 3,
last_action: str = None,
domain_description: str = None,
**kwargs,
) -> List[str]:
"""Async version of generate_available_actions for concurrent execution."""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
last_action_str = last_action if last_action else "None"
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"[Current State]{state}\n"
f"[Last executed action]{last_action_str}\n"
f"{GENERATE_AVAILABLE_ACTIONS_PROMPT}\n"
)
for attempt in range(max_retries):
response = await AsyncRequestSender(prompt, **LLM_params)
if not response.startswith("Request Failed"):
extracted = ContentExtraction(response)
if extracted.startswith("Extraction failed"):
print(
f"[Warning] Async action extraction failed (attempt {attempt + 1}/{max_retries})"
)
continue
actions = [a.strip() for a in extracted.split(".") if a.strip()]
if not actions:
print(
f"[Warning] No actions from async generation (attempt {attempt + 1}/{max_retries})"
)
continue
return actions
print(f"[Warning] Async generate actions failed (attempt {attempt + 1}/{max_retries})")
return []
def take_action(
state: str,
action: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> str:
"""
Execute an action and return the new state.
Parameters
----------
state : str
Current state description
action : str
Action to execute
max_retries : int
Maximum number of retry attempts
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
str
New state after executing the action
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"[Current State]{state}\n"
f"[Action]{action}\n"
f"{PROGRESSION_PROMPT}\n"
)
for attempt in range(max_retries):
response = RequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
# Check if extraction was successful
if not extracted.startswith("Extraction failed"):
return extracted
print(
f"[Warning] State progression extraction failed (attempt {attempt + 1}/{max_retries}): {extracted}"
)
# All retries failed
print(f"[Error] State progression failed after {max_retries} attempts")
return state # Return original state if all retries fail
def evaluate_state(
state: str,
goal: str,
max_retries: int = 3,
domain_description: str = None,
**kwargs,
) -> float:
"""
USED IN TOT.
Evaluate how promising a state is for reaching the goal.
Returns a score between 0 and 10, where higher is better.
Parameters
----------
state : str
Current state description
goal : str
Goal state description
max_retries : int
Maximum number of retry attempts
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
float
Score between 0 and 10 indicating how close the state is to the goal
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_desc = domain_description or DOMAIN_DESCRIPTION_BLOCKSWORLD
prompt = (
f"{domain_desc}\n"
f"[Current State]{state}\n"
f"[Goal State]{goal}\n"
f"{STATE_SCORE_PROMPT}\n"
)
for attempt in range(max_retries):
response = RequestSender(prompt, **LLM_params)
extracted = ContentExtraction(response)
# Check if extraction was successful
if not extracted.startswith("Extraction failed"):
try:
score = float(extracted.strip())
# Ensure score is in valid range
return max(0.0, min(10.0, score))
except ValueError:
print(
f"[Warning] Could not parse score '{extracted}' (attempt {attempt + 1}/{max_retries})"
)
continue
print(
f"[Warning] State evaluation extraction failed (attempt {attempt + 1}/{max_retries}): {extracted}"
)
raise RuntimeError(f"state evaluation failed after {max_retries} attempts")
def tot_search(
initial_state: str,
goal: str,
max_depth: int = 10,
beam_width: int = 3,
thoughts_per_state: int = 5,
max_nodes: int = 300,
save_tree: bool = True,
output_path: str = None,
save_incremental: bool = True,
domain: str = "blocksworld",
**kwargs,
) -> Tuple[Optional[List[str]], Dict[int, Node], int]:
"""
Perform Tree of Thought (ToT) search using beam search strategy.
ToT generates multiple possible next actions (thoughts) for each state,
evaluates them, and keeps only the top-k most promising ones.
Parameters
----------
initial_state : str
Initial state description
goal : str
Goal state description
max_depth : int
Maximum search depth
beam_width : int
Number of best nodes to keep at each depth level (beam search width)
thoughts_per_state : int
Number of candidate actions to generate and evaluate per state
max_nodes : int
Maximum total number of nodes to create
save_tree : bool
Whether to save the search tree to a JSON file
output_path : str, optional
Output file path for the search tree
domain : str
Planning domain name (e.g., "blocksworld", "logistics", "depots")
**kwargs : dict
LLM parameters (model, api_key, base_url)
Returns
-------
Tuple[Optional[List[str]], Dict[int, Node], int]
Tuple of (list of actions to reach goal or None, dictionary of all nodes,
number of nodes actually explored/expanded)
"""
LLM_params = {
"model": kwargs.get("model", "gpt-4o"),
"api_key": kwargs.get("api_key", "null"),
"base_url": kwargs.get("base_url", "null"),
}
domain_description = _get_domain_description(domain)
print(f"[INFO] Using domain: {domain}")
# Initialize the root node
root = Node(
node_id=0,
parent_id=None,
state=initial_state,
query=goal,
g_cost=0.0,
h_cost=0.0,
history_actions=[],
state_score=5.0,
)
# Tracking structures
nodes_dict = {0: root}
next_node_id = 1
current_beam = [root] # Nodes at current depth level
nodes_explored_count = 0 # Count of nodes actually expanded/checked
print(f"Starting Tree of Thought (ToT) search...")
print(f"Initial state: {initial_state}")
print(f"Goal: {goal}")
print(
f"Parameters: max_depth={max_depth}, beam_width={beam_width}, thoughts_per_state={thoughts_per_state}, max_nodes={max_nodes}\n"
)
# Helper function to save tree before returning
def _save_and_return(
result: Optional[List[str]], explored_count: int, found_goal: bool = False
):
if save_tree:
metadata = {
"initial_state": initial_state,
"goal": goal,
"max_depth": max_depth,
"beam_width": beam_width,
"thoughts_per_state": thoughts_per_state,
"max_nodes": max_nodes,
"domain": domain,
"solution_found": found_goal,
"solution": result,
"nodes_explored": explored_count,
"nodes_generated": len(nodes_dict),
}
save_search_tree(
nodes_dict, output_path, search_type="tot", metadata=metadata
)
return result, nodes_dict, explored_count
def _save_incremental():
if save_incremental and save_tree:
metadata = {
"initial_state": initial_state,
"goal": goal,
"max_depth": max_depth,
"beam_width": beam_width,
"thoughts_per_state": thoughts_per_state,
"max_nodes": max_nodes,
"domain": domain,
"solution_found": False,
"solution": None,
"nodes_explored": nodes_explored_count,
"nodes_generated": len(nodes_dict),
}
save_search_tree(
nodes_dict, output_path, search_type="tot", metadata=metadata
)
# Beam search through depth levels
for depth in range(max_depth):
print(f"\n{'=' * 60}")
print(f"[DEPTH {depth}] Processing {len(current_beam)} nodes in beam")
print(f"Total nodes so far: {len(nodes_dict)}/{max_nodes}")
if not current_beam:
print("Beam is empty, search terminated")
break
# --- PHASE 1: Concurrent goal checks for all beam nodes ---
async def _check_goals(nodes):
tasks = [
async_check_goal_state(
node.state, goal, domain_description=domain_description, **LLM_params
)
for node in nodes
]
return await asyncio.gather(*tasks)
goal_results = asyncio.run(_check_goals(current_beam))
nodes_explored_count += len(current_beam)
for node, is_goal in zip(current_beam, goal_results):
if is_goal:
print(f"\n{'=' * 60}")
print("GOAL FOUND!")
print(f"Solution path: {node.history_actions}")
print(f"Number of actions: {len(node.history_actions)}")
print(f"Total nodes created: {len(nodes_dict)}")
print(f"Total nodes explored: {nodes_explored_count}")
node.flag = True
return _save_and_return(
node.history_actions, nodes_explored_count, found_goal=True
)
if len(nodes_dict) >= max_nodes:
print(f"\n[LIMIT REACHED] Maximum total nodes ({max_nodes}) reached")
break
# --- PHASE 2: Concurrent action generation for all beam nodes ---
async def _gen_all(nodes):
tasks = [
async_generate_available_actions(
node.state,
domain_description=domain_description,
**LLM_params,
)
for node in nodes
]
return await asyncio.gather(*tasks)
all_actions_per_node = asyncio.run(_gen_all(current_beam))
for node, actions in zip(current_beam, all_actions_per_node):
print(f"\nNode {node.node_id}: {len(actions)} potential actions generated")
# --- PHASE 3: Concurrent executability checks ---
# Collect (beam_idx, action) candidate pairs, take up to thoughts_per_state*2 per node
candidate_pairs: List[tuple] = []
for beam_idx, (node, actions) in enumerate(zip(current_beam, all_actions_per_node)):
for action in actions[: thoughts_per_state * 2]:
candidate_pairs.append((beam_idx, action))
async def _check_exec_all(pairs):
tasks = [
async_check_action_executability(
current_beam[bi].state,
act,
domain_description=domain_description,
**LLM_params,
)
for bi, act in pairs
]
return await asyncio.gather(*tasks)
exec_results = asyncio.run(_check_exec_all(candidate_pairs))
# Collect executable actions per beam node, limited to thoughts_per_state
executable_per_node: dict = {bi: [] for bi in range(len(current_beam))}
for (bi, action), ok in zip(candidate_pairs, exec_results):
if ok and len(executable_per_node[bi]) < thoughts_per_state:
executable_per_node[bi].append(action)
print(f" ✓ [Node {current_beam[bi].node_id}] {action}")
else:
print(f" ✗ [Node {current_beam[bi].node_id}] {action}")
# --- PHASE 4: Concurrent take_action for all expansion pairs ---
expansion_pairs: List[tuple] = []
for bi in range(len(current_beam)):
for action in executable_per_node[bi]:
if next_node_id + len(expansion_pairs) >= max_nodes:
break
expansion_pairs.append((bi, action))