self-evolve-framework 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/package.json +1 -1
  2. package/template/skills/skillopt-sleep/SKILL.md +42 -0
  3. package/template/skills/skillopt-sleep/configs/_base_/default.yaml +103 -0
  4. package/template/skills/skillopt-sleep/configs/alfworld/default.yaml +29 -0
  5. package/template/skills/skillopt-sleep/configs/docvqa/default.yaml +28 -0
  6. package/template/skills/skillopt-sleep/configs/features/soft_gate.yaml +47 -0
  7. package/template/skills/skillopt-sleep/configs/livemathematicianbench/default.yaml +22 -0
  8. package/template/skills/skillopt-sleep/configs/officeqa/default.yaml +34 -0
  9. package/template/skills/skillopt-sleep/configs/searchqa/default.yaml +32 -0
  10. package/template/skills/skillopt-sleep/configs/spreadsheetbench/default.yaml +34 -0
  11. package/template/skills/skillopt-sleep/scripts/framework/skillopt/__init__.py +28 -0
  12. package/template/skills/skillopt-sleep/scripts/framework/skillopt/config.py +282 -0
  13. package/template/skills/skillopt-sleep/scripts/framework/skillopt/datasets/__init__.py +7 -0
  14. package/template/skills/skillopt-sleep/scripts/framework/skillopt/datasets/base.py +512 -0
  15. package/template/skills/skillopt-sleep/scripts/framework/skillopt/engine/__init__.py +9 -0
  16. package/template/skills/skillopt-sleep/scripts/framework/skillopt/engine/trainer.py +2379 -0
  17. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/__init__.py +1 -0
  18. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/README.md +43 -0
  19. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/config_template.yaml +55 -0
  20. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/env_template.py +151 -0
  21. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/_template/loader_template.py +87 -0
  22. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/__init__.py +5 -0
  23. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/adapter.py +428 -0
  24. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/dataloader.py +123 -0
  25. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/analyst_error.md +55 -0
  26. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/analyst_success.md +33 -0
  27. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_no_history.md +8 -0
  28. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_with_history.md +9 -0
  29. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/prompts/rollout_with_memory.md +16 -0
  30. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/reflect.py +4 -0
  31. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/rollout.py +366 -0
  32. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/skills/initial.md +45 -0
  33. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/__init__.py +9 -0
  34. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_envs.py +221 -0
  35. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_projection.py +60 -0
  36. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/alfworld_prompts.py +8 -0
  37. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/config_tw.yaml +145 -0
  38. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/env_base.py +84 -0
  39. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/env_manager.py +139 -0
  40. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/alfworld/vendor/memory.py +87 -0
  41. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/base.py +329 -0
  42. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/__init__.py +1 -0
  43. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/adapter.py +90 -0
  44. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/dataloader.py +61 -0
  45. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/evaluator.py +113 -0
  46. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/analyst_error.md +35 -0
  47. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/analyst_success.md +24 -0
  48. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/prompts/rollout_system.md +12 -0
  49. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/rollout.py +391 -0
  50. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/docvqa/skills/initial.md +11 -0
  51. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/__init__.py +1 -0
  52. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/adapter.py +129 -0
  53. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/dataloader.py +308 -0
  54. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/evaluator.py +62 -0
  55. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/analyst_error.md +37 -0
  56. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/analyst_success.md +25 -0
  57. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/prompts/rollout_system.md +12 -0
  58. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/reflect.py +4 -0
  59. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/rollout.py +434 -0
  60. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/livemathematicianbench/skills/initial.md +16 -0
  61. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/__init__.py +1 -0
  62. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/adapter.py +112 -0
  63. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/dataloader.py +71 -0
  64. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/evaluator.py +46 -0
  65. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/analyst_error.md +37 -0
  66. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/analyst_success.md +25 -0
  67. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/prompts/rollout_system.md +15 -0
  68. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/rollout.py +799 -0
  69. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/skills/initial.md +15 -0
  70. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/officeqa/tool_runtime.py +552 -0
  71. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/__init__.py +1 -0
  72. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/adapter.py +96 -0
  73. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/dataloader.py +42 -0
  74. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/evaluator.py +100 -0
  75. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/analyst_error.md +46 -0
  76. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/analyst_success.md +32 -0
  77. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/prompts/rollout_system.md +13 -0
  78. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/reflect.py +4 -0
  79. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/rollout.py +494 -0
  80. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/searchqa/skills/initial.md +3 -0
  81. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/__init__.py +5 -0
  82. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/adapter.py +159 -0
  83. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/codegen_agent.py +731 -0
  84. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/dataloader.py +37 -0
  85. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/evaluator.py +158 -0
  86. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/executor.py +67 -0
  87. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/analyst_error.md +46 -0
  88. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/analyst_success.md +32 -0
  89. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/codegen_system.md +1 -0
  90. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/critical_rules.md +9 -0
  91. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/prompts/react_system.md +21 -0
  92. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/react_agent.py +395 -0
  93. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/reflect.py +4 -0
  94. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/rollout.py +979 -0
  95. package/template/skills/skillopt-sleep/scripts/framework/skillopt/envs/spreadsheetbench/skills/initial.md +56 -0
  96. package/template/skills/skillopt-sleep/scripts/framework/skillopt/evaluation/__init__.py +13 -0
  97. package/template/skills/skillopt-sleep/scripts/framework/skillopt/evaluation/gate.py +148 -0
  98. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/__init__.py +15 -0
  99. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/aggregate.py +253 -0
  100. package/template/skills/skillopt-sleep/scripts/framework/skillopt/gradient/reflect.py +635 -0
  101. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/__init__.py +514 -0
  102. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/azure_openai.py +915 -0
  103. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/backend_config.py +185 -0
  104. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/claude_backend.py +371 -0
  105. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/codex_backend.py +666 -0
  106. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/codex_harness.py +1057 -0
  107. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/common.py +229 -0
  108. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/minimax_backend.py +277 -0
  109. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/qwen_backend.py +456 -0
  110. package/template/skills/skillopt-sleep/scripts/framework/skillopt/model/router.py +236 -0
  111. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/__init__.py +15 -0
  112. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/appendix.py +156 -0
  113. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/clip.py +109 -0
  114. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/lr_autonomous.py +108 -0
  115. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/meta_skill.py +79 -0
  116. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/rewrite.py +59 -0
  117. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/scheduler.py +127 -0
  118. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/select.py +4 -0
  119. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/skill.py +201 -0
  120. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/skill_aware.py +206 -0
  121. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/slow_update.py +396 -0
  122. package/template/skills/skillopt-sleep/scripts/framework/skillopt/optimizer/update_modes.py +135 -0
  123. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/__init__.py +63 -0
  124. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error.md +41 -0
  125. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error_full_rewrite.md +32 -0
  126. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_error_rewrite.md +44 -0
  127. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success.md +36 -0
  128. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success_full_rewrite.md +30 -0
  129. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/analyst_success_rewrite.md +33 -0
  130. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/lr_autonomous.md +20 -0
  131. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure.md +30 -0
  132. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure_full_rewrite.md +28 -0
  133. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_failure_rewrite.md +26 -0
  134. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final.md +33 -0
  135. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final_full_rewrite.md +28 -0
  136. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_final_rewrite.md +25 -0
  137. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success.md +28 -0
  138. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success_full_rewrite.md +28 -0
  139. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/merge_success_rewrite.md +25 -0
  140. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/meta_skill.md +40 -0
  141. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/ranking.md +20 -0
  142. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/ranking_rewrite.md +15 -0
  143. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/rewrite_skill.md +25 -0
  144. package/template/skills/skillopt-sleep/scripts/framework/skillopt/prompts/slow_update.md +60 -0
  145. package/template/skills/skillopt-sleep/scripts/framework/skillopt/scheduler/__init__.py +8 -0
  146. package/template/skills/skillopt-sleep/scripts/framework/skillopt/types.py +306 -0
  147. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/__init__.py +4 -0
  148. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/json_utils.py +172 -0
  149. package/template/skills/skillopt-sleep/scripts/framework/skillopt/utils/scoring.py +28 -0
