synth-ai 0.2.9.dev0__py3-none-any.whl → 0.2.23.dev3__py3-none-any.whl

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 (890) hide show
  1. examples/README.md +1 -0
  2. examples/__init__.py +16 -0
  3. examples/analyze_semantic_words.sh +17 -0
  4. examples/baseline/banking77_baseline.py +243 -0
  5. examples/baseline/banking77_pipeline_baseline.py +294 -0
  6. examples/baseline/crafter_baseline.py +407 -0
  7. examples/baseline/pokemon_red_baseline.py +326 -0
  8. examples/baseline/simple_baseline.py +56 -0
  9. examples/baseline/warming_up_to_rl_baseline.py +239 -0
  10. examples/blog_posts/gepa/README.md +355 -0
  11. examples/blog_posts/gepa/configs/banking77_gepa_local.toml +95 -0
  12. examples/blog_posts/gepa/configs/banking77_gepa_test.toml +80 -0
  13. examples/blog_posts/gepa/configs/banking77_mipro_local.toml +50 -0
  14. examples/blog_posts/gepa/configs/banking77_pipeline_gepa_local.toml +101 -0
  15. examples/blog_posts/gepa/configs/banking77_pipeline_gepa_test.toml +96 -0
  16. examples/blog_posts/gepa/configs/hotpotqa_gepa_local.toml +57 -0
  17. examples/blog_posts/gepa/configs/hotpotqa_gepa_qwen.toml +35 -0
  18. examples/blog_posts/gepa/configs/hotpotqa_mipro_local.toml +51 -0
  19. examples/blog_posts/gepa/configs/hover_gepa_local.toml +57 -0
  20. examples/blog_posts/gepa/configs/hover_gepa_qwen.toml +35 -0
  21. examples/blog_posts/gepa/configs/hover_mipro_local.toml +51 -0
  22. examples/blog_posts/gepa/configs/ifbench_gepa_local.toml +57 -0
  23. examples/blog_posts/gepa/configs/ifbench_gepa_qwen.toml +35 -0
  24. examples/blog_posts/gepa/configs/ifbench_mipro_local.toml +51 -0
  25. examples/blog_posts/gepa/configs/pupa_gepa_local.toml +58 -0
  26. examples/blog_posts/gepa/configs/pupa_mipro_local.toml +52 -0
  27. examples/blog_posts/gepa/deploy_banking77_task_app.sh +54 -0
  28. examples/blog_posts/gepa/gepa_baseline.py +204 -0
  29. examples/blog_posts/gepa/query_prompts_example.py +97 -0
  30. examples/blog_posts/gepa/run_gepa_banking77.sh +112 -0
  31. examples/blog_posts/gepa/run_gepa_banking77_pipeline.sh +163 -0
  32. examples/blog_posts/gepa/task_apps.py +105 -0
  33. examples/blog_posts/gepa/test_gepa_local.sh +67 -0
  34. examples/blog_posts/gepa/verify_banking77_setup.sh +123 -0
  35. examples/blog_posts/mipro/README.md +415 -0
  36. examples/blog_posts/mipro/configs/banking77_mipro_local.toml +91 -0
  37. examples/blog_posts/mipro/configs/banking77_mipro_test.toml +87 -0
  38. examples/blog_posts/mipro/configs/banking77_pipeline_mipro_gemini_flash_lite_local.toml +98 -0
  39. examples/blog_posts/mipro/configs/banking77_pipeline_mipro_gpt41mini_local.toml +96 -0
  40. examples/blog_posts/mipro/configs/banking77_pipeline_mipro_local.toml +94 -0
  41. examples/blog_posts/mipro/configs/banking77_pipeline_mipro_test.toml +170 -0
  42. examples/blog_posts/mipro/deploy_banking77_pipeline_task_app.sh +59 -0
  43. examples/blog_posts/mipro/deploy_banking77_task_app.sh +41 -0
  44. examples/blog_posts/mipro/multi_step.md +79 -0
  45. examples/blog_posts/mipro/run_mipro_banking77.sh +191 -0
  46. examples/blog_posts/mipro/run_mipro_banking77_pipeline.sh +171 -0
  47. examples/blog_posts/mipro/run_mipro_banking77_pipeline_gemini_flash_lite.sh +177 -0
  48. examples/blog_posts/mipro/run_mipro_banking77_pipeline_gpt41mini.sh +173 -0
  49. examples/blog_posts/mipro/verify_banking77_setup.sh +117 -0
  50. examples/blog_posts/pokemon_vl/README.md +98 -0
  51. examples/blog_posts/pokemon_vl/configs/eval_gpt5nano.toml +26 -0
  52. examples/blog_posts/pokemon_vl/configs/eval_qwen3_vl.toml +27 -0
  53. examples/blog_posts/pokemon_vl/configs/eval_rl_final.toml +24 -0
  54. examples/blog_posts/pokemon_vl/configs/filter_high_reward.toml +10 -0
  55. examples/blog_posts/pokemon_vl/configs/train_rl_from_sft.toml +43 -0
  56. examples/blog_posts/pokemon_vl/configs/train_sft_qwen4b_vl.toml +40 -0
  57. examples/blog_posts/pokemon_vl/extract_images.py +239 -0
  58. examples/blog_posts/pokemon_vl/pokemon_vl_baseline.py +326 -0
  59. examples/blog_posts/pokemon_vl/run_eval_extract_images.py +209 -0
  60. examples/blog_posts/pokemon_vl/run_qwen_eval_extract_images.py +212 -0
  61. examples/blog_posts/pokemon_vl/text_box_analysis.md +106 -0
  62. examples/blog_posts/warming_up_to_rl/ARCHITECTURE.md +195 -0
  63. examples/blog_posts/warming_up_to_rl/FINAL_TEST_RESULTS.md +127 -0
  64. examples/blog_posts/warming_up_to_rl/INFERENCE_SUCCESS.md +132 -0
  65. examples/blog_posts/warming_up_to_rl/README.md +158 -0
  66. examples/blog_posts/warming_up_to_rl/SMOKE_TESTING.md +164 -0
  67. examples/blog_posts/warming_up_to_rl/SMOKE_TEST_COMPLETE.md +253 -0
  68. examples/blog_posts/warming_up_to_rl/configs/eval_baseline_qwen32b_10x20.toml +25 -0
  69. examples/blog_posts/warming_up_to_rl/configs/eval_ft_qwen4b.toml +25 -0
  70. examples/blog_posts/warming_up_to_rl/configs/eval_ft_qwen4b_10x20.toml +26 -0
  71. examples/blog_posts/warming_up_to_rl/configs/eval_groq_qwen32b.toml +25 -0
  72. examples/blog_posts/warming_up_to_rl/configs/eval_openai_gpt_oss_120b.toml +29 -0
  73. examples/blog_posts/warming_up_to_rl/configs/filter_high_reward_dataset.toml +10 -0
  74. examples/blog_posts/warming_up_to_rl/configs/smoke_test.toml +75 -0
  75. examples/blog_posts/warming_up_to_rl/configs/train_rl_from_sft.toml +91 -0
  76. examples/blog_posts/warming_up_to_rl/configs/train_sft_qwen4b.toml +40 -0
  77. examples/blog_posts/warming_up_to_rl/warming_up_to_rl_baseline.py +187 -0
  78. examples/crafter_debug_render.py +186 -0
  79. examples/dev/qwen3_32b_qlora_4xh100.toml +45 -0
  80. examples/gepa/banking77_pipeline_gepa.toml +96 -0
  81. examples/gepa/multi_stage_gepa_example.toml +84 -0
  82. examples/gepa/run_gepa_banking77_pipeline.sh +157 -0
  83. examples/multi_step/SFT_README.md +147 -0
  84. examples/multi_step/configs/README_verilog_rl.md +77 -0
  85. examples/multi_step/configs/VERILOG_REWARDS.md +103 -0
  86. examples/multi_step/configs/VERILOG_RL_CHECKLIST.md +196 -0
  87. examples/multi_step/configs/crafter_eval_synth_qwen4b.toml +35 -0
  88. examples/multi_step/configs/crafter_eval_text_only_groq_qwen32b.toml +36 -0
  89. examples/multi_step/configs/crafter_rl_outcome.toml +75 -0
  90. examples/multi_step/configs/crafter_rl_stepwise_hosted_judge.toml +145 -0
  91. examples/multi_step/configs/crafter_rl_stepwise_shaped.toml +84 -0
  92. examples/multi_step/configs/crafter_rl_stepwise_simple.toml +79 -0
  93. examples/multi_step/configs/crafter_rl_stepwise_simple_NEW_FORMAT.toml +105 -0
  94. examples/multi_step/configs/crafter_sft_qwen30b_lora.toml +62 -0
  95. examples/multi_step/configs/crafter_synth_backend.md +40 -0
  96. examples/multi_step/configs/verilog_eval_groq_qwen32b.toml +31 -0
  97. examples/multi_step/configs/verilog_eval_synth_qwen8b.toml +33 -0
  98. examples/multi_step/configs/verilog_rl_lora.toml +147 -0
  99. examples/multi_step/convert_traces_to_sft.py +84 -0
  100. examples/multi_step/crafter_rl_lora.md +70 -0
  101. examples/multi_step/judges/crafter_backend_judge.py +220 -0
  102. examples/multi_step/judges/verilog_backend_judge.py +234 -0
  103. examples/multi_step/readme.md +48 -0
  104. examples/multi_step/run_sft_qwen30b.sh +45 -0
  105. examples/multi_step/sse_metrics_streaming_notes.md +357 -0
  106. examples/multi_step/task_app_config_notes.md +494 -0
  107. examples/multi_step/verilog_rl_lora.md +218 -0
  108. examples/qwen_coder/README.md +102 -0
  109. examples/qwen_coder/_shared.py +113 -0
  110. examples/qwen_coder/configs/coder_lora_30b.toml +60 -0
  111. examples/qwen_coder/configs/coder_lora_4b.toml +61 -0
  112. examples/qwen_coder/configs/coder_lora_small.toml +57 -0
  113. examples/qwen_coder/generate_dataset.py +98 -0
  114. examples/qwen_coder/infer_ft_smoke.py +65 -0
  115. examples/qwen_coder/infer_prod_proxy.py +73 -0
  116. examples/qwen_coder/infer_via_synth.py +87 -0
  117. examples/qwen_coder/scripts/infer_coder.sh +19 -0
  118. examples/qwen_coder/scripts/train_coder_30b.sh +22 -0
  119. examples/qwen_coder/sft_full_17b.py +103 -0
  120. examples/qwen_coder/sft_lora_30b.py +110 -0
  121. examples/qwen_coder/subset_jsonl.py +39 -0
  122. examples/qwen_coder/todos.md +38 -0
  123. examples/qwen_coder/validate_jsonl.py +60 -0
  124. examples/qwen_vl/BUGS_AND_FIXES.md +232 -0
  125. examples/qwen_vl/IMAGE_VALIDATION_COMPLETE.md +271 -0
  126. examples/qwen_vl/IMAGE_VALIDATION_SUMMARY.md +260 -0
  127. examples/qwen_vl/INFERENCE_SFT_TESTS.md +412 -0
  128. examples/qwen_vl/NEXT_STEPS_2B.md +325 -0
  129. examples/qwen_vl/QUICKSTART.md +327 -0
  130. examples/qwen_vl/QUICKSTART_RL_VISION.md +110 -0
  131. examples/qwen_vl/README.md +152 -0
  132. examples/qwen_vl/RL_VISION_COMPLETE.md +475 -0
  133. examples/qwen_vl/RL_VISION_TESTING.md +333 -0
  134. examples/qwen_vl/SDK_VISION_INTEGRATION.md +328 -0
  135. examples/qwen_vl/SETUP_COMPLETE.md +274 -0
  136. examples/qwen_vl/VISION_TESTS_COMPLETE.md +489 -0
  137. examples/qwen_vl/VLM_PIPELINE_COMPLETE.md +242 -0
  138. examples/qwen_vl/__init__.py +2 -0
  139. examples/qwen_vl/collect_data_via_cli.md +415 -0
  140. examples/qwen_vl/collect_vision_traces.py +368 -0
  141. examples/qwen_vl/configs/crafter_rl_vision_qwen3vl4b.toml +110 -0
  142. examples/qwen_vl/configs/crafter_vlm_sft_example.toml +59 -0
  143. examples/qwen_vl/configs/eval_gpt4o_mini_vision.toml +26 -0
  144. examples/qwen_vl/configs/eval_gpt4o_vision_proper.toml +29 -0
  145. examples/qwen_vl/configs/eval_gpt5nano_vision.toml +26 -0
  146. examples/qwen_vl/configs/eval_qwen3vl_vision.toml +26 -0
  147. examples/qwen_vl/configs/filter_qwen3vl_sft.toml +49 -0
  148. examples/qwen_vl/configs/filter_vision_sft.toml +52 -0
  149. examples/qwen_vl/configs/filter_vision_test.toml +8 -0
  150. examples/qwen_vl/configs/sft_qwen3_vl_2b_test.toml +54 -0
  151. examples/qwen_vl/crafter_gpt5nano_agent.py +308 -0
  152. examples/qwen_vl/crafter_qwen_vl_agent.py +300 -0
  153. examples/qwen_vl/run_vision_comparison.sh +61 -0
  154. examples/qwen_vl/run_vision_sft_pipeline.sh +175 -0
  155. examples/qwen_vl/test_image_validation.py +201 -0
  156. examples/qwen_vl/test_sft_vision_data.py +110 -0
  157. examples/rl/README.md +169 -0
  158. examples/rl/configs/eval_base_qwen.toml +17 -0
  159. examples/rl/configs/eval_rl_qwen.toml +13 -0
  160. examples/rl/configs/rl_from_base_qwen.toml +62 -0
  161. examples/rl/configs/rl_from_base_qwen17.toml +80 -0
  162. examples/rl/configs/rl_from_ft_qwen.toml +37 -0
  163. examples/rl/download_dataset.py +80 -0
  164. examples/rl/run_eval.py +436 -0
  165. examples/rl/run_rl_and_save.py +111 -0
  166. examples/rl/task_app/README.md +21 -0
  167. {synth_ai/task/apps → examples/rl/task_app}/math_single_step.py +188 -50
  168. examples/rl/task_app/math_task_app.py +111 -0
  169. examples/run_crafter_demo.sh +10 -0
  170. examples/sdk_prompt_learning_example.py +55 -0
  171. examples/sft/README.md +139 -0
  172. examples/sft/configs/crafter_fft_qwen0p6b.toml +49 -0
  173. examples/sft/configs/crafter_lora_qwen0p6b.toml +49 -0
  174. examples/sft/evaluate.py +117 -0
  175. examples/sft/export_dataset.py +120 -0
  176. examples/sft/generate_traces.py +164 -0
  177. examples/swe/__init__.py +12 -0
  178. examples/swe/task_app/README.md +135 -0
  179. examples/swe/task_app/__init__.py +2 -0
  180. examples/swe/task_app/grpo_swe_mini.py +604 -0
  181. examples/swe/task_app/grpo_swe_mini_task_app.py +124 -0
  182. examples/swe/task_app/hosted/README.md +173 -0
  183. examples/swe/task_app/hosted/__init__.py +5 -0
  184. examples/swe/task_app/hosted/branching.py +143 -0
  185. examples/swe/task_app/hosted/environment_routes.py +1289 -0
  186. examples/swe/task_app/hosted/envs/__init__.py +1 -0
  187. examples/swe/task_app/hosted/envs/crafter/__init__.py +6 -0
  188. examples/swe/task_app/hosted/envs/crafter/app.py +1 -0
  189. examples/swe/task_app/hosted/envs/crafter/environment.py +522 -0
  190. examples/swe/task_app/hosted/envs/crafter/policy.py +478 -0
  191. examples/swe/task_app/hosted/envs/crafter/react_agent.py +108 -0
  192. examples/swe/task_app/hosted/envs/crafter/shared.py +305 -0
  193. examples/swe/task_app/hosted/envs/crafter/tools.py +47 -0
  194. examples/swe/task_app/hosted/envs/mini_swe/__init__.py +8 -0
  195. examples/swe/task_app/hosted/envs/mini_swe/environment.py +1191 -0
  196. examples/swe/task_app/hosted/envs/mini_swe/policy.py +355 -0
  197. examples/swe/task_app/hosted/envs/mini_swe/shared.py +83 -0
  198. examples/swe/task_app/hosted/envs/mini_swe/tools.py +96 -0
  199. examples/swe/task_app/hosted/hosted_app.py +204 -0
  200. examples/swe/task_app/hosted/inference/__init__.py +5 -0
  201. examples/swe/task_app/hosted/inference/openai_client.py +584 -0
  202. examples/swe/task_app/hosted/main.py +100 -0
  203. examples/swe/task_app/hosted/policy_routes.py +1094 -0
  204. examples/swe/task_app/hosted/registry.py +195 -0
  205. examples/swe/task_app/hosted/rollout.py +1905 -0
  206. examples/swe/task_app/hosted/storage/__init__.py +5 -0
  207. examples/swe/task_app/hosted/storage/volume.py +211 -0
  208. examples/swe/task_app/hosted/test_agents.py +161 -0
  209. examples/swe/task_app/hosted/test_service.py +136 -0
  210. examples/swe/task_app/hosted/utils.py +62 -0
  211. examples/swe/task_app/morph_backend.py +178 -0
  212. examples/task_apps/IMAGE_ONLY_EVAL_QUICKSTART.md +258 -0
  213. examples/task_apps/TESTING.md +275 -0
  214. examples/task_apps/banking77/__init__.py +6 -0
  215. examples/task_apps/banking77/banking77_task_app.py +912 -0
  216. examples/task_apps/banking77/deploy_wrapper.py +46 -0
  217. examples/task_apps/banking77_pipeline/__init__.py +6 -0
  218. examples/task_apps/banking77_pipeline/banking77_pipeline_task_app.py +489 -0
  219. examples/task_apps/banking77_pipeline/deploy_wrapper.py +50 -0
  220. examples/task_apps/crafter/CREATE_SFT_DATASET.md +286 -0
  221. examples/task_apps/crafter/EVAL_IMAGE_ONLY_RESULTS.md +152 -0
  222. examples/task_apps/crafter/FILTER_COMMAND_STATUS.md +187 -0
  223. examples/task_apps/crafter/FILTER_COMMAND_SUCCESS.md +281 -0
  224. examples/task_apps/crafter/QUERY_EXAMPLES.md +203 -0
  225. examples/task_apps/crafter/README_IMAGE_ONLY_EVAL.md +316 -0
  226. examples/task_apps/crafter/eval_image_only_gpt4o.toml +28 -0
  227. examples/task_apps/crafter/eval_text_only_groq_llama.toml +36 -0
  228. examples/task_apps/crafter/filter_sft_dataset.toml +16 -0
  229. examples/task_apps/crafter/task_app/README.md +42 -0
  230. examples/task_apps/crafter/task_app/__init__.py +5 -0
  231. examples/task_apps/crafter/task_app/grpo_crafter.py +1055 -0
  232. examples/task_apps/crafter/task_app/grpo_crafter_task_app.py +146 -0
  233. examples/task_apps/crafter/task_app/synth_envs_hosted/README.md +173 -0
  234. examples/task_apps/crafter/task_app/synth_envs_hosted/__init__.py +5 -0
  235. examples/task_apps/crafter/task_app/synth_envs_hosted/branching.py +143 -0
  236. examples/task_apps/crafter/task_app/synth_envs_hosted/environment_routes.py +1226 -0
  237. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/__init__.py +1 -0
  238. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/__init__.py +6 -0
  239. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/app.py +1 -0
  240. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/environment.py +532 -0
  241. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/policy.py +583 -0
  242. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/react_agent.py +122 -0
  243. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/shared.py +305 -0
  244. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/tools.py +47 -0
  245. examples/task_apps/crafter/task_app/synth_envs_hosted/hosted_app.py +253 -0
  246. examples/task_apps/crafter/task_app/synth_envs_hosted/inference/__init__.py +5 -0
  247. examples/task_apps/crafter/task_app/synth_envs_hosted/inference/openai_client.py +999 -0
  248. examples/task_apps/crafter/task_app/synth_envs_hosted/main.py +100 -0
  249. examples/task_apps/crafter/task_app/synth_envs_hosted/policy_routes.py +1252 -0
  250. examples/task_apps/crafter/task_app/synth_envs_hosted/registry.py +195 -0
  251. examples/task_apps/crafter/task_app/synth_envs_hosted/rollout.py +2233 -0
  252. examples/task_apps/crafter/task_app/synth_envs_hosted/storage/__init__.py +5 -0
  253. examples/task_apps/crafter/task_app/synth_envs_hosted/storage/volume.py +211 -0
  254. examples/task_apps/crafter/task_app/synth_envs_hosted/test_agents.py +161 -0
  255. examples/task_apps/crafter/task_app/synth_envs_hosted/test_service.py +136 -0
  256. examples/task_apps/crafter/task_app/synth_envs_hosted/utils.py +411 -0
  257. examples/task_apps/dev/pokemon_emerald/__init__.py +2 -0
  258. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/README.md +811 -0
  259. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/__init__.py +120 -0
  260. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/action.py +160 -0
  261. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/memory.py +155 -0
  262. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/perception.py +69 -0
  263. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/planning.py +96 -0
  264. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/simple.py +1502 -0
  265. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/system_prompt.py +4 -0
  266. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/grab_map.py +68 -0
  267. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/manual.py +216 -0
  268. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/__init__.py +35 -0
  269. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/emerald_utils.py +631 -0
  270. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/emulator.py +1544 -0
  271. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/enums.py +1428 -0
  272. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/memory_reader.py +4848 -0
  273. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/types.py +41 -0
  274. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/utils.py +298 -0
  275. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pyproject.toml +95 -0
  276. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/run.py +204 -0
  277. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server/app.py +2152 -0
  278. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server/client.py +429 -0
  279. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server/frame_server.py +155 -0
  280. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/README.md +78 -0
  281. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/run_tests.py +122 -0
  282. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_agent_direct.py +76 -0
  283. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_agent_prompts.py +413 -0
  284. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_battle_state_formatting.py +204 -0
  285. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_dialogue_detection.py +133 -0
  286. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_dialogue_detection_comprehensive.py +229 -0
  287. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_direct_agent_emulator.py +300 -0
  288. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_fps_adjustment_pytest.py +205 -0
  289. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_house_to_outside_direct.py +200 -0
  290. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_house_to_outside_transition.py +284 -0
  291. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_map_ground_truth_comparison.py +468 -0
  292. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_memory_map.py +575 -0
  293. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_server_map_validation.py +311 -0
  294. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_torchic_state.py +259 -0
  295. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/anticheat.py +372 -0
  296. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/checkpoint.py +296 -0
  297. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/error_handler.py +275 -0
  298. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/get_local_ip.py +22 -0
  299. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/helpers.py +44 -0
  300. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/llm_logger.py +514 -0
  301. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_formatter.py +415 -0
  302. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_stitcher.py +1763 -0
  303. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_stitcher_singleton.py +33 -0
  304. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_trimmer.py +106 -0
  305. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_visualizer.py +334 -0
  306. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/ocr_dialogue.py +1020 -0
  307. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/recording.py +188 -0
  308. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/state_formatter.py +1481 -0
  309. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/vlm.py +862 -0
  310. examples/task_apps/dev/pokemon_emerald/modal_app.py +114 -0
  311. examples/task_apps/dev/pokemon_emerald/task_app/README.md +81 -0
  312. examples/task_apps/dev/pokemon_emerald/task_app/__init__.py +6 -0
  313. examples/task_apps/dev/pokemon_emerald/task_app/pokemon_emerald.py +685 -0
  314. examples/task_apps/enron/__init__.py +2 -0
  315. examples/task_apps/enron/eval_groq_qwen32.toml +16 -0
  316. examples/task_apps/enron/filter_sft.toml +5 -0
  317. examples/task_apps/enron/task_app/README.md +14 -0
  318. examples/task_apps/enron/task_app/__init__.py +1 -0
  319. examples/task_apps/enron/task_app/grpo_enron.py +906 -0
  320. examples/task_apps/enron/task_app/grpo_enron_task_app.py +146 -0
  321. examples/task_apps/enron/tests/__init__.py +4 -0
  322. examples/task_apps/enron/tests/conftest.py +115 -0
  323. examples/task_apps/enron/tests/integration/__init__.py +4 -0
  324. examples/task_apps/enron/tests/integration/test_enron_eval.py +179 -0
  325. examples/task_apps/enron/tests/integration/test_enron_rollout.py +135 -0
  326. examples/task_apps/enron/tests/unit/__init__.py +4 -0
  327. examples/task_apps/enron/tests/unit/test_enron_environment.py +126 -0
  328. examples/task_apps/gepa_benchmarks/__init__.py +7 -0
  329. examples/task_apps/gepa_benchmarks/common.py +260 -0
  330. examples/task_apps/gepa_benchmarks/hotpotqa_task_app.py +507 -0
  331. examples/task_apps/gepa_benchmarks/hover_task_app.py +436 -0
  332. examples/task_apps/gepa_benchmarks/ifbench_task_app.py +563 -0
  333. examples/task_apps/gepa_benchmarks/pupa_task_app.py +460 -0
  334. examples/task_apps/math/README.md +21 -0
  335. examples/task_apps/math/math_single_step.py +1000 -0
  336. examples/task_apps/math/math_task_app.py +115 -0
  337. examples/task_apps/pokemon_battle/__init__.py +2 -0
  338. examples/task_apps/pokemon_battle/modal_app.py +104 -0
  339. examples/task_apps/pokemon_battle/task_app/README.md +68 -0
  340. examples/task_apps/pokemon_battle/task_app/__init__.py +6 -0
  341. examples/task_apps/pokemon_battle/task_app/pokemon_showdown.py +932 -0
  342. examples/task_apps/pokemon_red/EVAL_IMAGE_ONLY_COMPLETE.md +283 -0
  343. examples/task_apps/pokemon_red/EVAL_IMAGE_ONLY_STATUS.md +155 -0
  344. examples/task_apps/pokemon_red/README.md +356 -0
  345. examples/task_apps/pokemon_red/README_IMAGE_ONLY_EVAL.md +428 -0
  346. examples/task_apps/pokemon_red/__init__.py +3 -0
  347. examples/task_apps/pokemon_red/eval_image_only_gpt4o.toml +30 -0
  348. examples/task_apps/pokemon_red/eval_pokemon_red_policy.py +224 -0
  349. examples/task_apps/pokemon_red/pallet_town_rl_config.toml +75 -0
  350. examples/task_apps/pokemon_red/task_app.py +1048 -0
  351. examples/task_apps/pokemon_red/test_pallet_town_rewards.py +193 -0
  352. examples/task_apps/sokoban/README.md +306 -0
  353. examples/task_apps/sokoban/__init__.py +3 -0
  354. examples/task_apps/sokoban/eval_groq_qwen32.toml +16 -0
  355. examples/task_apps/sokoban/eval_openai_gpt5.toml +16 -0
  356. examples/task_apps/sokoban/filter_sft.toml +5 -0
  357. examples/task_apps/sokoban/task_app.py +1058 -0
  358. examples/task_apps/sokoban/tests/__init__.py +4 -0
  359. examples/task_apps/sokoban/tests/conftest.py +113 -0
  360. examples/task_apps/sokoban/tests/integration/__init__.py +4 -0
  361. examples/task_apps/sokoban/tests/integration/test_sokoban_eval.py +57 -0
  362. examples/task_apps/sokoban/tests/integration/test_sokoban_rollout.py +198 -0
  363. examples/task_apps/sokoban/tests/unit/__init__.py +4 -0
  364. examples/task_apps/sokoban/tests/unit/test_sokoban_environment.py +114 -0
  365. examples/task_apps/verilog/__init__.py +1 -0
  366. examples/task_apps/verilog/eval_groq_qwen32b.toml +22 -0
  367. examples/task_apps/verilog/filter_sft.toml +5 -0
  368. examples/task_apps/verilog/task_app/README.md +12 -0
  369. examples/task_apps/verilog/task_app/__init__.py +1 -0
  370. examples/task_apps/verilog/task_app/grpo_verilog.py +1166 -0
  371. examples/task_apps/verilog/task_app/grpo_verilog_task_app.py +145 -0
  372. examples/task_apps/verilog/tests/__init__.py +4 -0
  373. examples/task_apps/verilog/tests/conftest.py +115 -0
  374. examples/task_apps/verilog/tests/integration/__init__.py +4 -0
  375. examples/task_apps/verilog/tests/integration/test_verilog_eval.py +181 -0
  376. examples/task_apps/verilog/tests/integration/test_verilog_rollout.py +55 -0
  377. examples/task_apps/verilog/tests/unit/__init__.py +4 -0
  378. examples/task_apps/verilog/tests/unit/test_verilog_scoring.py +118 -0
  379. examples/tunnel_gepa_banking77/README.md +106 -0
  380. examples/tunnel_gepa_banking77/banking77_gepa_tunnel.toml +95 -0
  381. examples/tunnel_gepa_banking77/keep_tunnel_running.py +60 -0
  382. examples/tunnel_gepa_banking77/run_gepa_with_tunnel.sh +226 -0
  383. examples/vlm/PROPOSAL.md +53 -0
  384. examples/vlm/README.md +68 -0
  385. examples/vlm/configs/crafter_vlm_gpt4o.toml +49 -0
  386. examples/vlm/crafter_image_only_agent.py +207 -0
  387. examples/vlm/crafter_openai_vlm_agent.py +275 -0
  388. examples/vlm/filter_image_rows.py +63 -0
  389. examples/vlm/run_crafter_vlm_benchmark.py +316 -0
  390. examples/warming_up_to_rl/_utils.py +92 -0
  391. examples/warming_up_to_rl/analyze_trace_db.py +422 -0
  392. examples/warming_up_to_rl/configs/crafter_fft.toml +53 -0
  393. examples/warming_up_to_rl/configs/crafter_fft_4b.toml +54 -0
  394. examples/warming_up_to_rl/configs/eval_fft_qwen4b.toml +22 -0
  395. examples/warming_up_to_rl/configs/eval_groq_qwen32b.toml +15 -0
  396. examples/warming_up_to_rl/configs/eval_modal_qwen4b.toml +24 -0
  397. examples/warming_up_to_rl/configs/eval_stepwise_complex.toml +35 -0
  398. examples/warming_up_to_rl/configs/eval_stepwise_consistent.toml +26 -0
  399. examples/warming_up_to_rl/configs/eval_stepwise_per_achievement.toml +36 -0
  400. examples/warming_up_to_rl/configs/eval_stepwise_simple.toml +32 -0
  401. examples/warming_up_to_rl/configs/rl_from_base_qwen4b.toml +85 -0
  402. examples/warming_up_to_rl/configs/rl_from_ft.toml +58 -0
  403. examples/warming_up_to_rl/export_trace_sft.py +837 -0
  404. examples/warming_up_to_rl/groq_test.py +97 -0
  405. examples/warming_up_to_rl/manage_secrets.py +131 -0
  406. examples/warming_up_to_rl/old/event_rewards.md +234 -0
  407. examples/warming_up_to_rl/old/notes.md +73 -0
  408. examples/warming_up_to_rl/readme.md +110 -0
  409. examples/warming_up_to_rl/run_eval.py +736 -0
  410. examples/warming_up_to_rl/run_fft_and_save.py +380 -0
  411. examples/warming_up_to_rl/run_local_rollout.py +239 -0
  412. examples/warming_up_to_rl/run_local_rollout_modal.py +248 -0
  413. examples/warming_up_to_rl/run_local_rollout_parallel.py +405 -0
  414. examples/warming_up_to_rl/run_local_rollout_traced.py +477 -0
  415. examples/warming_up_to_rl/run_rl_and_save.py +124 -0
  416. examples/warming_up_to_rl/run_rollout_remote.py +156 -0
  417. examples/warming_up_to_rl/task_app/README.md +42 -0
  418. examples/warming_up_to_rl/task_app/grpo_crafter.py +876 -0
  419. examples/warming_up_to_rl/task_app/grpo_crafter_task_app.py +135 -0
  420. examples/warming_up_to_rl/task_app/synth_envs_hosted/README.md +173 -0
  421. examples/warming_up_to_rl/task_app/synth_envs_hosted/__init__.py +5 -0
  422. examples/warming_up_to_rl/task_app/synth_envs_hosted/branching.py +143 -0
  423. examples/warming_up_to_rl/task_app/synth_envs_hosted/environment_routes.py +1226 -0
  424. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/__init__.py +1 -0
  425. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/__init__.py +6 -0
  426. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/app.py +1 -0
  427. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/environment.py +522 -0
  428. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/policy.py +454 -0
  429. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/react_agent.py +108 -0
  430. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/shared.py +305 -0
  431. examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/tools.py +47 -0
  432. examples/warming_up_to_rl/task_app/synth_envs_hosted/hosted_app.py +253 -0
  433. examples/warming_up_to_rl/task_app/synth_envs_hosted/inference/__init__.py +5 -0
  434. examples/warming_up_to_rl/task_app/synth_envs_hosted/inference/openai_client.py +729 -0
  435. examples/warming_up_to_rl/task_app/synth_envs_hosted/main.py +100 -0
  436. examples/warming_up_to_rl/task_app/synth_envs_hosted/policy_routes.py +1114 -0
  437. examples/warming_up_to_rl/task_app/synth_envs_hosted/registry.py +195 -0
  438. examples/warming_up_to_rl/task_app/synth_envs_hosted/rollout.py +1891 -0
  439. examples/warming_up_to_rl/task_app/synth_envs_hosted/storage/__init__.py +5 -0
  440. examples/warming_up_to_rl/task_app/synth_envs_hosted/storage/volume.py +211 -0
  441. examples/warming_up_to_rl/task_app/synth_envs_hosted/test_agents.py +161 -0
  442. examples/warming_up_to_rl/task_app/synth_envs_hosted/test_service.py +137 -0
  443. examples/warming_up_to_rl/task_app/synth_envs_hosted/utils.py +129 -0
  444. examples/workflows/math_rl/configs/eval_base_qwen.toml +15 -0
  445. examples/workflows/math_rl/configs/eval_rl_qwen.toml +11 -0
  446. examples/workflows/math_rl/configs/rl_from_base_qwen.toml +62 -0
  447. examples/workflows/math_rl/configs/rl_from_base_qwen17.toml +80 -0
  448. examples/workflows/math_rl/configs/rl_from_ft_qwen.toml +35 -0
  449. examples/workflows/math_rl/download_dataset.py +80 -0
  450. examples/workflows/math_rl/run_eval.py +436 -0
  451. examples/workflows/math_rl/run_rl_and_save.py +111 -0
  452. synth_ai/__init__.py +47 -23
  453. synth_ai/_utils/__init__.py +47 -0
  454. synth_ai/_utils/base_url.py +10 -0
  455. synth_ai/_utils/http.py +10 -0
  456. synth_ai/_utils/prompts.py +10 -0
  457. synth_ai/_utils/task_app_state.py +12 -0
  458. synth_ai/_utils/user_config.py +10 -0
  459. synth_ai/api/models/supported.py +514 -0
  460. synth_ai/api/train/__init__.py +60 -2
  461. synth_ai/api/train/builders.py +347 -39
  462. synth_ai/api/train/cli.py +895 -160
  463. synth_ai/api/train/config_finder.py +103 -25
  464. synth_ai/api/train/configs/__init__.py +65 -0
  465. synth_ai/api/train/configs/prompt_learning.py +496 -0
  466. synth_ai/api/train/configs/rl.py +188 -0
  467. synth_ai/api/train/configs/sft.py +99 -0
  468. synth_ai/api/train/configs/shared.py +81 -0
  469. synth_ai/api/train/env_resolver.py +70 -20
  470. synth_ai/api/train/pollers.py +29 -4
  471. synth_ai/api/train/prompt_learning.py +425 -0
  472. synth_ai/api/train/sft.py +390 -0
  473. synth_ai/api/train/supported_algos.py +147 -0
  474. synth_ai/api/train/task_app.py +6 -4
  475. synth_ai/api/train/utils.py +64 -52
  476. synth_ai/api/train/validators.py +1117 -0
  477. synth_ai/api/tunnel.py +49 -0
  478. synth_ai/auth/credentials.py +94 -0
  479. synth_ai/baseline/__init__.py +25 -0
  480. synth_ai/baseline/config.py +209 -0
  481. synth_ai/baseline/discovery.py +214 -0
  482. synth_ai/baseline/execution.py +146 -0
  483. synth_ai/cfgs.py +227 -0
  484. synth_ai/cli/__init__.py +85 -63
  485. synth_ai/cli/_modal_wrapper.py +31 -0
  486. synth_ai/cli/_storage.py +20 -0
  487. synth_ai/cli/_typer_patch.py +47 -0
  488. synth_ai/cli/_validate_task_app.py +29 -0
  489. synth_ai/cli/balance.py +16 -4
  490. synth_ai/cli/calc.py +36 -21
  491. synth_ai/cli/claude.py +70 -0
  492. synth_ai/cli/codex.py +267 -0
  493. synth_ai/cli/commands/__init__.py +18 -0
  494. synth_ai/cli/commands/baseline/__init__.py +12 -0
  495. synth_ai/cli/commands/baseline/core.py +637 -0
  496. synth_ai/cli/commands/baseline/list.py +93 -0
  497. synth_ai/cli/commands/demo/__init__.py +6 -0
  498. synth_ai/cli/commands/demo/core.py +163 -0
  499. synth_ai/cli/commands/eval/__init__.py +19 -0
  500. synth_ai/cli/commands/eval/core.py +1112 -0
  501. synth_ai/cli/commands/eval/errors.py +81 -0
  502. synth_ai/cli/commands/eval/validation.py +133 -0
  503. synth_ai/cli/commands/filter/__init__.py +12 -0
  504. synth_ai/cli/commands/filter/core.py +424 -0
  505. synth_ai/cli/commands/filter/errors.py +55 -0
  506. synth_ai/cli/commands/filter/validation.py +77 -0
  507. synth_ai/cli/commands/help/__init__.py +185 -0
  508. synth_ai/cli/commands/help/core.py +72 -0
  509. synth_ai/cli/commands/smoke/__init__.py +7 -0
  510. synth_ai/cli/commands/smoke/core.py +1437 -0
  511. synth_ai/cli/commands/status/__init__.py +66 -0
  512. synth_ai/cli/commands/status/client.py +192 -0
  513. synth_ai/cli/commands/status/config.py +92 -0
  514. synth_ai/cli/commands/status/errors.py +20 -0
  515. synth_ai/cli/commands/status/formatters.py +164 -0
  516. synth_ai/cli/commands/status/subcommands/__init__.py +9 -0
  517. synth_ai/cli/commands/status/subcommands/files.py +79 -0
  518. synth_ai/cli/commands/status/subcommands/jobs.py +334 -0
  519. synth_ai/cli/commands/status/subcommands/models.py +79 -0
  520. synth_ai/cli/commands/status/subcommands/pricing.py +22 -0
  521. synth_ai/cli/commands/status/subcommands/runs.py +81 -0
  522. synth_ai/cli/commands/status/subcommands/session.py +183 -0
  523. synth_ai/cli/commands/status/subcommands/summary.py +47 -0
  524. synth_ai/cli/commands/status/subcommands/usage.py +203 -0
  525. synth_ai/cli/commands/status/utils.py +114 -0
  526. synth_ai/cli/commands/train/__init__.py +53 -0
  527. synth_ai/cli/commands/train/core.py +21 -0
  528. synth_ai/cli/commands/train/errors.py +117 -0
  529. synth_ai/cli/commands/train/judge_schemas.py +200 -0
  530. synth_ai/cli/commands/train/judge_validation.py +305 -0
  531. synth_ai/cli/commands/train/validation.py +386 -0
  532. synth_ai/cli/demo.py +32 -140
  533. synth_ai/cli/deploy.py +233 -0
  534. synth_ai/cli/eval/__init__.py +36 -0
  535. synth_ai/cli/eval/core.py +5 -0
  536. synth_ai/cli/eval/errors.py +31 -0
  537. synth_ai/cli/eval/validation.py +5 -0
  538. synth_ai/cli/filter/__init__.py +28 -0
  539. synth_ai/cli/filter/core.py +5 -0
  540. synth_ai/cli/filter/errors.py +23 -0
  541. synth_ai/cli/filter/validation.py +5 -0
  542. synth_ai/cli/legacy_root_backup.py +28 -22
  543. synth_ai/cli/lib/__init__.py +10 -0
  544. synth_ai/cli/lib/task_app_discovery.py +7 -0
  545. synth_ai/cli/lib/task_app_env.py +518 -0
  546. synth_ai/cli/mcp.py +34 -0
  547. synth_ai/cli/modal_serve/__init__.py +12 -0
  548. synth_ai/cli/modal_serve/core.py +14 -0
  549. synth_ai/cli/modal_serve/errors.py +8 -0
  550. synth_ai/cli/modal_serve/validation.py +11 -0
  551. synth_ai/cli/opencode.py +256 -0
  552. synth_ai/cli/recent.py +13 -7
  553. synth_ai/cli/rl_demo.py +156 -116
  554. synth_ai/cli/root.py +131 -132
  555. synth_ai/cli/serve/__init__.py +12 -0
  556. synth_ai/cli/serve/core.py +14 -0
  557. synth_ai/cli/serve/errors.py +8 -0
  558. synth_ai/cli/serve/validation.py +11 -0
  559. synth_ai/cli/setup.py +49 -0
  560. synth_ai/cli/status.py +7 -125
  561. synth_ai/cli/task_app_deploy.py +7 -0
  562. synth_ai/cli/task_app_list.py +25 -0
  563. synth_ai/cli/task_app_modal_serve.py +11 -0
  564. synth_ai/cli/task_app_serve.py +11 -0
  565. synth_ai/cli/task_apps.py +2284 -257
  566. synth_ai/cli/traces.py +9 -5
  567. synth_ai/cli/train/__init__.py +12 -0
  568. synth_ai/cli/train/core.py +21 -0
  569. synth_ai/cli/train/errors.py +8 -0
  570. synth_ai/cli/train/validation.py +24 -0
  571. synth_ai/cli/train.py +5 -0
  572. synth_ai/cli/turso.py +73 -0
  573. synth_ai/cli/watch.py +13 -18
  574. synth_ai/demos/__init__.py +10 -0
  575. synth_ai/demos/core/__init__.py +28 -1
  576. synth_ai/demos/core/cli.py +579 -291
  577. synth_ai/demos/crafter/__init__.py +1 -0
  578. synth_ai/demos/crafter/crafter_fft_4b.toml +55 -0
  579. synth_ai/demos/crafter/grpo_crafter_task_app.py +185 -0
  580. synth_ai/demos/crafter/rl_from_base_qwen4b.toml +74 -0
  581. synth_ai/demos/demo_registry.py +176 -0
  582. synth_ai/demos/demo_task_apps/__init__.py +3 -3
  583. synth_ai/demos/demo_task_apps/core.py +64 -28
  584. synth_ai/demos/demo_task_apps/crafter/__init__.py +1 -0
  585. synth_ai/demos/demo_task_apps/crafter/configs/crafter_fft_4b.toml +53 -0
  586. synth_ai/demos/demo_task_apps/crafter/configs/rl_from_base_qwen4b.toml +73 -0
  587. synth_ai/demos/demo_task_apps/crafter/grpo_crafter_task_app.py +184 -0
  588. synth_ai/demos/demo_task_apps/math/_common.py +1 -2
  589. synth_ai/demos/demo_task_apps/math/app.py +2 -1
  590. synth_ai/demos/demo_task_apps/math/deploy_modal.py +3 -6
  591. synth_ai/demos/demo_task_apps/math/modal_task_app.py +185 -83
  592. synth_ai/demos/demo_task_apps/math/task_app_entry.py +0 -2
  593. synth_ai/demos/math/__init__.py +1 -0
  594. synth_ai/demos/math/_common.py +16 -0
  595. synth_ai/demos/math/app.py +38 -0
  596. synth_ai/demos/math/config.toml +76 -0
  597. synth_ai/demos/math/deploy_modal.py +54 -0
  598. synth_ai/demos/math/modal_task_app.py +703 -0
  599. synth_ai/demos/math/task_app_entry.py +51 -0
  600. synth_ai/environments/environment/core.py +7 -1
  601. synth_ai/environments/examples/bandit/engine.py +12 -5
  602. synth_ai/environments/examples/bandit/environment.py +0 -1
  603. synth_ai/environments/examples/bandit/taskset.py +4 -4
  604. synth_ai/environments/examples/crafter_classic/engine_deterministic_patch.py +7 -4
  605. synth_ai/environments/examples/crafter_classic/engine_serialization_patch_v3.py +9 -5
  606. synth_ai/environments/examples/crafter_classic/environment.py +93 -2
  607. synth_ai/environments/examples/crafter_classic/world_config_patch_simple.py +4 -3
  608. synth_ai/environments/examples/enron/engine.py +7 -2
  609. synth_ai/environments/examples/enron/environment.py +68 -0
  610. synth_ai/environments/examples/red/engine.py +60 -12
  611. synth_ai/environments/examples/red/engine_helpers/memory_map.py +7 -0
  612. synth_ai/environments/examples/red/engine_helpers/reward_components.py +151 -179
  613. synth_ai/environments/examples/red/engine_helpers/reward_library/pallet_town_progression.py +477 -0
  614. synth_ai/environments/examples/red/engine_helpers/state_extraction.py +32 -0
  615. synth_ai/environments/examples/red/environment.py +86 -0
  616. synth_ai/environments/examples/red/trace_hooks_v3.py +168 -0
  617. synth_ai/environments/examples/sokoban/taskset.py +116 -0
  618. synth_ai/environments/examples/verilog/engine.py +104 -12
  619. synth_ai/environments/examples/wordle/environment.py +0 -1
  620. synth_ai/environments/reproducibility/tree.py +5 -6
  621. synth_ai/environments/service/app.py +11 -12
  622. synth_ai/environments/service/core_routes.py +10 -9
  623. synth_ai/environments/stateful/engine.py +1 -1
  624. synth_ai/environments/tasks/core.py +1 -0
  625. synth_ai/environments/tasks/filters.py +5 -6
  626. synth_ai/environments/tasks/utils.py +4 -5
  627. synth_ai/evals/__init__.py +15 -0
  628. synth_ai/evals/base.py +14 -5
  629. synth_ai/evals/client.py +82 -0
  630. synth_ai/evals/types.py +42 -0
  631. synth_ai/http.py +8 -22
  632. synth_ai/http_client.py +45 -12
  633. synth_ai/inference/__init__.py +0 -2
  634. synth_ai/inference/client.py +21 -7
  635. synth_ai/jobs/client.py +129 -80
  636. synth_ai/judge_schemas.py +127 -0
  637. synth_ai/learning/__init__.py +51 -6
  638. synth_ai/learning/algorithms.py +14 -0
  639. synth_ai/learning/client.py +122 -30
  640. synth_ai/learning/config.py +2 -40
  641. synth_ai/learning/constants.py +0 -2
  642. synth_ai/learning/ft_client.py +4 -56
  643. synth_ai/learning/health.py +14 -8
  644. synth_ai/learning/jobs.py +43 -47
  645. synth_ai/learning/prompt_learning_client.py +276 -0
  646. synth_ai/learning/prompt_learning_types.py +185 -0
  647. synth_ai/{rl → learning/rl}/__init__.py +14 -5
  648. synth_ai/learning/rl/client.py +269 -0
  649. synth_ai/learning/rl/config.py +31 -0
  650. synth_ai/{rl → learning/rl}/contracts.py +5 -10
  651. synth_ai/{rl → learning/rl}/env_keys.py +45 -16
  652. synth_ai/learning/rl/secrets.py +13 -0
  653. synth_ai/learning/rl_client.py +2 -253
  654. synth_ai/learning/sft/__init__.py +29 -0
  655. synth_ai/learning/sft/client.py +68 -0
  656. synth_ai/learning/sft/config.py +270 -0
  657. synth_ai/learning/sft/data.py +698 -0
  658. synth_ai/learning/sse.py +25 -26
  659. synth_ai/learning/validators.py +29 -25
  660. synth_ai/mcp/__init__.py +5 -0
  661. synth_ai/mcp/__main__.py +8 -0
  662. synth_ai/mcp/main.py +254 -0
  663. synth_ai/mcp/setup.py +100 -0
  664. synth_ai/modal.py +257 -0
  665. synth_ai/pricing/__init__.py +3 -0
  666. synth_ai/pricing/model_pricing.py +64 -0
  667. synth_ai/session/__init__.py +75 -0
  668. synth_ai/session/client.py +383 -0
  669. synth_ai/session/constants.py +63 -0
  670. synth_ai/session/exceptions.py +105 -0
  671. synth_ai/session/manager.py +139 -0
  672. synth_ai/session/models.py +89 -0
  673. synth_ai/session/query.py +110 -0
  674. synth_ai/spec/__init__.py +46 -0
  675. synth_ai/spec/dataclasses.py +149 -0
  676. synth_ai/spec/loader.py +144 -0
  677. synth_ai/spec/serializer.py +199 -0
  678. synth_ai/spec/validation.py +250 -0
  679. synth_ai/streaming/__init__.py +29 -0
  680. synth_ai/streaming/config.py +94 -0
  681. synth_ai/streaming/handlers.py +589 -0
  682. synth_ai/streaming/streamer.py +320 -0
  683. synth_ai/streaming/types.py +95 -0
  684. synth_ai/task/__init__.py +50 -30
  685. synth_ai/task/apps/__init__.py +63 -19
  686. synth_ai/task/auth.py +35 -23
  687. synth_ai/task/client.py +15 -13
  688. synth_ai/task/config.py +261 -0
  689. synth_ai/task/contracts.py +165 -64
  690. synth_ai/task/datasets.py +9 -6
  691. synth_ai/task/errors.py +11 -10
  692. synth_ai/task/health.py +17 -11
  693. synth_ai/task/inference_api.py +101 -0
  694. synth_ai/task/json.py +58 -24
  695. synth_ai/task/proxy.py +59 -66
  696. synth_ai/task/rubrics/__init__.py +55 -0
  697. synth_ai/task/rubrics/loaders.py +156 -0
  698. synth_ai/task/rubrics/models.py +57 -0
  699. synth_ai/task/rubrics/scoring.py +116 -0
  700. synth_ai/task/rubrics/strict.py +149 -0
  701. synth_ai/task/rubrics.py +22 -15
  702. synth_ai/task/server.py +65 -31
  703. synth_ai/task/trace_correlation_helpers.py +328 -0
  704. synth_ai/task/tracing_utils.py +44 -28
  705. synth_ai/task/validators.py +449 -6
  706. synth_ai/task/vendors.py +5 -7
  707. synth_ai/tracing_v3/__init__.py +4 -0
  708. synth_ai/tracing_v3/abstractions.py +21 -4
  709. synth_ai/tracing_v3/config.py +167 -22
  710. synth_ai/tracing_v3/constants.py +21 -0
  711. synth_ai/tracing_v3/db_config.py +42 -29
  712. synth_ai/tracing_v3/decorators.py +80 -45
  713. synth_ai/tracing_v3/examples/basic_usage.py +15 -9
  714. synth_ai/tracing_v3/hooks.py +6 -4
  715. synth_ai/tracing_v3/llm_call_record_helpers.py +161 -61
  716. synth_ai/tracing_v3/migration_helper.py +1 -2
  717. synth_ai/tracing_v3/replica_sync.py +12 -7
  718. synth_ai/tracing_v3/serialization.py +130 -0
  719. synth_ai/tracing_v3/session_tracer.py +73 -16
  720. synth_ai/tracing_v3/storage/base.py +89 -1
  721. synth_ai/tracing_v3/storage/config.py +63 -16
  722. synth_ai/tracing_v3/storage/factory.py +11 -9
  723. synth_ai/tracing_v3/storage/utils.py +15 -11
  724. synth_ai/tracing_v3/trace_utils.py +317 -0
  725. synth_ai/tracing_v3/turso/__init__.py +8 -21
  726. synth_ai/tracing_v3/turso/daemon.py +123 -15
  727. synth_ai/tracing_v3/turso/models.py +5 -2
  728. synth_ai/tracing_v3/turso/native_manager.py +1293 -0
  729. synth_ai/tracing_v3/utils.py +5 -4
  730. synth_ai/tunnel.py +143 -0
  731. synth_ai/tunnel_deploy.py +278 -0
  732. synth_ai/types.py +8 -0
  733. synth_ai/urls.py +11 -0
  734. synth_ai/utils/__init__.py +166 -0
  735. synth_ai/utils/agents.py +74 -0
  736. synth_ai/utils/apps.py +152 -0
  737. synth_ai/utils/base_url.py +94 -0
  738. synth_ai/utils/bin.py +39 -0
  739. synth_ai/utils/claude.py +36 -0
  740. synth_ai/utils/cli.py +284 -0
  741. synth_ai/utils/config.py +81 -0
  742. synth_ai/utils/env.py +346 -0
  743. synth_ai/utils/errors.py +85 -0
  744. synth_ai/utils/http.py +172 -0
  745. synth_ai/utils/json.py +72 -0
  746. synth_ai/utils/log_filter.py +99 -0
  747. synth_ai/utils/logging.py +198 -0
  748. synth_ai/utils/modal.py +299 -0
  749. synth_ai/utils/paths.py +95 -0
  750. synth_ai/utils/process.py +233 -0
  751. synth_ai/utils/prompts.py +39 -0
  752. synth_ai/utils/sqld.py +122 -0
  753. synth_ai/utils/ssl.py +25 -0
  754. synth_ai/utils/task_app_discovery.py +882 -0
  755. synth_ai/utils/task_app_env.py +186 -0
  756. synth_ai/utils/task_app_state.py +318 -0
  757. synth_ai/utils/tunnel/__init__.py +12 -0
  758. synth_ai/utils/tunnel/config.py +55 -0
  759. synth_ai/utils/user_config.py +137 -0
  760. synth_ai/uvicorn.py +77 -0
  761. synth_ai-0.2.23.dev3.dist-info/METADATA +357 -0
  762. synth_ai-0.2.23.dev3.dist-info/RECORD +983 -0
  763. {synth_ai-0.2.9.dev0.dist-info → synth_ai-0.2.23.dev3.dist-info}/entry_points.txt +0 -1
  764. {synth_ai-0.2.9.dev0.dist-info → synth_ai-0.2.23.dev3.dist-info}/top_level.txt +1 -0
  765. synth_ai/cli/man.py +0 -106
  766. synth_ai/core/experiment.py +0 -15
  767. synth_ai/core/system.py +0 -15
  768. synth_ai/demo_registry.py +0 -258
  769. synth_ai/environments/examples/sokoban/units/astar_common.py +0 -95
  770. synth_ai/experimental/synth_oss.py +0 -446
  771. synth_ai/handshake.py +0 -107
  772. synth_ai/install_sqld.sh +0 -40
  773. synth_ai/learning/offline/dpo.py +0 -0
  774. synth_ai/learning/offline/providers.py +0 -7
  775. synth_ai/learning/offline/sft.py +0 -0
  776. synth_ai/learning/offline/shared.py +0 -0
  777. synth_ai/learning/online/grpo.py +0 -0
  778. synth_ai/learning/online/irft.py +0 -0
  779. synth_ai/learning/prompts/banking77_injection_eval.py +0 -168
  780. synth_ai/learning/prompts/gepa.py +0 -0
  781. synth_ai/learning/prompts/hello_world_in_context_injection_ex.py +0 -213
  782. synth_ai/learning/prompts/mipro.py +0 -289
  783. synth_ai/learning/prompts/random_search.py +0 -246
  784. synth_ai/learning/prompts/run_mipro_banking77.py +0 -172
  785. synth_ai/learning/prompts/run_random_search_banking77.py +0 -324
  786. synth_ai/lm/__init__.py +0 -51
  787. synth_ai/lm/caching/constants.py +0 -6
  788. synth_ai/lm/caching/dbs.py +0 -0
  789. synth_ai/lm/caching/ephemeral.py +0 -102
  790. synth_ai/lm/caching/handler.py +0 -137
  791. synth_ai/lm/caching/initialize.py +0 -11
  792. synth_ai/lm/caching/persistent.py +0 -114
  793. synth_ai/lm/config.py +0 -110
  794. synth_ai/lm/constants.py +0 -32
  795. synth_ai/lm/core/__init__.py +0 -8
  796. synth_ai/lm/core/all.py +0 -73
  797. synth_ai/lm/core/exceptions.py +0 -7
  798. synth_ai/lm/core/main.py +0 -319
  799. synth_ai/lm/core/main_v3.py +0 -594
  800. synth_ai/lm/core/synth_models.py +0 -48
  801. synth_ai/lm/core/vendor_clients.py +0 -188
  802. synth_ai/lm/cost/monitor.py +0 -1
  803. synth_ai/lm/cost/statefulness.py +0 -1
  804. synth_ai/lm/injection.py +0 -80
  805. synth_ai/lm/overrides.py +0 -206
  806. synth_ai/lm/provider_support/__init__.py +0 -8
  807. synth_ai/lm/provider_support/anthropic.py +0 -972
  808. synth_ai/lm/provider_support/openai.py +0 -1139
  809. synth_ai/lm/provider_support/suppress_logging.py +0 -31
  810. synth_ai/lm/structured_outputs/handler.py +0 -440
  811. synth_ai/lm/structured_outputs/inject.py +0 -297
  812. synth_ai/lm/structured_outputs/rehabilitate.py +0 -185
  813. synth_ai/lm/tools/__init__.py +0 -3
  814. synth_ai/lm/tools/base.py +0 -172
  815. synth_ai/lm/unified_interface.py +0 -202
  816. synth_ai/lm/vendors/base.py +0 -81
  817. synth_ai/lm/vendors/core/anthropic_api.py +0 -387
  818. synth_ai/lm/vendors/core/gemini_api.py +0 -292
  819. synth_ai/lm/vendors/core/mistral_api.py +0 -322
  820. synth_ai/lm/vendors/core/openai_api.py +0 -225
  821. synth_ai/lm/vendors/core/synth_dev_api.py +0 -0
  822. synth_ai/lm/vendors/local/ollama.py +0 -0
  823. synth_ai/lm/vendors/openai_standard.py +0 -780
  824. synth_ai/lm/vendors/openai_standard_responses.py +0 -256
  825. synth_ai/lm/vendors/retries.py +0 -22
  826. synth_ai/lm/vendors/supported/custom_endpoint.py +0 -417
  827. synth_ai/lm/vendors/supported/deepseek.py +0 -69
  828. synth_ai/lm/vendors/supported/grok.py +0 -75
  829. synth_ai/lm/vendors/supported/groq.py +0 -16
  830. synth_ai/lm/vendors/supported/ollama.py +0 -15
  831. synth_ai/lm/vendors/supported/openrouter.py +0 -74
  832. synth_ai/lm/vendors/supported/together.py +0 -11
  833. synth_ai/lm/vendors/synth_client.py +0 -808
  834. synth_ai/lm/warmup.py +0 -186
  835. synth_ai/rl/secrets.py +0 -19
  836. synth_ai/scripts/verify_rewards.py +0 -100
  837. synth_ai/task/apps/grpo_crafter.py +0 -438
  838. synth_ai/tracing/__init__.py +0 -30
  839. synth_ai/tracing_v1/__init__.py +0 -33
  840. synth_ai/tracing_v3/turso/manager.py +0 -774
  841. synth_ai/v0/tracing/abstractions.py +0 -224
  842. synth_ai/v0/tracing/base_client.py +0 -91
  843. synth_ai/v0/tracing/client_manager.py +0 -131
  844. synth_ai/v0/tracing/config.py +0 -142
  845. synth_ai/v0/tracing/context.py +0 -146
  846. synth_ai/v0/tracing/decorators.py +0 -682
  847. synth_ai/v0/tracing/events/__init__.py +0 -0
  848. synth_ai/v0/tracing/events/manage.py +0 -147
  849. synth_ai/v0/tracing/events/scope.py +0 -86
  850. synth_ai/v0/tracing/events/store.py +0 -228
  851. synth_ai/v0/tracing/immediate_client.py +0 -151
  852. synth_ai/v0/tracing/local.py +0 -18
  853. synth_ai/v0/tracing/log_client_base.py +0 -73
  854. synth_ai/v0/tracing/retry_queue.py +0 -186
  855. synth_ai/v0/tracing/trackers.py +0 -515
  856. synth_ai/v0/tracing/upload.py +0 -512
  857. synth_ai/v0/tracing/utils.py +0 -9
  858. synth_ai/v0/tracing_v1/__init__.py +0 -16
  859. synth_ai/v0/tracing_v1/abstractions.py +0 -224
  860. synth_ai/v0/tracing_v1/base_client.py +0 -91
  861. synth_ai/v0/tracing_v1/client_manager.py +0 -131
  862. synth_ai/v0/tracing_v1/config.py +0 -142
  863. synth_ai/v0/tracing_v1/context.py +0 -146
  864. synth_ai/v0/tracing_v1/decorators.py +0 -703
  865. synth_ai/v0/tracing_v1/events/__init__.py +0 -0
  866. synth_ai/v0/tracing_v1/events/manage.py +0 -147
  867. synth_ai/v0/tracing_v1/events/scope.py +0 -86
  868. synth_ai/v0/tracing_v1/events/store.py +0 -228
  869. synth_ai/v0/tracing_v1/immediate_client.py +0 -151
  870. synth_ai/v0/tracing_v1/local.py +0 -18
  871. synth_ai/v0/tracing_v1/log_client_base.py +0 -73
  872. synth_ai/v0/tracing_v1/retry_queue.py +0 -186
  873. synth_ai/v0/tracing_v1/trackers.py +0 -515
  874. synth_ai/v0/tracing_v1/upload.py +0 -527
  875. synth_ai/v0/tracing_v1/utils.py +0 -9
  876. synth_ai/zyk/__init__.py +0 -30
  877. synth_ai-0.2.9.dev0.dist-info/METADATA +0 -131
  878. synth_ai-0.2.9.dev0.dist-info/RECORD +0 -444
  879. {synth_ai/lm/caching → examples/task_apps}/__init__.py +0 -0
  880. {synth_ai/lm/cost → examples/task_apps/crafter}/__init__.py +0 -0
  881. {synth_ai/lm/structured_outputs → examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server}/__init__.py +0 -0
  882. {synth_ai/lm/vendors → examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests}/__init__.py +0 -0
  883. {synth_ai/lm/vendors/core → examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils}/__init__.py +0 -0
  884. {synth_ai/lm/vendors/local → examples/task_apps/math}/__init__.py +0 -0
  885. {synth_ai/lm/vendors/supported → examples/workflows}/__init__.py +0 -0
  886. {synth_ai/v0/tracing → examples/workflows/math_rl}/__init__.py +0 -0
  887. /synth_ai/{compound/cais.py → cli/__main__.py} +0 -0
  888. /synth_ai/{learning/filtering.py → py.typed} +0 -0
  889. {synth_ai-0.2.9.dev0.dist-info → synth_ai-0.2.23.dev3.dist-info}/WHEEL +0 -0
  890. {synth_ai-0.2.9.dev0.dist-info → synth_ai-0.2.23.dev3.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,1905 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import json
5
+ import logging
6
+ import os
7
+ import time as _time
8
+ from datetime import datetime
9
+ from typing import Any
10
+
11
+ from fastapi import APIRouter, HTTPException, Request, status
12
+ from pydantic import BaseModel
13
+ from synth_ai.tracing_v3 import BaseLMResponse
14
+ from synth_ai.task.tracing_utils import unique_sft_path
15
+ from synth_ai.task.contracts import RolloutMode
16
+ from synth_ai.tracing_v3.abstractions import EnvironmentEvent, LMCAISEvent, TimeRecord
17
+ from synth_ai.tracing_v3.llm_call_record_helpers import create_llm_call_record_from_response
18
+ from synth_ai.tracing_v3.session_tracer import SessionTracer
19
+
20
+ from .registry import registry
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ # --- Seeding utilities (robust, optional deps) ---
26
+ def _set_global_seed(seed_value: int) -> dict[str, Any]:
27
+ """Set global RNG seeds across common libraries; return details for logging/restoration.
28
+
29
+ Returns a dict containing which libraries were seeded and prior states if obtainable.
30
+ """
31
+ seeded: dict[str, Any] = {"seed": int(seed_value), "libs": []}
32
+ with contextlib.suppress(Exception):
33
+ import random as _random # type: ignore
34
+
35
+ _random.seed(seed_value)
36
+ seeded["libs"].append("random")
37
+ with contextlib.suppress(Exception):
38
+ import numpy as _np # type: ignore
39
+
40
+ _np.random.seed(seed_value)
41
+ seeded["libs"].append("numpy")
42
+ with contextlib.suppress(Exception):
43
+ import torch as _torch # type: ignore
44
+
45
+ if hasattr(_torch, "manual_seed"):
46
+ _torch.manual_seed(seed_value)
47
+ seeded["libs"].append("torch")
48
+ # Make CUDA deterministic if present (best-effort)
49
+ with contextlib.suppress(Exception):
50
+ if getattr(_torch, "cuda", None) and _torch.cuda.is_available():
51
+ _torch.cuda.manual_seed_all(seed_value)
52
+ seeded.setdefault("cuda", True)
53
+ # CUDNN deterministic flags (optional)
54
+ with contextlib.suppress(Exception):
55
+ if getattr(_torch, "backends", None) and getattr(_torch.backends, "cudnn", None):
56
+ _torch.backends.cudnn.deterministic = True # type: ignore[attr-defined]
57
+ _torch.backends.cudnn.benchmark = False # type: ignore[attr-defined]
58
+ return seeded
59
+
60
+
61
+ def _clear_seed_side_effects() -> None:
62
+ """Best-effort cleanup to avoid global deterministic side-effects between requests."""
63
+ # We cannot truly restore prior RNG states without capturing them; we just avoid
64
+ # leaving aggressive deterministic flags enabled where it matters.
65
+ with contextlib.suppress(Exception):
66
+ import torch as _torch # type: ignore
67
+
68
+ with contextlib.suppress(Exception):
69
+ if getattr(_torch, "backends", None) and getattr(_torch.backends, "cudnn", None):
70
+ # Re-enable cudnn.benchmark default True only if it was True; safest is False -> leave as is.
71
+ # We'll keep deterministic False to avoid global impact; benchmark left False for stability.
72
+ _torch.backends.cudnn.deterministic = False # type: ignore[attr-defined]
73
+
74
+
75
+ router = APIRouter()
76
+
77
+
78
+ class RolloutEnvSpec(BaseModel):
79
+ env_id: str | None = None
80
+ env_name: str | None = None
81
+ config: dict[str, Any] = {}
82
+ seed: int | None = None
83
+
84
+
85
+ class RolloutPolicySpec(BaseModel):
86
+ policy_id: str | None = None
87
+ policy_name: str | None = None
88
+ config: dict[str, Any] = {}
89
+
90
+
91
+ class RolloutBranchConfig(BaseModel):
92
+ branch_every_n_steps: int = 0
93
+ branch_on_condition: str | None = None
94
+ max_branches: int = 0
95
+ branch_policy: bool = False
96
+ branch_env: bool = False
97
+
98
+
99
+ class RolloutRecordConfig(BaseModel):
100
+ trajectories: bool = True
101
+ logprobs: bool = False
102
+ value: bool = False
103
+ return_trace: bool = False
104
+ trace_format: str = "compact"
105
+
106
+
107
+ class RolloutSafetyConfig(BaseModel):
108
+ max_ops: int = 100000
109
+ max_time_s: float = 3600.0
110
+
111
+
112
+ class RolloutRequest(BaseModel):
113
+ run_id: str
114
+ env: RolloutEnvSpec
115
+ policy: RolloutPolicySpec
116
+ ops: list[str] # ["agent", "env", ...]
117
+ record: RolloutRecordConfig = RolloutRecordConfig()
118
+ on_done: str = "reset" # "reset" | "terminate"
119
+ branch: RolloutBranchConfig | None = None
120
+ safety: RolloutSafetyConfig = RolloutSafetyConfig()
121
+ # Optional run/session context
122
+ training_session_id: str | None = None
123
+ synth_base_url: str | None = None
124
+ mode: RolloutMode # Required: explicit RL vs EVAL mode
125
+
126
+
127
+ class RolloutStep(BaseModel):
128
+ obs: dict[str, Any]
129
+ tool_calls: list[dict[str, Any]]
130
+ reward: float | None = None
131
+ done: bool = False
132
+ truncated: bool | None = None
133
+ logprob: float | None = None
134
+ value: float | None = None
135
+ info: dict[str, Any] | None = None
136
+
137
+
138
+ class RolloutTrajectory(BaseModel):
139
+ env_id: str
140
+ policy_id: str
141
+ steps: list[RolloutStep]
142
+ final: dict[str, Any] | None = None
143
+ length: int
144
+ decision_samples: list[dict[str, Any]] | None = None
145
+
146
+
147
+ def compute_stepwise_reward(
148
+ prev_achievements: dict[str, bool],
149
+ new_achievements: dict[str, bool],
150
+ decision_index: int,
151
+ actions_summary: list[dict[str, Any]],
152
+ indicator_lambda: float,
153
+ ) -> tuple[dict[str, Any], dict[str, Any], dict[str, float]]:
154
+ """Compute stepwise reward metadata given achievement states before/after a decision."""
155
+
156
+ prev_map = prev_achievements or {}
157
+ next_map = new_achievements or {}
158
+
159
+ unlocked = [name for name, value in next_map.items() if value and not prev_map.get(name, False)]
160
+ indicator = 1 if unlocked else 0
161
+ reward_value = float(indicator_lambda) * indicator
162
+
163
+ stepwise_info = {
164
+ "decision_index": decision_index,
165
+ "indicator": indicator,
166
+ "new_achievements": unlocked,
167
+ "reward": reward_value,
168
+ }
169
+ decision_sample = {
170
+ "decision_index": decision_index,
171
+ "indicator": indicator,
172
+ "r_i": reward_value,
173
+ "actions": actions_summary,
174
+ }
175
+ stats = {
176
+ "indicator": float(indicator),
177
+ "reward": reward_value,
178
+ "new_achievements_count": float(len(unlocked)),
179
+ }
180
+ return stepwise_info, decision_sample, stats
181
+
182
+
183
+ class RolloutMetrics(BaseModel):
184
+ episode_returns: list[float]
185
+ mean_return: float
186
+ num_steps: int
187
+ num_episodes: int = 0
188
+
189
+
190
+ class RolloutResponse(BaseModel):
191
+ run_id: str
192
+ trajectories: list[RolloutTrajectory]
193
+ branches: dict[str, list[str]] = {}
194
+ metrics: RolloutMetrics
195
+ aborted: bool = False
196
+ ops_executed: int = 0
197
+ trace: dict[str, Any] | None = None
198
+
199
+
200
+ class RolloutTracingContext:
201
+ """Helper managing tracing_v3 recording and optional SFT dumps for a rollout."""
202
+
203
+ def __init__(
204
+ self,
205
+ tracer: SessionTracer | None,
206
+ request: RolloutRequest,
207
+ fastapi_request: Request,
208
+ ) -> None:
209
+ self.tracer = tracer
210
+ self.enabled = tracer is not None
211
+ self.request = request
212
+ self.fastapi_request = fastapi_request
213
+ self.run_id = request.run_id
214
+ self.current_step_id: str | None = None
215
+ self.current_turn: int | None = None
216
+ self.lm_calls_summary: list[dict[str, Any]] = []
217
+ self.decision_rewards: list[dict[str, Any]] = []
218
+ self.sft_records: list[dict[str, Any]] = []
219
+ self.latest_system_messages: list[str] = []
220
+ self.latest_user_messages: list[str] = []
221
+ self.latest_system_prompt_content: list[Any] = []
222
+ self.latest_user_prompt_content: list[Any] = []
223
+ self.trace_format = (
224
+ getattr(request.record, "trace_format", "compact") or "compact"
225
+ ).lower()
226
+ self.return_trace = bool(getattr(request.record, "return_trace", False))
227
+ self.sft_output_dir = getattr(fastapi_request.app.state, "sft_output_dir", None)
228
+ self.session_trace = None
229
+ self.metadata_updates: dict[str, Any] = {}
230
+ self.policy_name = request.policy.policy_name or ""
231
+ self.env_name = request.env.env_name or ""
232
+ self.metadata_base: dict[str, Any] = {
233
+ "run_id": self.run_id,
234
+ "policy_name": self.policy_name,
235
+ "policy_id": request.policy.policy_id,
236
+ "env_name": self.env_name,
237
+ "env_id": request.env.env_id,
238
+ "seed": request.env.seed,
239
+ "training_session_id": request.training_session_id,
240
+ "synth_base_url": request.synth_base_url,
241
+ }
242
+
243
+ # Expose context for downstream calls inside this request lifecycle
244
+ fastapi_request.state.rollout_tracing = self
245
+ fastapi_request.state.rollout_run_id = self.run_id
246
+
247
+ async def start_session(self) -> None:
248
+ if not self.enabled or self.tracer is None:
249
+ return
250
+ try:
251
+ await self.tracer.initialize()
252
+ except Exception as exc:
253
+ logger.debug("TRACING_INIT_FAIL: %s", exc)
254
+ # Hard fail: tracing requested but cannot initialize
255
+ raise
256
+ try:
257
+ await self.tracer.start_session(
258
+ session_id=self.run_id, metadata=dict(self.metadata_base)
259
+ )
260
+ except Exception as exc:
261
+ logger.warning("TRACING_START_FAIL: %s", exc)
262
+ # Hard fail: tracing requested but cannot start session
263
+ raise
264
+
265
+ async def start_decision(self, turn_number: int) -> None:
266
+ self.current_turn = turn_number
267
+ self.current_step_id = f"decision_{turn_number}"
268
+ if not self.enabled or self.tracer is None:
269
+ return
270
+ try:
271
+ await self.tracer.start_timestep(step_id=self.current_step_id, turn_number=turn_number)
272
+ except Exception as exc:
273
+ logger.debug("TRACING_STEP_START_FAIL: %s", exc)
274
+
275
+ async def end_decision(self) -> None:
276
+ if not self.enabled or self.tracer is None:
277
+ return
278
+ try:
279
+ await self.tracer.end_timestep(step_id=self.current_step_id)
280
+ except Exception as exc:
281
+ logger.debug("TRACING_STEP_END_FAIL: %s", exc)
282
+ finally:
283
+ self.current_step_id = None
284
+
285
+ def _message_metadata(self) -> dict[str, Any]:
286
+ return {
287
+ "turn": self.current_turn,
288
+ "step_id": self.current_step_id,
289
+ }
290
+
291
+ async def record_policy_prompts(
292
+ self,
293
+ system_messages: list[Any],
294
+ user_messages: list[Any],
295
+ ) -> None:
296
+ self.latest_system_messages = [self._prompt_text(entry) for entry in system_messages]
297
+ self.latest_user_messages = [self._prompt_text(entry) for entry in user_messages]
298
+ self.latest_system_prompt_content = [
299
+ self._prompt_content(entry, role="system") for entry in system_messages
300
+ ]
301
+ self.latest_user_prompt_content = [
302
+ self._prompt_content(entry, role="user") for entry in user_messages
303
+ ]
304
+ if not self.enabled or self.tracer is None:
305
+ return
306
+ for entry in system_messages:
307
+ try:
308
+ await self.tracer.record_message(
309
+ content=self._prompt_payload(entry, role="system"),
310
+ message_type="policy_system_prompt",
311
+ metadata=self._message_metadata(),
312
+ )
313
+ except Exception as exc:
314
+ logger.debug("TRACING_SYSTEM_MSG_FAIL: %s", exc)
315
+ for entry in user_messages:
316
+ try:
317
+ await self.tracer.record_message(
318
+ content=self._prompt_payload(entry, role="user"),
319
+ message_type="policy_user_prompt",
320
+ metadata=self._message_metadata(),
321
+ )
322
+ except Exception as exc:
323
+ logger.debug("TRACING_USER_MSG_FAIL: %s", exc)
324
+
325
+ def _content_to_text(self, content: Any) -> str:
326
+ if isinstance(content, str):
327
+ return content
328
+ if isinstance(content, list):
329
+ parts: list[str] = []
330
+ for seg in content:
331
+ if isinstance(seg, dict):
332
+ text_val = seg.get("text") or seg.get("content")
333
+ if isinstance(text_val, str):
334
+ parts.append(text_val)
335
+ return "".join(parts)
336
+ if content is None:
337
+ return ""
338
+ return str(content)
339
+
340
+ def _prompt_text(self, entry: Any) -> str:
341
+ if isinstance(entry, dict):
342
+ text = entry.get("text")
343
+ if isinstance(text, str):
344
+ return text
345
+ content = entry.get("content")
346
+ return self._content_to_text(content)
347
+ return self._content_to_text(entry)
348
+
349
+ def _prompt_payload(self, entry: Any, *, role: str) -> dict[str, Any]:
350
+ if isinstance(entry, dict):
351
+ payload = dict(entry)
352
+ payload.setdefault("role", role)
353
+ return payload
354
+ return {
355
+ "role": role,
356
+ "text": self._prompt_text(entry),
357
+ "content": entry,
358
+ }
359
+
360
+ def _prompt_content(self, entry: Any, *, role: str) -> Any:
361
+ payload = self._prompt_payload(entry, role=role)
362
+ return payload.get("content", payload.get("text"))
363
+
364
+ def _content_has_image(self, content: Any) -> bool:
365
+ if isinstance(content, list):
366
+ return any(
367
+ isinstance(seg, dict)
368
+ and seg.get("type") in {"image", "image_url"}
369
+ for seg in content
370
+ )
371
+ if isinstance(content, dict):
372
+ if content.get("type") in {"image", "image_url"}:
373
+ return True
374
+ inner = content.get("content")
375
+ if isinstance(inner, list):
376
+ return any(
377
+ isinstance(seg, dict)
378
+ and seg.get("type") in {"image", "image_url"}
379
+ for seg in inner
380
+ )
381
+ return False
382
+
383
+ def _safe_json(self, payload: Any, limit: int = 4000) -> str:
384
+ try:
385
+ text = json.dumps(payload, ensure_ascii=False)
386
+ except Exception:
387
+ text = str(payload)
388
+ if len(text) > limit:
389
+ return text[:limit] + "…"
390
+ return text
391
+
392
+ async def record_tool_invocation(self, tool_calls: list[dict[str, Any]] | None) -> None:
393
+ if tool_calls is None:
394
+ return
395
+ if self.enabled and self.tracer is not None:
396
+ try:
397
+ await self.tracer.record_message(
398
+ content=self._safe_json(tool_calls),
399
+ message_type="policy_tool_call",
400
+ metadata=self._message_metadata(),
401
+ )
402
+ except Exception as exc:
403
+ logger.debug("TRACING_TOOL_MSG_FAIL: %s", exc)
404
+
405
+ async def _record_event(self, event: Any) -> int | None:
406
+ if not self.enabled or self.tracer is None:
407
+ return None
408
+ try:
409
+ return await self.tracer.record_event(event)
410
+ except Exception as exc:
411
+ logger.debug("TRACING_EVENT_FAIL: %s", exc)
412
+ return None
413
+
414
+ async def record_llm_call(
415
+ self,
416
+ *,
417
+ inference_request: dict[str, Any],
418
+ inference_response: dict[str, Any],
419
+ tool_calls: list[dict[str, Any]] | None,
420
+ provider: str,
421
+ model_name: str,
422
+ started_at: datetime,
423
+ completed_at: datetime,
424
+ latency_ms: int | None,
425
+ ) -> None:
426
+ usage = inference_response.get("usage") or {}
427
+ input_tokens = usage.get("input_tokens") or usage.get("prompt_tokens")
428
+ output_tokens = usage.get("output_tokens") or usage.get("completion_tokens")
429
+ total_tokens = usage.get("total_tokens")
430
+ cost_usd = usage.get("cost_usd") or usage.get("cost") or usage.get("total_cost")
431
+
432
+ assistant_message = None
433
+ choices = inference_response.get("choices") or []
434
+ if choices:
435
+ assistant_message = choices[0].get("message") or {}
436
+ assistant_content = (
437
+ assistant_message.get("content") if isinstance(assistant_message, dict) else None
438
+ )
439
+
440
+ raw_response = self._content_to_text(assistant_content)
441
+ if not raw_response:
442
+ raw_response = self._safe_json(inference_response, limit=2000)
443
+
444
+ base_response = BaseLMResponse(
445
+ raw_response=raw_response,
446
+ tool_calls=assistant_message.get("tool_calls")
447
+ if isinstance(assistant_message, dict)
448
+ else None,
449
+ usage=usage or None,
450
+ api_type="chat_completions",
451
+ )
452
+
453
+ request_messages = inference_request.get("messages") or []
454
+ try:
455
+ temperature = float(inference_request.get("temperature"))
456
+ except Exception:
457
+ temperature = 0.0
458
+
459
+ call_record = create_llm_call_record_from_response(
460
+ response=base_response,
461
+ model_name=model_name,
462
+ provider=provider,
463
+ messages=request_messages,
464
+ temperature=temperature,
465
+ request_params=inference_request,
466
+ tools=inference_request.get("tools"),
467
+ started_at=started_at,
468
+ completed_at=completed_at,
469
+ latency_ms=latency_ms,
470
+ )
471
+
472
+ event_metadata = {
473
+ "policy_id": self.request.policy.policy_id,
474
+ "turn": self.current_turn,
475
+ "run_id": self.run_id,
476
+ }
477
+
478
+ event = LMCAISEvent(
479
+ system_instance_id=f"policy:{self.policy_name or 'unknown'}",
480
+ time_record=TimeRecord(event_time=completed_at.timestamp()),
481
+ model_name=model_name,
482
+ provider=provider,
483
+ input_tokens=input_tokens,
484
+ output_tokens=output_tokens,
485
+ total_tokens=total_tokens,
486
+ cost_usd=cost_usd,
487
+ latency_ms=latency_ms,
488
+ call_records=[call_record],
489
+ metadata=event_metadata,
490
+ )
491
+
492
+ await self._record_event(event)
493
+
494
+ self.lm_calls_summary.append(
495
+ {
496
+ "turn": self.current_turn,
497
+ "model": model_name,
498
+ "provider": provider,
499
+ "total_tokens": total_tokens,
500
+ "input_tokens": input_tokens,
501
+ "output_tokens": output_tokens,
502
+ "latency_ms": latency_ms,
503
+ "tool_calls": len(tool_calls or []),
504
+ }
505
+ )
506
+
507
+ if self.sft_output_dir is not None:
508
+ assistant_structured = assistant_content if assistant_content is not None else ""
509
+ assistant_text = self._content_to_text(assistant_content)
510
+ dialogue_structured: list[dict[str, Any]] = []
511
+ for content in self.latest_system_prompt_content:
512
+ if content is None:
513
+ continue
514
+ dialogue_structured.append({"role": "system", "content": content})
515
+ for content in self.latest_user_prompt_content:
516
+ if content is None:
517
+ continue
518
+ dialogue_structured.append({"role": "user", "content": content})
519
+ dialogue_text = (
520
+ [{"role": "system", "content": s} for s in self.latest_system_messages]
521
+ + [{"role": "user", "content": u} for u in self.latest_user_messages]
522
+ )
523
+ user_has_image = any(
524
+ self._content_has_image(content) for content in self.latest_user_prompt_content
525
+ )
526
+ assistant_has_image = self._content_has_image(assistant_structured)
527
+ record = {
528
+ "run_id": self.run_id,
529
+ "turn": self.current_turn,
530
+ "model": model_name,
531
+ "provider": provider,
532
+ "dialogue": dialogue_structured,
533
+ "dialogue_text": dialogue_text,
534
+ "assistant": {
535
+ "content": assistant_structured,
536
+ "content_text": assistant_text,
537
+ "tool_calls": assistant_message.get("tool_calls")
538
+ if isinstance(assistant_message, dict)
539
+ else [],
540
+ "has_image": assistant_has_image,
541
+ },
542
+ "metadata": {
543
+ "user_has_image": user_has_image,
544
+ "assistant_has_image": assistant_has_image,
545
+ "has_image": user_has_image or assistant_has_image,
546
+ },
547
+ "timestamp": datetime.utcnow().isoformat(),
548
+ }
549
+ self.sft_records.append(record)
550
+
551
+ async def record_environment_event(
552
+ self,
553
+ *,
554
+ env_handle: Any,
555
+ prev_obs: dict[str, Any] | None,
556
+ env_response: Any,
557
+ next_obs: dict[str, Any] | None,
558
+ metadata: dict[str, Any] | None = None,
559
+ ) -> int | None:
560
+ if not self.enabled or self.tracer is None:
561
+ return None
562
+
563
+ try:
564
+ prev_summary = (
565
+ _summarize_observation_for_storage(env_handle, prev_obs or {})
566
+ if prev_obs is not None
567
+ else None
568
+ )
569
+ except Exception:
570
+ prev_summary = None
571
+ try:
572
+ next_summary = (
573
+ _summarize_observation_for_storage(env_handle, next_obs or {})
574
+ if next_obs is not None
575
+ else None
576
+ )
577
+ except Exception:
578
+ next_summary = None
579
+
580
+ reward_val = getattr(env_response, "reward", None)
581
+ try:
582
+ reward_float = float(reward_val) if reward_val is not None else 0.0
583
+ except Exception:
584
+ reward_float = 0.0
585
+
586
+ event = EnvironmentEvent(
587
+ system_instance_id=f"environment:{self.env_name or 'unknown'}",
588
+ time_record=TimeRecord(event_time=datetime.utcnow().timestamp()),
589
+ reward=reward_float,
590
+ terminated=bool(getattr(env_response, "done", False)),
591
+ truncated=bool(getattr(env_response, "truncated", False)),
592
+ system_state_before=prev_summary,
593
+ system_state_after=next_summary,
594
+ metadata={
595
+ "turn": self.current_turn,
596
+ "run_id": self.run_id,
597
+ **(metadata or {}),
598
+ },
599
+ )
600
+
601
+ return await self._record_event(event)
602
+
603
+ async def record_decision_reward(
604
+ self,
605
+ *,
606
+ event_id: int | None,
607
+ decision_meta: dict[str, Any] | None,
608
+ ) -> None:
609
+ decision_meta = decision_meta or {}
610
+ ach_delta = int(decision_meta.get("ach_delta", 0))
611
+ unique_delta = int(decision_meta.get("unique_delta", 0))
612
+ all_ach = list(decision_meta.get("all") or [])
613
+ unique_ach = list(decision_meta.get("unique") or [])
614
+
615
+ self.decision_rewards.append(
616
+ {
617
+ "turn": self.current_turn,
618
+ "ach_delta": ach_delta,
619
+ "unique_delta": unique_delta,
620
+ "achievements": all_ach,
621
+ "unique_achievements": unique_ach,
622
+ }
623
+ )
624
+
625
+ if not self.enabled or self.tracer is None or event_id is None:
626
+ return
627
+ try:
628
+ await self.tracer.record_event_reward(
629
+ event_id=event_id,
630
+ turn_number=self.current_turn,
631
+ reward_value=float(ach_delta),
632
+ reward_type="achievement_delta",
633
+ annotation={"achievements": all_ach},
634
+ source="environment",
635
+ )
636
+ if unique_delta:
637
+ await self.tracer.record_event_reward(
638
+ event_id=event_id,
639
+ turn_number=self.current_turn,
640
+ reward_value=float(unique_delta),
641
+ reward_type="unique_achievement_delta",
642
+ annotation={"achievements": unique_ach},
643
+ source="environment",
644
+ )
645
+ except Exception as exc:
646
+ logger.debug("TRACING_REWARD_FAIL: %s", exc)
647
+
648
+ def update_metadata(self, **kwargs: Any) -> None:
649
+ self.metadata_updates.update({k: v for k, v in kwargs.items() if v is not None})
650
+
651
+ async def finalize(
652
+ self,
653
+ *,
654
+ total_reward: float,
655
+ achievement_state: dict[str, bool] | None,
656
+ total_steps: int,
657
+ ) -> Any:
658
+ final_achievements = [key for key, val in (achievement_state or {}).items() if val]
659
+ self.metadata_updates.setdefault("final_achievements", final_achievements)
660
+ if self.enabled and self.tracer is not None:
661
+ try:
662
+ await self.tracer.record_outcome_reward(
663
+ total_reward=int(total_reward),
664
+ achievements_count=len(final_achievements),
665
+ total_steps=int(total_steps),
666
+ reward_metadata=dict(self.metadata_updates),
667
+ )
668
+ except Exception as exc:
669
+ logger.debug("TRACING_OUTCOME_FAIL: %s", exc)
670
+ try:
671
+ self.session_trace = await self.tracer.end_session()
672
+ if self.session_trace is not None:
673
+ self.session_trace.metadata.update(self.metadata_updates)
674
+ except Exception as exc:
675
+ logger.debug("TRACING_END_SESSION_FAIL: %s", exc)
676
+ self.session_trace = None
677
+ with contextlib.suppress(Exception):
678
+ await self.tracer.close()
679
+
680
+ if self.sft_records and self.sft_output_dir:
681
+ self.write_sft_records()
682
+
683
+ # Clear context from request state to avoid leaks
684
+ self.fastapi_request.state.rollout_tracing = None
685
+
686
+ return self.session_trace
687
+
688
+ def write_sft_records(self) -> None:
689
+ if not self.sft_output_dir or not self.sft_records:
690
+ return
691
+ try:
692
+ path = unique_sft_path(self.sft_output_dir, run_id=self.run_id)
693
+ path.parent.mkdir(parents=True, exist_ok=True)
694
+ with path.open("w", encoding="utf-8") as fh:
695
+ for record in self.sft_records:
696
+ json.dump(record, fh, ensure_ascii=False)
697
+ fh.write("\n")
698
+ logger.info(f"SFT_WRITTEN: {path}")
699
+ except Exception as exc:
700
+ logger.warning(f"SFT_WRITE_FAIL: {exc}")
701
+ finally:
702
+ self.sft_records.clear()
703
+
704
+ def build_trace_payload(self, session_trace: Any) -> dict[str, Any] | None:
705
+ if not self.return_trace or session_trace is None:
706
+ return None
707
+ if self.trace_format == "full":
708
+ payload = session_trace.to_dict()
709
+ payload.setdefault("metadata", {}).update(self.metadata_updates)
710
+ return payload
711
+ metadata = dict(session_trace.metadata)
712
+ metadata.update(self.metadata_updates)
713
+ return {
714
+ "session_id": session_trace.session_id,
715
+ "created_at": session_trace.created_at.isoformat(),
716
+ "metadata": metadata,
717
+ "events_count": len(session_trace.event_history),
718
+ "messages_count": len(session_trace.markov_blanket_message_history),
719
+ "lm_calls": self.lm_calls_summary,
720
+ "decision_rewards": self.decision_rewards,
721
+ }
722
+
723
+
724
+ def _summarize_observation_for_storage(
725
+ env_handle: Any, observation: dict[str, Any]
726
+ ) -> dict[str, Any]:
727
+ """Return a compact dict for trajectory storage instead of the raw observation.
728
+
729
+ - For Crafter, use the same summary used for the policy user prompt
730
+ - For others, keep a minimal subset or plain text preview
731
+ """
732
+ # Try Crafter-specific formatter
733
+ crafter_wrapper = None
734
+ with contextlib.suppress(Exception):
735
+ from .envs.crafter.environment import (
736
+ CrafterEnvironmentWrapper as _CrafterWrapper, # type: ignore
737
+ )
738
+
739
+ crafter_wrapper = _CrafterWrapper # type: ignore[assignment]
740
+
741
+ if crafter_wrapper is not None and isinstance(
742
+ getattr(env_handle, "env", None), crafter_wrapper
743
+ ):
744
+ with contextlib.suppress(Exception):
745
+ from .envs.crafter.shared import format_observation as _fmt # type: ignore
746
+
747
+ text = _fmt(observation or {})
748
+ return {"text": text}
749
+
750
+ # Generic fallback: extract a few small fields if present; avoid huge arrays
751
+ with contextlib.suppress(Exception):
752
+ inv = observation.get("inventory") if isinstance(observation, dict) else None
753
+ ach = observation.get("achievements_status") if isinstance(observation, dict) else None
754
+ pos = observation.get("player_position") if isinstance(observation, dict) else None
755
+ health = None
756
+ if isinstance(inv, dict):
757
+ health = inv.get("health")
758
+ summary = {
759
+ "position": pos,
760
+ "health": health,
761
+ "inventory_keys": sorted(k for k, v in (inv or {}).items() if v)[:10]
762
+ if isinstance(inv, dict)
763
+ else None,
764
+ "achievements_unlocked": sorted(k for k, v in (ach or {}).items() if v)[:10]
765
+ if isinstance(ach, dict)
766
+ else None,
767
+ }
768
+ return {"text": json.dumps(summary, ensure_ascii=False)}
769
+
770
+ # Last resort: plain string preview
771
+ try:
772
+ return {"text": str(observation)[:10000]}
773
+ except Exception:
774
+ return {"text": ""}
775
+
776
+
777
+ class RunAbortRequest(BaseModel):
778
+ run_id: str
779
+
780
+
781
+ class RunAbortResponse(BaseModel):
782
+ ok: bool
783
+ run_id: str
784
+
785
+
786
+ class RunStatusResponse(BaseModel):
787
+ run_id: str
788
+ status: str
789
+ started_at: datetime
790
+ finished_at: datetime | None = None
791
+
792
+
793
+ @router.post("/rollout", response_model=RolloutResponse)
794
+ async def execute_rollout(
795
+ request: RolloutRequest,
796
+ req: Request,
797
+ ) -> RolloutResponse:
798
+ """Execute a rollout with coordinated environment and policy steps."""
799
+ # Emit rollout identifier early for correlation
800
+ with contextlib.suppress(Exception):
801
+ _rid = getattr(request, "run_id", None)
802
+ _pol = getattr(request.policy, "policy_name", None) or getattr(request.policy, "policy_id", None)
803
+ _env = getattr(request.env, "env_name", None) or getattr(request.env, "env_id", None)
804
+ logger.info("ROLLOUT_BEGIN: run_id=%s policy=%s env=%s", _rid, _pol, _env)
805
+ print(f"[rollout] begin run_id={_rid} policy={_pol} env={_env}", flush=True)
806
+ # Enforce per-episode step cap via env-specific parameters; default to 20 if omitted
807
+ try:
808
+ _env_params = {}
809
+ if isinstance(request.env, RolloutEnvSpec) and isinstance(request.env.config, dict):
810
+ _env_params = dict(request.env.config.get("env_params") or {})
811
+ max_steps_per_episode = int(_env_params.get("max_steps_per_episode") or 20)
812
+ assert max_steps_per_episode > 0, "max_steps_per_episode must be a positive integer"
813
+ except Exception as _mse:
814
+ raise HTTPException(
815
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
816
+ detail={
817
+ "error": "invalid_env_params",
818
+ "message": f"Invalid or missing env_params.max_steps_per_episode: {_mse}",
819
+ },
820
+ ) from _mse
821
+ # Truncate incoming ops to the enforced cap (each step is [agent, env])
822
+ ops_seq: list[str] = list(request.ops or [])
823
+ allowed_ops = max(0, int(max_steps_per_episode) * 2)
824
+ if len(ops_seq) > allowed_ops:
825
+ with contextlib.suppress(Exception):
826
+ logger.info(
827
+ "ROLL_OUT: truncating ops to cap: requested_ops=%s allowed_ops=%s",
828
+ str(len(ops_seq)),
829
+ str(allowed_ops),
830
+ )
831
+ ops_seq = ops_seq[:allowed_ops]
832
+ # Simple API key auth for inbound rollout
833
+ header_key = req.headers.get("x-api-key")
834
+ env_key = os.getenv("ENVIRONMENT_API_KEY")
835
+ dev_key = os.getenv("DEV_ENVIRONMENT_API_KEY")
836
+ # Accept either ENVIRONMENT_API_KEY or DEV_ENVIRONMENT_API_KEY
837
+ expected_keys = [k for k in (env_key, dev_key) if k]
838
+ if not expected_keys:
839
+ missing = []
840
+ if not env_key:
841
+ missing.append("ENVIRONMENT_API_KEY")
842
+ if not dev_key:
843
+ missing.append("DEV_ENVIRONMENT_API_KEY")
844
+ msg = f"Auth not configured: missing {', '.join(missing)} in task service environment"
845
+ logger.error(msg)
846
+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=msg)
847
+ if not header_key:
848
+ raise HTTPException(
849
+ status_code=status.HTTP_401_UNAUTHORIZED,
850
+ detail="Invalid or missing API key: X-API-Key header not provided",
851
+ )
852
+ if header_key not in expected_keys:
853
+ # Do not leak secrets; include short prefix for diagnostics
854
+ exp_src = env_key if env_key else (dev_key or "")
855
+ exp_prefix = (exp_src[:7] + "…") if len(exp_src) >= 7 else "set"
856
+ got_prefix = (header_key[:7] + "…") if len(header_key) >= 7 else "set"
857
+ raise HTTPException(
858
+ status_code=status.HTTP_401_UNAUTHORIZED,
859
+ detail=f"Invalid API key: header does not match expected (got={got_prefix}, expected_prefix={exp_prefix})",
860
+ )
861
+
862
+ # Log contextual fields for traceability
863
+ if request.training_session_id:
864
+ logger.info(f"ROLL_OUT: training_session_id={request.training_session_id}")
865
+ if request.synth_base_url:
866
+ logger.info(f"ROLL_OUT: synth_base_url={request.synth_base_url}")
867
+
868
+ # Log masked OpenAI API key presence for diagnostics
869
+ with contextlib.suppress(Exception):
870
+ _oa = os.getenv("OPENAI_API_KEY")
871
+ if _oa:
872
+ _pref = (_oa[:6] + "…") if len(_oa) >= 6 else "set"
873
+ logger.info(f"ROLL_OUT: OPENAI_API_KEY present (prefix={_pref})")
874
+ else:
875
+ logger.warning("ROLL_OUT: OPENAI_API_KEY missing")
876
+
877
+ # Make synth_base_url available for outbound calls in this app
878
+ with contextlib.suppress(Exception):
879
+ task_app = req.app.state.task_app
880
+ if request.synth_base_url:
881
+ task_app.synth_base_url = request.synth_base_url
882
+
883
+ tracer_factory = getattr(req.app.state, "session_tracer_factory", None)
884
+ tracer_instance: SessionTracer | None = None
885
+ if callable(tracer_factory):
886
+ try:
887
+ inst = tracer_factory()
888
+ tracer_instance = inst if isinstance(inst, SessionTracer) else None
889
+ except Exception as exc:
890
+ logger.debug(f"TRACER_FACTORY_FAIL: {exc}")
891
+ tracing_context = RolloutTracingContext(tracer_instance, request, req)
892
+ await tracing_context.start_session()
893
+
894
+ # Register run
895
+ registry.register_run(request.run_id)
896
+
897
+ # Track resources created during this rollout so we can guarantee cleanup
898
+ created_env_id: str | None = None
899
+ created_policy_id: str | None = None
900
+ env_seed_used: int | None = None
901
+ trajectory_steps: list[RolloutStep] = []
902
+ decision_samples: list[dict[str, Any]] = []
903
+ pending_tool_calls: Any = None
904
+ current_obs: Any = {}
905
+ total_reward: float = 0.0
906
+ ops_executed = 0
907
+ last_agent_response_ts: float | None = None
908
+ last_policy_meta: dict[str, Any] | None = None
909
+ last_env_step_ms: float | None = None
910
+ last_env_step_completed_ts: float | None = None
911
+ decision_open = False
912
+ finalized = False
913
+ prev_achievements: dict[str, bool] = {}
914
+ session_trace = None
915
+ step_rewards_active = False
916
+
917
+ try:
918
+ # Initialize deterministic seed early for the entire rollout
919
+ seed_value: int | None = None
920
+ try:
921
+ if request.env and request.env.seed is not None:
922
+ seed_value = int(request.env.seed)
923
+ else:
924
+ # Derive a stable seed from run_id
925
+ import hashlib as _hashlib # local import to avoid global deps
926
+
927
+ _digest = _hashlib.sha256(request.run_id.encode("utf-8")).hexdigest()
928
+ # Use lower 32 bits to fit common RNG ranges
929
+ seed_value = int(_digest[:8], 16)
930
+ except Exception:
931
+ # Fallback to time-based seed if anything goes wrong
932
+ try:
933
+ seed_value = int((_time.time_ns() // 1_000_000) % (2**31 - 1))
934
+ except Exception:
935
+ seed_value = 42
936
+
937
+ _seed_info = _set_global_seed(int(seed_value))
938
+ with contextlib.suppress(Exception):
939
+ logger.info(
940
+ "ROLL_OUT: RNG seeded seed=%s libs=%s",
941
+ str(_seed_info.get("seed")),
942
+ ",".join(_seed_info.get("libs", [])),
943
+ )
944
+ # Resolve or create environment
945
+ if request.env.env_id:
946
+ env_handle = registry.get_env(request.env.env_id)
947
+ if not env_handle:
948
+ raise HTTPException(
949
+ status_code=404,
950
+ detail=f"Environment {request.env.env_id} not found",
951
+ )
952
+ env_id = request.env.env_id
953
+ else:
954
+ # Create new environment
955
+ from .environment_routes import EnvCreateRequest, create_environment
956
+
957
+ if not request.env.env_name:
958
+ raise ValueError("FATAL: env_name is required - NO FALLBACKS!")
959
+
960
+ # Propagate training_session_id via env config for downstream usage
961
+ _env_config = dict(request.env.config or {})
962
+ if request.training_session_id is not None:
963
+ _env_config.setdefault("training_session_id", request.training_session_id)
964
+ env_response = await create_environment(
965
+ EnvCreateRequest(
966
+ env_name=request.env.env_name,
967
+ config=_env_config,
968
+ seed=request.env.seed,
969
+ rl_run_id=request.run_id,
970
+ )
971
+ )
972
+ env_id = env_response.env_id
973
+ env_handle = registry.get_env(env_id)
974
+ created_env_id = env_id
975
+
976
+ tracing_context.update_metadata(env_id=env_id)
977
+
978
+ # Resolve or create policy
979
+ if request.policy.policy_id:
980
+ policy_handle = registry.get_policy(request.policy.policy_id)
981
+ if not policy_handle:
982
+ raise HTTPException(
983
+ status_code=404,
984
+ detail=f"Policy {request.policy.policy_id} not found",
985
+ )
986
+ policy_id = request.policy.policy_id
987
+ else:
988
+ # Create new policy
989
+ from .policy_routes import PolicyCreateRequest, create_policy
990
+
991
+ if not request.policy.policy_name:
992
+ raise ValueError("FATAL: policy_name is required - NO FALLBACKS!")
993
+
994
+ # Propagate training_session_id and synth_base_url via policy config
995
+ _policy_config = dict(request.policy.config or {})
996
+ if request.training_session_id is not None:
997
+ _policy_config.setdefault("training_session_id", request.training_session_id)
998
+ if request.synth_base_url is not None:
999
+ _policy_config.setdefault("synth_base_url", request.synth_base_url)
1000
+ policy_response = await create_policy(
1001
+ PolicyCreateRequest(
1002
+ policy_name=request.policy.policy_name,
1003
+ config=_policy_config,
1004
+ rl_run_id=request.run_id,
1005
+ bound_env_id=env_id,
1006
+ ),
1007
+ req,
1008
+ )
1009
+ policy_id = policy_response.policy_id
1010
+ policy_handle = registry.get_policy(policy_id)
1011
+ created_policy_id = policy_id
1012
+
1013
+ tracing_context.update_metadata(policy_id=policy_id)
1014
+
1015
+ # Bind policy to environment if not already bound
1016
+ if policy_handle and not policy_handle.bound_env_id:
1017
+ policy_handle.bound_env_id = env_id
1018
+
1019
+ # Record seed bound to environment for end-of-rollout verification/logging
1020
+ try:
1021
+ env_seed_used = int(getattr(env_handle, "seed", 0) or 0)
1022
+ except Exception:
1023
+ env_seed_used = None
1024
+ tracing_context.update_metadata(env_seed=env_seed_used)
1025
+ # Initialize trajectory
1026
+ trajectory_steps = []
1027
+ pending_tool_calls = None
1028
+ current_obs = env_handle.last_observation
1029
+ total_reward = 0.0
1030
+ ops_executed = 0
1031
+ last_agent_response_ts = None
1032
+ last_policy_meta = None
1033
+ last_env_step_ms = None
1034
+ last_env_step_completed_ts = None
1035
+
1036
+ # Stepwise reward configuration (Crafter shaping; gate on explicit enable)
1037
+ step_rewards_cfg_raw: dict[str, Any] = {}
1038
+ try:
1039
+ if isinstance(request.policy.config, dict):
1040
+ step_rewards_cfg_raw = dict(request.policy.config.get("step_rewards") or {})
1041
+ except Exception:
1042
+ step_rewards_cfg_raw = {}
1043
+ if not step_rewards_cfg_raw:
1044
+ try:
1045
+ if isinstance(request.env.config, dict):
1046
+ step_rewards_cfg_raw = dict(request.env.config.get("step_rewards") or {})
1047
+ except Exception:
1048
+ step_rewards_cfg_raw = {}
1049
+
1050
+ step_rewards_enabled = bool(step_rewards_cfg_raw.get("enabled", False))
1051
+ step_rewards_mode = str(step_rewards_cfg_raw.get("mode") or "off").lower()
1052
+ try:
1053
+ step_rewards_indicator_lambda = float(
1054
+ step_rewards_cfg_raw.get("indicator_lambda") or 0.0
1055
+ )
1056
+ except Exception:
1057
+ step_rewards_indicator_lambda = 0.0
1058
+ try:
1059
+ step_rewards_beta = float(step_rewards_cfg_raw.get("step_beta") or 0.0)
1060
+ except Exception:
1061
+ step_rewards_beta = 0.0
1062
+ step_rewards_active = step_rewards_enabled and step_rewards_mode == "decision_stepwise"
1063
+
1064
+ def _extract_achievements(obs: Any) -> dict[str, bool]:
1065
+ if not isinstance(obs, dict):
1066
+ return {}
1067
+ ach = obs.get("achievements_status")
1068
+ if isinstance(ach, dict):
1069
+ return {str(k): bool(v) for k, v in ach.items()}
1070
+ return {}
1071
+
1072
+ def _summarize_tool_calls(tool_calls: Any) -> list[dict[str, Any]]:
1073
+ if not tool_calls:
1074
+ return []
1075
+ try:
1076
+ items = (
1077
+ tool_calls
1078
+ if isinstance(tool_calls, list)
1079
+ else list(tool_calls) # tolerates tuples or pydantic lists
1080
+ )
1081
+ except Exception:
1082
+ return []
1083
+ summary: list[dict[str, Any]] = []
1084
+ for tc in items:
1085
+ tool_name = None
1086
+ args: Any = {}
1087
+ if isinstance(tc, dict):
1088
+ tool_name = tc.get("tool") or tc.get("tool_name") or tc.get("name")
1089
+ raw_args = tc.get("arguments") or tc.get("args") or {}
1090
+ else:
1091
+ tool_name = getattr(tc, "tool", None) or getattr(tc, "tool_name", None)
1092
+ raw_args = getattr(tc, "arguments", None) or getattr(tc, "args", None) or {}
1093
+ args = raw_args
1094
+ if isinstance(raw_args, str):
1095
+ try:
1096
+ args = json.loads(raw_args)
1097
+ except Exception:
1098
+ args = raw_args
1099
+ summary.append({"tool": tool_name, "args": args})
1100
+ return summary
1101
+
1102
+ decision_samples: list[dict[str, Any]] = []
1103
+ decision_index = 0
1104
+ decision_open = False
1105
+ session_trace = None
1106
+ finalized = False
1107
+ prev_achievements = _extract_achievements(current_obs)
1108
+ # Track episode-level achievements that have been seen as true at any point so far
1109
+ episode_seen_achievements: set[str] = {
1110
+ k for k, v in (prev_achievements or {}).items() if bool(v)
1111
+ }
1112
+ stepwise_indicator_sum = 0.0
1113
+ stepwise_reward_sum = 0.0
1114
+ stepwise_new_achievements_total = 0
1115
+ final_achievement_count = sum(1 for v in prev_achievements.values() if v)
1116
+
1117
+ # Execute ops sequence (capped by env_params.max_steps_per_episode)
1118
+ for op_idx, op in enumerate(ops_seq):
1119
+ # Check for abort
1120
+ if registry.is_run_aborted(request.run_id):
1121
+ logger.info(f"Run {request.run_id} aborted at op {op_idx}")
1122
+ break
1123
+
1124
+ # Check safety limits
1125
+ if ops_executed >= request.safety.max_ops:
1126
+ logger.warning(f"Reached max_ops limit ({request.safety.max_ops})")
1127
+ break
1128
+
1129
+ if op == "agent":
1130
+ # Policy step
1131
+ from .policy_routes import PolicyStepRequest, step_policy
1132
+
1133
+ if not decision_open:
1134
+ await tracing_context.start_decision(decision_index)
1135
+ decision_open = True
1136
+
1137
+ agent_request_start = _time.perf_counter()
1138
+ if last_agent_response_ts is not None and last_policy_meta is not None:
1139
+ with contextlib.suppress(Exception):
1140
+ timing_prev = last_policy_meta.setdefault("timing", {})
1141
+ decision_ms = max(
1142
+ 0.0,
1143
+ (agent_request_start - float(last_agent_response_ts)) * 1000.0,
1144
+ )
1145
+ # Update timing on prior policy meta (kept by previous env step)
1146
+ timing_prev["decision_ms"] = decision_ms
1147
+ if last_env_step_ms is not None:
1148
+ timing_prev["env_step_ms"] = float(last_env_step_ms)
1149
+ timing_prev["overhead_ms"] = max(
1150
+ 0.0, decision_ms - float(last_env_step_ms)
1151
+ )
1152
+ else:
1153
+ timing_prev.setdefault("overhead_ms", 0.0)
1154
+ timing_prev["decision_ready_s"] = agent_request_start
1155
+ # Also backfill the last appended trajectory step so the trainer
1156
+ # can always see decision_ms without relying on shared dict refs.
1157
+ if trajectory_steps:
1158
+ with contextlib.suppress(Exception):
1159
+ _last = trajectory_steps[-1]
1160
+ _info = dict(_last.info or {})
1161
+ _meta = dict(_info.get("meta") or {})
1162
+ _timing = dict(_meta.get("timing") or {})
1163
+ _timing["decision_ms"] = decision_ms
1164
+ if last_env_step_ms is not None:
1165
+ _timing.setdefault("env_step_ms", float(last_env_step_ms))
1166
+ _timing.setdefault(
1167
+ "overhead_ms",
1168
+ max(0.0, decision_ms - float(last_env_step_ms)),
1169
+ )
1170
+ else:
1171
+ _timing.setdefault("overhead_ms", 0.0)
1172
+ _meta["timing"] = _timing
1173
+ _info["meta"] = _meta
1174
+ _last.info = _info
1175
+ last_env_step_ms = None
1176
+ last_env_step_completed_ts = None
1177
+
1178
+ # Build metadata for policy (carry previous tool_calls and env result)
1179
+ metadata = {}
1180
+ if pending_tool_calls:
1181
+ metadata["prev_tool_calls"] = pending_tool_calls
1182
+ if len(trajectory_steps) > 0:
1183
+ last_step = trajectory_steps[-1]
1184
+ # Prefer the last executed tool calls to seed history
1185
+ if last_step.tool_calls:
1186
+ metadata["prev_tool_calls"] = last_step.tool_calls
1187
+ # Provide a compact env result snapshot
1188
+ metadata["prev_env_result"] = {
1189
+ "observation": last_step.obs,
1190
+ "reward": last_step.reward,
1191
+ "done": last_step.done,
1192
+ "truncated": last_step.truncated,
1193
+ "info": last_step.info,
1194
+ }
1195
+
1196
+ # Log compact metadata summary to confirm history threading
1197
+ with contextlib.suppress(Exception):
1198
+ _prev_calls = metadata.get("prev_tool_calls")
1199
+ _count = len(_prev_calls) if isinstance(_prev_calls, list) else 0
1200
+ _first_guess = None
1201
+ if _count > 0 and isinstance(_prev_calls[0], dict):
1202
+ _args = _prev_calls[0].get("arguments", None)
1203
+ if isinstance(_args, str):
1204
+ import json as _json
1205
+ with contextlib.suppress(Exception):
1206
+ _args = _json.loads(_args)
1207
+ if not isinstance(_args, dict):
1208
+ _args = {}
1209
+ _first_guess = _args.get("guess") or _args.get("word")
1210
+ logger.info(
1211
+ "POLICY_METADATA: prev_tool_calls=%d first_guess=%r has_prev_env_result=%s",
1212
+ _count,
1213
+ _first_guess,
1214
+ str("prev_env_result" in metadata),
1215
+ )
1216
+
1217
+ try:
1218
+ policy_response = await step_policy(
1219
+ PolicyStepRequest(
1220
+ policy_id=policy_id,
1221
+ observation=current_obs,
1222
+ metadata=metadata,
1223
+ ),
1224
+ req,
1225
+ )
1226
+ except Exception as _pe:
1227
+ # Do not 500 the rollout; finalize with partial trajectory
1228
+ with contextlib.suppress(Exception):
1229
+ logger.warning(
1230
+ "POLICY_STEP_FAIL: terminating episode early run_id=%s op_idx=%s err=%s",
1231
+ request.run_id,
1232
+ str(op_idx),
1233
+ str(_pe),
1234
+ )
1235
+
1236
+ # Build partial trajectory and return HTTP 200
1237
+ # Extract inference_url from policy meta (best effort)
1238
+ inference_url = None
1239
+ if policy_handle is not None:
1240
+ try:
1241
+ policy_snapshot = policy_handle.snapshot()
1242
+ inference_url = policy_snapshot.get("config", {}).get("inference_url")
1243
+ except Exception:
1244
+ pass
1245
+
1246
+ trajectory = RolloutTrajectory(
1247
+ env_id=env_id,
1248
+ policy_id=policy_id,
1249
+ steps=trajectory_steps,
1250
+ final={
1251
+ "observation": current_obs,
1252
+ "rollout_status": "partial_policy_error",
1253
+ "error": str(_pe),
1254
+ "at_op": op,
1255
+ },
1256
+ length=len(trajectory_steps),
1257
+ inference_url=inference_url, # NEW: Required for trace correlation
1258
+ decision_samples=decision_samples if step_rewards_active else None,
1259
+ )
1260
+ metrics = RolloutMetrics(
1261
+ episode_returns=[total_reward],
1262
+ mean_return=total_reward,
1263
+ num_steps=len(trajectory_steps),
1264
+ num_episodes=1,
1265
+ )
1266
+ aborted = registry.is_run_aborted(request.run_id)
1267
+ if not aborted:
1268
+ registry.complete_run(request.run_id)
1269
+ if decision_open:
1270
+ await tracing_context.end_decision()
1271
+ decision_open = False
1272
+ if not finalized:
1273
+ session_trace = await tracing_context.finalize(
1274
+ total_reward=total_reward,
1275
+ achievement_state=prev_achievements,
1276
+ total_steps=len(trajectory_steps),
1277
+ )
1278
+ finalized = True
1279
+ trace_payload = tracing_context.build_trace_payload(session_trace)
1280
+ return RolloutResponse(
1281
+ run_id=request.run_id,
1282
+ trajectories=[trajectory],
1283
+ branches={},
1284
+ metrics=metrics,
1285
+ aborted=aborted,
1286
+ ops_executed=ops_executed,
1287
+ trace=trace_payload,
1288
+ )
1289
+
1290
+ agent_response_ts = _time.perf_counter()
1291
+ if isinstance(policy_response.meta, dict):
1292
+ with contextlib.suppress(Exception):
1293
+ timing_cur = policy_response.meta.setdefault("timing", {})
1294
+ timing_cur["agent_request_start_s"] = agent_request_start
1295
+ timing_cur["agent_response_s"] = agent_response_ts
1296
+ if "inference_ms" in policy_response.meta:
1297
+ with contextlib.suppress(Exception):
1298
+ timing_cur.setdefault(
1299
+ "inference_ms",
1300
+ float(policy_response.meta["inference_ms"]),
1301
+ )
1302
+ timing_cur.setdefault(
1303
+ "inference_s",
1304
+ float(policy_response.meta["inference_ms"]) / 1000.0,
1305
+ )
1306
+ last_policy_meta = policy_response.meta
1307
+ else:
1308
+ last_policy_meta = None
1309
+ last_agent_response_ts = agent_response_ts
1310
+
1311
+ # Diagnostic: summarize policy step target and tool calls
1312
+ try:
1313
+ model_name = None
1314
+ target_url = None
1315
+ if isinstance(policy_response.meta, dict):
1316
+ req_body = policy_response.meta.get("inference_request") or {}
1317
+ model_name = req_body.get("model")
1318
+ target_url = policy_response.meta.get("inference_url")
1319
+ _tc = policy_response.tool_calls or []
1320
+ print(
1321
+ {
1322
+ "rollout.policy_step": True,
1323
+ "run_id": request.run_id,
1324
+ "model": model_name,
1325
+ "inference_url": target_url,
1326
+ "tool_calls_count": len(_tc) if isinstance(_tc, list) else 0,
1327
+ },
1328
+ flush=True,
1329
+ )
1330
+ except Exception:
1331
+ pass
1332
+
1333
+ pending_tool_calls = policy_response.tool_calls
1334
+ # Log summarized agent tool calls
1335
+ with contextlib.suppress(Exception):
1336
+ _tc = pending_tool_calls or []
1337
+ _summary = []
1338
+ for _item in (_tc if isinstance(_tc, list) else []):
1339
+ try:
1340
+ if isinstance(_item, dict):
1341
+ _tool = _item.get("tool")
1342
+ _args = _item.get("args")
1343
+ _keys = list(_args.keys()) if isinstance(_args, dict) else []
1344
+ _summary.append({"tool": _tool, "args_keys": _keys})
1345
+ except Exception:
1346
+ continue
1347
+ _rid = getattr(request, "run_id", None)
1348
+ logger.info("AGENT_TOOL_CALLS: run_id=%s count=%d summary=%s", _rid, len(_tc), _summary)
1349
+ print(f"[rollout] agent tool_calls run_id={_rid} count={len(_tc)} summary={_summary}", flush=True)
1350
+ await tracing_context.record_tool_invocation(pending_tool_calls)
1351
+ ops_executed += 1
1352
+
1353
+ elif op == "env":
1354
+ if not pending_tool_calls:
1355
+ # Treat absence of tool calls as a soft terminal condition; yield partial trajectory
1356
+ with contextlib.suppress(Exception):
1357
+ logger.warning(
1358
+ "NO_TOOL_CALLS: terminating episode early run_id=%s op_idx=%s",
1359
+ request.run_id,
1360
+ str(op_idx),
1361
+ )
1362
+ print(
1363
+ f"[rollout] no tool_calls; terminating early run_id={request.run_id} op_idx={op_idx}",
1364
+ flush=True,
1365
+ )
1366
+ term_step = RolloutStep(
1367
+ obs=current_obs,
1368
+ tool_calls=[],
1369
+ reward=None,
1370
+ done=True,
1371
+ truncated=False,
1372
+ info={
1373
+ "terminated": True,
1374
+ "reason": "no_tool_calls",
1375
+ },
1376
+ )
1377
+ trajectory_steps.append(term_step)
1378
+ # Extract inference_url from policy meta (best effort)
1379
+ inference_url = None
1380
+ if policy_handle is not None:
1381
+ try:
1382
+ policy_snapshot = policy_handle.snapshot()
1383
+ inference_url = policy_snapshot.get("config", {}).get("inference_url")
1384
+ except Exception:
1385
+ pass
1386
+
1387
+ trajectory = RolloutTrajectory(
1388
+ env_id=env_id,
1389
+ policy_id=policy_id,
1390
+ steps=trajectory_steps,
1391
+ final={
1392
+ "observation": current_obs,
1393
+ "rollout_status": "partial_no_tool_calls",
1394
+ "at_op": op,
1395
+ },
1396
+ length=len(trajectory_steps),
1397
+ inference_url=inference_url, # NEW: Required for trace correlation
1398
+ decision_samples=decision_samples if step_rewards_active else None,
1399
+ )
1400
+ metrics = RolloutMetrics(
1401
+ episode_returns=[total_reward],
1402
+ mean_return=total_reward,
1403
+ num_steps=len(trajectory_steps),
1404
+ num_episodes=1,
1405
+ )
1406
+ aborted = registry.is_run_aborted(request.run_id)
1407
+ if not aborted:
1408
+ registry.complete_run(request.run_id)
1409
+ if decision_open:
1410
+ await tracing_context.end_decision()
1411
+ decision_open = False
1412
+ if not finalized:
1413
+ session_trace = await tracing_context.finalize(
1414
+ total_reward=total_reward,
1415
+ achievement_state=prev_achievements,
1416
+ total_steps=len(trajectory_steps),
1417
+ )
1418
+ finalized = True
1419
+ trace_payload = tracing_context.build_trace_payload(session_trace)
1420
+ return RolloutResponse(
1421
+ run_id=request.run_id,
1422
+ trajectories=[trajectory],
1423
+ branches={},
1424
+ metrics=metrics,
1425
+ aborted=aborted,
1426
+ ops_executed=ops_executed,
1427
+ trace=trace_payload,
1428
+ )
1429
+
1430
+ # Environment step
1431
+ from .environment_routes import EnvStepRequest, step_environment
1432
+
1433
+ env_step_error: Exception | None = None
1434
+ env_response = None
1435
+ env_step_start = _time.perf_counter()
1436
+ try:
1437
+ env_response = await step_environment(
1438
+ EnvStepRequest(
1439
+ env_id=env_id,
1440
+ tool_calls=pending_tool_calls,
1441
+ )
1442
+ )
1443
+ except Exception as _ee:
1444
+ env_step_error = _ee
1445
+ env_step_end = _time.perf_counter()
1446
+ env_step_duration_ms = (env_step_end - env_step_start) * 1000.0
1447
+ last_env_step_ms = env_step_duration_ms
1448
+ last_env_step_completed_ts = env_step_end
1449
+ if last_policy_meta is not None:
1450
+ with contextlib.suppress(Exception):
1451
+ timing_env = last_policy_meta.setdefault("timing", {})
1452
+ timing_env["env_step_ms"] = env_step_duration_ms
1453
+ timing_env["env_step_end_s"] = env_step_end
1454
+
1455
+ if env_step_error is not None:
1456
+ # Invalid action or environment rejection — terminate episode early with partial trajectory
1457
+ with contextlib.suppress(Exception):
1458
+ logger.warning(
1459
+ "ENV_STEP_FAIL: terminating episode early run_id=%s op_idx=%s err=%s",
1460
+ request.run_id,
1461
+ str(op_idx),
1462
+ str(env_step_error),
1463
+ )
1464
+
1465
+ term_step = RolloutStep(
1466
+ obs=current_obs,
1467
+ tool_calls=pending_tool_calls,
1468
+ reward=None,
1469
+ done=True,
1470
+ truncated=False,
1471
+ info={
1472
+ "terminated": True,
1473
+ "reason": "invalid_action",
1474
+ "error": str(env_step_error),
1475
+ },
1476
+ )
1477
+ trajectory_steps.append(term_step)
1478
+ # Build partial response
1479
+ # Extract inference_url from policy meta (best effort)
1480
+ inference_url = None
1481
+ if policy_handle is not None:
1482
+ try:
1483
+ policy_snapshot = policy_handle.snapshot()
1484
+ inference_url = policy_snapshot.get("config", {}).get("inference_url")
1485
+ except Exception:
1486
+ pass
1487
+
1488
+ trajectory = RolloutTrajectory(
1489
+ env_id=env_id,
1490
+ policy_id=policy_id,
1491
+ steps=trajectory_steps,
1492
+ final={
1493
+ "observation": current_obs,
1494
+ "rollout_status": "partial_invalid_action",
1495
+ "error": str(env_step_error),
1496
+ "at_op": op,
1497
+ },
1498
+ length=len(trajectory_steps),
1499
+ inference_url=inference_url, # NEW: Required for trace correlation
1500
+ decision_samples=decision_samples if step_rewards_active else None,
1501
+ )
1502
+ metrics = RolloutMetrics(
1503
+ episode_returns=[total_reward],
1504
+ mean_return=total_reward,
1505
+ num_steps=len(trajectory_steps),
1506
+ num_episodes=1,
1507
+ )
1508
+ aborted = registry.is_run_aborted(request.run_id)
1509
+ if not aborted:
1510
+ registry.complete_run(request.run_id)
1511
+ if (
1512
+ last_policy_meta is not None
1513
+ and last_agent_response_ts is not None
1514
+ and "decision_ms" not in last_policy_meta.get("timing", {})
1515
+ ):
1516
+ with contextlib.suppress(Exception):
1517
+ timing_last = last_policy_meta.setdefault("timing", {})
1518
+ decision_ms = max(
1519
+ 0.0,
1520
+ (env_step_end - float(last_agent_response_ts)) * 1000.0,
1521
+ )
1522
+ timing_last["decision_ms"] = decision_ms
1523
+ timing_last.setdefault(
1524
+ "overhead_ms", max(0.0, decision_ms - env_step_duration_ms)
1525
+ )
1526
+ if decision_open:
1527
+ await tracing_context.end_decision()
1528
+ decision_open = False
1529
+ if not finalized:
1530
+ session_trace = await tracing_context.finalize(
1531
+ total_reward=total_reward,
1532
+ achievement_state=prev_achievements,
1533
+ total_steps=len(trajectory_steps),
1534
+ )
1535
+ finalized = True
1536
+ trace_payload = tracing_context.build_trace_payload(session_trace)
1537
+ return RolloutResponse(
1538
+ run_id=request.run_id,
1539
+ trajectories=[trajectory],
1540
+ branches={},
1541
+ metrics=metrics,
1542
+ aborted=aborted,
1543
+ ops_executed=ops_executed,
1544
+ trace=trace_payload,
1545
+ )
1546
+
1547
+ # Reaching here means env step succeeded
1548
+ assert env_response is not None
1549
+
1550
+ # Record step, including policy meta if present for timing/tokens observability
1551
+ _info = env_response.info if isinstance(env_response.info, dict) else {}
1552
+ # Attach policy meta from the immediately preceding agent step
1553
+ with contextlib.suppress(Exception):
1554
+ prev_meta = {}
1555
+ if "policy_response" in locals() and isinstance(policy_response.meta, dict): # type: ignore[name-defined]
1556
+ prev_meta = policy_response.meta
1557
+ if prev_meta:
1558
+ _info = dict(_info)
1559
+ _info["meta"] = prev_meta
1560
+
1561
+ event_metadata = {
1562
+ "op_index": op_idx,
1563
+ }
1564
+ event_id = await tracing_context.record_environment_event(
1565
+ env_handle=env_handle,
1566
+ prev_obs=current_obs,
1567
+ env_response=env_response,
1568
+ next_obs=getattr(env_response, "observation", None),
1569
+ metadata=event_metadata,
1570
+ )
1571
+
1572
+ decision_index += 1
1573
+ next_obs = env_response.observation
1574
+ new_achievement_state = _extract_achievements(next_obs)
1575
+ final_achievement_count = sum(
1576
+ 1 for _, unlocked in new_achievement_state.items() if unlocked
1577
+ )
1578
+ indicator_val = 0
1579
+ reward_stepwise = 0.0
1580
+ decision_rewards_meta: dict[str, Any] | None = None
1581
+ if step_rewards_active:
1582
+ decision_actions = _summarize_tool_calls(pending_tool_calls)
1583
+ stepwise_info, decision_record, stats = compute_stepwise_reward(
1584
+ prev_achievements or {},
1585
+ new_achievement_state,
1586
+ decision_index,
1587
+ decision_actions,
1588
+ step_rewards_indicator_lambda,
1589
+ )
1590
+ indicator_val = int(stats.get("indicator", 0.0))
1591
+ reward_stepwise = float(stats.get("reward", 0.0))
1592
+ stepwise_indicator_sum += float(stats.get("indicator", 0.0))
1593
+ stepwise_reward_sum += reward_stepwise
1594
+ stepwise_new_achievements_total += int(stats.get("new_achievements_count", 0.0))
1595
+ _info = {} if not isinstance(_info, dict) else dict(_info)
1596
+ _info["stepwise"] = stepwise_info
1597
+ # Compute decision-level rewards (absolute vs unique) and attach to metadata
1598
+ with contextlib.suppress(Exception):
1599
+ turned_true = set(stepwise_info.get("new_achievements") or [])
1600
+ seen_before = set(episode_seen_achievements)
1601
+ new_unique = sorted(turned_true - seen_before)
1602
+ ach_delta = int(len(turned_true))
1603
+ unique_delta = int(len(new_unique))
1604
+ # Prepare stable lists for logging/metadata
1605
+ all_list = sorted(turned_true)
1606
+ # Ensure nested meta exists
1607
+ meta_block = (
1608
+ _info.get("meta") if isinstance(_info.get("meta"), dict) else {}
1609
+ )
1610
+ decision_rewards = {
1611
+ "turn": int(decision_index),
1612
+ "ach_delta": ach_delta,
1613
+ "unique_delta": unique_delta,
1614
+ "all": all_list,
1615
+ "unique": new_unique,
1616
+ }
1617
+ decision_rewards_meta = decision_rewards
1618
+ meta_block["decision_rewards"] = decision_rewards
1619
+ _info["meta"] = meta_block
1620
+ # Update episode-level seen set after attributing uniqueness to this decision
1621
+ episode_seen_achievements.update(turned_true)
1622
+ decision_samples.append(decision_record)
1623
+ prev_achievements = new_achievement_state
1624
+
1625
+ await tracing_context.record_decision_reward(
1626
+ event_id=event_id,
1627
+ decision_meta=decision_rewards_meta,
1628
+ )
1629
+
1630
+ step = RolloutStep(
1631
+ obs=_summarize_observation_for_storage(env_handle, current_obs),
1632
+ tool_calls=pending_tool_calls,
1633
+ reward=env_response.reward,
1634
+ done=env_response.done,
1635
+ truncated=env_response.truncated,
1636
+ info=_info,
1637
+ )
1638
+ # Log summarized env application of tool calls and immediate reward/done
1639
+ with contextlib.suppress(Exception):
1640
+ _tc = pending_tool_calls or []
1641
+ _summary = []
1642
+ for _item in (_tc if isinstance(_tc, list) else []):
1643
+ try:
1644
+ if isinstance(_item, dict):
1645
+ _tool = _item.get("tool")
1646
+ _args = _item.get("args")
1647
+ _keys = list(_args.keys()) if isinstance(_args, dict) else []
1648
+ _summary.append({"tool": _tool, "args_keys": _keys})
1649
+ except Exception:
1650
+ continue
1651
+ _rid = getattr(request, "run_id", None)
1652
+ logger.info(
1653
+ "ENV_APPLY: run_id=%s tool_calls=%d reward=%s done=%s summary=%s",
1654
+ _rid,
1655
+ len(_tc),
1656
+ str(env_response.reward),
1657
+ str(env_response.done),
1658
+ _summary,
1659
+ )
1660
+ print(
1661
+ f"[rollout] env apply run_id={_rid} tool_calls={len(_tc)} reward={env_response.reward} done={env_response.done} summary={_summary}",
1662
+ flush=True,
1663
+ )
1664
+ trajectory_steps.append(step)
1665
+
1666
+ if env_response.reward is not None:
1667
+ total_reward += env_response.reward
1668
+
1669
+ # Update state
1670
+ current_obs = next_obs
1671
+ pending_tool_calls = None
1672
+ ops_executed += 1
1673
+
1674
+ # Handle episode end
1675
+ if env_response.done:
1676
+ if request.on_done == "reset":
1677
+ # Reset environment
1678
+ from .environment_routes import (
1679
+ EnvResetRequest,
1680
+ reset_environment,
1681
+ )
1682
+
1683
+ reset_response = await reset_environment(EnvResetRequest(env_id=env_id))
1684
+ current_obs = reset_response.observation
1685
+ elif request.on_done == "terminate":
1686
+ break
1687
+
1688
+ if decision_open:
1689
+ await tracing_context.end_decision()
1690
+ decision_open = False
1691
+
1692
+ else:
1693
+ logger.warning(f"Unknown op: {op}")
1694
+
1695
+ if (
1696
+ last_policy_meta is not None
1697
+ and last_agent_response_ts is not None
1698
+ and "timing" in last_policy_meta
1699
+ and isinstance(last_policy_meta["timing"], dict)
1700
+ and "decision_ms" not in last_policy_meta["timing"]
1701
+ ):
1702
+ with contextlib.suppress(Exception):
1703
+ final_now = last_env_step_completed_ts or _time.perf_counter()
1704
+ final_decision_ms = max(0.0, (final_now - float(last_agent_response_ts)) * 1000.0)
1705
+ timing_final = last_policy_meta.setdefault("timing", {})
1706
+ timing_final["decision_ms"] = final_decision_ms
1707
+ if last_env_step_ms is not None:
1708
+ timing_final.setdefault("env_step_ms", float(last_env_step_ms))
1709
+ timing_final.setdefault(
1710
+ "overhead_ms",
1711
+ max(0.0, final_decision_ms - float(last_env_step_ms)),
1712
+ )
1713
+ else:
1714
+ timing_final.setdefault("overhead_ms", 0.0)
1715
+
1716
+ # Build trajectory
1717
+ # Extract inference_url from policy meta
1718
+ inference_url = None
1719
+ if policy_handle is not None:
1720
+ try:
1721
+ policy_snapshot = policy_handle.snapshot()
1722
+ inference_url = policy_snapshot.get("config", {}).get("inference_url")
1723
+ except Exception:
1724
+ pass
1725
+
1726
+ trajectory = RolloutTrajectory(
1727
+ env_id=env_id,
1728
+ policy_id=policy_id,
1729
+ steps=trajectory_steps,
1730
+ final={"observation": _summarize_observation_for_storage(env_handle, current_obs)},
1731
+ length=len(trajectory_steps),
1732
+ inference_url=inference_url, # NEW: Required for trace correlation
1733
+ decision_samples=decision_samples if step_rewards_active else None,
1734
+ )
1735
+
1736
+ # Build metrics
1737
+ metrics = RolloutMetrics(
1738
+ episode_returns=[total_reward],
1739
+ mean_return=total_reward,
1740
+ num_steps=len(trajectory_steps),
1741
+ num_episodes=1,
1742
+ )
1743
+
1744
+ # Environment-specific: Log summary if available
1745
+ try:
1746
+ # Check if this is a Wordle environment and use Wordle helpers (lazy import)
1747
+ wordle_wrapper_cls = None
1748
+ try:
1749
+ from .envs.wordle.environment import WordleEnvironmentWrapper
1750
+ from .envs.wordle.helpers import (
1751
+ get_wordle_rollout_summary,
1752
+ log_wordle_rollout_summary,
1753
+ )
1754
+
1755
+ wordle_wrapper_cls = WordleEnvironmentWrapper
1756
+ except Exception:
1757
+ wordle_wrapper_cls = None # type: ignore[assignment]
1758
+ get_wordle_rollout_summary = None # type: ignore
1759
+ log_wordle_rollout_summary = None # type: ignore
1760
+
1761
+ is_wordle = wordle_wrapper_cls is not None and isinstance(
1762
+ env_handle.env,
1763
+ wordle_wrapper_cls, # type: ignore[arg-type]
1764
+ )
1765
+ if is_wordle:
1766
+ # Convert trajectory steps to expected format
1767
+ formatted_steps = []
1768
+ for step in trajectory_steps:
1769
+ formatted_steps.append({"tool_calls": step.tool_calls or []})
1770
+
1771
+ if (
1772
+ get_wordle_rollout_summary is not None
1773
+ and log_wordle_rollout_summary is not None
1774
+ ):
1775
+ summary = get_wordle_rollout_summary(formatted_steps, current_obs, env_handle)
1776
+ log_wordle_rollout_summary(request.run_id, summary)
1777
+ except ImportError:
1778
+ # Wordle helpers not available, skip Wordle-specific logging
1779
+ pass
1780
+ except Exception as e:
1781
+ logger.warning(f"Failed to generate environment-specific summary: {e}")
1782
+
1783
+ # Mark run as completed
1784
+ aborted = registry.is_run_aborted(request.run_id)
1785
+ if not aborted:
1786
+ registry.complete_run(request.run_id)
1787
+ if decision_open:
1788
+ await tracing_context.end_decision()
1789
+ decision_open = False
1790
+ if not finalized:
1791
+ session_trace = await tracing_context.finalize(
1792
+ total_reward=total_reward,
1793
+ achievement_state=prev_achievements,
1794
+ total_steps=len(trajectory_steps),
1795
+ )
1796
+ finalized = True
1797
+ trace_payload = tracing_context.build_trace_payload(session_trace)
1798
+
1799
+ return RolloutResponse(
1800
+ run_id=request.run_id,
1801
+ trajectories=[trajectory],
1802
+ branches={},
1803
+ metrics=metrics,
1804
+ aborted=aborted,
1805
+ ops_executed=ops_executed,
1806
+ trace=trace_payload,
1807
+ )
1808
+
1809
+ except Exception as e:
1810
+ logger.error(f"Rollout failed for run {request.run_id}: {e}")
1811
+ registry.abort_run(request.run_id)
1812
+ if decision_open:
1813
+ with contextlib.suppress(Exception):
1814
+ await tracing_context.end_decision()
1815
+ decision_open = False
1816
+ if not finalized:
1817
+ session_trace = None
1818
+ with contextlib.suppress(Exception):
1819
+ session_trace = await tracing_context.finalize(
1820
+ total_reward=total_reward,
1821
+ achievement_state=prev_achievements,
1822
+ total_steps=len(trajectory_steps),
1823
+ )
1824
+ finalized = True
1825
+ raise HTTPException(status_code=500, detail=str(e)) from e
1826
+ finally:
1827
+ # Ensure any environment created for this rollout is terminated (no reuse across rollouts)
1828
+ try:
1829
+ if created_env_id:
1830
+ from .environment_routes import EnvTerminateRequest, terminate_environment
1831
+
1832
+ await terminate_environment(EnvTerminateRequest(env_id=created_env_id))
1833
+ logger.info(
1834
+ "ROLL_OUT: terminated environment env_id=%s seed=%s",
1835
+ str(created_env_id),
1836
+ str(env_seed_used) if env_seed_used is not None else "unknown",
1837
+ )
1838
+ # Verify removal from registry
1839
+ with contextlib.suppress(Exception):
1840
+ _post = registry.get_env(created_env_id)
1841
+ logger.info(
1842
+ "ROLL_OUT: env_killed=%s (post_lookup=%s)",
1843
+ str(_post is None),
1844
+ str(_post),
1845
+ )
1846
+ except Exception as _te:
1847
+ logger.warning(f"ROLL_OUT: failed to terminate environment {created_env_id}: {_te}")
1848
+
1849
+ # Best-effort policy cleanup if we created one (avoid reuse across rollouts)
1850
+ with contextlib.suppress(Exception):
1851
+ if created_policy_id:
1852
+ from .policy_routes import PolicyTerminateRequest, terminate_policy
1853
+
1854
+ await terminate_policy(PolicyTerminateRequest(policy_id=created_policy_id))
1855
+ logger.info("ROLL_OUT: terminated policy policy_id=%s", str(created_policy_id))
1856
+
1857
+ if not finalized:
1858
+ session_trace = None
1859
+ with contextlib.suppress(Exception):
1860
+ session_trace = await tracing_context.finalize(
1861
+ total_reward=total_reward,
1862
+ achievement_state=prev_achievements,
1863
+ total_steps=len(trajectory_steps),
1864
+ )
1865
+ finalized = True
1866
+
1867
+ with contextlib.suppress(Exception):
1868
+ _clear_seed_side_effects()
1869
+ logger.info("ROLL_OUT: RNG seed terminated/cleared before conclusion")
1870
+
1871
+
1872
+ @router.post("/run/abort", response_model=RunAbortResponse)
1873
+ async def abort_run(request: RunAbortRequest) -> RunAbortResponse:
1874
+ """Abort a running rollout."""
1875
+ success = registry.abort_run(request.run_id)
1876
+
1877
+ if not success:
1878
+ raise HTTPException(
1879
+ status_code=404,
1880
+ detail=f"Run {request.run_id} not found",
1881
+ )
1882
+
1883
+ return RunAbortResponse(
1884
+ ok=True,
1885
+ run_id=request.run_id,
1886
+ )
1887
+
1888
+
1889
+ @router.get("/run/status/{run_id}", response_model=RunStatusResponse)
1890
+ async def get_run_status(run_id: str) -> RunStatusResponse:
1891
+ """Get the status of a run."""
1892
+ run_handle = registry.get_run(run_id)
1893
+
1894
+ if not run_handle:
1895
+ raise HTTPException(
1896
+ status_code=404,
1897
+ detail=f"Run {run_id} not found",
1898
+ )
1899
+
1900
+ return RunStatusResponse(
1901
+ run_id=run_id,
1902
+ status=run_handle.status,
1903
+ started_at=run_handle.started_at,
1904
+ finished_at=run_handle.finished_at,
1905
+ )