-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathverl_v0.6.1_modifications.diff
More file actions
4108 lines (4062 loc) · 199 KB
/
Copy pathverl_v0.6.1_modifications.diff
File metadata and controls
4108 lines (4062 loc) · 199 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
diff --git a/verl/interactions/checklist_interaction.py b/verl/interactions/checklist_interaction.py
new file mode 100644
index 00000000..9da2d945
--- /dev/null
+++ b/verl/interactions/checklist_interaction.py
@@ -0,0 +1,289 @@
+# Copyright 2024 Bytedance Ltd. and/or its affiliates
+# Copyright 2023-2024 SGLang Team
+# Copyright 2025 ModelBest Inc. and/or its affiliates
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from collections import defaultdict
+import logging
+import os
+import json
+import asyncio
+from typing import Any, Optional
+from uuid import uuid4
+import random
+
+import httpx
+from verl import DataProto
+from verl.utils.reward_score import checklist_reward
+
+from .base import BaseInteraction
+
+logger = logging.getLogger(__name__)
+logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
+
+
+class ChecklistInteraction(BaseInteraction):
+ """A demo interaction for calculating the reward of gsm8k.
+
+ - `start_interaction`: start a interaction instance for a trajectory.
+ - `generate_response`: generate the response of the assistant.
+ - `calculate_score`: calculate the score of the interaction.
+ - `finalize_interaction`: finalize the interaction instance.
+ """
+
+ def __init__(self, config: dict):
+ super().__init__(config)
+
+ self._sglang_url = config.get("sglang_url", [])
+ self._sglang_model = config.get("sglang_model")
+ self._retry_times = config.get("retry_times")
+ self._semaphore_size = config.get("semaphore_size")
+ self._temperature = config.get("temperature")
+ self._top_p = config.get("top_p")
+ self._max_new_tokens = config.get("max_new_tokens")
+ self._max_tokens = config.get("max_tokens")
+ self._timeout = config.get("timeout", 120.0)
+ self._max_checklist_to_use = config.get("max_checklist_to_use",1)
+
+ self._instance_dict = {}
+
+ # Initialize shared client and semaphore
+ try:
+ self._timeout_value = float(self._timeout)
+ except Exception:
+ self._timeout_value = 120.0
+ try:
+ semaphore_size = int(self._semaphore_size) if self._semaphore_size is not None else 64
+ except Exception:
+ semaphore_size = 64
+ self._semaphore = asyncio.Semaphore(semaphore_size)
+ self._httpx_limits = httpx.Limits(
+ max_connections=semaphore_size,
+ max_keepalive_connections=semaphore_size // 2,
+ )
+ self._client = httpx.AsyncClient(
+ timeout=httpx.Timeout(
+ timeout=self._timeout_value,
+ read=self._timeout_value,
+ write=self._timeout_value,
+ connect=self._timeout_value,
+ ),
+ limits=self._httpx_limits,
+ )
+
+
+ async def start_interaction(
+ self, instance_id: Optional[str] = None, checklist_list: list[list[list[dict[str, Any]]]] = None, **kwargs
+ ) -> str:
+ if instance_id is None:
+ instance_id = str(uuid4())
+ self._instance_dict[instance_id] = {
+ "response": "",
+ "reward": 0.0,
+ "turns": 0,
+ "checklist_list": checklist_list,
+ "num_turns": len(checklist_list[0])
+ }
+ return instance_id
+
+ async def generate_response(
+ self, instance_id: str, messages: list[dict[str, Any]], all_messages: list[dict[str, Any]], **kwargs
+ ) -> tuple[bool, str, float, dict]:
+ checklist_list = kwargs.get("checklist_list")
+ results = []
+ call_success = []
+ for checklist in checklist_list:
+ results.append(asyncio.create_task(self.generate_response_for_single_checklist(instance_id, messages, all_messages, checklist=checklist)))
+ # await asyncio.sleep(0.001)
+ results = await asyncio.gather(*results)
+
+ per_step_results_list = [result[1] for result in results] # (len(checklist_list), step, len(this_turn_checklist)), len(this_turn_checklist) is not the same for each checklist
+ per_step_call_success_list = [result[2] for result in results]
+ should_terminate_sequence_list = [result[0] for result in results]
+
+ if self._instance_dict[instance_id]["turns"]+1 < self._instance_dict[instance_id]["num_turns"]:
+ user_idx = 0
+ for i in range(0, len(all_messages)):
+ item = all_messages[i]
+ if item.get("role") == "user":
+ if user_idx == self._instance_dict[instance_id]["turns"]+1:
+ response = item.get("content")
+ logger.debug(f"Proceeding with the next turn response: {response}")
+ break
+ user_idx += 1
+ assert response != ""
+ should_terminate_sequence = False
+ else:
+ response = ""
+ should_terminate_sequence = True
+
+ # Check if more than half of the should_terminate_sequence_list are True
+ true_count = sum(should_terminate_sequence_list)
+ if true_count > len(should_terminate_sequence_list) / 2:
+ should_terminate_sequence = True
+
+ for x in per_step_call_success_list:
+ for y in x:
+ for z in y:
+ if z==False:
+ logger.warning("reward gen failed, terminate seq")
+ should_terminate_sequence = True
+
+ self._instance_dict[instance_id]["turns"] += 1
+
+ return should_terminate_sequence, response, (per_step_results_list, [self._instance_dict[instance_id]["turns"]-1]*len(per_step_results_list[0]), per_step_call_success_list), {}
+
+ async def generate_response_for_single_checklist(
+ self, instance_id: str, messages: list[dict[str, Any]], all_messages: list[dict[str, Any]], checklist: list[list[dict[str, Any]]], **kwargs
+ ) -> tuple[bool, str, float, dict]:
+
+
+ this_turn_checklist = checklist[self._instance_dict[instance_id]["turns"]]
+ not_required_for_next_turn_list = [not single_step_checklist["required_for_next_turn"] for single_step_checklist in this_turn_checklist]
+ all_step_results_this_turn = []
+
+ args = {
+ "sglang_model": self._sglang_model,
+ "sglang_url": None,
+ "temperature": self._temperature,
+ "top_p": self._top_p,
+ "max_new_tokens": self._max_new_tokens,
+ "max_tokens": self._max_tokens,
+ "retry_times": self._retry_times
+ }
+
+ # find last user message idx
+ last_user_message_idx = -1
+ for i in range(len(messages)-1, -1, -1):
+ if messages[i].role == "user":
+ last_user_message_idx = i
+ break
+ assert last_user_message_idx != -1
+
+
+ step = 0
+ for i in range(last_user_message_idx+1, len(messages)):
+ if messages[i].role == "assistant":
+ this_step_message = [messages[i]]
+ messages_before_this_step = messages[:i]
+ this_step_message_str = checklist_reward.get_messages_str_v2(this_step_message, step)
+ messages_str_before_this_turn = checklist_reward.get_messages_str_v2(messages[:last_user_message_idx])
+ messages_str_before_this_step = checklist_reward.get_messages_str_v2(messages_before_this_step)
+ following_tool_response_str = "No following tool response"
+ this_turn_messages_util_now = messages[last_user_message_idx:i+1]
+ tool_call_failed = False
+ if i + 1 < len(messages) and messages[i + 1].role in ["observation", "tool"]:
+ tool_messages = []
+ j = i + 1
+ while j < len(messages) and messages[j].role in ["observation", "tool"]:
+ # Safely check for error_tool_call in message content
+ try:
+ content = messages[j].content
+ if content and isinstance(content, str):
+ parsed_content = json.loads(content)
+ if isinstance(parsed_content, dict) and "error_tool_call" in parsed_content:
+ tool_call_failed = True
+ except (json.JSONDecodeError, TypeError):
+ # Content is not valid JSON or empty, skip error check
+ pass
+ tool_messages.append(messages[j])
+ this_turn_messages_util_now.append(messages[j])
+ j += 1
+ following_tool_response_str = checklist_reward.get_messages_str_v2(tool_messages)
+ for single_step_checklist in this_turn_checklist:
+ # input_prompt = checklist_reward.get_input_prompt(messages_str_before_this_step, this_step_message_str, following_tool_response_str, single_step_checklist)
+ messages_str_in_this_turn_until_now = checklist_reward.get_messages_str_v2(this_turn_messages_util_now)
+ input_prompt = checklist_reward.get_input_prompt_v2(messages_str_before_this_turn, messages_str_in_this_turn_until_now, single_step_checklist)
+ selected_url = random.choice(self._sglang_url) if isinstance(self._sglang_url, list) and self._sglang_url else self._sglang_url
+ args["sglang_url"] = selected_url
+
+ async def _guarded_eval(prompt: str) -> bool:
+ async with self._semaphore:
+ return await checklist_reward.eval_one_check(self._client, prompt, args)
+ async def _guarded_eval_tool_error() -> bool:
+ return False, True # type: ignore[arg-type]
+ if (single_step_checklist["focus_on"]=="assistant.tool_calls" or single_step_checklist["focus_on"]=="tool.content") and tool_call_failed:
+ all_step_results_this_turn.append(asyncio.create_task(_guarded_eval_tool_error()))
+ else:
+ all_step_results_this_turn.append(asyncio.create_task(_guarded_eval(input_prompt)))
+ # await asyncio.sleep(0.001)
+ step += 1
+
+ org_flat_per_step_results: list[(bool, bool)] = await asyncio.gather(*all_step_results_this_turn) # a list of bool lenght is steps * len(this_turn_checklist), the first len(this_turn_checklist) is for step 0
+
+ assert len(org_flat_per_step_results) == len(this_turn_checklist) * (step), f"len(per_step_results) != len(this_turn_checklist) * step, {len(org_flat_per_step_results)} != {len(this_turn_checklist)} * {step}"
+
+ flat_per_step_results = [x[0] for x in org_flat_per_step_results ]
+ flat_per_step_call_success = [x[1] for x in org_flat_per_step_results ]
+
+
+ per_step_results = [flat_per_step_results[i:i+len(this_turn_checklist)] for i in range(0, len(flat_per_step_results), len(this_turn_checklist))] # (step, len(this_turn_checklist))
+ per_step_call_success = [flat_per_step_call_success[i:i+len(this_turn_checklist)] for i in range(0, len(flat_per_step_call_success), len(this_turn_checklist))] # (step, len(this_turn_checklist))
+
+
+ turn = self._instance_dict[instance_id]["turns"]
+ step = 0
+ start = 0
+ per_step_scores = []
+ this_turn_checklist_mask = [1] * len(this_turn_checklist)
+ for i in range(last_user_message_idx+1, len(messages)):
+ message = messages[i]
+ role = message.role
+ assert role != "user"
+
+ if role == "assistant":
+ # calculate the score of this step
+ # If one checklist is completed, later step can not finish it anymore
+ # also check is all required_for_next_turn checklist are satisfied
+ end = start + len(this_turn_checklist)
+ this_step_results = flat_per_step_results[start:end]
+ not_required_for_next_turn_list = [a or b for a,b in zip(not_required_for_next_turn_list, this_step_results)]
+ weights = [float(single_step_checklist["weight"]) for single_step_checklist in this_turn_checklist]
+ this_step_score = sum([weight * result * mask for weight, result, mask in zip(weights, this_step_results, this_turn_checklist_mask)])
+ this_step_score = round(this_step_score, 8)
+ this_turn_checklist_mask = [bool(int(a*(1-b))) for a,b in zip(this_turn_checklist_mask, this_step_results)]
+
+ per_step_scores.append(this_step_score)
+ start = end
+ step += 1
+
+ # reward = round(sum(per_step_scores), 4)
+
+ if self._instance_dict[instance_id]["turns"]+1 < self._instance_dict[instance_id]["num_turns"]:
+ user_idx = 0
+ for i in range(0, len(all_messages)):
+ item = all_messages[i]
+ if item.get("role") == "user":
+ if user_idx == self._instance_dict[instance_id]["turns"]+1:
+ response = item.get("content")
+ logger.debug(f"Proceeding with the next turn response: {response}")
+ break
+ user_idx += 1
+ assert response != ""
+ should_terminate_sequence = False
+ else:
+ response = ""
+ should_terminate_sequence = True
+
+ if not all(not_required_for_next_turn_list):
+ should_terminate_sequence = True
+
+
+
+
+ return should_terminate_sequence, per_step_results, per_step_call_success
+
+ async def finalize_interaction(self, instance_id: str, **kwargs) -> None:
+ del self._instance_dict[instance_id]
+
diff --git a/verl/tools/base_tool.py b/verl/tools/base_tool.py
index bec813a5..92c3876c 100644
--- a/verl/tools/base_tool.py
+++ b/verl/tools/base_tool.py
@@ -38,7 +38,7 @@ class BaseTool:
self.tool_schema = tool_schema or self.get_openai_tool_schema()
assert self.tool_schema is not None, "Tool schema is not set!"
self.name = self.tool_schema.function.name
- print(json.dumps(self.tool_schema.model_dump(exclude_unset=True, exclude_none=True), indent=2))
+ # print(json.dumps(self.tool_schema.model_dump(exclude_unset=True, exclude_none=True), indent=2))
def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema:
return self.tool_schema
diff --git a/verl/tools/mcp_base_tool.py b/verl/tools/mcp_base_tool.py
index 9e1f7db6..58cf8ab9 100644
--- a/verl/tools/mcp_base_tool.py
+++ b/verl/tools/mcp_base_tool.py
@@ -78,6 +78,7 @@ class MCPBaseTool(BaseTool):
if err_msg:
result = err_msg
metadata["api_request_error"] = err_msg
+ logger.warning(f"err_msg: {err_msg}")
else:
metadata["api_request_error"] = None
return result, metadata
diff --git a/verl/tools/mcp_checklist_tool.py b/verl/tools/mcp_checklist_tool.py
new file mode 100644
index 00000000..cddc2dc0
--- /dev/null
+++ b/verl/tools/mcp_checklist_tool.py
@@ -0,0 +1,740 @@
+# Copyright 2025 Bytedance Ltd. and/or its affiliates
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import asyncio
+import json
+import logging
+import os
+import re
+from typing import Any, Dict, List, Tuple
+import httpx
+from collections import defaultdict
+from mcp.types import ContentBlock, Tool as MCPTool
+import threading
+import pickle
+import hashlib
+import copy
+import random
+
+from verl.tools.mcp_base_tool import MCPBaseTool
+from verl.tools.utils.mcp_clients.McpClientManager import ClientManager
+from .schemas import OpenAIFunctionToolSchema, ToolResponse
+
+logger = logging.getLogger(__name__)
+logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
+
+# Suppress third-party library logging to prevent stack traces from being printed
+# logging.getLogger('mcp').setLevel(logging.CRITICAL)
+# logging.getLogger('httpx').setLevel(logging.CRITICAL)
+# logging.getLogger('httpcore').setLevel(logging.CRITICAL)
+# logging.getLogger('fastmcp').setLevel(logging.CRITICAL)
+
+
+class MCPChecklistTool(MCPBaseTool):
+ # 类级别的数据缓存,键为dataset_path,值为解析后的数据
+ _dataset_cache: Dict[str, Dict[str, Any]] = {}
+ _cache_lock = threading.Lock()
+ # 共享的 HTTP 客户端与并发控制
+ _shared_client: httpx.AsyncClient | None = None
+ _shared_semaphore: asyncio.Semaphore | None = None
+
+ def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema):
+ super().__init__(config, tool_schema)
+ self.return_raw: bool = bool(config.get("return_raw", True))
+
+ self._dataset_path = config.get("dataset_path", None)
+
+ # 从缓存或新建数据
+ cached_data = self._get_or_load_dataset_data(self._dataset_path)
+ self._id_by_tool_call_response = cached_data["id_by_tool_call_response"]
+ self._id_by_candidate_tools = cached_data["id_by_candidate_tools"]
+ self._id_by_candidate_tools_name = cached_data["id_by_candidate_tools_name"]
+ self._tool_by_name = cached_data["tool_by_name"]
+ self._tools = cached_data["tools"]
+
+ self._sglang_url = config.get("sglang_url", [])
+ self._sglang_model = config.get("sglang_model", None)
+ # self._system_instruction = config.get("system_instruction", None) or (
+ # "You are a precise tool executor that learns from examples.\n"
+ # "You will be given:\n"
+ # "- Tool call JSON Schema\n"
+ # "- Few-shot examples showing tool calls and their execution results\n"
+ # "- A new tool call with specific arguments\n"
+ # "\n"
+ # "Your task:\n"
+ # "1) Learn the OUTPUT FORMAT from the provided examples - follow the exact structure, data types, and response patterns\n"
+ # "2) Ensure FACTUAL CONSISTENCY - your output should align with the factual information demonstrated in the examples\n"
+ # "3) For the new tool call:\n"
+ # " - Apply the learned format to the new arguments\n"
+ # " - Maintain factual consistency with example patterns\n"
+ # " - If arguments are similar to examples, adapt the example results appropriately\n"
+ # " - If arguments are significantly different, generate new results following the learned format and factual patterns\n"
+ # " - May need to fix some type or error in the examples\n"
+ # "4) Handle errors gracefully - if arguments are invalid or missing, return error messages in the same format as examples\n"
+ # "\n"
+ # "Critical constraints:\n"
+ # "- Act as a silent function executor - NO explanations, suggestions, or hints\n"
+ # "- NO guidance on how to fix errors or improve calls\n"
+ # "- NO references to examples or comparisons\n"
+ # "- Return ONLY the raw execution result as valid JSON\n"
+ # "- For errors, return minimal error information without instructional content\n"
+ # "\n"
+ # "Output requirements:\n"
+ # "- Return ONLY the execution result as valid JSON\n"
+ # "- No explanations, markdown, or code fences\n"
+ # "- Use correct JSON data types\n"
+ # "- Follow the exact output structure learned from examples\n"
+ # "- Maintain factual consistency with the example patterns\n"
+ # )
+ self._system_instruction = config.get("system_instruction", None) or (
+ "You are a precise tool executor that learns from examples.\n"
+ "You will be given:\n"
+ "- Tool call JSON Schema\n"
+ "- Few-shot examples showing tool calls and their execution results\n"
+ "- A new tool call with specific arguments\n"
+ "\n"
+ "Your task:\n"
+ "1) Learn the OUTPUT FORMAT from the provided examples - follow the exact structure, data types, and response patterns\n"
+ "2) Ensure FACTUAL CONSISTENCY - your output should align with the factual information demonstrated in the examples\n"
+ "3) For the new tool call:\n"
+ " - Apply the learned format to the new arguments\n"
+ " - Maintain factual consistency with example patterns\n"
+ " - If arguments are similar to examples, adapt the example results appropriately\n"
+ " - If arguments are significantly different, generate new results following the learned format and factual patterns\n"
+ " - May need to fix some type or error in the examples\n"
+ "4) Handle errors gracefully - if arguments are invalid or missing, return error messages in the same format as examples\n"
+ "\n"
+ "Critical constraints:\n"
+ "- Act as a silent function executor - NO explanations, suggestions, or hints\n"
+ "- NO guidance on how to fix errors or improve calls\n"
+ "- NO references to examples or comparisons\n"
+ "- Return ONLY the raw execution result as valid JSON\n"
+ "- For errors, return minimal error information without instructional content\n"
+ "\n"
+ "Output requirements:\n"
+ "- First do some analysis on how to mock the execution results. Then return ONLY the execution result as valid JSON array or object\n"
+ "- No explanations, markdown, or code fences\n"
+ "- Follow the exact output structure learned from examples\n"
+ "- Maintain factual consistency with the example patterns\n"
+ "Format:\n"
+ "{\n"
+ " \"analysis\": str,\n"
+ " \"execution_result\": JSON array or object,\n"
+ "}"
+ ""
+ )
+
+ self._temperature = config.get("temperature", 0.6)
+ self._max_new_tokens = config.get("max_new_tokens", 2048)
+ self._json_retry_attempts = config.get("retry_attempts", 1)
+ self._top_p = config.get("top_p", 0.8)
+ self._max_tokens = config.get("max_tokens", 2048)
+ self._timeout = config.get("timeout", 120)
+ try:
+ self._semaphore_size = int(config.get("semaphore_size", 64))
+ except Exception:
+ self._semaphore_size = 64
+
+ # 初始化全局共享 client 和 semaphore(按首次实例的配置创建)
+ try:
+ timeout_value = float(self._timeout)
+ except Exception:
+ timeout_value = 120.0
+ limits = httpx.Limits(
+ max_connections=max(16, self._semaphore_size),
+ max_keepalive_connections=max(8, self._semaphore_size // 2),
+ )
+ if MCPChecklistTool._shared_client is None:
+ MCPChecklistTool._shared_client = httpx.AsyncClient(
+ timeout=httpx.Timeout(timeout=timeout_value, read=timeout_value, write=timeout_value, connect=timeout_value),
+ limits=limits,
+ )
+ if MCPChecklistTool._shared_semaphore is None:
+ MCPChecklistTool._shared_semaphore = asyncio.Semaphore(self._semaphore_size)
+ @classmethod
+ def _get_or_load_dataset_data(cls, dataset_path: str) -> Dict[str, Any]:
+ """获取或加载数据集数据,使用类级别缓存避免重复加载"""
+ if dataset_path is None:
+ raise ValueError("dataset_path cannot be None")
+
+ # 使用线程锁确保线程安全
+ with cls._cache_lock:
+ if dataset_path in cls._dataset_cache:
+ logger.info(f"Using cached dataset data for path: {dataset_path}")
+ return cls._dataset_cache[dataset_path]
+
+ logger.info(f"Loading and caching dataset data for path: {dataset_path}")
+
+ # 可选:尝试从磁盘缓存加载(适合大数据集)
+ disk_cache_data = cls._try_load_disk_cache(dataset_path)
+ if disk_cache_data:
+ logger.info(f"Loaded dataset from disk cache: {dataset_path}")
+ cls._dataset_cache[dataset_path] = disk_cache_data
+ return disk_cache_data
+
+ # 加载数据
+ data = cls._load_dataset_data(dataset_path)
+ cls._dataset_cache[dataset_path] = data
+
+ # 可选:保存到磁盘缓存
+ cls._try_save_disk_cache(dataset_path, data)
+
+ return data
+
+ @staticmethod
+ def _load_dataset_data(dataset_path: str) -> Dict[str, Any]:
+ """加载数据集并构建所需的数据结构"""
+ with open(dataset_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+ id_by_tool_call_response = {}
+ id_by_candidate_tools = {}
+ id_by_candidate_tools_name = {}
+ tool_by_name = {}
+ tools = []
+ all_tools = []
+
+ # 构建tool_call_response映射
+ for item in data:
+ tools = json.loads(item["extra_info"]["tools"])
+ all_tools.extend(tools)
+ tool_call_response_map = MCPChecklistTool._get_called_tools_and_response_static(item)
+ id_by_tool_call_response[str(item["extra_info"]["original_index"])] = tool_call_response_map
+
+ # 构建candidate_tools映射
+ for item in data:
+ tools = json.loads(item["extra_info"]["tools"])
+ id_by_candidate_tools[str(item["extra_info"]["original_index"])] = {tool["function"]["name"]: tool for tool in tools}
+ id_by_candidate_tools_name[str(item["extra_info"]["original_index"])] = [x["function"]["name"] for x in tools]
+
+ # 构建tool映射
+ all_tools_name = set([x["function"]["name"] for x in all_tools])
+ for name in all_tools_name:
+ mcp_tool = MCPTool(name=name, description="", inputSchema={"type": "object", "properties": {}, "required": []})
+ tools.append(mcp_tool)
+ tool_by_name[name] = mcp_tool
+
+ return {
+ "id_by_tool_call_response": id_by_tool_call_response,
+ "id_by_candidate_tools": id_by_candidate_tools,
+ "id_by_candidate_tools_name": id_by_candidate_tools_name,
+ "tool_by_name": tool_by_name,
+ "tools": tools
+ }
+
+ @staticmethod
+ def _get_called_tools_and_response_static(item: Dict[str, Any]) -> List[Any]:
+ """静态版本的get_called_tools_and_response方法,供数据加载使用"""
+ if "extra_info" in item and "messages" in item["extra_info"]:
+ messages = item["extra_info"]["messages"]
+ else:
+ raise ValueError(f"No messages found in item: {item}")
+
+ results = defaultdict(list)
+ if not isinstance(messages, list):
+ raise ValueError(f"Unexpected messages format: {type(messages)}")
+
+ for i in range(len(messages)):
+ message = messages[i]
+ if message.get("role") != "assistant":
+ continue
+
+ tool_calls = message.get("tool_calls") or []
+ if not tool_calls:
+ continue
+
+ # Collect contiguous following tool messages for this assistant turn
+ following_tool_msgs: List[Dict] = []
+
+ for j in range(i+1, i+len(tool_calls)+1):
+ assert messages[j].get("role") == "tool" or messages[j].get("role") == "observation", f"Unexpected role: {messages[j].get('role')}"
+ following_tool_msgs.append(messages[j]["content"])
+
+ for call, content in zip(tool_calls, following_tool_msgs, strict=True):
+ results[call["function"]["name"]].append((json.loads(call["function"]["arguments"]), content))
+ return results
+
+ def get_called_tools_and_response(self, item: Dict[str, Any]) -> List[Any]:
+ """实例方法版本,调用静态方法实现"""
+ return self._get_called_tools_and_response_static(item)
+
+ @staticmethod
+ def _sanitize_text_for_tokenizer(text: Any) -> Any:
+ """Remove invalid Unicode surrogate code points that may break fast tokenizers or downstream consumers.
+
+ This keeps valid non-ASCII characters intact while stripping only the surrogate range U+D800..U+DFFF.
+ Accepts non-str inputs and returns them unchanged for convenience.
+ """
+ if not isinstance(text, str):
+ return text
+ has_surrogate = False
+ sanitized_chars = []
+ for ch in text:
+ code = ord(ch)
+ if 0xD800 <= code <= 0xDFFF:
+ has_surrogate = True
+ continue
+ sanitized_chars.append(ch)
+ if has_surrogate:
+ try:
+ logger.debug("[MCPChecklistTool] Stripped invalid surrogate code points from text.")
+ except Exception:
+ pass
+ return "".join(sanitized_chars)
+
+ def _format_error(self, code: str, message: str, details: Dict[str, Any] | None = None) -> str:
+ """Return a standardized JSON error string."""
+ payload: Dict[str, Any] = {
+ "error_tool_call": {
+ "code": code,
+ "message": message,
+ }
+ }
+ if details is not None:
+ payload["error_tool_call"]["details"] = details
+ # Ensure ASCII for safety with downstream JSON-only consumers
+ return json.dumps(payload, ensure_ascii=True)
+
+ def _validate_parameters_against_schema(self, original_index: str, parameters: Dict[str, Any]) -> tuple[bool, List[str]]:
+ """Lightweight validation of parameters against OpenAI-style tool schema from dataset.
+
+ Checks:
+ - required fields present
+ - basic type conformity for primitive types
+ - optional strict mode to disallow additional properties
+ """
+ errors: List[str] = []
+ tool_schema: Dict[str, Any] = self._id_by_candidate_tools[original_index][self.name]
+
+ fn = tool_schema.get("function", {}) if isinstance(tool_schema, dict) else {}
+ params_schema = fn.get("parameters", {}) if isinstance(fn, dict) else {}
+
+ if not isinstance(parameters, dict):
+ return False, ["parameters must be a JSON object"]
+
+ properties: Dict[str, Any] = params_schema.get("properties", {}) if isinstance(params_schema, dict) else {}
+ required: List[str] = params_schema.get("required", []) if isinstance(params_schema, dict) else []
+ strict: bool = bool(fn.get("strict", True))
+
+ # required fields
+ for key in required:
+ if key not in parameters:
+ errors.append(f"missing required field: {key}")
+
+ # type checks (primitive only)
+ def _matches_type(value: Any, expected: Any) -> bool:
+ if isinstance(expected, list):
+ return any(_matches_type(value, t) for t in expected)
+ if expected == "string":
+ return isinstance(value, str)
+ if expected == "number":
+ return (isinstance(value, (int, float)) and not isinstance(value, bool))
+ if expected == "integer":
+ return (isinstance(value, int) and not isinstance(value, bool))
+ if expected == "boolean":
+ return isinstance(value, bool)
+ if expected == "null":
+ return value is None
+ if expected == "object":
+ return isinstance(value, dict)
+ if expected == "array":
+ return isinstance(value, list)
+ # unknown type keywords are treated as pass
+ return True
+
+ for key, value in parameters.items():
+ if key not in properties:
+ if strict:
+ errors.append(f"unexpected field not allowed: {key}")
+ continue
+ prop = properties.get(key, {})
+ expected_type = prop.get("type")
+ if expected_type is not None and not _matches_type(value, expected_type):
+ errors.append(f"field '{key}' type mismatch: expected {expected_type}")
+ # enum constraint
+ if "enum" in prop:
+ enum_values = prop.get("enum")
+ try:
+ # allow int/float equivalence only if exactly equal (no bool)
+ if isinstance(value, bool):
+ in_enum = value in enum_values
+ else:
+ in_enum = value in enum_values
+ except Exception:
+ in_enum = False
+ if not in_enum:
+ errors.append(f"field '{key}' not in enum: {enum_values}")
+
+ return len(errors) == 0, errors
+
+ @classmethod
+ def clear_cache(cls, dataset_path: str = None):
+ """清理缓存数据"""
+ with cls._cache_lock:
+ if dataset_path is None:
+ # 清理所有缓存
+ cls._dataset_cache.clear()
+ logger.info("Cleared all dataset cache")
+ else:
+ # 清理特定路径的缓存
+ if dataset_path in cls._dataset_cache:
+ del cls._dataset_cache[dataset_path]
+ logger.info(f"Cleared cache for dataset: {dataset_path}")
+
+ @classmethod
+ def get_cache_info(cls) -> Dict[str, int]:
+ """获取缓存信息"""
+ with cls._cache_lock:
+ return {
+ "cached_datasets": len(cls._dataset_cache),
+ "dataset_paths": list(cls._dataset_cache.keys())
+ }
+
+ @staticmethod
+ def _get_disk_cache_path(dataset_path: str) -> str:
+ """生成磁盘缓存文件路径"""
+ cache_dir = os.getenv("MCP_CACHE_DIR", "/tmp/mcp_cache")
+ os.makedirs(cache_dir, exist_ok=True)
+
+ path_hash = hashlib.md5(dataset_path.encode()).hexdigest()
+ return os.path.join(cache_dir, f"dataset_{path_hash}.pkl")
+
+ @staticmethod
+ def _try_load_disk_cache(dataset_path: str) -> Dict[str, Any]:
+ """尝试从磁盘缓存加载数据"""
+ try:
+ cache_path = MCPChecklistTool._get_disk_cache_path(dataset_path)
+ if not os.path.exists(cache_path):
+ return None
+
+ # 检查缓存是否过期
+ cache_mtime = os.path.getmtime(cache_path)
+ dataset_mtime = os.path.getmtime(dataset_path)
+ if cache_mtime < dataset_mtime:
+ logger.info(f"Disk cache expired for {dataset_path}")
+ return None
+
+ with open(cache_path, 'rb') as f:
+ return pickle.load(f)
+ except Exception as e:
+ logger.warning(f"Failed to load disk cache for {dataset_path}: {e}")
+ return None
+
+ @staticmethod
+ def _try_save_disk_cache(dataset_path: str, data: Dict[str, Any]):
+ """尝试保存数据到磁盘缓存"""
+ try:
+ cache_path = MCPChecklistTool._get_disk_cache_path(dataset_path)
+ with open(cache_path, 'wb') as f:
+ pickle.dump(data, f)
+ logger.info(f"Saved dataset to disk cache: {dataset_path}")
+ except Exception as e:
+ logger.warning(f"Failed to save disk cache for {dataset_path}: {e}")
+ def get_candidate_tools(self, item: Dict[str, Any]) -> List[Any]:
+ messages = item["extra_info"]["messages"]
+
+
+ results = defaultdict(list)
+ if not isinstance(messages, list):
+ raise ValueError(f"Unexpected messages format: {type(messages)}")
+
+ for i in range(len(messages)):
+ message = messages[i]
+ if message.get("role") != "assistant":
+ continue
+
+ tool_calls = message.get("tool_calls") or []
+ if not tool_calls:
+ continue
+
+ # Collect contiguous following tool messages for this assistant turn
+ following_tool_msgs: List[Dict] = []
+
+ for j in range(i+1, i+len(tool_calls)+1):
+ assert messages[j].get("role") == "tool" or messages[j].get("role") == "observation", f"Unexpected role: {messages[j].get('role')}"
+ following_tool_msgs.append(messages[j]["content"])
+
+ for call, content in zip(tool_calls, following_tool_msgs, strict=True):
+ results[call["function"]["name"]].append((json.loads(call["function"]["arguments"]), content))
+ return results
+
+ async def execute(self, instance_id: str, parameters: dict[str, Any], original_index: str, **kwargs) -> tuple[ToolResponse, float, dict]:
+ original_index = str(original_index)
+ if original_index not in self._id_by_candidate_tools_name:
+ msg = self._format_error(
+ "INDEX_NOT_FOUND",
+ f"original_index {original_index} not found",
+ {"original_index": original_index},
+ )
+ logger.warning(f"[MCPTool] {msg}")
+ return ToolResponse(text=msg), 0.0, {"success": False}
+ if self.name not in self._id_by_candidate_tools_name[original_index]:
+ msg = self._format_error(
+ "TOOL_NOT_AVAILABLE",
+ f"tool {self.name} not available for original_index {original_index}",
+ {"tool": self.name, "original_index": original_index},
+ )
+ logger.warning(f"[MCPTool] {msg}")
+ return ToolResponse(text=msg), 0.0, {"success": False}
+ if original_index not in self._id_by_tool_call_response:
+ msg = self._format_error(
+ "INDEX_NOT_FOUND",
+ f"original_index {original_index} not found in call responses",
+ {"original_index": original_index},
+ )
+ logger.warning(f"[MCPTool] {msg}")
+ return ToolResponse(text=msg), 0.0, {"success": False}
+
+ if not self.name or parameters is None or not isinstance(parameters, dict):
+ msg = self._format_error(
+ "INVALID_PARAMETERS",
+ "'parameters' is missing, empty, or not a JSON object.",
+ {"tool": self.name, "parameters_type": type(parameters).__name__},
+ )
+ logger.warning(f"[MCPTool] {msg}")
+ return ToolResponse(text=msg), 0.0, {"success": False}
+
+
+ tool_call_response_map = self._id_by_tool_call_response[original_index]
+ def _canonicalize_parameters(parameters: Dict[str, Any]) -> Any:
+ # Keep ensure_ascii=False to preserve matching semantics with dataset; do not sanitize here
+ return json.dumps(parameters, sort_keys=True, ensure_ascii=True, separators=(",", ":"))
+ if self.name in tool_call_response_map:
+ tool_call_response = tool_call_response_map[self.name]
+ # find if arguments can match any of the tool call responses
+ for args, content in tool_call_response:
+ if _canonicalize_parameters(args) == _canonicalize_parameters(parameters):
+ logger.info(f"Found match for tool {self.name} with arguments {parameters}")
+ safe_text = (
+ self._sanitize_text_for_tokenizer(content)
+ if isinstance(content, str)
+ else json.dumps(content, ensure_ascii=True)
+ )
+ return ToolResponse(text=safe_text), 0.0, {"success": True}
+
+ # Validate against schema before any attempt
+ ok, validation_errors = self._validate_parameters_against_schema(original_index, parameters)
+ if not ok:
+ msg = self._format_error(
+ "SCHEMA_VALIDATION_FAILED",
+ "parameters do not conform to the tool schema",
+ {"errors": validation_errors, "tool": self.name, "original_index": original_index},
+ )
+ logger.info(f"[MCPTool] Schema validation failed: {validation_errors}")
+ return ToolResponse(text=msg), 0.0, {"success": True}
+
+
+ # logger.info(f"No match for tool {self.name} with arguments {parameters}, but schema is correct, will call llm to mock the response.")
+ # if valid, call llm to mock the response.
+ # We have valid the tool name is unique, so we can get the schema from the candidate tools.
+ schema_str = json.dumps(self._id_by_candidate_tools[original_index][self.name], ensure_ascii=True, indent=0)
+ schema_str = self._sanitize_text_for_tokenizer(schema_str)
+
+ # Build few-shot examples from this original index across all tool calls
+ examples_lines = ["Previous tool calls and results (few-shot):"]
+ try:
+ for ex_tool_name, pairs in tool_call_response_map.items():
+ for ex_args, ex_content in pairs:
+ # try:
+ ex_args_str = json.dumps(ex_args, ensure_ascii=True, indent=0)
+ ex_args_str = self._sanitize_text_for_tokenizer(ex_args_str)
+ # except Exception:
+ # ex_args_str = str(ex_args)
+ if isinstance(ex_content, (dict, list)):
+ try:
+ ex_content_str = json.dumps(ex_content, ensure_ascii=True, indent=0)
+ ex_content_str = self._sanitize_text_for_tokenizer(ex_content_str)
+ except Exception:
+ raise Exception(f"Error: {ex_content}")
+ else:
+ assert isinstance(ex_content, str), f"Unexpected ex_content type: {type(ex_content)}"
+ ex_content_str = self._sanitize_text_for_tokenizer(ex_content)
+ examples_lines.append(
+ "Tool name:\n" + ex_tool_name + "\n"
+ + "Tool arguments:\n" + ex_args_str + "\n"
+ + "Tool execution result:\n" + ex_content_str +"\n"
+ )
+ except Exception:
+ logger.warning("Failed to build few-shot examples, using <unavailable> instead")
+ examples_lines = ["Previous tool calls and results (few-shot): <unavailable>"]
+
+ user_prompt = (
+ "\n".join(examples_lines)
+ + "\n\n"
+ + "Current tool name: "
+ + self.name
+ + "\n"
+ + "Current tool input schema (JSON Schema):\n"
+ + schema_str
+ + "\n"
+ + "Current arguments (JSON):\n"
+ + self._sanitize_text_for_tokenizer(json.dumps(parameters, ensure_ascii=True, indent=0))
+ + "\n"
+ + "Generate tool execution result in JSON format."
+ )
+ user_prompt = self._sanitize_text_for_tokenizer(user_prompt)
+
+ base_messages = [
+ {"role": "system", "content": self._system_instruction},
+ {"role": "user", "content": user_prompt},
+ ]
+
+ async def _single_attempt(attempt_idx: int) -> tuple[int, str]:
+ payload = {
+ "model": self._sglang_model,
+ "messages": base_messages,
+ "temperature": self._temperature,
+ "max_new_tokens": self._max_new_tokens,
+ "max_tokens": self._max_tokens,
+ "top_p": self._top_p,
+ # "json_schema": {
+ # "type": ["object", "array"] # 允许对象或数组
+ # },
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "tool_execution_response",
+ "schema": {
+ "type": "object",
+ "required": ["analysis", "execution_result"],
+ "additionalProperties": False,
+ "properties": {
+ "analysis": {
+ "type": "string",
+ },
+ "execution_result": {
+ "anyOf": [
+ {
+ "type": "object",
+ "minProperties": 1,
+ "additionalProperties": True
+ },
+ {
+ "type": "array",
+ "items": {}
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+
+ "sampling_params": {
+ "temperature": self._temperature,
+ "max_new_tokens": self._max_new_tokens,
+ "top_p": self._top_p,
+ "max_tokens": self._max_tokens,
+ },
+
+
+ }
+ try:
+ # 确保共享资源已初始化(惰性补充 + 健康检查)
+ try:
+ timeout_value = float(self._timeout)
+ except Exception:
+ timeout_value = 120.0
+ limits = httpx.Limits(
+ max_connections=max(16, self._semaphore_size),
+ max_keepalive_connections=max(8, self._semaphore_size // 2),
+ )
+ client = MCPChecklistTool._shared_client
+ # 如果 client 缺失或已关闭,则重建
+ if client is None or getattr(client, "is_closed", False):
+ if client is not None:
+ try:
+ await client.aclose()
+ except Exception:
+ pass
+ MCPChecklistTool._shared_client = httpx.AsyncClient(
+ timeout=httpx.Timeout(timeout=timeout_value, read=timeout_value, write=timeout_value, connect=timeout_value),
+ limits=limits,
+ )
+ client = MCPChecklistTool._shared_client
+ if MCPChecklistTool._shared_semaphore is None:
+ MCPChecklistTool._shared_semaphore = asyncio.Semaphore(self._semaphore_size)
+
+ selected_url = random.choice(self._sglang_url) if isinstance(self._sglang_url, list) and self._sglang_url else self._sglang_url
+ async with MCPChecklistTool._shared_semaphore:
+ try:
+ resp = await client.post(selected_url, json=payload)
+ except (httpx.ReadError, httpx.HTTPError, httpx.TimeoutException, httpx.ConnectError, httpx.RemoteProtocolError, RuntimeError): # type: ignore[attr-defined]
+ # 出现网络/关闭异常,重建 client 并重试一次