@@ -0,0 +1,391 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import time
6
+ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
7
+
8
+ from skillopt.envs.docvqa.evaluator import evaluate
9
+ from skillopt.model import chat_target_messages, get_target_backend, is_target_exec_backend
10
+ from skillopt.model.codex_harness import prepare_workspace, render_skill_md, run_target_exec
11
+ from skillopt.prompts import load_prompt
12
+
13
+
14
+ def _build_system(skill_content: str) -> str:
15
+ if skill_content.strip():
16
+ skill_section = f"## Skill\n{skill_content.strip()}\n\n"
17
+ else:
18
+ skill_section = ""
19
+ return load_prompt("rollout_system", env="docvqa").format(skill_section=skill_section)
20
+
21
+
22
+ def _image_to_data_uri(path: str) -> str:
23
+ import base64
24
+ import mimetypes
25
+
26
+ mime = mimetypes.guess_type(path)[0] or "image/png"
27
+ with open(path, "rb") as f:
28
+ encoded = base64.b64encode(f.read()).decode("ascii")
29
+ return f"data:{mime};base64,{encoded}"
30
+
31
+
32
+ def _build_messages(
33
+ item: dict,
34
+ skill_content: str,
35
+ image_detail: str,
36
+ *,
37
+ diagnostic_mode: bool = False,
38
+ diagnostic_instruction: str = "",
39
+ ) -> tuple[list[dict], str, str]:
40
+ system = _build_system(skill_content)
41
+ user_text = item["question"] + "\n\nReturn the final answer inside <answer>...</answer>."
42
+ if diagnostic_mode and diagnostic_instruction.strip():
43
+ user_text += f"\n\n## Training Readout\n{diagnostic_instruction.strip()}"
44
+ image_url = {"url": _image_to_data_uri(item["image_path"])}
45
+ if image_detail and image_detail != "auto":
46
+ image_url["detail"] = image_detail
47
+ messages = [
48
+ {"role": "system", "content": system},
49
+ {
50
+ "role": "user",
51
+ "content": [
52
+ {"type": "text", "text": user_text},
53
+ {"type": "image_url", "image_url": image_url},
54
+ ],
55
+ },
56
+ ]
57
+ return messages, system, user_text
58
+
59
+
60
+ def _build_codex_skill(skill_content: str) -> str:
61
+ return render_skill_md(
62
+ skill_content,
63
+ description="Dynamic ReflACT skill for solving the current DocVQA document-image question.",
64
+ preamble=(
65
+ "Use this skill when answering the current DocVQA question.\n"
66
+ "Inspect the attached document image carefully and return the final answer inside <answer>...</answer>."
67
+ ),
68
+ )
69
+
70
+
71
+ def _run_codex_once(
72
+ *,
73
+ pred_dir: str,
74
+ item: dict,
75
+ skill_content: str,
76
+ model: str,
77
+ timeout: int,
78
+ image_detail: str,
79
+ diagnostic_mode: bool = False,
80
+ diagnostic_instruction: str = "",
81
+ previous_response: str = "",
82
+ ) -> tuple[str, str, str, str]:
83
+ _ = image_detail
84
+ _messages, _system, user_text = _build_messages(
85
+ item,
86
+ skill_content,
87
+ image_detail,
88
+ diagnostic_mode=diagnostic_mode,
89
+ diagnostic_instruction=diagnostic_instruction,
90
+ )
91
+ task_parts = [user_text]
92
+ image_abs = os.path.abspath(item["image_path"])
93
+ task_parts.append(
94
+ "## Document Image\n"
95
+ "The document image is available in this workspace via `ATTACHMENTS.md`.\n"
96
+ f"Original image path: `{image_abs}`\n"
97
+ "Open or inspect that image before answering; do not answer from memory."
98
+ )
99
+ if previous_response:
100
+ task_parts.append(
101
+ "## Previous Attempt\n"
102
+ f"{previous_response}\n\n"
103
+ "Review the same document image carefully and correct the answer if needed."
104
+ )
105
+ task_text = "\n\n".join(task_parts)
106
+ skill_md = _build_codex_skill(skill_content)
107
+ work_dir = os.path.join(pred_dir, "codex_exec")
108
+ prepare_workspace(
109
+ work_dir=work_dir,
110
+ skill_md=skill_md,
111
+ task_text=task_text,
112
+ images=[item["image_path"]],
113
+ )
114
+ prompt = (
115
+ "Use the `skillopt-target` skill available in this workspace.\n"
116
+ "Read `task.md`, inspect the attached document image, and answer the DocVQA question.\n"
117
+ "Return the final answer inside <answer>...</answer>."
118
+ )
119
+ final_message, raw = run_target_exec(
120
+ work_dir=work_dir,
121
+ prompt=prompt,
122
+ model=model,
123
+ timeout=timeout,
124
+ images=[item["image_path"]],
125
+ )
126
+ return final_message or raw, raw, skill_md, task_text
127
+
128
+
129
+ def process_one(
130
+ item: dict,
131
+ out_root: str,
132
+ skill_content: str,
133
+ *,
134
+ max_turns: int = 1,
135
+ exec_timeout: int = 120,
136
+ image_detail: str = "auto",
137
+ max_completion_tokens: int = 16384,
138
+ diagnostic_mode: bool = False,
139
+ diagnostic_instruction: str = "",
140
+ ) -> dict:
141
+ item_id = str(item["id"])
142
+ result = {
143
+ "id": item_id,
144
+ "question": item["question"],
145
+ "task_type": item.get("subtask") or item.get("task_type") or "docvqa",
146
+ "task_description": item["question"],
147
+ "hard": 0,
148
+ "soft": 0.0,
149
+ "predicted_answer": "",
150
+ "response": "",
151
+ "fail_reason": "",
152
+ "agent_ok": False,
153
+ "n_turns": 0,
154
+ "image_paths": item.get("image_paths", []),
155
+ "gold_answer": item.get("answers", []),
156
+ }
157
+ try:
158
+ response = ""
159
+ system_prompt = ""
160
+ user_text = ""
161
+ conversation: list[dict] = []
162
+ if is_target_exec_backend():
163
+ from skillopt.model import azure_openai as _llm
164
+
165
+ conversation = [
166
+ {
167
+ "role": "user",
168
+ "content": item["question"] + "\n\n" + f"[image] {os.path.basename(item['image_path'])}",
169
+ }
170
+ ]
171
+ for turn in range(max_turns):
172
+ response, _raw, system_prompt, user_text = _run_codex_once(
173
+ pred_dir=os.path.join(out_root, "predictions", item_id),
174
+ item=item,
175
+ skill_content=skill_content,
176
+ model=_llm.TARGET_DEPLOYMENT,
177
+ timeout=exec_timeout,
178
+ image_detail=image_detail,
179
+ diagnostic_mode=diagnostic_mode if turn == 0 else False,
180
+ diagnostic_instruction=diagnostic_instruction if turn == 0 else "",
181
+ previous_response=response if turn > 0 else "",
182
+ )
183
+ conversation.append({"type": "message", "turn": turn + 1, "content": response})
184
+ if "<answer>" in response.lower():
185
+ break
186
+ else:
187
+ messages, system_prompt, user_text = _build_messages(
188
+ item,
189
+ skill_content,
190
+ image_detail,
191
+ diagnostic_mode=diagnostic_mode,
192
+ diagnostic_instruction=diagnostic_instruction,
193
+ )
194
+ conversation = [
195
+ {
196
+ "role": "user",
197
+ "content": user_text + "\n\n" + f"[image] {os.path.basename(item['image_path'])}",
198
+ }
199
+ ]
200
+ for turn in range(max_turns):
201
+ if turn == 0:
202
+ resp_text, _ = chat_target_messages(
203
+ messages=messages,
204
+ max_completion_tokens=max_completion_tokens,
205
+ retries=5,
206
+ stage="rollout",
207
+ timeout=exec_timeout,
208
+ )
209
+ else:
210
+ refinement_messages = [
211
+ messages[0],
212
+ messages[1],
213
+ {"role": "assistant", "content": response},
214
+ {"role": "user", "content": "Review the same image carefully and answer again. Keep the final answer inside <answer>...</answer>."},
215
+ ]
216
+ resp_text, _ = chat_target_messages(
217
+ messages=refinement_messages,
218
+ max_completion_tokens=max_completion_tokens,
219
+ retries=5,
220
+ stage="rollout",
221
+ timeout=exec_timeout,
222
+ )
223
+ response = resp_text
224
+ conversation.append({"type": "message", "turn": turn + 1, "content": resp_text})
225
+ if "<answer>" in resp_text.lower():
226
+ break
227
+
228
+ result["response"] = response
229
+ result["agent_ok"] = True
230
+ result["n_turns"] = len(conversation) - 1
231
+
232
+ pred_dir = os.path.join(out_root, "predictions", item_id)
233
+ os.makedirs(pred_dir, exist_ok=True)
234
+ with open(os.path.join(pred_dir, "target_system_prompt.txt"), "w", encoding="utf-8") as f:
235
+ f.write(system_prompt)
236
+ with open(os.path.join(pred_dir, "target_user_prompt.txt"), "w", encoding="utf-8") as f:
237
+ f.write(user_text)
238
+
239
+ eval_result = evaluate(response, item.get("answers", []))
240
+ result["predicted_answer"] = eval_result["predicted_answer"]
241
+ result["hard"] = int(eval_result["anls"] >= 0.999)
242
+ result["soft"] = eval_result["anls"]
243
+ if result["soft"] <= 0.0:
244
+ result["fail_reason"] = f"predicted '{eval_result['predicted_answer']}' but expected one of {item.get('answers', [])}"
245
+
246
+ eval_detail = (
247
+ "[EVALUATION RESULT]\n"
248
+ f"Question: {item['question']}\n"
249
+ f"Predicted answer: {eval_result['predicted_answer']!r}\n"
250
+ f"Gold answers: {item.get('answers', [])!r}\n"
251
+ f"ANLS: {eval_result['anls']:.4f}"
252
+ )
253
+ conversation.append({"role": "system", "content": eval_detail})
254
+ with open(os.path.join(pred_dir, "conversation.json"), "w", encoding="utf-8") as f:
255
+ json.dump(conversation, f, ensure_ascii=False, indent=2)
256
+ except Exception as e: # noqa: BLE001
257
+ result["fail_reason"] = f"error: {e}"
258
+ return result
259
+
260
+
261
+ def run_batch(
262
+ items: list[dict],
263
+ out_root: str,
264
+ skill_content: str,
265
+ *,
266
+ max_turns: int = 1,
267
+ exec_timeout: int = 120,
268
+ workers: int = 16,
269
+ image_detail: str = "auto",
270
+ max_completion_tokens: int = 16384,
271
+ diagnostic_mode: bool = False,
272
+ diagnostic_instruction: str = "",
273
+ task_timeout: int = 600,
274
+ ) -> list[dict]:
275
+ task_timeout = max(int(task_timeout), int(exec_timeout) + 60)
276
+ results_path = os.path.join(out_root, "results.jsonl")
277
+ os.makedirs(out_root, exist_ok=True)
278
+
279
+ done_ids: set[str] = set()
280
+ existing: list[dict] = []
281
+ if os.path.exists(results_path):
282
+ with open(results_path, encoding="utf-8") as f:
283
+ for line in f:
284
+ try:
285
+ row = json.loads(line)
286
+ except Exception:
287
+ continue
288
+ done_ids.add(str(row["id"]))
289
+ existing.append(row)
290
+
291
+ pending = [item for item in items if str(item["id"]) not in done_ids]
292
+ if not pending:
293
+ return existing
294
+
295
+ def _timeout_result(item: dict) -> dict:
296
+ return {
297
+ "id": str(item["id"]),
298
+ "question": item.get("question", ""),
299
+ "task_type": item.get("subtask") or item.get("task_type") or "docvqa",
300
+ "task_description": item.get("question", ""),
301
+ "hard": 0,
302
+ "soft": 0.0,
303
+ "predicted_answer": "",
304
+ "response": "",
305
+ "fail_reason": f"task-timeout-{task_timeout}s",
306
+ "agent_ok": False,
307
+ "n_turns": 0,
308
+ "image_paths": item.get("image_paths", []),
309
+ "gold_answer": item.get("answers", []),
310
+ "phase": "timeout",
311
+ }
312
+
313
+ def _error_result(item: dict, exc: Exception) -> dict:
314
+ row = _timeout_result(item)
315
+ row["phase"] = "error"
316
+ row["fail_reason"] = f"unexpected: {type(exc).__name__}: {exc}"
317
+ return row
318
+
319
+ started_at: dict[str, float] = {}
320
+
321
+ def _run_one(item: dict) -> dict:
322
+ started_at[str(item["id"])] = time.time()
323
+ return process_one(
324
+ item,
325
+ out_root,
326
+ skill_content,
327
+ max_turns=max_turns,
328
+ exec_timeout=exec_timeout,
329
+ image_detail=image_detail,
330
+ max_completion_tokens=max_completion_tokens,
331
+ diagnostic_mode=diagnostic_mode,
332
+ diagnostic_instruction=diagnostic_instruction,
333
+ )
334
+
335
+ total = len(existing) + len(pending)
336
+ completed = len(existing)
337
+ correct = sum(1 for r in existing if r.get("hard", 0))
338
+ if existing:
339
+ print(f" [rollout] resuming: {completed}/{total} already done", flush=True)
340
+
341
+ results = list(existing)
342
+ with open(results_path, "a", encoding="utf-8") as outf:
343
+ ex = ThreadPoolExecutor(max_workers=workers)
344
+ try:
345
+ futs = {ex.submit(_run_one, item): item for item in pending}
346
+ pending_futs = set(futs)
347
+ while pending_futs:
348
+ done, _ = wait(pending_futs, timeout=5, return_when=FIRST_COMPLETED)
349
+ now = time.time()
350
+ timed_out = [
351
+ fut for fut in pending_futs - done
352
+ if str(futs[fut]["id"]) in started_at
353
+ and now - started_at[str(futs[fut]["id"])] >= task_timeout
354
+ ]
355
+ for fut in done:
356
+ pending_futs.remove(fut)
357
+ item = futs[fut]
358
+ try:
359
+ res = fut.result()
360
+ except Exception as exc: # noqa: BLE001
361
+ res = _error_result(item, exc)
362
+ results.append(res)
363
+ completed += 1
364
+ if res.get("hard", 0):
365
+ correct += 1
366
+ acc = correct / completed if completed else 0
367
+ print(
368
+ f" [rollout] {completed}/{total} "
369
+ f"(acc={acc:.3f}) id={res['id']} "
370
+ f"hard={res.get('hard', '?')}",
371
+ flush=True,
372
+ )
373
+ outf.write(json.dumps(res, ensure_ascii=False) + "\n")
374
+ outf.flush()
375
+ for fut in timed_out:
376
+ pending_futs.remove(fut)
377
+ fut.cancel()
378
+ res = _timeout_result(futs[fut])
379
+ results.append(res)
380
+ completed += 1
381
+ acc = correct / completed if completed else 0
382
+ print(
383
+ f" [rollout] {completed}/{total} "
384
+ f"(acc={acc:.3f}) id={res['id']} TIMEOUT",
385
+ flush=True,
386
+ )
387
+ outf.write(json.dumps(res, ensure_ascii=False) + "\n")
388
+ outf.flush()
389
+ finally:
390
+ ex.shutdown(wait=False, cancel_futures=True)
391
+ return results
@@ -0,0 +1,11 @@
1
+ # DocVQA Skill
2
+
3
+ ## Visual Evidence Discipline
4
+ - Read the document carefully before answering.
5
+ - Prefer the smallest exact text span that answers the question.
6
+ - When several nearby strings look similar, choose the one whose surrounding labels or layout best match the question.
7
+
8
+ ## Exact Answer Discipline
9
+ - Copy names, numbers, and dates exactly from the document whenever possible.
10
+ - Prefer direct extraction over paraphrase.
11
+ - Before finalizing, compare the answer against nearby alternatives and keep the best-supported exact span.
@@ -0,0 +1 @@
1
+ """LiveMathematicianBench environment package for ReflACT."""
@@ -0,0 +1,129 @@
1
+ """LiveMathematicianBench environment adapter for ReflACT."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+
6
+ from skillopt.datasets.base import BatchSpec
7
+ from skillopt.envs.base import EnvAdapter
8
+ from skillopt.envs.livemathematicianbench.dataloader import LiveMathematicianBenchDataLoader
9
+ from skillopt.envs.livemathematicianbench.rollout import run_batch
10
+ from skillopt.model import get_target_backend
11
+
12
+
13
+ class LiveMathematicianBenchAdapter(EnvAdapter):
14
+ """LiveMathematicianBench adapter."""
15
+
16
+ def build_reference_text(self, item: dict) -> str:
17
+ parts: list[str] = []
18
+ theorem = str(item.get("theorem") or "").strip()
19
+ sketch = str(item.get("sketch") or "").strip()
20
+ if theorem:
21
+ parts.append(f"## Reference Theorem\n{theorem}")
22
+ if sketch:
23
+ parts.append(f"## Reference Sketch\n{sketch}")
24
+ return "\n\n".join(parts)
25
+
26
+ def get_reference_metadata(self, item: dict) -> dict:
27
+ fields: list[str] = []
28
+ previews: list[str] = []
29
+ theorem = str(item.get("theorem") or "").strip()
30
+ sketch = str(item.get("sketch") or "").strip()
31
+ if theorem:
32
+ fields.append("theorem")
33
+ previews.append(f"[theorem]\n{theorem[:220]}")
34
+ if sketch:
35
+ fields.append("sketch")
36
+ previews.append(f"[sketch]\n{sketch[:220]}")
37
+ return {
38
+ "fields": fields,
39
+ "preview": "\n\n".join(previews)[:500],
40
+ }
41
+
42
+ def __init__(
43
+ self,
44
+ split_dir: str = "",
45
+ data_path: str = "",
46
+ split_mode: str = "ratio",
47
+ split_ratio: str = "2:1:7",
48
+ split_seed: int = 42,
49
+ split_output_dir: str = "",
50
+ max_turns: int = 1,
51
+ exec_timeout: int = 600,
52
+ workers: int = 64,
53
+ analyst_workers: int = 16,
54
+ failure_only: bool = False,
55
+ minibatch_size: int = 8,
56
+ edit_budget: int = 4,
57
+ seed: int = 42,
58
+ limit: int = 0,
59
+ shuffle_choices: bool = True,
60
+ use_theorem: bool = False,
61
+ use_sketch: bool = False,
62
+ max_completion_tokens: int = 16384,
63
+ ) -> None:
64
+ self.max_turns = max_turns
65
+ self.exec_timeout = exec_timeout
66
+ self.workers = workers
67
+ self.max_completion_tokens = int(max_completion_tokens)
68
+ self.analyst_workers = analyst_workers
69
+ self.failure_only = failure_only
70
+ self.minibatch_size = minibatch_size
71
+ self.edit_budget = edit_budget
72
+ self.use_theorem = use_theorem
73
+ self.use_sketch = use_sketch
74
+ self.dataloader = LiveMathematicianBenchDataLoader(
75
+ split_dir=split_dir,
76
+ data_path=data_path,
77
+ split_mode=split_mode,
78
+ split_ratio=split_ratio,
79
+ split_seed=split_seed,
80
+ split_output_dir=split_output_dir,
81
+ seed=seed,
82
+ limit=limit,
83
+ shuffle_choices=shuffle_choices,
84
+ )
85
+
86
+ def setup(self, cfg: dict) -> None:
87
+ super().setup(cfg)
88
+ self.dataloader.setup(cfg)
89
+
90
+ def get_dataloader(self):
91
+ return self.dataloader
92
+
93
+ def build_env_from_batch(self, batch: BatchSpec, **kwargs):
94
+ return list(batch.payload or [])
95
+
96
+ def build_train_env(self, batch_size: int, seed: int, **kwargs):
97
+ batch = self.dataloader.build_train_batch(batch_size=batch_size, seed=seed, **kwargs)
98
+ return self.build_env_from_batch(batch, **kwargs)
99
+
100
+ def build_eval_env(self, env_num: int, split: str, seed: int, **kwargs):
101
+ batch = self.dataloader.build_eval_batch(env_num=env_num, split=split, seed=seed, **kwargs)
102
+ return self.build_env_from_batch(batch, **kwargs)
103
+
104
+ def rollout(
105
+ self,
106
+ env_manager,
107
+ skill_content: str,
108
+ out_dir: str,
109
+ **kwargs,
110
+ ) -> list[dict]:
111
+ items: list[dict] = env_manager
112
+ return run_batch(
113
+ items=items,
114
+ out_root=out_dir,
115
+ skill_content=skill_content,
116
+ max_turns=self.max_turns,
117
+ exec_timeout=self.exec_timeout,
118
+ workers=self.workers,
119
+ max_completion_tokens=self.max_completion_tokens,
120
+ use_theorem=self.use_theorem,
121
+ use_sketch=self.use_sketch,
122
+ diagnostic_mode=kwargs.get("diagnostic_mode", False),
123
+ diagnostic_instruction=kwargs.get("diagnostic_instruction", ""),
124
+ diagnostic_trace_context_by_id=kwargs.get("diagnostic_trace_context_by_id"),
125
+ task_timeout=self.exec_timeout,
126
+ )
127
+
128
+ def get_task_types(self) -> list[str]:
129
+ return self.dataloader.get_task_types()