synth-ai 0.2.14__py3-none-any.whl → 0.4.4__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.

Potentially problematic release.


This version of synth-ai might be problematic. Click here for more details.

Files changed (1086) hide show
  1. synth_ai/__init__.py +25 -46
  2. synth_ai/__main__.py +30 -3
  3. synth_ai/cli/__init__.py +98 -72
  4. synth_ai/cli/__main__.py +42 -0
  5. synth_ai/cli/_internal/__init__.py +5 -0
  6. synth_ai/cli/_internal/modal_wrapper.py +31 -0
  7. synth_ai/cli/_internal/storage.py +20 -0
  8. synth_ai/cli/_internal/typer_patch.py +47 -0
  9. synth_ai/cli/_internal/validate_task_app.py +29 -0
  10. synth_ai/cli/agents/__init__.py +17 -0
  11. synth_ai/cli/agents/claude.py +77 -0
  12. synth_ai/cli/agents/codex.py +265 -0
  13. synth_ai/cli/agents/opencode.py +253 -0
  14. synth_ai/cli/commands/__init__.py +18 -0
  15. synth_ai/cli/commands/artifacts/__init__.py +13 -0
  16. synth_ai/cli/commands/artifacts/client.py +119 -0
  17. synth_ai/cli/commands/artifacts/config.py +57 -0
  18. synth_ai/cli/commands/artifacts/core.py +24 -0
  19. synth_ai/cli/commands/artifacts/download.py +188 -0
  20. synth_ai/cli/commands/artifacts/export.py +186 -0
  21. synth_ai/cli/commands/artifacts/list.py +156 -0
  22. synth_ai/cli/commands/artifacts/parsing.py +250 -0
  23. synth_ai/cli/commands/artifacts/show.py +336 -0
  24. synth_ai/cli/commands/demo/__init__.py +3 -0
  25. synth_ai/cli/commands/demo/core.py +153 -0
  26. synth_ai/cli/commands/eval/__init__.py +10 -0
  27. synth_ai/cli/commands/eval/config.py +338 -0
  28. synth_ai/cli/commands/eval/core.py +258 -0
  29. synth_ai/cli/commands/eval/runner.py +704 -0
  30. synth_ai/cli/commands/eval/validation.py +60 -0
  31. synth_ai/cli/commands/filter/__init__.py +12 -0
  32. synth_ai/cli/commands/filter/core.py +424 -0
  33. synth_ai/cli/commands/filter/errors.py +55 -0
  34. synth_ai/cli/commands/filter/validation.py +77 -0
  35. synth_ai/cli/commands/help/__init__.py +185 -0
  36. synth_ai/cli/commands/help/core.py +72 -0
  37. synth_ai/cli/commands/scan/__init__.py +19 -0
  38. synth_ai/cli/commands/scan/cloudflare_scanner.py +403 -0
  39. synth_ai/cli/commands/scan/core.py +344 -0
  40. synth_ai/cli/commands/scan/health_checker.py +242 -0
  41. synth_ai/cli/commands/scan/local_scanner.py +278 -0
  42. synth_ai/cli/commands/scan/models.py +83 -0
  43. synth_ai/cli/commands/smoke/__init__.py +7 -0
  44. synth_ai/cli/commands/smoke/core.py +1428 -0
  45. synth_ai/cli/commands/status/__init__.py +3 -0
  46. synth_ai/cli/commands/status/client.py +91 -0
  47. synth_ai/cli/commands/status/config.py +12 -0
  48. synth_ai/cli/commands/status/errors.py +11 -0
  49. synth_ai/cli/commands/status/subcommands/__init__.py +3 -0
  50. synth_ai/cli/commands/status/subcommands/config.py +13 -0
  51. synth_ai/cli/commands/status/subcommands/files.py +34 -0
  52. synth_ai/cli/commands/status/subcommands/jobs.py +51 -0
  53. synth_ai/cli/commands/status/subcommands/models.py +35 -0
  54. synth_ai/cli/commands/status/subcommands/runs.py +34 -0
  55. synth_ai/cli/commands/status/subcommands/session.py +77 -0
  56. synth_ai/cli/commands/status/subcommands/summary.py +39 -0
  57. synth_ai/cli/commands/status/subcommands/utils.py +41 -0
  58. synth_ai/cli/commands/status/utils.py +23 -0
  59. synth_ai/cli/commands/train/__init__.py +51 -0
  60. synth_ai/cli/commands/train/core.py +22 -0
  61. synth_ai/cli/commands/train/errors.py +117 -0
  62. synth_ai/cli/commands/train/prompt_learning_validation.py +632 -0
  63. synth_ai/cli/commands/train/validation.py +392 -0
  64. synth_ai/cli/commands/train/verifier_schemas.py +200 -0
  65. synth_ai/cli/commands/train/verifier_validation.py +235 -0
  66. synth_ai/cli/demo_apps/__init__.py +10 -0
  67. synth_ai/cli/demo_apps/core/__init__.py +28 -0
  68. synth_ai/cli/demo_apps/core/cli.py +1735 -0
  69. synth_ai/cli/demo_apps/crafter/crafter_fft_4b.toml +55 -0
  70. synth_ai/cli/demo_apps/crafter/grpo_crafter_task_app.py +186 -0
  71. synth_ai/cli/demo_apps/crafter/rl_from_base_qwen4b.toml +74 -0
  72. synth_ai/cli/demo_apps/demo_registry.py +176 -0
  73. synth_ai/cli/demo_apps/demo_task_apps/core.py +440 -0
  74. synth_ai/cli/demo_apps/demo_task_apps/crafter/__init__.py +1 -0
  75. synth_ai/cli/demo_apps/demo_task_apps/crafter/grpo_crafter_task_app.py +185 -0
  76. synth_ai/cli/demo_apps/demo_task_apps/math/config.toml +73 -0
  77. synth_ai/cli/demo_apps/demo_task_apps/math/modal_task_app.py +738 -0
  78. synth_ai/cli/demo_apps/demo_task_apps/math/task_app_entry.py +39 -0
  79. synth_ai/cli/demo_apps/math/__init__.py +1 -0
  80. synth_ai/cli/demo_apps/math/_common.py +16 -0
  81. synth_ai/cli/demo_apps/math/app.py +38 -0
  82. synth_ai/cli/demo_apps/math/config.toml +75 -0
  83. synth_ai/cli/demo_apps/math/deploy_modal.py +54 -0
  84. synth_ai/cli/demo_apps/math/modal_task_app.py +698 -0
  85. synth_ai/cli/demo_apps/math/task_app_entry.py +53 -0
  86. synth_ai/cli/demo_apps/mipro/main.py +271 -0
  87. synth_ai/cli/demo_apps/mipro/task_app.py +911 -0
  88. synth_ai/cli/demo_apps/mipro/train_cfg.toml +92 -0
  89. synth_ai/cli/demos/__init__.py +12 -0
  90. synth_ai/cli/demos/demo.py +32 -0
  91. synth_ai/cli/demos/rl_demo.py +254 -0
  92. synth_ai/cli/deploy.py +216 -0
  93. synth_ai/cli/infra/__init__.py +14 -0
  94. synth_ai/cli/infra/balance.py +216 -0
  95. synth_ai/cli/infra/mcp.py +35 -0
  96. synth_ai/cli/infra/modal_app.py +36 -0
  97. synth_ai/cli/infra/setup.py +69 -0
  98. synth_ai/cli/infra/status.py +16 -0
  99. synth_ai/cli/infra/turso.py +77 -0
  100. synth_ai/cli/lib/__init__.py +10 -0
  101. synth_ai/cli/lib/agents.py +76 -0
  102. synth_ai/cli/lib/apps/modal_app.py +101 -0
  103. synth_ai/cli/lib/apps/task_app.py +642 -0
  104. synth_ai/cli/lib/bin.py +39 -0
  105. synth_ai/cli/lib/env.py +375 -0
  106. synth_ai/cli/lib/errors.py +85 -0
  107. synth_ai/cli/lib/modal.py +315 -0
  108. synth_ai/cli/lib/plotting.py +126 -0
  109. synth_ai/cli/lib/prompt_args.py +39 -0
  110. synth_ai/cli/lib/prompts.py +284 -0
  111. synth_ai/cli/lib/sqld.py +122 -0
  112. synth_ai/cli/lib/task_app_discovery.py +884 -0
  113. synth_ai/cli/lib/task_app_env.py +295 -0
  114. synth_ai/cli/lib/train_cfgs.py +300 -0
  115. synth_ai/cli/lib/tunnel_records.py +207 -0
  116. synth_ai/cli/local/__init__.py +14 -0
  117. synth_ai/cli/local/experiment_queue/__init__.py +72 -0
  118. synth_ai/cli/local/experiment_queue/api_schemas.py +221 -0
  119. synth_ai/cli/local/experiment_queue/celery_app.py +208 -0
  120. synth_ai/cli/local/experiment_queue/config.py +128 -0
  121. synth_ai/cli/local/experiment_queue/config_utils.py +272 -0
  122. synth_ai/cli/local/experiment_queue/database.py +175 -0
  123. synth_ai/cli/local/experiment_queue/dispatcher.py +119 -0
  124. synth_ai/cli/local/experiment_queue/models.py +231 -0
  125. synth_ai/cli/local/experiment_queue/progress_info.py +160 -0
  126. synth_ai/cli/local/experiment_queue/results.py +373 -0
  127. synth_ai/cli/local/experiment_queue/schemas.py +131 -0
  128. synth_ai/cli/local/experiment_queue/service.py +344 -0
  129. synth_ai/cli/local/experiment_queue/status.py +372 -0
  130. synth_ai/cli/local/experiment_queue/status_tracker.py +360 -0
  131. synth_ai/cli/local/experiment_queue/tasks.py +1984 -0
  132. synth_ai/cli/local/experiment_queue/trace_storage.py +65 -0
  133. synth_ai/cli/local/experiment_queue/validation.py +157 -0
  134. synth_ai/cli/local/session/__init__.py +92 -0
  135. synth_ai/cli/local/session/client.py +383 -0
  136. synth_ai/cli/local/session/constants.py +63 -0
  137. synth_ai/cli/local/session/exceptions.py +105 -0
  138. synth_ai/cli/local/session/manager.py +139 -0
  139. synth_ai/cli/local/session/models.py +89 -0
  140. synth_ai/cli/local/session/query.py +110 -0
  141. synth_ai/cli/root.py +30 -6
  142. synth_ai/cli/task_apps/__init__.py +37 -0
  143. synth_ai/cli/task_apps/commands.py +3145 -0
  144. synth_ai/cli/task_apps/deploy.py +7 -0
  145. synth_ai/cli/task_apps/list.py +26 -0
  146. synth_ai/cli/task_apps/main.py +36 -0
  147. synth_ai/cli/task_apps/modal_serve.py +11 -0
  148. synth_ai/cli/task_apps/serve.py +11 -0
  149. synth_ai/cli/training/__init__.py +8 -0
  150. synth_ai/cli/training/train.py +5 -0
  151. synth_ai/cli/training/train_cfg.py +34 -0
  152. synth_ai/cli/training/watch.py +506 -0
  153. synth_ai/cli/turso.py +34 -55
  154. synth_ai/cli/utils/__init__.py +8 -0
  155. synth_ai/cli/utils/experiments.py +235 -0
  156. synth_ai/cli/utils/queue.py +504 -0
  157. synth_ai/cli/utils/recent.py +133 -0
  158. synth_ai/cli/utils/traces.py +164 -0
  159. synth_ai/contracts/__init__.py +67 -0
  160. synth_ai/core/__init__.py +100 -0
  161. synth_ai/core/_utils/__init__.py +54 -0
  162. synth_ai/core/_utils/base_url.py +10 -0
  163. synth_ai/core/_utils/http.py +10 -0
  164. synth_ai/core/_utils/prompts.py +14 -0
  165. synth_ai/core/_utils/task_app_state.py +12 -0
  166. synth_ai/core/_utils/user_config.py +10 -0
  167. synth_ai/core/apps/common.py +116 -0
  168. synth_ai/core/auth.py +95 -0
  169. synth_ai/core/cfgs.py +240 -0
  170. synth_ai/core/config/__init__.py +16 -0
  171. synth_ai/core/config/base.py +168 -0
  172. synth_ai/core/config/resolver.py +89 -0
  173. synth_ai/core/env.py +231 -0
  174. synth_ai/core/errors.py +125 -0
  175. synth_ai/core/http.py +230 -0
  176. synth_ai/core/integrations/__init__.py +11 -0
  177. synth_ai/core/integrations/cloudflare.py +1886 -0
  178. synth_ai/core/integrations/mcp/__init__.py +6 -0
  179. synth_ai/core/integrations/mcp/__main__.py +8 -0
  180. synth_ai/core/integrations/mcp/claude.py +36 -0
  181. synth_ai/core/integrations/mcp/main.py +254 -0
  182. synth_ai/core/integrations/mcp/setup.py +100 -0
  183. synth_ai/core/integrations/modal.py +277 -0
  184. synth_ai/core/json.py +72 -0
  185. synth_ai/core/log_filter.py +99 -0
  186. synth_ai/core/logging.py +82 -0
  187. synth_ai/core/paths.py +107 -0
  188. synth_ai/core/pricing.py +109 -0
  189. synth_ai/core/process.py +233 -0
  190. synth_ai/core/ssl.py +25 -0
  191. synth_ai/core/storage/__init__.py +71 -0
  192. synth_ai/core/task_app_state.py +318 -0
  193. synth_ai/core/telemetry.py +282 -0
  194. synth_ai/core/tracing_v3/__init__.py +99 -0
  195. synth_ai/core/tracing_v3/abstractions.py +348 -0
  196. synth_ai/core/tracing_v3/config.py +229 -0
  197. synth_ai/core/tracing_v3/constants.py +21 -0
  198. synth_ai/core/tracing_v3/db_config.py +182 -0
  199. synth_ai/core/tracing_v3/decorators.py +401 -0
  200. synth_ai/core/tracing_v3/llm_call_record_helpers.py +437 -0
  201. synth_ai/core/tracing_v3/migration_helper.py +119 -0
  202. synth_ai/core/tracing_v3/session_tracer.py +542 -0
  203. synth_ai/core/tracing_v3/storage/base.py +211 -0
  204. synth_ai/core/tracing_v3/storage/config.py +109 -0
  205. synth_ai/core/tracing_v3/storage/factory.py +39 -0
  206. synth_ai/core/tracing_v3/trace_utils.py +326 -0
  207. synth_ai/core/tracing_v3/turso/daemon.py +278 -0
  208. synth_ai/core/tracing_v3/turso/models.py +470 -0
  209. synth_ai/core/tracing_v3/turso/native_manager.py +1385 -0
  210. synth_ai/core/tracing_v3/utils.py +108 -0
  211. synth_ai/core/urls.py +18 -0
  212. synth_ai/core/user_config.py +137 -0
  213. synth_ai/core/uvicorn.py +222 -0
  214. synth_ai/data/__init__.py +83 -0
  215. synth_ai/data/enums.py +122 -0
  216. synth_ai/data/rewards.py +249 -0
  217. synth_ai/data/traces.py +35 -0
  218. synth_ai/products/__init__.py +6 -0
  219. synth_ai/products/graph_evolve/__init__.py +45 -0
  220. synth_ai/products/graph_evolve/client.py +226 -0
  221. synth_ai/products/graph_evolve/config.py +591 -0
  222. synth_ai/products/graph_evolve/converters/__init__.py +42 -0
  223. synth_ai/products/graph_evolve/converters/openai_sft.py +484 -0
  224. synth_ai/products/graph_evolve/examples/hotpotqa/config.toml +109 -0
  225. synth_ai/products/graph_evolve/run.py +222 -0
  226. synth_ai/products/graph_gepa/__init__.py +23 -0
  227. synth_ai/products/graph_gepa/converters/__init__.py +19 -0
  228. synth_ai/products/graph_gepa/converters/openai_sft.py +29 -0
  229. synth_ai/sdk/__init__.py +129 -0
  230. synth_ai/sdk/api/__init__.py +1 -0
  231. synth_ai/sdk/api/eval/__init__.py +33 -0
  232. synth_ai/sdk/api/eval/job.py +732 -0
  233. synth_ai/sdk/api/models/supported.py +514 -0
  234. synth_ai/sdk/api/research_agent/__init__.py +296 -0
  235. synth_ai/sdk/api/train/__init__.py +85 -0
  236. synth_ai/sdk/api/train/builders.py +1076 -0
  237. synth_ai/sdk/api/train/cli.py +2196 -0
  238. synth_ai/sdk/api/train/config_finder.py +267 -0
  239. synth_ai/sdk/api/train/configs/__init__.py +67 -0
  240. synth_ai/sdk/api/train/configs/prompt_learning.py +1800 -0
  241. synth_ai/sdk/api/train/configs/rl.py +436 -0
  242. synth_ai/sdk/api/train/configs/sft.py +263 -0
  243. synth_ai/sdk/api/train/configs/shared.py +81 -0
  244. synth_ai/sdk/api/train/context_learning.py +312 -0
  245. synth_ai/sdk/api/train/env_resolver.py +418 -0
  246. synth_ai/sdk/api/train/graph_validators.py +216 -0
  247. synth_ai/sdk/api/train/graphgen.py +1102 -0
  248. synth_ai/sdk/api/train/graphgen_models.py +873 -0
  249. synth_ai/sdk/api/train/graphgen_validators.py +109 -0
  250. synth_ai/sdk/api/train/local_api.py +10 -0
  251. synth_ai/sdk/api/train/pollers.py +160 -0
  252. synth_ai/sdk/api/train/progress/__init__.py +97 -0
  253. synth_ai/sdk/api/train/progress/dataclasses.py +569 -0
  254. synth_ai/sdk/api/train/progress/events.py +326 -0
  255. synth_ai/sdk/api/train/progress/results.py +428 -0
  256. synth_ai/sdk/api/train/progress/tracker.py +641 -0
  257. synth_ai/sdk/api/train/prompt_learning.py +800 -0
  258. synth_ai/sdk/api/train/rl.py +478 -0
  259. synth_ai/sdk/api/train/sft.py +398 -0
  260. synth_ai/sdk/api/train/summary.py +522 -0
  261. synth_ai/sdk/api/train/supported_algos.py +147 -0
  262. synth_ai/sdk/api/train/task_app.py +351 -0
  263. synth_ai/sdk/api/train/utils.py +279 -0
  264. synth_ai/sdk/api/train/validators.py +2424 -0
  265. synth_ai/sdk/graphs/__init__.py +15 -0
  266. synth_ai/sdk/graphs/completions.py +776 -0
  267. synth_ai/sdk/graphs/verifier_schemas.py +222 -0
  268. synth_ai/sdk/inference/__init__.py +6 -0
  269. synth_ai/sdk/inference/client.py +128 -0
  270. synth_ai/sdk/jobs/__init__.py +16 -0
  271. synth_ai/sdk/jobs/client.py +371 -0
  272. synth_ai/sdk/learning/__init__.py +99 -0
  273. synth_ai/sdk/learning/client.py +240 -0
  274. synth_ai/sdk/learning/context_learning_client.py +531 -0
  275. synth_ai/sdk/learning/context_learning_types.py +294 -0
  276. synth_ai/sdk/learning/ft_client.py +7 -0
  277. synth_ai/sdk/learning/health.py +49 -0
  278. synth_ai/sdk/learning/jobs.py +202 -0
  279. synth_ai/sdk/learning/prompt_extraction.py +334 -0
  280. synth_ai/sdk/learning/prompt_learning_client.py +455 -0
  281. synth_ai/sdk/learning/prompt_learning_types.py +186 -0
  282. synth_ai/sdk/learning/rl/__init__.py +35 -0
  283. synth_ai/sdk/learning/rl/client.py +268 -0
  284. synth_ai/sdk/learning/rl/contracts.py +23 -0
  285. synth_ai/sdk/learning/rl/env_keys.py +166 -0
  286. synth_ai/sdk/learning/rl/secrets.py +13 -0
  287. synth_ai/sdk/learning/sft/client.py +95 -0
  288. synth_ai/sdk/learning/sft/config.py +270 -0
  289. synth_ai/sdk/learning/sft/data.py +698 -0
  290. synth_ai/sdk/learning/validators.py +52 -0
  291. synth_ai/sdk/localapi/__init__.py +40 -0
  292. synth_ai/sdk/localapi/apps/__init__.py +28 -0
  293. synth_ai/sdk/localapi/client.py +10 -0
  294. synth_ai/sdk/localapi/contracts.py +10 -0
  295. synth_ai/sdk/localapi/helpers.py +519 -0
  296. synth_ai/sdk/localapi/rollouts.py +93 -0
  297. synth_ai/sdk/localapi/server.py +29 -0
  298. synth_ai/sdk/localapi/template.py +49 -0
  299. synth_ai/sdk/streaming/__init__.py +35 -0
  300. synth_ai/sdk/streaming/config.py +94 -0
  301. synth_ai/sdk/streaming/handlers.py +1997 -0
  302. synth_ai/sdk/streaming/streamer.py +708 -0
  303. synth_ai/sdk/streaming/types.py +112 -0
  304. synth_ai/sdk/task/__init__.py +164 -0
  305. synth_ai/sdk/task/apps/__init__.py +169 -0
  306. synth_ai/sdk/task/client.py +175 -0
  307. synth_ai/sdk/task/config.py +256 -0
  308. synth_ai/sdk/task/contracts.py +340 -0
  309. synth_ai/sdk/task/datasets.py +108 -0
  310. synth_ai/sdk/task/in_process.py +1200 -0
  311. synth_ai/sdk/task/in_process_runner.py +314 -0
  312. synth_ai/sdk/task/inference_api.py +299 -0
  313. synth_ai/sdk/task/proxy.py +287 -0
  314. synth_ai/sdk/task/rubrics/__init__.py +54 -0
  315. synth_ai/sdk/task/rubrics/loaders.py +156 -0
  316. synth_ai/sdk/task/rubrics/strict.py +148 -0
  317. synth_ai/sdk/task/rubrics.py +219 -0
  318. synth_ai/sdk/task/server.py +640 -0
  319. synth_ai/sdk/task/trace_correlation_helpers.py +557 -0
  320. synth_ai/sdk/task/tracing_utils.py +95 -0
  321. synth_ai/sdk/task/validators.py +441 -0
  322. synth_ai/sdk/training/__init__.py +93 -0
  323. synth_ai/sdk/tunnels/__init__.py +118 -0
  324. synth_ai/sdk/tunnels/cleanup.py +83 -0
  325. synth_ai/sdk/tunnels/ports.py +120 -0
  326. synth_ai/sdk/tunnels/tunneled_api.py +363 -0
  327. synth_ai/utils/__init__.py +213 -0
  328. synth_ai-0.4.4.dist-info/METADATA +262 -0
  329. synth_ai-0.4.4.dist-info/RECORD +369 -0
  330. synth_ai-0.4.4.dist-info/top_level.txt +1 -0
  331. examples/__init__.py +0 -16
  332. examples/analyze_semantic_words.sh +0 -17
  333. examples/crafter_debug_render.py +0 -186
  334. examples/dev/qwen3_32b_qlora_4xh100.toml +0 -40
  335. examples/multi_step/configs/README_verilog_rl.md +0 -77
  336. examples/multi_step/configs/VERILOG_REWARDS.md +0 -90
  337. examples/multi_step/configs/VERILOG_RL_CHECKLIST.md +0 -183
  338. examples/multi_step/configs/crafter_eval_synth_qwen4b.toml +0 -35
  339. examples/multi_step/configs/crafter_eval_text_only_groq_qwen32b.toml +0 -36
  340. examples/multi_step/configs/crafter_rl_outcome.toml +0 -74
  341. examples/multi_step/configs/crafter_rl_stepwise_hosted_judge.toml +0 -187
  342. examples/multi_step/configs/crafter_rl_stepwise_shaped.toml +0 -83
  343. examples/multi_step/configs/crafter_rl_stepwise_simple.toml +0 -78
  344. examples/multi_step/configs/crafter_synth_backend.md +0 -40
  345. examples/multi_step/configs/verilog_eval_groq_qwen32b.toml +0 -31
  346. examples/multi_step/configs/verilog_eval_synth_qwen8b.toml +0 -33
  347. examples/multi_step/configs/verilog_rl_lora.toml +0 -190
  348. examples/multi_step/crafter_rl_lora.md +0 -70
  349. examples/multi_step/judges/crafter_backend_judge.py +0 -220
  350. examples/multi_step/judges/verilog_backend_judge.py +0 -234
  351. examples/multi_step/readme.md +0 -48
  352. examples/multi_step/sse_metrics_streaming_notes.md +0 -357
  353. examples/multi_step/task_app_config_notes.md +0 -494
  354. examples/multi_step/verilog_rl_lora.md +0 -218
  355. examples/qwen_coder/README.md +0 -102
  356. examples/qwen_coder/_shared.py +0 -113
  357. examples/qwen_coder/configs/coder_lora_30b.toml +0 -61
  358. examples/qwen_coder/configs/coder_lora_4b.toml +0 -57
  359. examples/qwen_coder/configs/coder_lora_small.toml +0 -58
  360. examples/qwen_coder/generate_dataset.py +0 -98
  361. examples/qwen_coder/infer_ft_smoke.py +0 -65
  362. examples/qwen_coder/infer_prod_proxy.py +0 -73
  363. examples/qwen_coder/infer_via_synth.py +0 -87
  364. examples/qwen_coder/scripts/infer_coder.sh +0 -19
  365. examples/qwen_coder/scripts/train_coder_30b.sh +0 -22
  366. examples/qwen_coder/sft_full_17b.py +0 -103
  367. examples/qwen_coder/sft_lora_30b.py +0 -110
  368. examples/qwen_coder/subset_jsonl.py +0 -39
  369. examples/qwen_coder/todos.md +0 -38
  370. examples/qwen_coder/validate_jsonl.py +0 -60
  371. examples/rl/README.md +0 -169
  372. examples/rl/download_dataset.py +0 -80
  373. examples/run_crafter_demo.sh +0 -10
  374. examples/sft/README.md +0 -139
  375. examples/sft/configs/crafter_fft_qwen0p6b.toml +0 -44
  376. examples/sft/configs/crafter_lora_qwen0p6b.toml +0 -45
  377. examples/sft/evaluate.py +0 -119
  378. examples/sft/export_dataset.py +0 -117
  379. examples/sft/generate_traces.py +0 -164
  380. examples/swe/__init__.py +0 -12
  381. examples/swe/task_app/README.md +0 -105
  382. examples/swe/task_app/__init__.py +0 -2
  383. examples/swe/task_app/grpo_swe_mini.py +0 -601
  384. examples/swe/task_app/grpo_swe_mini_task_app.py +0 -136
  385. examples/swe/task_app/hosted/README.md +0 -173
  386. examples/swe/task_app/hosted/__init__.py +0 -5
  387. examples/swe/task_app/hosted/branching.py +0 -143
  388. examples/swe/task_app/hosted/environment_routes.py +0 -1289
  389. examples/swe/task_app/hosted/envs/__init__.py +0 -1
  390. examples/swe/task_app/hosted/envs/crafter/__init__.py +0 -6
  391. examples/swe/task_app/hosted/envs/crafter/app.py +0 -1
  392. examples/swe/task_app/hosted/envs/crafter/environment.py +0 -522
  393. examples/swe/task_app/hosted/envs/crafter/policy.py +0 -478
  394. examples/swe/task_app/hosted/envs/crafter/react_agent.py +0 -108
  395. examples/swe/task_app/hosted/envs/crafter/shared.py +0 -305
  396. examples/swe/task_app/hosted/envs/crafter/tools.py +0 -47
  397. examples/swe/task_app/hosted/envs/mini_swe/__init__.py +0 -8
  398. examples/swe/task_app/hosted/envs/mini_swe/environment.py +0 -1164
  399. examples/swe/task_app/hosted/envs/mini_swe/policy.py +0 -355
  400. examples/swe/task_app/hosted/envs/mini_swe/shared.py +0 -83
  401. examples/swe/task_app/hosted/envs/mini_swe/tools.py +0 -96
  402. examples/swe/task_app/hosted/hosted_app.py +0 -204
  403. examples/swe/task_app/hosted/inference/__init__.py +0 -5
  404. examples/swe/task_app/hosted/inference/openai_client.py +0 -618
  405. examples/swe/task_app/hosted/main.py +0 -100
  406. examples/swe/task_app/hosted/policy_routes.py +0 -1079
  407. examples/swe/task_app/hosted/registry.py +0 -195
  408. examples/swe/task_app/hosted/rollout.py +0 -1911
  409. examples/swe/task_app/hosted/storage/__init__.py +0 -5
  410. examples/swe/task_app/hosted/storage/volume.py +0 -211
  411. examples/swe/task_app/hosted/test_agents.py +0 -161
  412. examples/swe/task_app/hosted/test_service.py +0 -136
  413. examples/swe/task_app/hosted/utils.py +0 -62
  414. examples/task_apps/IMAGE_ONLY_EVAL_QUICKSTART.md +0 -258
  415. examples/task_apps/TESTING.md +0 -275
  416. examples/task_apps/crafter/CREATE_SFT_DATASET.md +0 -273
  417. examples/task_apps/crafter/EVAL_IMAGE_ONLY_RESULTS.md +0 -152
  418. examples/task_apps/crafter/FILTER_COMMAND_STATUS.md +0 -174
  419. examples/task_apps/crafter/FILTER_COMMAND_SUCCESS.md +0 -268
  420. examples/task_apps/crafter/QUERY_EXAMPLES.md +0 -203
  421. examples/task_apps/crafter/README_IMAGE_ONLY_EVAL.md +0 -316
  422. examples/task_apps/crafter/__init__.py +0 -0
  423. examples/task_apps/crafter/eval_image_only_gpt4o.toml +0 -28
  424. examples/task_apps/crafter/eval_text_only_groq_llama.toml +0 -36
  425. examples/task_apps/crafter/filter_sft_dataset.toml +0 -16
  426. examples/task_apps/crafter/task_app/README.md +0 -42
  427. examples/task_apps/crafter/task_app/__init__.py +0 -5
  428. examples/task_apps/crafter/task_app/grpo_crafter.py +0 -973
  429. examples/task_apps/crafter/task_app/grpo_crafter_task_app.py +0 -146
  430. examples/task_apps/crafter/task_app/synth_envs_hosted/README.md +0 -173
  431. examples/task_apps/crafter/task_app/synth_envs_hosted/__init__.py +0 -5
  432. examples/task_apps/crafter/task_app/synth_envs_hosted/branching.py +0 -143
  433. examples/task_apps/crafter/task_app/synth_envs_hosted/environment_routes.py +0 -1226
  434. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/__init__.py +0 -1
  435. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/__init__.py +0 -6
  436. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/app.py +0 -1
  437. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/environment.py +0 -532
  438. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/policy.py +0 -547
  439. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/react_agent.py +0 -123
  440. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/shared.py +0 -305
  441. examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/tools.py +0 -47
  442. examples/task_apps/crafter/task_app/synth_envs_hosted/hosted_app.py +0 -204
  443. examples/task_apps/crafter/task_app/synth_envs_hosted/inference/__init__.py +0 -5
  444. examples/task_apps/crafter/task_app/synth_envs_hosted/inference/openai_client.py +0 -704
  445. examples/task_apps/crafter/task_app/synth_envs_hosted/main.py +0 -100
  446. examples/task_apps/crafter/task_app/synth_envs_hosted/policy_routes.py +0 -1152
  447. examples/task_apps/crafter/task_app/synth_envs_hosted/registry.py +0 -195
  448. examples/task_apps/crafter/task_app/synth_envs_hosted/rollout.py +0 -2160
  449. examples/task_apps/crafter/task_app/synth_envs_hosted/storage/__init__.py +0 -5
  450. examples/task_apps/crafter/task_app/synth_envs_hosted/storage/volume.py +0 -211
  451. examples/task_apps/crafter/task_app/synth_envs_hosted/test_agents.py +0 -161
  452. examples/task_apps/crafter/task_app/synth_envs_hosted/test_service.py +0 -136
  453. examples/task_apps/crafter/task_app/synth_envs_hosted/utils.py +0 -218
  454. examples/task_apps/dev/pokemon_emerald/__init__.py +0 -2
  455. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/README.md +0 -811
  456. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/__init__.py +0 -120
  457. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/action.py +0 -160
  458. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/memory.py +0 -155
  459. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/perception.py +0 -69
  460. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/planning.py +0 -96
  461. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/simple.py +0 -1502
  462. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/agent/system_prompt.py +0 -4
  463. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/grab_map.py +0 -68
  464. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/manual.py +0 -216
  465. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/__init__.py +0 -35
  466. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/emerald_utils.py +0 -631
  467. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/emulator.py +0 -1544
  468. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/enums.py +0 -1428
  469. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/memory_reader.py +0 -4848
  470. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/types.py +0 -41
  471. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pokemon_env/utils.py +0 -298
  472. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/pyproject.toml +0 -95
  473. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/run.py +0 -204
  474. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server/__init__.py +0 -0
  475. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server/app.py +0 -2152
  476. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server/client.py +0 -429
  477. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/server/frame_server.py +0 -155
  478. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/README.md +0 -78
  479. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/__init__.py +0 -0
  480. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/run_tests.py +0 -122
  481. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_agent_direct.py +0 -76
  482. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_agent_prompts.py +0 -413
  483. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_battle_state_formatting.py +0 -204
  484. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_dialogue_detection.py +0 -133
  485. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_dialogue_detection_comprehensive.py +0 -229
  486. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_direct_agent_emulator.py +0 -300
  487. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_fps_adjustment_pytest.py +0 -205
  488. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_house_to_outside_direct.py +0 -200
  489. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_house_to_outside_transition.py +0 -284
  490. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_map_ground_truth_comparison.py +0 -468
  491. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_memory_map.py +0 -575
  492. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_server_map_validation.py +0 -311
  493. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/tests/test_torchic_state.py +0 -259
  494. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/__init__.py +0 -0
  495. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/anticheat.py +0 -372
  496. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/checkpoint.py +0 -296
  497. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/error_handler.py +0 -275
  498. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/get_local_ip.py +0 -22
  499. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/helpers.py +0 -44
  500. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/llm_logger.py +0 -514
  501. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_formatter.py +0 -415
  502. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_stitcher.py +0 -1763
  503. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_stitcher_singleton.py +0 -33
  504. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_trimmer.py +0 -106
  505. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/map_visualizer.py +0 -334
  506. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/ocr_dialogue.py +0 -1020
  507. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/recording.py +0 -188
  508. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/state_formatter.py +0 -1481
  509. examples/task_apps/dev/pokemon_emerald/external/pokeagent-speedrun/utils/vlm.py +0 -862
  510. examples/task_apps/dev/pokemon_emerald/modal_app.py +0 -114
  511. examples/task_apps/dev/pokemon_emerald/task_app/README.md +0 -81
  512. examples/task_apps/dev/pokemon_emerald/task_app/__init__.py +0 -6
  513. examples/task_apps/dev/pokemon_emerald/task_app/pokemon_emerald.py +0 -685
  514. examples/task_apps/enron/__init__.py +0 -1
  515. examples/task_apps/enron/eval_groq_qwen32.toml +0 -16
  516. examples/task_apps/enron/filter_sft.toml +0 -5
  517. examples/task_apps/enron/task_app/README.md +0 -14
  518. examples/task_apps/enron/task_app/__init__.py +0 -1
  519. examples/task_apps/enron/task_app/grpo_enron.py +0 -906
  520. examples/task_apps/enron/task_app/grpo_enron_task_app.py +0 -146
  521. examples/task_apps/enron/tests/__init__.py +0 -4
  522. examples/task_apps/enron/tests/conftest.py +0 -115
  523. examples/task_apps/enron/tests/integration/__init__.py +0 -4
  524. examples/task_apps/enron/tests/integration/test_enron_eval.py +0 -179
  525. examples/task_apps/enron/tests/integration/test_enron_rollout.py +0 -135
  526. examples/task_apps/enron/tests/unit/__init__.py +0 -4
  527. examples/task_apps/enron/tests/unit/test_enron_environment.py +0 -126
  528. examples/task_apps/math/README.md +0 -22
  529. examples/task_apps/math/__init__.py +0 -0
  530. examples/task_apps/math/math_single_step.py +0 -1000
  531. examples/task_apps/math/math_task_app.py +0 -115
  532. examples/task_apps/pokemon_battle/__init__.py +0 -2
  533. examples/task_apps/pokemon_battle/modal_app.py +0 -104
  534. examples/task_apps/pokemon_battle/task_app/README.md +0 -68
  535. examples/task_apps/pokemon_battle/task_app/__init__.py +0 -6
  536. examples/task_apps/pokemon_battle/task_app/pokemon_showdown.py +0 -932
  537. examples/task_apps/pokemon_red/EVAL_IMAGE_ONLY_COMPLETE.md +0 -283
  538. examples/task_apps/pokemon_red/EVAL_IMAGE_ONLY_STATUS.md +0 -155
  539. examples/task_apps/pokemon_red/README.md +0 -357
  540. examples/task_apps/pokemon_red/README_IMAGE_ONLY_EVAL.md +0 -415
  541. examples/task_apps/pokemon_red/__init__.py +0 -3
  542. examples/task_apps/pokemon_red/eval_image_only_gpt4o.toml +0 -29
  543. examples/task_apps/pokemon_red/eval_pokemon_red_policy.py +0 -225
  544. examples/task_apps/pokemon_red/pallet_town_rl_config.toml +0 -75
  545. examples/task_apps/pokemon_red/task_app.py +0 -799
  546. examples/task_apps/pokemon_red/test_pallet_town_rewards.py +0 -193
  547. examples/task_apps/sokoban/README.md +0 -307
  548. examples/task_apps/sokoban/__init__.py +0 -3
  549. examples/task_apps/sokoban/eval_groq_qwen32.toml +0 -16
  550. examples/task_apps/sokoban/eval_openai_gpt5.toml +0 -16
  551. examples/task_apps/sokoban/filter_sft.toml +0 -5
  552. examples/task_apps/sokoban/task_app.py +0 -1058
  553. examples/task_apps/sokoban/tests/__init__.py +0 -4
  554. examples/task_apps/sokoban/tests/conftest.py +0 -113
  555. examples/task_apps/sokoban/tests/integration/__init__.py +0 -4
  556. examples/task_apps/sokoban/tests/integration/test_sokoban_eval.py +0 -57
  557. examples/task_apps/sokoban/tests/integration/test_sokoban_rollout.py +0 -198
  558. examples/task_apps/sokoban/tests/unit/__init__.py +0 -4
  559. examples/task_apps/sokoban/tests/unit/test_sokoban_environment.py +0 -114
  560. examples/task_apps/verilog/__init__.py +0 -1
  561. examples/task_apps/verilog/eval_groq_qwen32b.toml +0 -24
  562. examples/task_apps/verilog/filter_sft.toml +0 -5
  563. examples/task_apps/verilog/task_app/README.md +0 -12
  564. examples/task_apps/verilog/task_app/__init__.py +0 -1
  565. examples/task_apps/verilog/task_app/grpo_verilog.py +0 -1166
  566. examples/task_apps/verilog/task_app/grpo_verilog_task_app.py +0 -145
  567. examples/task_apps/verilog/tests/__init__.py +0 -4
  568. examples/task_apps/verilog/tests/conftest.py +0 -115
  569. examples/task_apps/verilog/tests/integration/__init__.py +0 -4
  570. examples/task_apps/verilog/tests/integration/test_verilog_eval.py +0 -181
  571. examples/task_apps/verilog/tests/integration/test_verilog_rollout.py +0 -55
  572. examples/task_apps/verilog/tests/unit/__init__.py +0 -4
  573. examples/task_apps/verilog/tests/unit/test_verilog_scoring.py +0 -118
  574. examples/vlm/PROPOSAL.md +0 -53
  575. examples/vlm/README.md +0 -68
  576. examples/vlm/configs/crafter_vlm_gpt4o.toml +0 -44
  577. examples/vlm/crafter_image_only_agent.py +0 -207
  578. examples/vlm/crafter_openai_vlm_agent.py +0 -277
  579. examples/vlm/filter_image_rows.py +0 -63
  580. examples/vlm/run_crafter_vlm_benchmark.py +0 -316
  581. examples/warming_up_to_rl/analyze_trace_db.py +0 -422
  582. examples/warming_up_to_rl/configs/crafter_fft.toml +0 -48
  583. examples/warming_up_to_rl/configs/crafter_fft_4b.toml +0 -54
  584. examples/warming_up_to_rl/configs/eval_fft_qwen4b.toml +0 -20
  585. examples/warming_up_to_rl/configs/eval_groq_qwen32b.toml +0 -13
  586. examples/warming_up_to_rl/configs/eval_modal_qwen4b.toml +0 -23
  587. examples/warming_up_to_rl/configs/eval_stepwise_complex.toml +0 -35
  588. examples/warming_up_to_rl/configs/eval_stepwise_consistent.toml +0 -26
  589. examples/warming_up_to_rl/configs/eval_stepwise_per_achievement.toml +0 -36
  590. examples/warming_up_to_rl/configs/eval_stepwise_simple.toml +0 -32
  591. examples/warming_up_to_rl/configs/rl_from_base_qwen4b.toml +0 -83
  592. examples/warming_up_to_rl/configs/rl_from_ft.toml +0 -56
  593. examples/warming_up_to_rl/export_trace_sft.py +0 -723
  594. examples/warming_up_to_rl/groq_test.py +0 -97
  595. examples/warming_up_to_rl/manage_secrets.py +0 -131
  596. examples/warming_up_to_rl/old/event_rewards.md +0 -234
  597. examples/warming_up_to_rl/old/notes.md +0 -73
  598. examples/warming_up_to_rl/readme.md +0 -179
  599. examples/warming_up_to_rl/run_eval.py +0 -736
  600. examples/warming_up_to_rl/run_fft_and_save.py +0 -380
  601. examples/warming_up_to_rl/run_local_rollout.py +0 -239
  602. examples/warming_up_to_rl/run_local_rollout_modal.py +0 -248
  603. examples/warming_up_to_rl/run_local_rollout_parallel.py +0 -405
  604. examples/warming_up_to_rl/run_local_rollout_traced.py +0 -477
  605. examples/warming_up_to_rl/run_rl_and_save.py +0 -124
  606. examples/warming_up_to_rl/run_rollout_remote.py +0 -156
  607. examples/workflows/__init__.py +0 -0
  608. examples/workflows/math_rl/__init__.py +0 -0
  609. examples/workflows/math_rl/configs/eval_base_qwen.toml +0 -15
  610. examples/workflows/math_rl/configs/eval_rl_qwen.toml +0 -11
  611. examples/workflows/math_rl/configs/rl_from_base_qwen.toml +0 -35
  612. examples/workflows/math_rl/configs/rl_from_base_qwen17.toml +0 -74
  613. examples/workflows/math_rl/configs/rl_from_ft_qwen.toml +0 -35
  614. examples/workflows/math_rl/download_dataset.py +0 -80
  615. examples/workflows/math_rl/run_eval.py +0 -436
  616. examples/workflows/math_rl/run_rl_and_save.py +0 -111
  617. synth_ai/api/models/supported.py +0 -377
  618. synth_ai/api/train/__init__.py +0 -5
  619. synth_ai/api/train/builders.py +0 -351
  620. synth_ai/api/train/cli.py +0 -635
  621. synth_ai/api/train/config_finder.py +0 -228
  622. synth_ai/api/train/configs/__init__.py +0 -44
  623. synth_ai/api/train/configs/rl.py +0 -134
  624. synth_ai/api/train/configs/sft.py +0 -95
  625. synth_ai/api/train/configs/shared.py +0 -24
  626. synth_ai/api/train/env_resolver.py +0 -349
  627. synth_ai/api/train/pollers.py +0 -75
  628. synth_ai/api/train/supported_algos.py +0 -147
  629. synth_ai/api/train/task_app.py +0 -195
  630. synth_ai/api/train/utils.py +0 -225
  631. synth_ai/cli/_modal_wrapper.py +0 -29
  632. synth_ai/cli/_storage.py +0 -20
  633. synth_ai/cli/_typer_patch.py +0 -49
  634. synth_ai/cli/_validate_task_app.py +0 -11
  635. synth_ai/cli/balance.py +0 -216
  636. synth_ai/cli/calc.py +0 -84
  637. synth_ai/cli/demo.py +0 -165
  638. synth_ai/cli/legacy_root_backup.py +0 -468
  639. synth_ai/cli/man.py +0 -106
  640. synth_ai/cli/recent.py +0 -132
  641. synth_ai/cli/rl_demo.py +0 -254
  642. synth_ai/cli/status.py +0 -134
  643. synth_ai/cli/task_apps.py +0 -4523
  644. synth_ai/cli/traces.py +0 -164
  645. synth_ai/cli/tui.py +0 -57
  646. synth_ai/cli/watch.py +0 -506
  647. synth_ai/compound/cais.py +0 -0
  648. synth_ai/config/base_url.py +0 -107
  649. synth_ai/core/experiment.py +0 -13
  650. synth_ai/core/system.py +0 -15
  651. synth_ai/demo_registry.py +0 -295
  652. synth_ai/demos/core/__init__.py +0 -1
  653. synth_ai/demos/core/cli.py +0 -1718
  654. synth_ai/demos/demo_task_apps/core.py +0 -440
  655. synth_ai/demos/demo_task_apps/crafter/grpo_crafter_task_app.py +0 -184
  656. synth_ai/demos/demo_task_apps/math/config.toml +0 -74
  657. synth_ai/demos/demo_task_apps/math/deploy_task_app.sh +0 -22
  658. synth_ai/demos/demo_task_apps/math/modal_task_app.py +0 -739
  659. synth_ai/demos/demo_task_apps/math/task_app_entry.py +0 -37
  660. synth_ai/environments/__init__.py +0 -31
  661. synth_ai/environments/environment/__init__.py +0 -1
  662. synth_ai/environments/environment/artifacts/__init__.py +0 -1
  663. synth_ai/environments/environment/artifacts/base.py +0 -52
  664. synth_ai/environments/environment/core.py +0 -67
  665. synth_ai/environments/environment/db/__init__.py +0 -1
  666. synth_ai/environments/environment/db/sqlite.py +0 -45
  667. synth_ai/environments/environment/registry.py +0 -233
  668. synth_ai/environments/environment/resources/sqlite.py +0 -45
  669. synth_ai/environments/environment/results.py +0 -1
  670. synth_ai/environments/environment/rewards/__init__.py +0 -1
  671. synth_ai/environments/environment/rewards/core.py +0 -29
  672. synth_ai/environments/environment/shared_engine.py +0 -26
  673. synth_ai/environments/environment/tools/__init__.py +0 -200
  674. synth_ai/environments/examples/__init__.py +0 -1
  675. synth_ai/environments/examples/bandit/__init__.py +0 -33
  676. synth_ai/environments/examples/bandit/engine.py +0 -302
  677. synth_ai/environments/examples/bandit/environment.py +0 -194
  678. synth_ai/environments/examples/bandit/taskset.py +0 -200
  679. synth_ai/environments/examples/crafter_classic/__init__.py +0 -8
  680. synth_ai/environments/examples/crafter_classic/agent_demos/analyze_semantic_words_markdown.py +0 -250
  681. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_comprehensive_evaluation.py +0 -59
  682. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_browser.py +0 -152
  683. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_config.toml +0 -24
  684. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_framework.py +0 -1194
  685. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/crafter_synth_config.toml +0 -56
  686. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/filter_config_modal.toml +0 -32
  687. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/filter_traces_sft_turso.py +0 -738
  688. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/kick_off_ft_modal.py +0 -384
  689. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_action_results.py +0 -53
  690. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_agent_actions.py +0 -178
  691. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_latest_run.py +0 -222
  692. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_lm_traces.py +0 -183
  693. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_no_rewards.py +0 -210
  694. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_trace_issue.py +0 -206
  695. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/check_db_schema.py +0 -49
  696. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/check_latest_results.py +0 -64
  697. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/debug_agent_responses.py +0 -88
  698. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/quick_trace_check.py +0 -77
  699. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/compare_experiments.py +0 -324
  700. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/filter_traces_sft_turso.py +0 -580
  701. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/kick_off_ft_oai.py +0 -362
  702. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/multi_model_config.toml +0 -49
  703. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/analyze_enhanced_hooks.py +0 -332
  704. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/analyze_hook_events.py +0 -97
  705. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/analyze_hook_results.py +0 -217
  706. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/check_hook_storage.py +0 -87
  707. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/check_seeds.py +0 -88
  708. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/compare_seed_performance.py +0 -195
  709. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/custom_eval_pipelines.py +0 -400
  710. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/plot_hook_frequency.py +0 -195
  711. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/seed_analysis_summary.py +0 -56
  712. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/run_rollouts_for_models_and_compare_v3.py +0 -858
  713. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_quick_evaluation.py +0 -52
  714. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_react_agent.py +0 -874
  715. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_trace_evaluation.py +0 -1412
  716. synth_ai/environments/examples/crafter_classic/agent_demos/example_v3_usage.py +0 -216
  717. synth_ai/environments/examples/crafter_classic/agent_demos/old/compare_traces.py +0 -296
  718. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_comprehensive_evaluation.py +0 -58
  719. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_env_serialization.py +0 -464
  720. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_evaluation_browser.py +0 -152
  721. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_quick_evaluation.py +0 -51
  722. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_trace_evaluation.py +0 -1412
  723. synth_ai/environments/examples/crafter_classic/agent_demos/old/debug_player_loss.py +0 -112
  724. synth_ai/environments/examples/crafter_classic/agent_demos/old/diagnose_service.py +0 -203
  725. synth_ai/environments/examples/crafter_classic/agent_demos/old/diagnose_slowness.py +0 -305
  726. synth_ai/environments/examples/crafter_classic/agent_demos/old/eval_by_difficulty.py +0 -126
  727. synth_ai/environments/examples/crafter_classic/agent_demos/old/eval_example.py +0 -94
  728. synth_ai/environments/examples/crafter_classic/agent_demos/old/explore_saved_states.py +0 -142
  729. synth_ai/environments/examples/crafter_classic/agent_demos/old/filter_traces_sft.py +0 -26
  730. synth_ai/environments/examples/crafter_classic/agent_demos/old/filter_traces_sft_OLD.py +0 -984
  731. synth_ai/environments/examples/crafter_classic/agent_demos/old/generate_ft_data_gemini.py +0 -724
  732. synth_ai/environments/examples/crafter_classic/agent_demos/old/generate_ft_data_modal.py +0 -386
  733. synth_ai/environments/examples/crafter_classic/agent_demos/old/generate_ft_metadata.py +0 -205
  734. synth_ai/environments/examples/crafter_classic/agent_demos/old/kick_off_ft_gemini.py +0 -150
  735. synth_ai/environments/examples/crafter_classic/agent_demos/old/kick_off_ft_modal.py +0 -283
  736. synth_ai/environments/examples/crafter_classic/agent_demos/old/prepare_vertex_ft.py +0 -280
  737. synth_ai/environments/examples/crafter_classic/agent_demos/old/profile_env_slowness.py +0 -456
  738. synth_ai/environments/examples/crafter_classic/agent_demos/old/replicate_issue.py +0 -166
  739. synth_ai/environments/examples/crafter_classic/agent_demos/old/run_and_eval.py +0 -102
  740. synth_ai/environments/examples/crafter_classic/agent_demos/old/run_comparison.py +0 -128
  741. synth_ai/environments/examples/crafter_classic/agent_demos/old/run_qwen_rollouts.py +0 -655
  742. synth_ai/environments/examples/crafter_classic/agent_demos/old/trace_eval_OLD.py +0 -202
  743. synth_ai/environments/examples/crafter_classic/agent_demos/old/validate_openai_format.py +0 -166
  744. synth_ai/environments/examples/crafter_classic/config_logging.py +0 -111
  745. synth_ai/environments/examples/crafter_classic/debug_translation.py +0 -0
  746. synth_ai/environments/examples/crafter_classic/engine.py +0 -579
  747. synth_ai/environments/examples/crafter_classic/engine_deterministic_patch.py +0 -64
  748. synth_ai/environments/examples/crafter_classic/engine_helpers/action_map.py +0 -6
  749. synth_ai/environments/examples/crafter_classic/engine_helpers/serialization.py +0 -75
  750. synth_ai/environments/examples/crafter_classic/engine_serialization_patch_v3.py +0 -267
  751. synth_ai/environments/examples/crafter_classic/environment.py +0 -495
  752. synth_ai/environments/examples/crafter_classic/taskset.py +0 -233
  753. synth_ai/environments/examples/crafter_classic/trace_hooks_v3.py +0 -228
  754. synth_ai/environments/examples/crafter_classic/world_config_patch_simple.py +0 -299
  755. synth_ai/environments/examples/crafter_custom/__init__.py +0 -4
  756. synth_ai/environments/examples/crafter_custom/agent_demos/__init__.py +0 -1
  757. synth_ai/environments/examples/crafter_custom/agent_demos/trace_eval.py +0 -202
  758. synth_ai/environments/examples/crafter_custom/crafter/__init__.py +0 -7
  759. synth_ai/environments/examples/crafter_custom/crafter/config.py +0 -182
  760. synth_ai/environments/examples/crafter_custom/crafter/constants.py +0 -8
  761. synth_ai/environments/examples/crafter_custom/crafter/engine.py +0 -269
  762. synth_ai/environments/examples/crafter_custom/crafter/env.py +0 -262
  763. synth_ai/environments/examples/crafter_custom/crafter/objects.py +0 -417
  764. synth_ai/environments/examples/crafter_custom/crafter/recorder.py +0 -187
  765. synth_ai/environments/examples/crafter_custom/crafter/worldgen.py +0 -118
  766. synth_ai/environments/examples/crafter_custom/dataset_builder.py +0 -373
  767. synth_ai/environments/examples/crafter_custom/environment.py +0 -312
  768. synth_ai/environments/examples/crafter_custom/old/analyze_diamond_issue.py +0 -159
  769. synth_ai/environments/examples/crafter_custom/old/analyze_diamond_spawning.py +0 -158
  770. synth_ai/environments/examples/crafter_custom/old/compare_worlds.py +0 -71
  771. synth_ai/environments/examples/crafter_custom/old/dataset_stats.py +0 -105
  772. synth_ai/environments/examples/crafter_custom/old/diamond_spawning_summary.py +0 -119
  773. synth_ai/environments/examples/crafter_custom/old/example_dataset_usage.py +0 -52
  774. synth_ai/environments/examples/crafter_custom/run_dataset.py +0 -305
  775. synth_ai/environments/examples/enron/art_helpers/email_search_tools.py +0 -156
  776. synth_ai/environments/examples/enron/art_helpers/local_email_db.py +0 -281
  777. synth_ai/environments/examples/enron/art_helpers/types_enron.py +0 -25
  778. synth_ai/environments/examples/enron/engine.py +0 -300
  779. synth_ai/environments/examples/enron/environment.py +0 -234
  780. synth_ai/environments/examples/enron/taskset.py +0 -112
  781. synth_ai/environments/examples/enron/units/keyword_stats.py +0 -112
  782. synth_ai/environments/examples/minigrid/__init__.py +0 -48
  783. synth_ai/environments/examples/minigrid/agent_demos/minigrid_evaluation_framework.py +0 -1188
  784. synth_ai/environments/examples/minigrid/agent_demos/minigrid_quick_evaluation.py +0 -48
  785. synth_ai/environments/examples/minigrid/agent_demos/minigrid_react_agent.py +0 -562
  786. synth_ai/environments/examples/minigrid/agent_demos/minigrid_trace_evaluation.py +0 -221
  787. synth_ai/environments/examples/minigrid/engine.py +0 -589
  788. synth_ai/environments/examples/minigrid/environment.py +0 -274
  789. synth_ai/environments/examples/minigrid/environment_mapping.py +0 -242
  790. synth_ai/environments/examples/minigrid/puzzle_loader.py +0 -417
  791. synth_ai/environments/examples/minigrid/taskset.py +0 -583
  792. synth_ai/environments/examples/nethack/__init__.py +0 -7
  793. synth_ai/environments/examples/nethack/achievements.py +0 -337
  794. synth_ai/environments/examples/nethack/agent_demos/nethack_evaluation_framework.py +0 -981
  795. synth_ai/environments/examples/nethack/agent_demos/nethack_quick_evaluation.py +0 -74
  796. synth_ai/environments/examples/nethack/agent_demos/nethack_react_agent.py +0 -831
  797. synth_ai/environments/examples/nethack/engine.py +0 -739
  798. synth_ai/environments/examples/nethack/environment.py +0 -256
  799. synth_ai/environments/examples/nethack/helpers/__init__.py +0 -41
  800. synth_ai/environments/examples/nethack/helpers/action_mapping.py +0 -301
  801. synth_ai/environments/examples/nethack/helpers/nle_wrapper.py +0 -402
  802. synth_ai/environments/examples/nethack/helpers/observation_utils.py +0 -433
  803. synth_ai/environments/examples/nethack/helpers/recording_wrapper.py +0 -200
  804. synth_ai/environments/examples/nethack/helpers/trajectory_recorder.py +0 -269
  805. synth_ai/environments/examples/nethack/helpers/visualization/replay_viewer.py +0 -308
  806. synth_ai/environments/examples/nethack/helpers/visualization/visualizer.py +0 -431
  807. synth_ai/environments/examples/nethack/taskset.py +0 -323
  808. synth_ai/environments/examples/red/__init__.py +0 -7
  809. synth_ai/environments/examples/red/agent_demos/__init__.py +0 -1
  810. synth_ai/environments/examples/red/config_logging.py +0 -110
  811. synth_ai/environments/examples/red/engine.py +0 -721
  812. synth_ai/environments/examples/red/engine_helpers/__init__.py +0 -1
  813. synth_ai/environments/examples/red/engine_helpers/memory_map.py +0 -35
  814. synth_ai/environments/examples/red/engine_helpers/reward_components.py +0 -276
  815. synth_ai/environments/examples/red/engine_helpers/reward_library/__init__.py +0 -142
  816. synth_ai/environments/examples/red/engine_helpers/reward_library/adaptive_rewards.py +0 -57
  817. synth_ai/environments/examples/red/engine_helpers/reward_library/battle_rewards.py +0 -284
  818. synth_ai/environments/examples/red/engine_helpers/reward_library/composite_rewards.py +0 -150
  819. synth_ai/environments/examples/red/engine_helpers/reward_library/economy_rewards.py +0 -138
  820. synth_ai/environments/examples/red/engine_helpers/reward_library/efficiency_rewards.py +0 -57
  821. synth_ai/environments/examples/red/engine_helpers/reward_library/exploration_rewards.py +0 -331
  822. synth_ai/environments/examples/red/engine_helpers/reward_library/novelty_rewards.py +0 -121
  823. synth_ai/environments/examples/red/engine_helpers/reward_library/pallet_town_progression.py +0 -477
  824. synth_ai/environments/examples/red/engine_helpers/reward_library/pallet_town_rewards.py +0 -559
  825. synth_ai/environments/examples/red/engine_helpers/reward_library/pokemon_rewards.py +0 -313
  826. synth_ai/environments/examples/red/engine_helpers/reward_library/social_rewards.py +0 -148
  827. synth_ai/environments/examples/red/engine_helpers/reward_library/story_rewards.py +0 -247
  828. synth_ai/environments/examples/red/engine_helpers/screen_analysis.py +0 -368
  829. synth_ai/environments/examples/red/engine_helpers/state_extraction.py +0 -172
  830. synth_ai/environments/examples/red/environment.py +0 -298
  831. synth_ai/environments/examples/red/taskset.py +0 -79
  832. synth_ai/environments/examples/red/units/__init__.py +0 -1
  833. synth_ai/environments/examples/sokoban/__init__.py +0 -1
  834. synth_ai/environments/examples/sokoban/agent_demos/sokoban_full_eval.py +0 -899
  835. synth_ai/environments/examples/sokoban/engine.py +0 -678
  836. synth_ai/environments/examples/sokoban/engine_helpers/__init__.py +0 -1
  837. synth_ai/environments/examples/sokoban/engine_helpers/room_utils.py +0 -657
  838. synth_ai/environments/examples/sokoban/engine_helpers/vendored/__init__.py +0 -18
  839. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/__init__.py +0 -3
  840. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/boxoban_env.py +0 -131
  841. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/render_utils.py +0 -370
  842. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/room_utils.py +0 -332
  843. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env.py +0 -306
  844. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_fixed_targets.py +0 -67
  845. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_pull.py +0 -115
  846. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_two_player.py +0 -123
  847. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_variations.py +0 -394
  848. synth_ai/environments/examples/sokoban/environment.py +0 -229
  849. synth_ai/environments/examples/sokoban/generate_verified_puzzles.py +0 -440
  850. synth_ai/environments/examples/sokoban/puzzle_loader.py +0 -312
  851. synth_ai/environments/examples/sokoban/taskset.py +0 -544
  852. synth_ai/environments/examples/tictactoe/__init__.py +0 -1
  853. synth_ai/environments/examples/tictactoe/engine.py +0 -368
  854. synth_ai/environments/examples/tictactoe/environment.py +0 -240
  855. synth_ai/environments/examples/tictactoe/taskset.py +0 -215
  856. synth_ai/environments/examples/verilog/__init__.py +0 -10
  857. synth_ai/environments/examples/verilog/engine.py +0 -421
  858. synth_ai/environments/examples/verilog/environment.py +0 -350
  859. synth_ai/environments/examples/verilog/taskset.py +0 -420
  860. synth_ai/environments/examples/wordle/__init__.py +0 -29
  861. synth_ai/environments/examples/wordle/engine.py +0 -398
  862. synth_ai/environments/examples/wordle/environment.py +0 -159
  863. synth_ai/environments/examples/wordle/helpers/generate_instances_wordfreq.py +0 -75
  864. synth_ai/environments/examples/wordle/taskset.py +0 -230
  865. synth_ai/environments/reproducibility/core.py +0 -42
  866. synth_ai/environments/reproducibility/helpers.py +0 -0
  867. synth_ai/environments/reproducibility/tree.py +0 -363
  868. synth_ai/environments/service/app.py +0 -97
  869. synth_ai/environments/service/core_routes.py +0 -1021
  870. synth_ai/environments/service/external_registry.py +0 -56
  871. synth_ai/environments/service/registry.py +0 -9
  872. synth_ai/environments/stateful/__init__.py +0 -1
  873. synth_ai/environments/stateful/core.py +0 -163
  874. synth_ai/environments/stateful/engine.py +0 -21
  875. synth_ai/environments/stateful/state.py +0 -7
  876. synth_ai/environments/tasks/api.py +0 -19
  877. synth_ai/environments/tasks/core.py +0 -81
  878. synth_ai/environments/tasks/filters.py +0 -40
  879. synth_ai/environments/tasks/utils.py +0 -90
  880. synth_ai/environments/v0_observability/history.py +0 -3
  881. synth_ai/environments/v0_observability/log.py +0 -2
  882. synth_ai/evals/__init__.py +0 -15
  883. synth_ai/evals/base.py +0 -13
  884. synth_ai/evals/client.py +0 -82
  885. synth_ai/evals/types.py +0 -42
  886. synth_ai/handshake.py +0 -109
  887. synth_ai/http.py +0 -26
  888. synth_ai/http_client.py +0 -136
  889. synth_ai/inference/__init__.py +0 -5
  890. synth_ai/inference/client.py +0 -34
  891. synth_ai/jobs/client.py +0 -295
  892. synth_ai/judge_schemas.py +0 -127
  893. synth_ai/learning/__init__.py +0 -59
  894. synth_ai/learning/client.py +0 -241
  895. synth_ai/learning/ft_client.py +0 -7
  896. synth_ai/learning/health.py +0 -49
  897. synth_ai/learning/jobs.py +0 -201
  898. synth_ai/learning/rl/__init__.py +0 -39
  899. synth_ai/learning/rl/client.py +0 -267
  900. synth_ai/learning/rl/contracts.py +0 -27
  901. synth_ai/learning/rl/env_keys.py +0 -166
  902. synth_ai/learning/rl/secrets.py +0 -13
  903. synth_ai/learning/sft/client.py +0 -68
  904. synth_ai/learning/sft/config.py +0 -270
  905. synth_ai/learning/sft/data.py +0 -295
  906. synth_ai/learning/validators.py +0 -49
  907. synth_ai/lm/__init__.py +0 -25
  908. synth_ai/task/__init__.py +0 -121
  909. synth_ai/task/apps/__init__.py +0 -129
  910. synth_ai/task/client.py +0 -167
  911. synth_ai/task/config.py +0 -257
  912. synth_ai/task/contracts.py +0 -236
  913. synth_ai/task/datasets.py +0 -108
  914. synth_ai/task/proxy.py +0 -251
  915. synth_ai/task/rubrics/__init__.py +0 -56
  916. synth_ai/task/rubrics/loaders.py +0 -152
  917. synth_ai/task/rubrics/strict.py +0 -149
  918. synth_ai/task/server.py +0 -432
  919. synth_ai/task/trace_correlation_helpers.py +0 -315
  920. synth_ai/task/tracing_utils.py +0 -84
  921. synth_ai/task/validators.py +0 -418
  922. synth_ai/tracing_v3/__init__.py +0 -97
  923. synth_ai/tracing_v3/abstractions.py +0 -302
  924. synth_ai/tracing_v3/config.py +0 -84
  925. synth_ai/tracing_v3/db_config.py +0 -194
  926. synth_ai/tracing_v3/decorators.py +0 -398
  927. synth_ai/tracing_v3/llm_call_record_helpers.py +0 -391
  928. synth_ai/tracing_v3/migration_helper.py +0 -120
  929. synth_ai/tracing_v3/session_tracer.py +0 -540
  930. synth_ai/tracing_v3/storage/base.py +0 -210
  931. synth_ai/tracing_v3/storage/config.py +0 -75
  932. synth_ai/tracing_v3/storage/factory.py +0 -39
  933. synth_ai/tracing_v3/trace_utils.py +0 -317
  934. synth_ai/tracing_v3/turso/daemon.py +0 -151
  935. synth_ai/tracing_v3/turso/models.py +0 -469
  936. synth_ai/tracing_v3/turso/native_manager.py +0 -1209
  937. synth_ai/tracing_v3/utils.py +0 -108
  938. synth_ai/tui/__init__.py +0 -5
  939. synth_ai/tui/__main__.py +0 -13
  940. synth_ai/tui/cli/__init__.py +0 -1
  941. synth_ai/tui/cli/query_experiments.py +0 -164
  942. synth_ai/tui/cli/query_experiments_v3.py +0 -164
  943. synth_ai/tui/dashboard.py +0 -906
  944. synth_ai/v0/api/__init__.py +0 -8
  945. synth_ai/v0/api/models/__init__.py +0 -8
  946. synth_ai/v0/api/models/supported.py +0 -8
  947. synth_ai/v0/config/__init__.py +0 -15
  948. synth_ai/v0/config/base_url.py +0 -12
  949. synth_ai/v0/lm/__init__.py +0 -51
  950. synth_ai/v0/lm/caching/__init__.py +0 -0
  951. synth_ai/v0/lm/caching/constants.py +0 -6
  952. synth_ai/v0/lm/caching/dbs.py +0 -0
  953. synth_ai/v0/lm/caching/ephemeral.py +0 -100
  954. synth_ai/v0/lm/caching/handler.py +0 -137
  955. synth_ai/v0/lm/caching/initialize.py +0 -11
  956. synth_ai/v0/lm/caching/persistent.py +0 -114
  957. synth_ai/v0/lm/config.py +0 -115
  958. synth_ai/v0/lm/constants.py +0 -32
  959. synth_ai/v0/lm/core/__init__.py +0 -8
  960. synth_ai/v0/lm/core/all.py +0 -73
  961. synth_ai/v0/lm/core/exceptions.py +0 -5
  962. synth_ai/v0/lm/core/main.py +0 -331
  963. synth_ai/v0/lm/core/main_v3.py +0 -594
  964. synth_ai/v0/lm/core/synth_models.py +0 -35
  965. synth_ai/v0/lm/core/vendor_clients.py +0 -190
  966. synth_ai/v0/lm/cost/__init__.py +0 -0
  967. synth_ai/v0/lm/cost/monitor.py +0 -1
  968. synth_ai/v0/lm/cost/statefulness.py +0 -1
  969. synth_ai/v0/lm/injection.py +0 -80
  970. synth_ai/v0/lm/overrides.py +0 -206
  971. synth_ai/v0/lm/provider_support/__init__.py +0 -8
  972. synth_ai/v0/lm/provider_support/anthropic.py +0 -972
  973. synth_ai/v0/lm/provider_support/openai.py +0 -1139
  974. synth_ai/v0/lm/provider_support/suppress_logging.py +0 -31
  975. synth_ai/v0/lm/structured_outputs/__init__.py +0 -0
  976. synth_ai/v0/lm/structured_outputs/handler.py +0 -440
  977. synth_ai/v0/lm/structured_outputs/inject.py +0 -297
  978. synth_ai/v0/lm/structured_outputs/rehabilitate.py +0 -185
  979. synth_ai/v0/lm/tools/__init__.py +0 -3
  980. synth_ai/v0/lm/tools/base.py +0 -172
  981. synth_ai/v0/lm/unified_interface.py +0 -202
  982. synth_ai/v0/lm/vendors/__init__.py +0 -0
  983. synth_ai/v0/lm/vendors/base.py +0 -81
  984. synth_ai/v0/lm/vendors/core/__init__.py +0 -0
  985. synth_ai/v0/lm/vendors/core/anthropic_api.py +0 -387
  986. synth_ai/v0/lm/vendors/core/gemini_api.py +0 -292
  987. synth_ai/v0/lm/vendors/core/mistral_api.py +0 -322
  988. synth_ai/v0/lm/vendors/core/openai_api.py +0 -227
  989. synth_ai/v0/lm/vendors/core/synth_dev_api.py +0 -0
  990. synth_ai/v0/lm/vendors/local/__init__.py +0 -0
  991. synth_ai/v0/lm/vendors/local/ollama.py +0 -0
  992. synth_ai/v0/lm/vendors/openai_standard.py +0 -782
  993. synth_ai/v0/lm/vendors/openai_standard_responses.py +0 -259
  994. synth_ai/v0/lm/vendors/retries.py +0 -22
  995. synth_ai/v0/lm/vendors/supported/__init__.py +0 -0
  996. synth_ai/v0/lm/vendors/supported/custom_endpoint.py +0 -415
  997. synth_ai/v0/lm/vendors/supported/deepseek.py +0 -69
  998. synth_ai/v0/lm/vendors/supported/grok.py +0 -75
  999. synth_ai/v0/lm/vendors/supported/groq.py +0 -16
  1000. synth_ai/v0/lm/vendors/supported/ollama.py +0 -15
  1001. synth_ai/v0/lm/vendors/supported/openrouter.py +0 -74
  1002. synth_ai/v0/lm/vendors/supported/together.py +0 -11
  1003. synth_ai/v0/lm/vendors/synth_client.py +0 -835
  1004. synth_ai/v0/lm/warmup.py +0 -186
  1005. synth_ai/v0/tracing/__init__.py +0 -0
  1006. synth_ai/v0/tracing/abstractions.py +0 -224
  1007. synth_ai/v0/tracing/base_client.py +0 -91
  1008. synth_ai/v0/tracing/client_manager.py +0 -131
  1009. synth_ai/v0/tracing/config.py +0 -142
  1010. synth_ai/v0/tracing/context.py +0 -146
  1011. synth_ai/v0/tracing/decorators.py +0 -682
  1012. synth_ai/v0/tracing/events/__init__.py +0 -0
  1013. synth_ai/v0/tracing/events/manage.py +0 -147
  1014. synth_ai/v0/tracing/events/scope.py +0 -86
  1015. synth_ai/v0/tracing/events/store.py +0 -228
  1016. synth_ai/v0/tracing/immediate_client.py +0 -151
  1017. synth_ai/v0/tracing/local.py +0 -18
  1018. synth_ai/v0/tracing/log_client_base.py +0 -73
  1019. synth_ai/v0/tracing/retry_queue.py +0 -186
  1020. synth_ai/v0/tracing/trackers.py +0 -515
  1021. synth_ai/v0/tracing/upload.py +0 -409
  1022. synth_ai/v0/tracing/utils.py +0 -9
  1023. synth_ai/v0/tracing_v1/__init__.py +0 -16
  1024. synth_ai/v0/tracing_v1/abstractions.py +0 -224
  1025. synth_ai/v0/tracing_v1/base_client.py +0 -91
  1026. synth_ai/v0/tracing_v1/client_manager.py +0 -131
  1027. synth_ai/v0/tracing_v1/config.py +0 -142
  1028. synth_ai/v0/tracing_v1/context.py +0 -146
  1029. synth_ai/v0/tracing_v1/decorators.py +0 -703
  1030. synth_ai/v0/tracing_v1/events/__init__.py +0 -0
  1031. synth_ai/v0/tracing_v1/events/manage.py +0 -147
  1032. synth_ai/v0/tracing_v1/events/scope.py +0 -86
  1033. synth_ai/v0/tracing_v1/events/store.py +0 -228
  1034. synth_ai/v0/tracing_v1/immediate_client.py +0 -151
  1035. synth_ai/v0/tracing_v1/local.py +0 -18
  1036. synth_ai/v0/tracing_v1/log_client_base.py +0 -73
  1037. synth_ai/v0/tracing_v1/retry_queue.py +0 -186
  1038. synth_ai/v0/tracing_v1/trackers.py +0 -515
  1039. synth_ai/v0/tracing_v1/upload.py +0 -527
  1040. synth_ai/v0/tracing_v1/utils.py +0 -9
  1041. synth_ai/v0/tracing_v3/__init__.py +0 -10
  1042. synth_ai/v0/tracing_v3/abstractions.py +0 -3
  1043. synth_ai/v0/tracing_v3/decorators.py +0 -3
  1044. synth_ai/v0/tracing_v3/llm_call_record_helpers.py +0 -3
  1045. synth_ai/v0/tracing_v3/session_tracer.py +0 -3
  1046. synth_ai-0.2.14.dist-info/METADATA +0 -139
  1047. synth_ai-0.2.14.dist-info/RECORD +0 -762
  1048. synth_ai-0.2.14.dist-info/top_level.txt +0 -2
  1049. /synth_ai/{demos/demo_task_apps → cli/demo_apps}/crafter/__init__.py +0 -0
  1050. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/__init__.py +0 -0
  1051. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/crafter/configs/crafter_fft_4b.toml +0 -0
  1052. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/crafter/configs/rl_from_base_qwen4b.toml +0 -0
  1053. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/__init__.py +0 -0
  1054. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/_common.py +0 -0
  1055. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/app.py +0 -0
  1056. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/deploy_modal.py +0 -0
  1057. {examples/task_apps → synth_ai/core/apps}/__init__.py +0 -0
  1058. /synth_ai/{tracing_v3 → core/tracing_v3}/examples/basic_usage.py +0 -0
  1059. /synth_ai/{tracing_v3 → core/tracing_v3}/hooks.py +0 -0
  1060. /synth_ai/{tracing_v3 → core/tracing_v3}/lm_call_record_abstractions.py +0 -0
  1061. /synth_ai/{tracing_v3 → core/tracing_v3}/replica_sync.py +0 -0
  1062. /synth_ai/{tracing_v3 → core/tracing_v3}/serialization.py +0 -0
  1063. /synth_ai/{tracing_v3 → core/tracing_v3}/storage/__init__.py +0 -0
  1064. /synth_ai/{tracing_v3 → core/tracing_v3}/storage/exceptions.py +0 -0
  1065. /synth_ai/{tracing_v3 → core/tracing_v3}/storage/types.py +0 -0
  1066. /synth_ai/{tracing_v3 → core/tracing_v3}/storage/utils.py +0 -0
  1067. /synth_ai/{tracing_v3 → core/tracing_v3}/turso/__init__.py +0 -0
  1068. /synth_ai/{learning → sdk/learning}/algorithms.py +0 -0
  1069. /synth_ai/{learning → sdk/learning}/config.py +0 -0
  1070. /synth_ai/{learning → sdk/learning}/constants.py +0 -0
  1071. /synth_ai/{learning → sdk/learning}/core.py +0 -0
  1072. /synth_ai/{learning → sdk/learning}/gateway.py +0 -0
  1073. /synth_ai/{learning → sdk/learning}/rl/config.py +0 -0
  1074. /synth_ai/{learning → sdk/learning}/rl_client.py +0 -0
  1075. /synth_ai/{learning → sdk/learning}/sft/__init__.py +0 -0
  1076. /synth_ai/{learning → sdk/learning}/sse.py +0 -0
  1077. /synth_ai/{task → sdk/task}/auth.py +0 -0
  1078. /synth_ai/{task → sdk/task}/errors.py +0 -0
  1079. /synth_ai/{task → sdk/task}/health.py +0 -0
  1080. /synth_ai/{task → sdk/task}/json.py +0 -0
  1081. /synth_ai/{task → sdk/task}/rubrics/models.py +0 -0
  1082. /synth_ai/{task → sdk/task}/rubrics/scoring.py +0 -0
  1083. /synth_ai/{task → sdk/task}/vendors.py +0 -0
  1084. {synth_ai-0.2.14.dist-info → synth_ai-0.4.4.dist-info}/WHEEL +0 -0
  1085. {synth_ai-0.2.14.dist-info → synth_ai-0.4.4.dist-info}/entry_points.txt +0 -0
  1086. {synth_ai-0.2.14.dist-info → synth_ai-0.4.4.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,2196 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import importlib
6
+ import json
7
+ import os
8
+ from collections.abc import Callable, Mapping
9
+ from pathlib import Path
10
+ from typing import Any, NoReturn, cast
11
+
12
+ import click
13
+
14
+ from synth_ai.cli.lib.env import get_synth_and_env_keys, mask_str
15
+ from synth_ai.cli.lib.train_cfgs import find_train_cfgs_in_cwd, validate_train_cfg
16
+ from synth_ai.core.paths import print_paths_formatted
17
+
18
+ try:
19
+ _config_module = cast(
20
+ Any, importlib.import_module("synth_ai.core.env")
21
+ )
22
+ get_backend_from_env = cast(Callable[[], str], _config_module.get_backend_from_env)
23
+ except Exception as exc: # pragma: no cover - critical dependency
24
+ raise RuntimeError("Unable to load backend configuration helpers") from exc
25
+
26
+ from synth_ai.cli.lib.env import load_env_file
27
+ from synth_ai.cli.lib.errors import format_error_message, get_required_value
28
+ from synth_ai.core.telemetry import flush_logger, log_error, log_info
29
+ from synth_ai.sdk.streaming import (
30
+ GraphGenHandler,
31
+ CLIHandler,
32
+ JobStreamer,
33
+ LossCurveHandler,
34
+ PromptLearningHandler,
35
+ StreamConfig,
36
+ StreamEndpoints,
37
+ StreamType,
38
+ )
39
+
40
+ from .builders import build_prompt_learning_payload, build_rl_payload, build_sft_payload
41
+ from .local_api import check_local_api_health
42
+ from .graphgen import GraphGenJob
43
+ from .graphgen_models import load_graphgen_taskset
44
+ from .context_learning import ContextLearningJob
45
+ from .utils import (
46
+ TrainError,
47
+ ensure_api_base,
48
+ http_get,
49
+ http_post,
50
+ limit_jsonl_examples,
51
+ mask_value,
52
+ post_multipart,
53
+ preview_json,
54
+ sleep,
55
+ validate_sft_jsonl,
56
+ )
57
+
58
+ # Constants for prompt learning event types
59
+ _PROMPT_LEARNING_EVENT_BEST_PROMPT = "prompt.learning.best.prompt"
60
+ _PROMPT_LEARNING_EVENT_FINAL_RESULTS = "prompt.learning.final.results"
61
+ _PROMPT_LEARNING_EVENT_VALIDATION_SCORED = "prompt.learning.validation.scored"
62
+ _PROMPT_LEARNING_EVENT_GEPA_COMPLETE = "prompt.learning.gepa.complete"
63
+ _PROMPT_LEARNING_EVENT_MIPRO_COMPLETE = "prompt.learning.mipro.complete"
64
+ _PROMPT_LEARNING_EVENT_GEPA_NEW_BEST = "prompt.learning.gepa.new_best"
65
+ _PROMPT_LEARNING_EVENT_PHASE_CHANGED = "prompt.learning.phase.changed"
66
+ _PROMPT_LEARNING_EVENT_PROGRESS = "prompt.learning.progress"
67
+ _PROMPT_LEARNING_EVENT_STREAM_CONNECTED = "prompt.learning.stream.connected"
68
+
69
+ # Constants for formatting
70
+ _MAX_TEXT_REPLACEMENTS_DISPLAY = 3 # Max number of text replacements to show in output
71
+ _RESULTS_FILE_MAX_EVENTS = 10000 # Max events to fetch for results file generation
72
+
73
+
74
+ def _format_text_replacements(obj: dict[str, Any] | None, max_display: int = _MAX_TEXT_REPLACEMENTS_DISPLAY) -> list[str]:
75
+ """Extract and format text replacements from a candidate object.
76
+
77
+ Args:
78
+ obj: Candidate object dictionary containing text_replacements
79
+ max_display: Maximum number of replacements to display
80
+
81
+ Returns:
82
+ List of formatted lines showing role and replacement text
83
+ """
84
+ lines = []
85
+ if not obj or not isinstance(obj, dict):
86
+ return lines
87
+
88
+ text_replacements = obj.get("text_replacements", [])
89
+ if not text_replacements or not isinstance(text_replacements, list):
90
+ return lines
91
+
92
+ for replacement in text_replacements[:max_display]:
93
+ if isinstance(replacement, dict):
94
+ new_text = replacement.get("new_text", "")
95
+ role = replacement.get("apply_to_role", "system")
96
+ if new_text:
97
+ lines.append(f" [{role.upper()}]: {new_text}")
98
+ lines.append("")
99
+
100
+ return lines
101
+
102
+
103
+ def _default_backend() -> str:
104
+ """Resolve backend URL with proper production default.
105
+
106
+ Priority order:
107
+ 1. BACKEND_BASE_URL env var (highest priority) - checked FIRST before any .env loading
108
+ 2. BACKEND_OVERRIDE env var
109
+ 3. get_backend_from_env() standard resolution (which may use SYNTH_BASE_URL from .env)
110
+
111
+ CRITICAL: This function MUST check BACKEND_BASE_URL directly from os.getenv()
112
+ to ensure it's not overridden by .env file loading.
113
+ """
114
+ # Check explicit override first (BACKEND_BASE_URL takes absolute precedence)
115
+ # Read directly from os.environ to avoid any dotenv interference
116
+ explicit = os.environ.get("BACKEND_BASE_URL", "").strip()
117
+ if explicit:
118
+ # Return as-is, ensure_api_base() will normalize it
119
+ return explicit
120
+
121
+ # Fallback to BACKEND_OVERRIDE (also read directly from environ)
122
+ override = os.environ.get("BACKEND_OVERRIDE", "").strip()
123
+ if override:
124
+ return override
125
+
126
+ # Use standard resolution logic (may use SYNTH_BASE_URL from .env)
127
+ base, _ = get_backend_from_env()
128
+ return f"{base}/api" if not base.endswith("/api") else base
129
+
130
+
131
+ _DEFAULT_SFT_HIDDEN_EVENTS = {
132
+ "sft.created",
133
+ "sft.pricing.check.requested",
134
+ "sft.pricing.check.allowed",
135
+ "sft.stage",
136
+ "snapshot.fetch",
137
+ "hatchet.preflight",
138
+ "hatchet.submission.attempt",
139
+ "hatchet.submission.result",
140
+ "sft.running",
141
+ "sft.status",
142
+ "sft.worker.alive",
143
+ "sft.dispatch.selected",
144
+ "sft.config.prepared",
145
+ "sft.strategy.selected",
146
+ "sft.training.args",
147
+ }
148
+
149
+ _DEFAULT_RL_HIDDEN_SUBSTRINGS = {"modal", "hatchet"}
150
+
151
+ _DEFAULT_PROMPT_LEARNING_HIDDEN_EVENTS = {
152
+ "prompt.learning.policy.tokens",
153
+ "mipro.bootstrap.progress", # Hide individual bootstrap seed scores
154
+ "mipro.tpe.rankings", # Hide verbose TPE rankings
155
+ "mipro.tpe.selected", # Hide TPE selection details
156
+ "mipro.tpe.update", # Hide TPE density updates
157
+ "mipro.trial.duplicate", # Hide duplicate trial messages
158
+ "mipro.trial.started", # Hide individual trial start messages (too verbose with instructions)
159
+ "mipro.trial.minibatch", # Hide minibatch completion (only show full eval)
160
+ "mipro.trial.complete", # Hide individual trial completion
161
+ "mipro.iteration.skip_generation", # Hide skip generation messages
162
+ "mipro.budget.update", # Hide verbose budget updates (progress handler shows summary)
163
+ "mipro.instruction.proposed", # Hide proposed instructions (shown in results/logs only)
164
+ "gepa.transformation.proposed", # Hide proposed transformations (shown in results/logs only)
165
+ # Note: mipro.stage_proposer.called is shown so users know instruction generation is happening
166
+ }
167
+
168
+
169
+ def _load_toml_config(config_path: Path) -> dict[str, Any]:
170
+ """Load TOML config file."""
171
+ try:
172
+ import tomli # type: ignore[import-untyped]
173
+ except ImportError:
174
+ # Fallback to tomllib for Python 3.11+
175
+ try:
176
+ import tomllib as tomli
177
+ except ImportError:
178
+ return {}
179
+
180
+ try:
181
+ with open(config_path, "rb") as f:
182
+ return tomli.load(f)
183
+ except Exception:
184
+ return {}
185
+
186
+
187
+ def parse_env_file_path_from_config(config_path: Path) -> str | None:
188
+ """Parse env_file_path from TOML config.
189
+
190
+ Checks both [prompt_learning] and top-level sections.
191
+ """
192
+ config = _load_toml_config(config_path)
193
+
194
+ # Check prompt_learning section first
195
+ pl_section = config.get("prompt_learning", {})
196
+ if isinstance(pl_section, dict):
197
+ env_file_path = pl_section.get("env_file_path")
198
+ if env_file_path:
199
+ return str(env_file_path)
200
+
201
+ # Check top-level
202
+ env_file_path = config.get("env_file_path")
203
+ if env_file_path:
204
+ return str(env_file_path)
205
+
206
+ return None
207
+
208
+
209
+ def parse_results_folder(config_path: Path) -> Path:
210
+ """Parse results_folder from TOML config and validate it exists.
211
+
212
+ Checks both [prompt_learning] and top-level sections.
213
+ Raises ClickException if missing or invalid.
214
+ """
215
+ config = _load_toml_config(config_path)
216
+
217
+ # Check prompt_learning section first
218
+ pl_section = config.get("prompt_learning", {})
219
+ if isinstance(pl_section, dict):
220
+ results_folder = pl_section.get("results_folder")
221
+ if results_folder:
222
+ results_folder_str = str(results_folder).strip()
223
+ # Resolve relative to config file's directory if path is relative
224
+ if not Path(results_folder_str).is_absolute():
225
+ config_dir = config_path.parent.resolve()
226
+ results_path = (config_dir / results_folder_str).resolve()
227
+ else:
228
+ results_path = Path(results_folder_str).expanduser().resolve()
229
+
230
+ # Validate that the folder exists or can be created
231
+ try:
232
+ results_path.mkdir(parents=True, exist_ok=True)
233
+ except (OSError, PermissionError) as e:
234
+ raise click.ClickException(
235
+ f"Could not create results folder: {results_path}\n"
236
+ f" Error: {e}\n"
237
+ f" Config: {config_path}\n"
238
+ f" TOML results_folder: {results_folder}"
239
+ ) from e
240
+
241
+ return results_path
242
+
243
+ # Check top-level section
244
+ results_folder = config.get("results_folder")
245
+ if results_folder:
246
+ results_folder_str = str(results_folder).strip()
247
+ # Resolve relative to config file's directory if path is relative
248
+ if not Path(results_folder_str).is_absolute():
249
+ config_dir = config_path.parent.resolve()
250
+ results_path = (config_dir / results_folder_str).resolve()
251
+ else:
252
+ results_path = Path(results_folder_str).expanduser().resolve()
253
+
254
+ # Validate that the folder exists or can be created
255
+ try:
256
+ results_path.mkdir(parents=True, exist_ok=True)
257
+ except (OSError, PermissionError) as e:
258
+ raise click.ClickException(
259
+ f"Could not create results folder: {results_path}\n"
260
+ f" Error: {e}\n"
261
+ f" Config: {config_path}\n"
262
+ f" TOML results_folder: {results_folder}"
263
+ ) from e
264
+
265
+ return results_path
266
+
267
+ # Missing - raise error
268
+ raise click.ClickException(
269
+ f"Missing required 'results_folder' field in TOML config: {config_path}\n"
270
+ f" Please add 'results_folder = \"path/to/results\"' to [prompt_learning] section or top-level.\n"
271
+ f" Paths can be relative (to config file directory) or absolute."
272
+ )
273
+
274
+
275
+ def parse_display_config(config_path: Path) -> dict[str, Any]:
276
+ """Parse [display] section from TOML config."""
277
+ config = _load_toml_config(config_path)
278
+ display_section = config.get("display", {})
279
+
280
+ # Also extract termination_config for max limits
281
+ termination_section = config.get("termination_config", {})
282
+ # Also check prompt_learning.termination_config
283
+ pl_section = config.get("prompt_learning", {})
284
+ if isinstance(pl_section, dict):
285
+ pl_termination = pl_section.get("termination_config", {})
286
+ if isinstance(pl_termination, dict):
287
+ # Merge with top-level termination_config (top-level takes precedence)
288
+ termination_section = {**pl_termination, **termination_section}
289
+
290
+ return {
291
+ "local_backend": display_section.get("local_backend", False),
292
+ "tui": display_section.get("tui", False),
293
+ "show_curve": display_section.get("show_curve", True),
294
+ "verbose_summary": display_section.get("verbose_summary", True),
295
+ "show_trial_results": display_section.get("show_trial_results", True),
296
+ "show_transformations": display_section.get("show_transformations", False),
297
+ "show_validation": display_section.get("show_validation", True),
298
+ "max_tokens": termination_section.get("max_tokens"),
299
+ "max_time_seconds": termination_section.get("max_time_seconds"),
300
+ "max_rollouts": termination_section.get("max_rollouts"),
301
+ }
302
+
303
+
304
+ def _build_stream_components(
305
+ stream_format: str,
306
+ *,
307
+ hidden_event_types: set[str] | None = None,
308
+ hidden_event_substrings: set[str] | None = None,
309
+ ) -> tuple[StreamConfig, list]:
310
+ """Return stream configuration and handlers for the requested format."""
311
+ if stream_format == "chart":
312
+ config = StreamConfig(
313
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS},
314
+ event_types={
315
+ "sft.progress",
316
+ "sft.training.started",
317
+ "sft.training.finish",
318
+ "sft.validation.summary",
319
+ "rl.train.step",
320
+ "rl.train.started",
321
+ "rl.train.completed",
322
+ "workflow.completed",
323
+ "workflow.failed",
324
+ },
325
+ metric_names={"train.loss"},
326
+ )
327
+ handlers = [LossCurveHandler()]
328
+ else:
329
+ config = StreamConfig.default()
330
+ handlers = [
331
+ CLIHandler(
332
+ hidden_event_types=hidden_event_types or set(),
333
+ hidden_event_substrings=hidden_event_substrings or set(),
334
+ )
335
+ ]
336
+ return config, handlers
337
+
338
+
339
+ def _validate_openai_key_if_provider_is_openai(cfg_path: Path) -> None:
340
+ """Validate that OPENAI_API_KEY is set if the provider is OpenAI.
341
+
342
+ For prompt learning jobs, checks if policy.provider is 'openai' and raises
343
+ a ClickException if OPENAI_API_KEY is not set in the environment.
344
+ """
345
+ cfg = _load_toml_config(cfg_path)
346
+
347
+ # Check prompt_learning section
348
+ pl_section = cfg.get("prompt_learning", {})
349
+ if not isinstance(pl_section, dict):
350
+ return
351
+
352
+ policy = pl_section.get("policy", {})
353
+ if not isinstance(policy, dict):
354
+ return
355
+
356
+ provider = policy.get("provider", "").lower()
357
+
358
+ if provider == "openai":
359
+ openai_key = os.environ.get("OPENAI_API_KEY", "").strip()
360
+ if not openai_key:
361
+ raise click.ClickException(
362
+ "OPENAI_API_KEY is required when using provider='openai'.\n"
363
+ "Please set OPENAI_API_KEY in your .env file or environment."
364
+ )
365
+
366
+
367
+ # Module-level logging to track import and registration
368
+ import logging as _logging # noqa: E402
369
+ import sys # noqa: E402
370
+
371
+ _logger = _logging.getLogger(__name__)
372
+ _logger.debug("[TRAIN_MODULE] Module synth_ai.sdk.api.train.cli imported")
373
+
374
+ @click.command("train")
375
+ @click.argument(
376
+ "cfg_path",
377
+ required=False,
378
+ type=click.Path(exists=True, path_type=Path)
379
+ )
380
+ @click.option(
381
+ "--env",
382
+ "env_file",
383
+ type=click.Path(exists=True, path_type=Path),
384
+ help=".env file(s) to preload (skips selection prompt)",
385
+ )
386
+ @click.option(
387
+ "--task-url",
388
+ default=None,
389
+ help="Override task app base URL (RL only)"
390
+ )
391
+ @click.option(
392
+ "--dataset",
393
+ "dataset_path",
394
+ type=click.Path(),
395
+ default=None,
396
+ help="Override dataset JSONL path (SFT)",
397
+ )
398
+ @click.option("--model", default=None, help="Override model identifier")
399
+ @click.option(
400
+ "--allow-experimental",
401
+ "allow_experimental",
402
+ is_flag=True,
403
+ flag_value=True,
404
+ default=None,
405
+ help="Allow experimental models (overrides SDK_EXPERIMENTAL env)",
406
+ )
407
+ @click.option(
408
+ "--no-allow-experimental",
409
+ "allow_experimental",
410
+ is_flag=True,
411
+ flag_value=False,
412
+ help="Disallow experimental models (overrides SDK_EXPERIMENTAL env)",
413
+ )
414
+ @click.option("--idempotency", default=None, help="Idempotency-Key header for job creation")
415
+ @click.option("--dry-run", is_flag=True, hidden=True, help="Deprecated: no-op")
416
+ @click.option("--poll/--no-poll", default=True, help="Poll job status until terminal state")
417
+ @click.option(
418
+ "--poll-timeout", default=3600.0, type=float, help="Maximum seconds to poll before timing out"
419
+ )
420
+ @click.option("--poll-interval", default=5.0, type=float, help="Seconds between poll attempts")
421
+ @click.option(
422
+ "--stream-format",
423
+ type=click.Choice(["cli", "chart"]),
424
+ default="cli",
425
+ show_default=True,
426
+ help="Streaming output style (cli = line updates, chart = live loss panel)",
427
+ )
428
+ @click.option(
429
+ "--examples",
430
+ "examples_limit",
431
+ type=int,
432
+ default=None,
433
+ help="Limit SFT training to the first N examples",
434
+ )
435
+ @click.option(
436
+ "--backend",
437
+ "backend_override",
438
+ default=None,
439
+ help="Backend base URL (e.g., http://localhost:8000). Overrides BACKEND_BASE_URL env var.",
440
+ )
441
+ @click.option(
442
+ "--local-backend",
443
+ is_flag=True,
444
+ default=None,
445
+ help="Use local backend (localhost:8000). Overrides TOML [display].local_backend",
446
+ )
447
+ @click.option(
448
+ "--tui",
449
+ is_flag=True,
450
+ default=None,
451
+ help="Enable live TUI dashboard. Overrides TOML [display].tui",
452
+ )
453
+ @click.option(
454
+ "--show-curve",
455
+ is_flag=True,
456
+ default=None,
457
+ help="Show optimization curve at end. Overrides TOML [display].show_curve",
458
+ )
459
+ @click.option(
460
+ "--verbose-summary",
461
+ is_flag=True,
462
+ default=None,
463
+ help="Show detailed final summary. Overrides TOML [display].verbose_summary",
464
+ )
465
+ @click.option(
466
+ "--type",
467
+ "train_type_override",
468
+ type=click.Choice(["prompt", "rl", "sft", "graphgen", "context_learning"]),
469
+ default=None,
470
+ help="Explicitly set training type. Required for GraphGen (uses JSON datasets).",
471
+ )
472
+ @click.option(
473
+ "--rollout-budget",
474
+ "rollout_budget",
475
+ type=int,
476
+ default=None,
477
+ help="Rollout budget for GraphGen optimization (default: 100)",
478
+ )
479
+ @click.option(
480
+ "--proposer-effort",
481
+ "proposer_effort",
482
+ type=click.Choice(["low", "medium", "high"]),
483
+ default=None,
484
+ help="Proposer effort level for GraphGen (default: medium)",
485
+ )
486
+ def train_command(
487
+ cfg_path: Path | None,
488
+ env_file: Path | None,
489
+ task_url: str | None,
490
+ dataset_path: str | None,
491
+ model: str | None,
492
+ allow_experimental: bool | None,
493
+ idempotency: str | None,
494
+ dry_run: bool,
495
+ poll: bool,
496
+ poll_timeout: float,
497
+ poll_interval: float,
498
+ stream_format: str,
499
+ examples_limit: int | None,
500
+ backend_override: str | None,
501
+ local_backend: bool | None,
502
+ tui: bool | None,
503
+ show_curve: bool | None,
504
+ verbose_summary: bool | None,
505
+ train_type_override: str | None,
506
+ rollout_budget: int | None,
507
+ proposer_effort: str | None,
508
+ ) -> None:
509
+
510
+ """Interactive launcher for RL / SFT / Prompt Learning / GraphGen / Context Learning jobs."""
511
+ import traceback
512
+
513
+ ctx: dict[str, Any] = {
514
+ "cfg_path": str(cfg_path) if cfg_path else None,
515
+ "poll": poll,
516
+ "poll_timeout": poll_timeout,
517
+ "poll_interval": poll_interval,
518
+ "stream_format": stream_format,
519
+ "backend_override": backend_override,
520
+ }
521
+ log_info("train_command invoked", ctx=ctx)
522
+
523
+ # Wrap entire function in try-except to catch ALL exceptions
524
+ try:
525
+ # Log entry point IMMEDIATELY - this should always appear
526
+ sys.stderr.write("[TRAIN_CMD] Starting train command\n")
527
+ sys.stderr.flush()
528
+ click.echo(f"[TRAIN_CMD] Args: cfg_path={cfg_path}, poll={poll}", err=True)
529
+ click.echo(f"[TRAIN_CMD] Python executable: {sys.executable}", err=True)
530
+ click.echo(f"[TRAIN_CMD] Working directory: {os.getcwd()}", err=True)
531
+
532
+ try:
533
+ load_env_file()
534
+ click.echo("[TRAIN_CMD] Environment file loaded", err=True)
535
+ except Exception as e:
536
+ click.echo(f"[TRAIN_CMD] ERROR loading env file: {e}", err=True)
537
+ traceback.print_exc(file=sys.stderr)
538
+ raise
539
+
540
+ # CRITICAL: Load explicit .env file BEFORE config validation to ensure BACKEND_BASE_URL is available
541
+ if env_file and Path(env_file).exists():
542
+ from dotenv import load_dotenv
543
+ # Load with override=True to ensure BACKEND_BASE_URL from .env takes precedence
544
+ load_dotenv(Path(env_file), override=True)
545
+ click.echo(f"[TRAIN_CMD] Loaded explicit .env: {env_file}", err=True)
546
+
547
+ # Handle GraphGen specially - it uses JSON datasets, not TOML configs
548
+ if train_type_override == "graphgen":
549
+ # For GraphGen, dataset_path is required and cfg_path is ignored
550
+ if not dataset_path:
551
+ raise click.ClickException(
552
+ "GraphGen requires --dataset flag with path to JSON dataset file.\n"
553
+ "Usage: synth-ai train --type graphgen --dataset my_tasks.json"
554
+ )
555
+ train_type = train_type_override
556
+ click.echo(f"[TRAIN_CMD] GraphGen mode: using dataset {dataset_path}", err=True)
557
+ else:
558
+ # Non-GraphGen: use TOML config
559
+ if not cfg_path:
560
+ available_cfgs = find_train_cfgs_in_cwd()
561
+ if len(available_cfgs) == 1:
562
+ train_type, cfg_path_str, _ = available_cfgs[0]
563
+ cfg_path = Path(cfg_path_str)
564
+ print(f"Automatically selected {train_type} training config at", cfg_path)
565
+ else:
566
+ if len(available_cfgs) == 0:
567
+ print("No training config found in cwd.")
568
+ print("Validate your training config: synth-ai train-cfg check [CFG_PATH]")
569
+ else:
570
+ print("Multiple training configs found. Please specify which one to use:")
571
+ print_paths_formatted(available_cfgs)
572
+ print("Usage: synth-ai train --config [CFG_PATH]")
573
+ return None
574
+
575
+ train_type = train_type_override or validate_train_cfg(cfg_path)
576
+
577
+ synth_api_key, _ = get_synth_and_env_keys(env_file)
578
+
579
+ # Resolve backend URL with priority: --backend flag > BACKEND_BASE_URL env > default
580
+ if backend_override:
581
+ # CLI flag takes highest precedence
582
+ backend_base = ensure_api_base(backend_override.strip())
583
+ click.echo(f"Backend base: {backend_base} (from --backend flag)")
584
+ else:
585
+ # Check BACKEND_BASE_URL AFTER loading env file
586
+ backend_base_url_env = os.environ.get("BACKEND_BASE_URL", "").strip()
587
+ backend_override_env = os.environ.get("BACKEND_OVERRIDE", "").strip()
588
+
589
+ # Debug: Show what env vars are set
590
+ click.echo(f"🔍 DEBUG: BACKEND_BASE_URL={backend_base_url_env or '(not set)'}", err=True)
591
+ click.echo(f"🔍 DEBUG: BACKEND_OVERRIDE={backend_override_env or '(not set)'}", err=True)
592
+
593
+ # Use _default_backend() to respect BACKEND_BASE_URL env var
594
+ backend_raw = _default_backend()
595
+ click.echo(f"🔍 DEBUG: _default_backend() returned: {backend_raw}", err=True)
596
+ backend_base = ensure_api_base(backend_raw)
597
+
598
+ # Assertion: Validate backend URL is what we expect
599
+ if backend_base_url_env:
600
+ expected_backend = ensure_api_base(backend_base_url_env)
601
+ if backend_base != expected_backend:
602
+ raise click.ClickException(
603
+ f"Backend URL mismatch! Expected: {expected_backend}, Got: {backend_base}. "
604
+ f"BACKEND_BASE_URL={backend_base_url_env} but resolved to {backend_base}. "
605
+ f"This indicates BACKEND_BASE_URL is not being respected.\n"
606
+ f"💡 Solutions:\n"
607
+ f" 1. Add BACKEND_BASE_URL=http://localhost:8000 to your .env file\n"
608
+ f" 2. Use --backend http://localhost:8000 flag (requires package rebuild)\n"
609
+ f" 3. Set BACKEND_OVERRIDE=http://localhost:8000 in your shell\n"
610
+ f" 4. Set SYNTH_BACKEND_URL_OVERRIDE=local and LOCAL_BACKEND_URL=http://localhost:8000"
611
+ )
612
+
613
+ click.echo(f"Backend base: {backend_base} (key {mask_str(synth_api_key)})")
614
+ if backend_base_url_env:
615
+ click.echo(f" (from BACKEND_BASE_URL={backend_base_url_env})")
616
+
617
+ # Skip TOML-based validation for GraphGen (uses JSON datasets)
618
+ if train_type != "graphgen" and cfg_path:
619
+ _validate_openai_key_if_provider_is_openai(cfg_path)
620
+
621
+ match train_type:
622
+ case "prompt":
623
+ if not cfg_path:
624
+ raise click.ClickException("Prompt Learning requires a TOML config file.")
625
+ handle_prompt_learning(
626
+ cfg_path=cfg_path,
627
+ backend_base=backend_base,
628
+ synth_key=synth_api_key,
629
+ task_url_override=task_url,
630
+ allow_experimental=allow_experimental,
631
+ dry_run=dry_run,
632
+ poll=poll,
633
+ poll_timeout=poll_timeout,
634
+ poll_interval=poll_interval,
635
+ stream_format=stream_format,
636
+ )
637
+ case "context_learning":
638
+ if not cfg_path:
639
+ raise click.ClickException(
640
+ "Context Learning requires a TOML config file.\n"
641
+ "Usage: synth-ai train --type context_learning --config my_context.toml"
642
+ )
643
+ handle_context_learning(
644
+ cfg_path=cfg_path,
645
+ backend_base=backend_base,
646
+ synth_key=synth_api_key,
647
+ poll=poll,
648
+ stream_format=stream_format,
649
+ )
650
+ case "rl":
651
+ if not cfg_path:
652
+ raise click.ClickException("RL requires a TOML config file.")
653
+ handle_rl(
654
+ cfg_path=cfg_path,
655
+ backend_base=backend_base,
656
+ synth_key=synth_api_key,
657
+ task_url_override=task_url,
658
+ model_override=model,
659
+ idempotency=idempotency,
660
+ allow_experimental=allow_experimental,
661
+ dry_run=dry_run,
662
+ poll=poll,
663
+ poll_timeout=poll_timeout,
664
+ poll_interval=poll_interval,
665
+ stream_format=stream_format,
666
+ )
667
+ case "sft":
668
+ if not cfg_path:
669
+ raise click.ClickException("SFT requires a TOML config file.")
670
+ dataset_override_path = Path(dataset_path).expanduser().resolve() if dataset_path else None
671
+ handle_sft(
672
+ cfg_path=cfg_path,
673
+ backend_base=backend_base,
674
+ synth_key=synth_api_key,
675
+ dataset_override=dataset_override_path,
676
+ allow_experimental=allow_experimental,
677
+ dry_run=dry_run,
678
+ poll=poll,
679
+ poll_timeout=poll_timeout,
680
+ poll_interval=poll_interval,
681
+ stream_format=stream_format,
682
+ examples_limit=examples_limit,
683
+ )
684
+ case "graphgen":
685
+ if not dataset_path:
686
+ raise click.ClickException("GraphGen requires a dataset path.")
687
+ graphgen_dataset_path = Path(dataset_path).expanduser().resolve()
688
+ handle_graphgen(
689
+ dataset_path=graphgen_dataset_path,
690
+ backend_base=backend_base,
691
+ synth_key=synth_api_key,
692
+ policy_model=model,
693
+ rollout_budget=rollout_budget,
694
+ proposer_effort=proposer_effort,
695
+ poll=poll,
696
+ poll_timeout=poll_timeout,
697
+ poll_interval=poll_interval,
698
+ stream_format=stream_format,
699
+ )
700
+ except Exception as e:
701
+ ctx["error"] = type(e).__name__
702
+ log_error("train_command failed", ctx=ctx)
703
+ click.echo(f"[TRAIN_CMD] FATAL ERROR: {e}", err=True)
704
+ traceback.print_exc(file=sys.stderr)
705
+ raise
706
+ finally:
707
+ flush_logger()
708
+
709
+
710
+ def handle_context_learning(
711
+ *,
712
+ cfg_path: Path,
713
+ backend_base: str,
714
+ synth_key: str,
715
+ poll: bool,
716
+ stream_format: str,
717
+ ) -> None:
718
+ """Submit and stream a Context Learning job.
719
+
720
+ Context Learning is SSE-first; polling flags are ignored.
721
+ """
722
+ if not poll:
723
+ click.echo("Note: --no-poll is ignored for context learning (SSE streaming only).")
724
+
725
+ click.echo("\n=== Submitting Context Learning Job ===")
726
+ try:
727
+ job = ContextLearningJob.from_config(
728
+ cfg_path,
729
+ backend_url=backend_base,
730
+ api_key=synth_key,
731
+ )
732
+ result = job.submit()
733
+ except Exception as e:
734
+ raise click.ClickException(str(e))
735
+
736
+ click.echo("\n✓ Job created:")
737
+ click.echo(f" Context Learning Job ID: {result.job_id}")
738
+ click.echo(f" Status: {result.status}")
739
+
740
+ click.echo("\n=== Streaming Job Progress ===")
741
+ if stream_format == "chart":
742
+ click.echo("Chart stream format is not supported for context learning; using CLI output.")
743
+
744
+ try:
745
+ final_status = job.stream_until_complete()
746
+ except Exception as e:
747
+ raise click.ClickException(str(e))
748
+
749
+ status = final_status.get("status") if isinstance(final_status, dict) else "unknown"
750
+ click.echo(f"\nFinal status: {status}")
751
+ click.echo(preview_json(final_status, limit=600))
752
+
753
+ if status in {"succeeded", "completed"}:
754
+ click.echo("\n=== Best Preflight Script ===")
755
+ try:
756
+ best = job.download_best_script()
757
+ if best.preflight_script:
758
+ click.echo(best.preflight_script[:2000])
759
+ if len(best.preflight_script) > 2000:
760
+ click.echo(
761
+ f"\n... (truncated, {len(best.preflight_script)} chars total)"
762
+ )
763
+ except Exception as e:
764
+ click.echo(f"⚠️ Could not download best script: {e}")
765
+
766
+
767
+ def _wait_for_training_file(
768
+ backend_base: str, api_key: str, file_id: str, *, timeout: float = 10.0
769
+ ) -> None:
770
+ """Wait for training file to be visible after upload.
771
+
772
+ Reduced from 120s to 10s because:
773
+ - POST response already confirms file is uploaded
774
+ - Backend now forces read-your-writes consistency
775
+ - By job creation time, replica lag has resolved
776
+ - Quick sanity check only, not critical path
777
+ """
778
+ url = f"{backend_base.rstrip('/')}/files/{file_id}"
779
+ headers = {"Authorization": f"Bearer {api_key}"}
780
+ elapsed = 0.0
781
+ interval = 2.0
782
+ first_check = True
783
+ while True:
784
+ resp = http_get(url, headers=headers, timeout=30.0)
785
+ if resp.status_code == 200:
786
+ try:
787
+ data = resp.json()
788
+ except json.JSONDecodeError:
789
+ data = {}
790
+ status = str(
791
+ data.get("status") or data.get("state") or data.get("storage_state") or "ready"
792
+ ).lower()
793
+ if first_check:
794
+ click.echo(f"File uploaded successfully (id={file_id}, status={status})")
795
+ first_check = False
796
+ if status in {"ready", "uploaded", "stored", "complete"}:
797
+ click.echo(f"✓ Training file ready (status={status})")
798
+ return
799
+ # Show progress for processing states
800
+ if status in {"processing", "pending", "validating"}:
801
+ click.echo(
802
+ f" Waiting for file processing... (status={status}, {elapsed:.0f}s elapsed)"
803
+ )
804
+ elif resp.status_code == 404:
805
+ # Keep polling; object may not be visible yet
806
+ if first_check:
807
+ click.echo(f"Waiting for file {file_id} to become visible...")
808
+ first_check = False
809
+ elif resp.status_code in {401, 403}:
810
+ # Auth errors won't resolve by polling - fail immediately
811
+ try:
812
+ error_body = resp.json()
813
+ except json.JSONDecodeError:
814
+ error_body = resp.text[:400]
815
+ click.echo("\n[ERROR] Authentication failed when checking training file:")
816
+ click.echo(f" URL: {url}")
817
+ click.echo(f" Status: {resp.status_code}")
818
+ click.echo(f" Response: {error_body}")
819
+ click.echo(f" API key: {mask_value(api_key)}")
820
+ raise click.ClickException(
821
+ f"Authentication error ({resp.status_code}). "
822
+ "Check that your SYNTH_API_KEY is valid and has permission to access this organization's files."
823
+ )
824
+ else:
825
+ # Other errors - show details but keep polling
826
+ try:
827
+ error_body = resp.json()
828
+ except json.JSONDecodeError:
829
+ error_body = resp.text[:400]
830
+ click.echo(f"[WARN] Unexpected response checking file {file_id}:")
831
+ click.echo(f" URL: {url}")
832
+ click.echo(f" Status: {resp.status_code}")
833
+ click.echo(f" Response: {error_body}")
834
+
835
+ if elapsed >= timeout:
836
+ raise click.ClickException(
837
+ f"Training file {file_id} not ready after {timeout:.0f}s (last status: {resp.status_code})"
838
+ )
839
+ sleep(interval)
840
+ elapsed += interval
841
+
842
+
843
+ def handle_rl(
844
+ *,
845
+ cfg_path: Path,
846
+ backend_base: str,
847
+ synth_key: str,
848
+ task_url_override: str | None,
849
+ model_override: str | None,
850
+ idempotency: str | None,
851
+ allow_experimental: bool | None,
852
+ dry_run: bool,
853
+ poll: bool,
854
+ poll_timeout: float,
855
+ poll_interval: float,
856
+ stream_format: str,
857
+ ) -> None:
858
+ ctx: dict[str, Any] = {
859
+ "cfg_path": str(cfg_path),
860
+ "backend_base": backend_base,
861
+ "task_url_override": task_url_override,
862
+ "poll": poll,
863
+ }
864
+ log_info("handle_rl invoked", ctx=ctx)
865
+ overrides: dict[str, Any] = {
866
+ "backend": backend_base,
867
+ "task_url": task_url_override,
868
+ "model": model_override,
869
+ }
870
+ build = build_rl_payload(
871
+ config_path=cfg_path,
872
+ task_url=task_url_override or os.environ.get("TASK_APP_URL", ""),
873
+ overrides=overrides,
874
+ idempotency=idempotency,
875
+ allow_experimental=allow_experimental,
876
+ )
877
+
878
+ # Backend-side verification: try ALL org environment keys against /health and /task_info
879
+ verify_url = f"{backend_base}/rl/verify_task_app"
880
+ verify_headers = {"Authorization": f"Bearer {synth_key}", "Content-Type": "application/json"}
881
+ try:
882
+ vresp = http_post(
883
+ verify_url, headers=verify_headers, json_body={"endpoint_base_url": build.task_url}
884
+ )
885
+ try:
886
+ parsed_json = vresp.json()
887
+ except json.JSONDecodeError:
888
+ parsed_json = None
889
+
890
+ if isinstance(parsed_json, Mapping):
891
+ vjs: dict[str, Any] = dict(parsed_json)
892
+ else:
893
+ vjs = {
894
+ "status": vresp.status_code,
895
+ "text": (vresp.text or "")[:400],
896
+ }
897
+ if parsed_json is not None:
898
+ vjs["body"] = parsed_json
899
+ except Exception as _ve:
900
+ raise click.ClickException(
901
+ f"Task app verification call failed: {type(_ve).__name__}: {_ve}"
902
+ ) from _ve
903
+ if vresp.status_code is not None and vresp.status_code >= 400:
904
+ click.echo("Task app verification error:\n" + preview_json(vjs, limit=800))
905
+ raise click.ClickException(f"Verification failed with status {vresp.status_code}")
906
+ if not bool(vjs.get("any_ok")):
907
+ click.echo("Task app verification failed; no auth combination succeeded. Full report:")
908
+ click.echo(preview_json(vjs, limit=1200))
909
+ raise click.ClickException("Task app verification failed (auth)")
910
+ else:
911
+ # Print concise summary
912
+ try:
913
+ cands = vjs.get("candidates_first15") or []
914
+ attempts_raw = vjs.get("attempts")
915
+ attempts: list[Mapping[str, Any]] = (
916
+ [a for a in attempts_raw if isinstance(a, Mapping)]
917
+ if isinstance(attempts_raw, list)
918
+ else []
919
+ )
920
+ statuses = [attempt.get("status") for attempt in attempts]
921
+ click.echo(f"Verification OK (candidates={cands}, statuses={statuses})")
922
+ except (KeyError, ValueError, AttributeError):
923
+ # Parsing verification summary failed, but verification itself succeeded
924
+ click.echo("Verification OK")
925
+
926
+ env_key = get_required_value(
927
+ "environment_api_key",
928
+ env_value=os.environ.get("ENVIRONMENT_API_KEY"),
929
+ )
930
+ os.environ["ENVIRONMENT_API_KEY"] = env_key
931
+
932
+ click.echo("Performing task app health check…")
933
+ health = check_local_api_health(build.task_url, env_key)
934
+ if not health.ok:
935
+ click.echo(f"Task app health check failed: {health.detail}")
936
+ raise click.ClickException("Aborting due to failing health check")
937
+ else:
938
+ click.echo("Task app healthy")
939
+
940
+ create_url = f"{backend_base}/rl/jobs"
941
+ headers = {"Authorization": f"Bearer {synth_key}", "Content-Type": "application/json"}
942
+ if build.idempotency:
943
+ headers["Idempotency-Key"] = build.idempotency
944
+
945
+ click.echo(f"POST {create_url}")
946
+ click.echo("Payload preview:\n" + preview_json(build.payload, limit=800))
947
+
948
+ resp = http_post(create_url, headers=headers, json_body=build.payload)
949
+ try:
950
+ js = resp.json()
951
+ except json.JSONDecodeError as e:
952
+ click.echo(f"⚠️ Failed to parse JSON response: {e}")
953
+ js = {"status": resp.status_code, "text": resp.text[:400]}
954
+ click.echo(f"Response {resp.status_code}: {preview_json(js, limit=400)}")
955
+ if resp.status_code not in (200, 201):
956
+ raise click.ClickException("Job creation failed")
957
+ job_id = js.get("job_id") or js.get("id")
958
+ if not job_id:
959
+ raise click.ClickException("Response missing job id")
960
+
961
+ if not poll:
962
+ click.echo(f"Created job {job_id} (polling disabled)")
963
+ return
964
+
965
+ click.echo("\n=== Streaming Job Progress ===")
966
+
967
+ # Enable metrics for prompt learning
968
+ if stream_format == "chart":
969
+ config = StreamConfig(
970
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS},
971
+ event_types={
972
+ "prompt.learning.progress",
973
+ "prompt.learning.gepa.start",
974
+ "prompt.learning.gepa.complete",
975
+ },
976
+ metric_names={"gepa.transformation.mean_score"},
977
+ )
978
+ handlers = [LossCurveHandler()]
979
+ click.echo("Using live chart (metric=gepa.transformation.mean_score)")
980
+ else:
981
+ config = StreamConfig(
982
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS},
983
+ metric_names={"gepa.transformation.mean_score"},
984
+ )
985
+ handlers = [CLIHandler(hidden_event_substrings=_DEFAULT_RL_HIDDEN_SUBSTRINGS)]
986
+
987
+ streamer = JobStreamer(
988
+ base_url=backend_base,
989
+ api_key=synth_key,
990
+ job_id=job_id,
991
+ endpoints=StreamEndpoints.rl(job_id),
992
+ config=config,
993
+ handlers=handlers,
994
+ interval_seconds=poll_interval,
995
+ timeout_seconds=poll_timeout,
996
+ )
997
+ final_status = asyncio.run(streamer.stream_until_terminal())
998
+ click.echo(f"Final status: {final_status.get('status', 'unknown')}")
999
+ click.echo(preview_json(final_status, limit=600))
1000
+
1001
+
1002
+ def handle_sft(
1003
+ *,
1004
+ cfg_path: Path,
1005
+ backend_base: str,
1006
+ synth_key: str,
1007
+ dataset_override: Path | None,
1008
+ allow_experimental: bool | None,
1009
+ dry_run: bool,
1010
+ poll: bool,
1011
+ poll_timeout: float,
1012
+ poll_interval: float,
1013
+ stream_format: str,
1014
+ examples_limit: int | None,
1015
+ ) -> None:
1016
+ ctx: dict[str, Any] = {
1017
+ "cfg_path": str(cfg_path),
1018
+ "backend_base": backend_base,
1019
+ "dataset_override": str(dataset_override) if dataset_override else None,
1020
+ "poll": poll,
1021
+ }
1022
+ log_info("handle_sft invoked", ctx=ctx)
1023
+ try:
1024
+ build = build_sft_payload(
1025
+ config_path=cfg_path,
1026
+ dataset_override=dataset_override,
1027
+ allow_experimental=allow_experimental,
1028
+ )
1029
+ except TrainError as exc:
1030
+ _raise_sft_usage_error(exc)
1031
+
1032
+ limited_path: Path | None = None
1033
+
1034
+ try:
1035
+ if examples_limit is not None:
1036
+ limited_path = limit_jsonl_examples(build.train_file, examples_limit)
1037
+ click.echo(
1038
+ f"Using first {examples_limit} examples from {build.train_file} -> {limited_path}"
1039
+ )
1040
+ build.train_file = limited_path
1041
+
1042
+ click.echo("Validating training dataset…")
1043
+ validate_sft_jsonl(build.train_file)
1044
+ if build.validation_file and build.validation_file.suffix == ".jsonl":
1045
+ click.echo("Validating validation dataset…")
1046
+ validate_sft_jsonl(build.validation_file)
1047
+
1048
+ upload_url = f"{backend_base.rstrip('/')}/files"
1049
+ click.echo("\n=== Uploading Training Data ===")
1050
+ click.echo(f"Dataset: {build.train_file}")
1051
+ click.echo(f"Destination: {upload_url}")
1052
+ resp = post_multipart(
1053
+ upload_url, api_key=synth_key, file_field="file", file_path=build.train_file
1054
+ )
1055
+ js = (
1056
+ resp.json()
1057
+ if resp.headers.get("content-type", "").startswith("application/json")
1058
+ else {}
1059
+ )
1060
+ if resp.status_code is not None and resp.status_code >= 400 or "id" not in js:
1061
+ click.echo("\n[ERROR] Training file upload failed:")
1062
+ click.echo(f" URL: {upload_url}")
1063
+ click.echo(f" Status: {resp.status_code}")
1064
+ click.echo(f" Response: {js or resp.text[:400]}")
1065
+ click.echo(f" File: {build.train_file}")
1066
+ raise click.ClickException(
1067
+ f"Training file upload failed with status {resp.status_code}"
1068
+ )
1069
+ train_file_id = js["id"]
1070
+ click.echo(f"✓ Training file uploaded (id={train_file_id})")
1071
+ val_file_id = None
1072
+ if build.validation_file:
1073
+ click.echo(f"Uploading validation dataset: {build.validation_file}")
1074
+ vresp = post_multipart(
1075
+ upload_url,
1076
+ api_key=synth_key,
1077
+ file_field="file",
1078
+ file_path=build.validation_file,
1079
+ )
1080
+ vjs = (
1081
+ vresp.json()
1082
+ if vresp.headers.get("content-type", "").startswith("application/json")
1083
+ else {}
1084
+ )
1085
+ if vresp.status_code is not None and vresp.status_code < 400 and "id" in vjs:
1086
+ val_file_id = vjs["id"]
1087
+ click.echo(f"✓ Validation file uploaded (id={val_file_id})")
1088
+ else:
1089
+ click.echo(
1090
+ f"[WARN] Validation upload failed ({vresp.status_code}): {vjs or vresp.text[:200]}"
1091
+ )
1092
+ payload = dict(build.payload)
1093
+ payload["training_file_id"] = train_file_id
1094
+ if val_file_id:
1095
+ payload.setdefault("metadata", {}).setdefault("effective_config", {}).setdefault(
1096
+ "data", {}
1097
+ )["validation_files"] = [val_file_id]
1098
+
1099
+ click.echo("\n=== Checking File Processing Status ===")
1100
+ try:
1101
+ _wait_for_training_file(backend_base, synth_key, train_file_id)
1102
+ except click.ClickException as exc:
1103
+ click.echo(f"[WARN] File readiness check failed: {exc}")
1104
+ click.echo("Proceeding anyway - backend will validate file during job creation...")
1105
+
1106
+ click.echo("\n=== Creating Training Job ===")
1107
+ click.echo("Job payload preview:")
1108
+ click.echo(preview_json(payload, limit=800))
1109
+
1110
+ create_url = f"{backend_base}/learning/jobs"
1111
+ headers = {"Authorization": f"Bearer {synth_key}", "Content-Type": "application/json"}
1112
+ click.echo(f"\nPOST {create_url}")
1113
+ resp = http_post(create_url, headers=headers, json_body=payload)
1114
+ js = (
1115
+ resp.json()
1116
+ if resp.headers.get("content-type", "").startswith("application/json")
1117
+ else {}
1118
+ )
1119
+ if resp.status_code not in (200, 201):
1120
+ click.echo("\n[ERROR] Job creation failed:")
1121
+ click.echo(f" URL: {create_url}")
1122
+ click.echo(f" Status: {resp.status_code}")
1123
+ click.echo(f" Response: {preview_json(js, limit=600)}")
1124
+ raise click.ClickException(f"Job creation failed with status {resp.status_code}")
1125
+ job_id = js.get("job_id") or js.get("id")
1126
+ if not job_id:
1127
+ raise click.ClickException("Response missing job id")
1128
+ click.echo(f"✓ Job created (id={job_id})")
1129
+
1130
+ click.echo("\n=== Starting Training Job ===")
1131
+ start_url = f"{backend_base}/learning/jobs/{job_id}/start"
1132
+ click.echo(f"POST {start_url}")
1133
+ start_resp = http_post(start_url, headers=headers, json_body={})
1134
+ if start_resp.status_code not in (200, 201):
1135
+ click.echo(f"[WARN] Job start returned status {start_resp.status_code}")
1136
+ else:
1137
+ click.echo("✓ Job started")
1138
+
1139
+ if not poll:
1140
+ click.echo(f"Started job {job_id} (polling disabled)")
1141
+ return
1142
+
1143
+ click.echo("\n=== Streaming Job Progress ===")
1144
+ config, handlers = _build_stream_components(
1145
+ stream_format, hidden_event_types=_DEFAULT_SFT_HIDDEN_EVENTS
1146
+ )
1147
+ if stream_format == "chart":
1148
+ click.echo("Using live loss chart (metric=train.loss)")
1149
+ streamer = JobStreamer(
1150
+ base_url=backend_base,
1151
+ api_key=synth_key,
1152
+ job_id=job_id,
1153
+ endpoints=StreamEndpoints.learning(job_id),
1154
+ config=config,
1155
+ handlers=handlers,
1156
+ interval_seconds=poll_interval,
1157
+ timeout_seconds=poll_timeout,
1158
+ )
1159
+ final_status = asyncio.run(streamer.stream_until_terminal())
1160
+ status = final_status.get('status') if isinstance(final_status, dict) else 'unknown'
1161
+ click.echo(f"Final status: {status}")
1162
+ click.echo(preview_json(final_status, limit=600))
1163
+ finally:
1164
+ if limited_path is not None:
1165
+ with contextlib.suppress(OSError):
1166
+ limited_path.unlink(missing_ok=True)
1167
+ # Clean up empty parent directory if possible
1168
+ with contextlib.suppress(OSError):
1169
+ limited_path.parent.rmdir()
1170
+
1171
+
1172
+ def handle_graphgen(
1173
+ *,
1174
+ dataset_path: Path,
1175
+ backend_base: str,
1176
+ synth_key: str,
1177
+ policy_model: str | None,
1178
+ rollout_budget: int | None,
1179
+ proposer_effort: str | None,
1180
+ poll: bool,
1181
+ poll_timeout: float,
1182
+ poll_interval: float,
1183
+ stream_format: str,
1184
+ ) -> None:
1185
+ """Handle GraphGen workflow optimization job creation and streaming.
1186
+
1187
+ GraphGen uses JSON dataset files and auto-generates task apps.
1188
+ """
1189
+ ctx: dict[str, Any] = {
1190
+ "dataset_path": str(dataset_path),
1191
+ "backend_base": backend_base,
1192
+ "poll": poll,
1193
+ }
1194
+ log_info("handle_graphgen invoked", ctx=ctx)
1195
+
1196
+ # Load dataset
1197
+ click.echo(f"Loading GraphGen dataset from: {dataset_path}")
1198
+ try:
1199
+ dataset = load_graphgen_taskset(dataset_path)
1200
+ except FileNotFoundError:
1201
+ raise click.ClickException(f"Dataset file not found: {dataset_path}")
1202
+ except ValueError as e:
1203
+ raise click.ClickException(f"Invalid GraphGen dataset format: {e}")
1204
+
1205
+ problem_spec = None
1206
+ try:
1207
+ raw_dataset = json.loads(dataset_path.read_text())
1208
+ problem_spec = raw_dataset.get("problem_spec") or raw_dataset.get("initial_prompt")
1209
+ except Exception:
1210
+ problem_spec = None
1211
+
1212
+ click.echo(f"Dataset loaded: {dataset.metadata.name}")
1213
+ click.echo(f" Tasks: {len(dataset.tasks)}")
1214
+ click.echo(f" Gold outputs: {len(dataset.gold_outputs)}")
1215
+ click.echo(f" Verifier mode: {dataset.verifier_config.mode}")
1216
+
1217
+ # Create GraphGen job
1218
+ job = GraphGenJob.from_dataset(
1219
+ dataset=dataset,
1220
+ policy_model=policy_model or "gpt-4o-mini",
1221
+ rollout_budget=rollout_budget or 100,
1222
+ proposer_effort=proposer_effort or "medium", # type: ignore
1223
+ problem_spec=problem_spec,
1224
+ backend_url=backend_base,
1225
+ api_key=synth_key,
1226
+ auto_start=True,
1227
+ )
1228
+
1229
+ click.echo("\n=== Submitting GraphGen Job ===")
1230
+ click.echo(f"Policy model: {job.config.policy_model}")
1231
+ click.echo(f"Rollout budget: {job.config.rollout_budget}")
1232
+ click.echo(f"Proposer effort: {job.config.proposer_effort}")
1233
+
1234
+ try:
1235
+ result = job.submit()
1236
+ except RuntimeError as e:
1237
+ raise click.ClickException(str(e))
1238
+
1239
+ click.echo(f"\n✓ Job created:")
1240
+ click.echo(f" GraphGen Job ID: {result.graphgen_job_id}")
1241
+ click.echo(f" Status: {result.status}")
1242
+
1243
+ if not poll:
1244
+ click.echo(f"\nCreated job {result.graphgen_job_id} (polling disabled)")
1245
+ return
1246
+
1247
+ click.echo("\n=== Streaming Job Progress ===")
1248
+
1249
+ # Build stream handlers
1250
+ if stream_format == "chart":
1251
+ config = StreamConfig(
1252
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS},
1253
+ metric_names={"gepa.transformation.mean_score"},
1254
+ )
1255
+ handlers = [LossCurveHandler()]
1256
+ click.echo("Using live loss chart (metric=gepa.transformation.mean_score)")
1257
+ else:
1258
+ config = StreamConfig(
1259
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS},
1260
+ max_events_per_poll=500,
1261
+ deduplicate=True,
1262
+ )
1263
+ handlers = [GraphGenHandler()]
1264
+
1265
+ # Stream until complete
1266
+ try:
1267
+ final_status = job.stream_until_complete(
1268
+ timeout=poll_timeout,
1269
+ interval=poll_interval,
1270
+ handlers=handlers,
1271
+ )
1272
+ except TimeoutError as e:
1273
+ raise click.ClickException(str(e))
1274
+
1275
+ status = final_status.get('status') if isinstance(final_status, dict) else 'unknown'
1276
+ click.echo(f"\nFinal status: {status}")
1277
+ click.echo(preview_json(final_status, limit=600))
1278
+
1279
+ # Download and display best prompt if succeeded
1280
+ if status == "succeeded" or status == "completed":
1281
+ click.echo("\n=== Best Optimized Prompt ===")
1282
+ try:
1283
+ prompt = job.download_prompt()
1284
+ if prompt:
1285
+ click.echo(prompt[:2000])
1286
+ if len(prompt) > 2000:
1287
+ click.echo(f"\n... (truncated, {len(prompt)} chars total)")
1288
+ except Exception as e:
1289
+ click.echo(f"⚠️ Could not download prompt: {e}")
1290
+
1291
+
1292
+ def _raise_sft_usage_error(exc: TrainError) -> NoReturn:
1293
+ message = str(exc).strip()
1294
+ lower_msg = message.lower()
1295
+ context = "Preparing SFT training job payload"
1296
+ impact = "Cannot submit training job without a valid dataset path"
1297
+
1298
+ if "dataset not specified" in lower_msg:
1299
+ raise click.UsageError(
1300
+ format_error_message(
1301
+ summary="Dataset path required",
1302
+ context=context,
1303
+ problem="No dataset path was provided via config or CLI",
1304
+ impact=impact,
1305
+ solutions=[
1306
+ ("Add [job].data = \"/path/to/data.jsonl\" to the config", "Persist the dataset path in the TOML file"),
1307
+ ("Re-run with --dataset /path/to/data.jsonl", "Override the dataset path from the CLI"),
1308
+ ("Use an absolute path accessible from the current working directory", "Relative paths are resolved from the shell cwd"),
1309
+ ],
1310
+ )
1311
+ ) from exc
1312
+
1313
+ if "dataset not found" in lower_msg:
1314
+ raise click.UsageError(
1315
+ format_error_message(
1316
+ summary="Dataset path not found",
1317
+ context=context,
1318
+ problem=message,
1319
+ impact=impact,
1320
+ solutions=[
1321
+ ("Verify the dataset path exists on disk", "Double-check spelling and that the file hasn't moved"),
1322
+ ("Provide an absolute path to the dataset file", "Avoid relying on relative paths that resolve incorrectly"),
1323
+ ("Sync the dataset to this machine before running the CLI", "Remote paths must be accessible locally"),
1324
+ ],
1325
+ )
1326
+ ) from exc
1327
+
1328
+ raise click.ClickException(message) from exc
1329
+
1330
+
1331
+ def _save_verbose_log_file(
1332
+ events: list[dict[str, Any]],
1333
+ log_file: Path,
1334
+ algorithm_name: str,
1335
+ job_id: str,
1336
+ append_summary: bool = False,
1337
+ ) -> None:
1338
+ """Save a verbose log file with all events in chronological order, including summary.
1339
+
1340
+ If append_summary is True, only append the summary section (events were already streamed live).
1341
+ """
1342
+ import json
1343
+ from datetime import datetime
1344
+
1345
+ try:
1346
+ lines = []
1347
+ if not append_summary:
1348
+ # Full log file with header and all events
1349
+ lines.append("=" * 80)
1350
+ lines.append(f"{algorithm_name} PROMPT LEARNING VERBOSE LOG")
1351
+ lines.append("=" * 80)
1352
+ lines.append(f"Job ID: {job_id}")
1353
+ lines.append(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
1354
+ lines.append(f"Total Events: {len(events)}")
1355
+ lines.append("=" * 80)
1356
+ lines.append("")
1357
+
1358
+ # Sort events by timestamp if available
1359
+ def get_timestamp(event: dict[str, Any]) -> str:
1360
+ return event.get("timestamp", event.get("created_at", ""))
1361
+
1362
+ sorted_events = sorted(events, key=get_timestamp)
1363
+
1364
+ # Only include events if not appending summary (events were already streamed live)
1365
+ if not append_summary:
1366
+ for idx, event in enumerate(sorted_events, 1):
1367
+ if not isinstance(event, dict):
1368
+ continue
1369
+
1370
+ event_type = event.get("type", "unknown")
1371
+ timestamp = event.get("timestamp") or event.get("created_at", "")
1372
+ level = event.get("level", "info")
1373
+ message = event.get("message", "")
1374
+ data = event.get("data", {})
1375
+
1376
+ lines.append(f"[{idx}] {timestamp} [{level.upper()}] {event_type}")
1377
+ if message:
1378
+ lines.append(f" Message: {message}")
1379
+ if data:
1380
+ # Format data nicely (truncate very long values)
1381
+ formatted_data = {}
1382
+ for key, value in data.items():
1383
+ if isinstance(value, dict | list):
1384
+ # Convert to JSON string, truncate if too long
1385
+ json_str = json.dumps(value, indent=2)
1386
+ if len(json_str) > 1000:
1387
+ json_str = json_str[:1000] + "... (truncated)"
1388
+ formatted_data[key] = json_str
1389
+ elif isinstance(value, str) and len(value) > 500:
1390
+ formatted_data[key] = value[:500] + "... (truncated)"
1391
+ else:
1392
+ formatted_data[key] = value
1393
+
1394
+ if formatted_data:
1395
+ lines.append(f" Data: {json.dumps(formatted_data, indent=2)}")
1396
+ lines.append("")
1397
+
1398
+ # Add summary table and chart at the end (always included)
1399
+ if append_summary:
1400
+ lines.append("\n\n")
1401
+ lines.append("=" * 80)
1402
+ lines.append("FINAL SUMMARY")
1403
+ lines.append("=" * 80)
1404
+
1405
+ try:
1406
+ from .summary import _generate_summary_text
1407
+ # Extract optimization curve from events
1408
+ optimization_curve = None
1409
+ trial_scores = []
1410
+ for event in sorted_events:
1411
+ if isinstance(event, dict):
1412
+ event_type = event.get("type", "")
1413
+ if event_type in ("prompt.learning.trial.complete", "mipro.new_incumbent"):
1414
+ data = event.get("data", {})
1415
+ trial_num = data.get("trial") or data.get("trial_num")
1416
+ score = data.get("score") or data.get("minibatch_score")
1417
+ if trial_num is not None and score is not None:
1418
+ trial_scores.append((trial_num, score))
1419
+
1420
+ if trial_scores:
1421
+ best_so_far = {}
1422
+ for trial_num, score in sorted(trial_scores):
1423
+ if trial_num not in best_so_far or score > best_so_far[trial_num]:
1424
+ best_so_far[trial_num] = score
1425
+ optimization_curve = sorted(best_so_far.items())
1426
+
1427
+ summary_text, curve_text = _generate_summary_text(
1428
+ events=sorted_events,
1429
+ algorithm=algorithm_name.lower() if algorithm_name else None,
1430
+ optimization_curve=optimization_curve,
1431
+ )
1432
+ if summary_text:
1433
+ lines.append(summary_text)
1434
+ if curve_text:
1435
+ lines.append("")
1436
+ lines.append(curve_text)
1437
+ except Exception as e:
1438
+ lines.append(f"⚠️ Could not generate summary: {e}")
1439
+
1440
+ lines.append("=" * 80)
1441
+ lines.append("END OF LOG")
1442
+ lines.append("=" * 80)
1443
+
1444
+ # Write to file (append if summary-only mode)
1445
+ mode = "a" if append_summary else "w"
1446
+ with open(log_file, mode, encoding="utf-8") as f:
1447
+ if append_summary:
1448
+ f.write("\n")
1449
+ f.write("\n".join(lines))
1450
+
1451
+ except Exception as e:
1452
+ click.echo(f"⚠️ Could not save verbose log file: {e}")
1453
+
1454
+
1455
+ def _save_prompt_learning_results_locally(
1456
+ *,
1457
+ backend_base: str,
1458
+ api_key: str,
1459
+ job_id: str,
1460
+ config_path: Path,
1461
+ results_folder: Path,
1462
+ ) -> None:
1463
+ """Fetch events and generate results file locally after prompt learning completes."""
1464
+ from datetime import datetime
1465
+
1466
+ try:
1467
+ # Fetch all events
1468
+ url = f"{backend_base}/prompt-learning/online/jobs/{job_id}/events?limit={_RESULTS_FILE_MAX_EVENTS}"
1469
+ headers = {"Authorization": f"Bearer {api_key}"}
1470
+ resp = http_get(url, headers=headers, timeout=30.0)
1471
+
1472
+ if resp.status_code != 200:
1473
+ click.echo(f"⚠️ Could not fetch events to generate results file (status={resp.status_code})")
1474
+ return
1475
+
1476
+ data = resp.json()
1477
+ # Handle both list response (backend) and dict response (legacy compatibility)
1478
+ if isinstance(data, list):
1479
+ events = data
1480
+ elif isinstance(data, dict):
1481
+ events = data.get("events", [])
1482
+ if not isinstance(events, list):
1483
+ click.echo(f"⚠️ Events field is not a list: {type(events).__name__}")
1484
+ return
1485
+ else:
1486
+ click.echo(f"⚠️ Unexpected response type: {type(data).__name__}")
1487
+ return
1488
+
1489
+ if not events:
1490
+ return
1491
+
1492
+ # Extract key data from events
1493
+ best_score = None
1494
+ best_prompt = None
1495
+ baseline_score = None
1496
+ attempted_candidates = []
1497
+ optimized_candidates = []
1498
+ mipro_topk_candidates = [] # Collect MIPRO top-K candidates
1499
+ proposed_instructions = [] # Collect proposed instructions from MIPRO
1500
+ proposed_transformations = [] # Collect proposed transformations from GEPA
1501
+
1502
+ for event in events:
1503
+ if not isinstance(event, dict):
1504
+ continue # Skip malformed events
1505
+
1506
+ event_type = event.get("type", "")
1507
+ event_data = event.get("data", {})
1508
+ if not isinstance(event_data, dict):
1509
+ event_data = {} # Fallback to empty dict for safety
1510
+
1511
+ if event_type == _PROMPT_LEARNING_EVENT_BEST_PROMPT:
1512
+ best_score = event_data.get("best_score")
1513
+ best_prompt = event_data.get("best_prompt")
1514
+ elif event_type == _PROMPT_LEARNING_EVENT_FINAL_RESULTS:
1515
+ attempted_candidates = event_data.get("attempted_candidates", [])
1516
+ optimized_candidates = event_data.get("optimized_candidates", [])
1517
+ elif event_type == _PROMPT_LEARNING_EVENT_VALIDATION_SCORED:
1518
+ # Check if this is the baseline by checking for is_baseline flag or baseline in message
1519
+ is_baseline = event_data.get("is_baseline", False)
1520
+ if not is_baseline:
1521
+ msg = event.get("message", "")
1522
+ is_baseline = "baseline" in msg.lower()
1523
+ if is_baseline:
1524
+ baseline_score = event_data.get("accuracy")
1525
+ elif event_type == _PROMPT_LEARNING_EVENT_GEPA_COMPLETE and best_score is None:
1526
+ best_score = event_data.get("best_score")
1527
+ elif event_type == _PROMPT_LEARNING_EVENT_MIPRO_COMPLETE:
1528
+ # MIPRO completion event includes best_prompt and best_score
1529
+ if best_score is None:
1530
+ best_score = event_data.get("best_score")
1531
+ if best_prompt is None:
1532
+ best_prompt = event_data.get("best_prompt")
1533
+ elif event_type == "mipro.topk.evaluated":
1534
+ # Extract MIPRO top-K candidate data with full details
1535
+ rank = event_data.get("rank")
1536
+ train_score = event_data.get("train_score")
1537
+ test_score = event_data.get("test_score")
1538
+ if rank is not None and train_score is not None and test_score is not None:
1539
+ # Extract full instruction text (may be multi-line)
1540
+ instruction_text = event_data.get("instruction_text", "")
1541
+ if not instruction_text:
1542
+ # Try to get from instruction_lines if available
1543
+ instruction_lines = event_data.get("instruction_lines", [])
1544
+ if instruction_lines:
1545
+ instruction_text = "\n".join(str(line) for line in instruction_lines)
1546
+
1547
+ mipro_topk_candidates.append({
1548
+ "rank": rank,
1549
+ "train_score": train_score,
1550
+ "test_score": test_score,
1551
+ "lift_absolute": event_data.get("lift_absolute"),
1552
+ "lift_percent": event_data.get("lift_percent"),
1553
+ "instruction_text": instruction_text,
1554
+ "instruction_lines": event_data.get("instruction_lines", []),
1555
+ "demo_indices": event_data.get("demo_indices", []),
1556
+ "stage_payloads": event_data.get("stage_payloads", {}),
1557
+ "instruction_indices": event_data.get("instruction_indices", []),
1558
+ "test_per_seed": event_data.get("test_per_seed", {}),
1559
+ })
1560
+ elif event_type == "mipro.baseline.test":
1561
+ # Extract baseline test score
1562
+ if baseline_score is None:
1563
+ baseline_score = event_data.get("test_score")
1564
+ elif event_type == "mipro.instruction.proposed":
1565
+ # Collect proposed instructions
1566
+ proposed_instructions.append({
1567
+ "iteration": event_data.get("iteration"),
1568
+ "stage_id": event_data.get("stage_id"),
1569
+ "module_id": event_data.get("module_id"),
1570
+ "instruction_id": event_data.get("instruction_id"),
1571
+ "instruction_text": event_data.get("instruction_text", ""),
1572
+ "instruction_lines": event_data.get("instruction_lines", []),
1573
+ "demo_indices": event_data.get("demo_indices", []),
1574
+ "proposal_id": event_data.get("proposal_id"),
1575
+ "timestamp": event.get("created_at"),
1576
+ })
1577
+ elif event_type == "gepa.transformation.proposed":
1578
+ # Collect proposed transformations
1579
+ proposed_transformations.append({
1580
+ "generation": event_data.get("generation"),
1581
+ "mutation_type": event_data.get("mutation_type"),
1582
+ "operator": event_data.get("operator"),
1583
+ "transformation_id": event_data.get("transformation_id"),
1584
+ "parent_id": event_data.get("parent_id"),
1585
+ "transformation_text": event_data.get("transformation_text", ""),
1586
+ "transformation_dict": event_data.get("transformation_dict", {}),
1587
+ "mutation_params": event_data.get("mutation_params", {}),
1588
+ "timestamp": event.get("created_at"),
1589
+ })
1590
+
1591
+ # Check if we have any results to display (best_prompt, best_score, or candidates)
1592
+ has_results = bool(attempted_candidates or optimized_candidates or best_prompt or best_score is not None)
1593
+ if not has_results:
1594
+ return
1595
+
1596
+ # Determine algorithm name from events
1597
+ algorithm_name = "PROMPT LEARNING"
1598
+ for event in events:
1599
+ if isinstance(event, dict):
1600
+ event_type = event.get("type", "")
1601
+ if "gepa" in event_type.lower():
1602
+ algorithm_name = "GEPA"
1603
+ break
1604
+ elif "mipro" in event_type.lower():
1605
+ algorithm_name = "MIPRO"
1606
+ break
1607
+
1608
+ # Generate formatted report
1609
+ lines = []
1610
+ lines.append("=" * 80)
1611
+ lines.append(f"{algorithm_name} PROMPT LEARNING RESULTS")
1612
+ lines.append("=" * 80)
1613
+ lines.append(f"Job ID: {job_id}")
1614
+ lines.append(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
1615
+ lines.append("")
1616
+ if baseline_score is not None:
1617
+ lines.append(f"📊 Baseline Score: {baseline_score:.4f} ({baseline_score*100:.1f}%)")
1618
+ if best_score is not None:
1619
+ lines.append(f"🏆 Best Score: {best_score:.4f} ({best_score*100:.1f}%)")
1620
+ if baseline_score is not None and best_score is not None:
1621
+ improvement = ((best_score - baseline_score) / baseline_score) * 100 if baseline_score > 0 else 0
1622
+ lines.append(f"📈 Improvement: {improvement:+.1f}% relative ({(best_score - baseline_score)*100:+.1f} pp absolute)")
1623
+ lines.append("=" * 80)
1624
+ lines.append("")
1625
+
1626
+ # Add best prompt if available
1627
+ if best_prompt and isinstance(best_prompt, dict):
1628
+ lines.append("🏆 BEST PROMPT")
1629
+ lines.append("-" * 80)
1630
+ sections = best_prompt.get("sections", [])
1631
+ if not isinstance(sections, list):
1632
+ sections = []
1633
+ for sec in sections:
1634
+ if not isinstance(sec, dict):
1635
+ continue
1636
+ role = sec.get("role", "unknown")
1637
+ content = sec.get("content", "")
1638
+ lines.append(f"\n[{role.upper()}]:")
1639
+ lines.append(content)
1640
+ lines.append("")
1641
+
1642
+ # Add optimized candidates
1643
+ if optimized_candidates and isinstance(optimized_candidates, list):
1644
+ lines.append("=" * 80)
1645
+ lines.append(f"✨ TOP OPTIMIZED CANDIDATES ({len(optimized_candidates)})")
1646
+ lines.append("=" * 80)
1647
+ lines.append("")
1648
+
1649
+ for idx, cand in enumerate(optimized_candidates):
1650
+ if not isinstance(cand, dict):
1651
+ continue
1652
+ candidate_score = cand.get("score") or {}
1653
+ accuracy = candidate_score.get("accuracy", 0.0)
1654
+ prompt_length = candidate_score.get("prompt_length", 0)
1655
+ payload_kind = cand.get("payload_kind", "unknown")
1656
+
1657
+ # Try score.instance_scores first, then cand.instance_scores (explicit check)
1658
+ instance_scores = (
1659
+ candidate_score.get('instance_scores')
1660
+ if 'instance_scores' in candidate_score
1661
+ else cand.get('instance_scores')
1662
+ )
1663
+ n_eval = len(instance_scores) if instance_scores and isinstance(instance_scores, list) else 0
1664
+
1665
+ lines.append(f"[{idx+1}] Accuracy: {accuracy:.4f} | Length: {prompt_length} | Type: {payload_kind} | N: {n_eval}")
1666
+ lines.append("-" * 80)
1667
+
1668
+ obj = cand.get("object")
1669
+ if obj and isinstance(obj, dict) and payload_kind == "transformation":
1670
+ # For transformations, text_replacements are nested in data
1671
+ data_obj = obj.get("data", {})
1672
+ replacement_lines = _format_text_replacements(data_obj)
1673
+ lines.extend(replacement_lines)
1674
+ lines.append("")
1675
+
1676
+ # Add MIPRO top-K candidates
1677
+ if mipro_topk_candidates and isinstance(mipro_topk_candidates, list):
1678
+ # Sort by rank
1679
+ mipro_topk_candidates.sort(key=lambda x: x.get("rank", 999))
1680
+ lines.append("=" * 80)
1681
+ lines.append(f"🎯 TOP-K CANDIDATES ({len(mipro_topk_candidates)})")
1682
+ lines.append("=" * 80)
1683
+ lines.append("")
1684
+
1685
+ for cand in mipro_topk_candidates:
1686
+ rank = cand.get("rank", 0)
1687
+ train_score = cand.get("train_score", 0.0)
1688
+ test_score = cand.get("test_score", 0.0)
1689
+ lift_abs = cand.get("lift_absolute")
1690
+ lift_pct = cand.get("lift_percent")
1691
+ instruction_text = cand.get("instruction_text", "")
1692
+ instruction_lines = cand.get("instruction_lines", [])
1693
+ demo_indices = cand.get("demo_indices", [])
1694
+ instruction_indices = cand.get("instruction_indices", [])
1695
+ stage_payloads = cand.get("stage_payloads", {})
1696
+ test_per_seed = cand.get("test_per_seed", {})
1697
+
1698
+ lift_str = ""
1699
+ if lift_abs is not None and lift_pct is not None:
1700
+ lift_str = f" | Lift: {lift_abs:+.3f} ({lift_pct:+.1f}%)"
1701
+
1702
+ lines.append(f"[Rank {rank}] Train: {train_score:.4f} ({train_score*100:.1f}%) | Test: {test_score:.4f} ({test_score*100:.1f}%){lift_str}")
1703
+ lines.append("-" * 80)
1704
+
1705
+ # Show full instruction text (use instruction_lines if available, otherwise instruction_text)
1706
+ if instruction_lines:
1707
+ lines.append("Instructions:")
1708
+ for idx, instr_line in enumerate(instruction_lines, 1):
1709
+ lines.append(f" {idx}. {instr_line}")
1710
+ elif instruction_text:
1711
+ # Split multi-line instructions
1712
+ instr_parts = instruction_text.split("\n")
1713
+ if len(instr_parts) > 1:
1714
+ lines.append("Instructions:")
1715
+ for idx, part in enumerate(instr_parts, 1):
1716
+ if part.strip():
1717
+ lines.append(f" {idx}. {part.strip()}")
1718
+ else:
1719
+ lines.append(f"Instruction: {instruction_text}")
1720
+
1721
+ if instruction_indices:
1722
+ lines.append(f"Instruction Indices: {instruction_indices}")
1723
+ if demo_indices:
1724
+ lines.append(f"Demo Indices: {demo_indices}")
1725
+
1726
+ # Show per-stage breakdown if available
1727
+ if stage_payloads:
1728
+ lines.append("Per-stage breakdown:")
1729
+ for stage_id, payload in stage_payloads.items():
1730
+ if isinstance(payload, dict):
1731
+ instr_ids = payload.get("instruction_indices", [])
1732
+ demo_ids = payload.get("demo_indices", [])
1733
+ module_id = payload.get("module_id", "unknown")
1734
+ lines.append(f" [{module_id}/{stage_id}] instr_ids={instr_ids} demo_ids={demo_ids}")
1735
+
1736
+ # Show test per-seed scores if available
1737
+ if test_per_seed:
1738
+ seed_scores = []
1739
+ for seed, score in sorted(test_per_seed.items()):
1740
+ seed_scores.append(f"{seed}: {score:.2f}")
1741
+ if seed_scores:
1742
+ lines.append(f"Test per-seed: {', '.join(seed_scores)}")
1743
+
1744
+ lines.append("")
1745
+
1746
+ # Add all proposal candidates
1747
+ if attempted_candidates and isinstance(attempted_candidates, list):
1748
+ lines.append("=" * 80)
1749
+ lines.append(f"💡 ALL PROPOSAL CANDIDATES ({len(attempted_candidates)})")
1750
+ lines.append("=" * 80)
1751
+ lines.append("")
1752
+
1753
+ for idx, cand in enumerate(attempted_candidates):
1754
+ if not isinstance(cand, dict):
1755
+ continue
1756
+ accuracy = cand.get('accuracy', 0.0)
1757
+ prompt_length = cand.get('prompt_length', 0)
1758
+ tool_rate = cand.get('tool_call_rate', 0.0)
1759
+ instance_scores = cand.get('instance_scores', [])
1760
+ n_eval = len(instance_scores) if instance_scores else 0
1761
+
1762
+ lines.append(f"[{idx+1}] Accuracy: {accuracy:.4f} | Length: {prompt_length} | Tool Rate: {tool_rate:.2f} | N: {n_eval}")
1763
+ lines.append("-" * 80)
1764
+
1765
+ obj = cand.get("object")
1766
+ if obj and isinstance(obj, dict):
1767
+ # For proposals, text_replacements are at top level of object
1768
+ replacement_lines = _format_text_replacements(obj)
1769
+ lines.extend(replacement_lines)
1770
+ lines.append("")
1771
+
1772
+ # Add proposed instructions section (MIPRO)
1773
+ if proposed_instructions and isinstance(proposed_instructions, list):
1774
+ lines.append("=" * 80)
1775
+ lines.append(f"💡 PROPOSED INSTRUCTIONS ({len(proposed_instructions)})")
1776
+ lines.append("=" * 80)
1777
+ lines.append("")
1778
+
1779
+ for idx, instr in enumerate(proposed_instructions):
1780
+ if not isinstance(instr, dict):
1781
+ continue
1782
+ iteration = instr.get("iteration", "?")
1783
+ stage_id = instr.get("stage_id", "?")
1784
+ module_id = instr.get("module_id", "?")
1785
+ instruction_id = instr.get("instruction_id", "?")
1786
+ instruction_text = instr.get("instruction_text", "")
1787
+ instruction_lines = instr.get("instruction_lines", [])
1788
+ demo_indices = instr.get("demo_indices", [])
1789
+
1790
+ lines.append(f"[{idx+1}] Iteration {iteration} | Stage: {stage_id} | Module: {module_id} | ID: {instruction_id}")
1791
+ if demo_indices:
1792
+ lines.append(f"Demo Indices: {demo_indices}")
1793
+ lines.append("-" * 80)
1794
+
1795
+ # Show instruction text (use instruction_lines if available, otherwise instruction_text)
1796
+ if instruction_lines:
1797
+ for line_idx, line in enumerate(instruction_lines, 1):
1798
+ if line.strip():
1799
+ lines.append(f" {line_idx}. {line.strip()}")
1800
+ elif instruction_text:
1801
+ # Split multi-line instructions
1802
+ instr_parts = instruction_text.split("\n")
1803
+ if len(instr_parts) > 1:
1804
+ for line_idx, part in enumerate(instr_parts, 1):
1805
+ if part.strip():
1806
+ lines.append(f" {line_idx}. {part.strip()}")
1807
+ else:
1808
+ lines.append(f" {instruction_text}")
1809
+
1810
+ lines.append("")
1811
+
1812
+ # Add proposed transformations section (GEPA)
1813
+ if proposed_transformations and isinstance(proposed_transformations, list):
1814
+ lines.append("=" * 80)
1815
+ lines.append(f"🧬 PROPOSED TRANSFORMATIONS ({len(proposed_transformations)})")
1816
+ lines.append("=" * 80)
1817
+ lines.append("")
1818
+
1819
+ for idx, trans in enumerate(proposed_transformations):
1820
+ if not isinstance(trans, dict):
1821
+ continue
1822
+ generation = trans.get("generation", "?")
1823
+ mutation_type = trans.get("mutation_type", "?")
1824
+ operator = trans.get("operator", "?")
1825
+ transformation_id = trans.get("transformation_id", "?")
1826
+ parent_id = trans.get("parent_id", "?")
1827
+ transformation_text = trans.get("transformation_text", "")
1828
+ transformation_dict = trans.get("transformation_dict", {})
1829
+
1830
+ lines.append(f"[{idx+1}] Generation {generation} | Type: {mutation_type} | Operator: {operator}")
1831
+ lines.append(f"Transformation ID: {transformation_id} | Parent ID: {parent_id}")
1832
+ lines.append("-" * 80)
1833
+
1834
+ # Show transformation text
1835
+ if transformation_text:
1836
+ lines.append("Transformation Text:")
1837
+ lines.append(f" {transformation_text}")
1838
+
1839
+ # Show transformation dict details if available
1840
+ if transformation_dict:
1841
+ text_replacements = transformation_dict.get("text_replacements", [])
1842
+ if text_replacements:
1843
+ lines.append("Text Replacements:")
1844
+ for repl_idx, repl in enumerate(text_replacements, 1):
1845
+ if isinstance(repl, dict):
1846
+ apply_to = repl.get("apply_to_role", "unknown")
1847
+ old_text = repl.get("old_text", "")[:100]
1848
+ new_text = repl.get("new_text", "")[:200]
1849
+ lines.append(f" {repl_idx}. [{apply_to}]")
1850
+ if old_text:
1851
+ lines.append(f" Old: {old_text}...")
1852
+ if new_text:
1853
+ lines.append(f" New: {new_text}...")
1854
+
1855
+ lines.append("")
1856
+
1857
+ # Add summary table and chart before END OF REPORT
1858
+ lines.append("")
1859
+ lines.append("=" * 80)
1860
+ lines.append("FINAL SUMMARY")
1861
+ lines.append("=" * 80)
1862
+
1863
+ # Generate summary table text (reuse summary.py logic)
1864
+ try:
1865
+ from .summary import _generate_summary_text
1866
+ # Extract optimization curve from events if available
1867
+ optimization_curve = None
1868
+ # Try to extract curve from trial events
1869
+ trial_scores = []
1870
+ for event in events:
1871
+ if isinstance(event, dict):
1872
+ event_type = event.get("type", "")
1873
+ if event_type in ("prompt.learning.trial.complete", "mipro.new_incumbent"):
1874
+ data = event.get("data", {})
1875
+ trial_num = data.get("trial") or data.get("trial_num")
1876
+ score = data.get("score") or data.get("minibatch_score")
1877
+ if trial_num is not None and score is not None:
1878
+ trial_scores.append((trial_num, score))
1879
+
1880
+ if trial_scores:
1881
+ # Build optimization curve (best score so far at each trial)
1882
+ best_so_far = {}
1883
+ for trial_num, score in sorted(trial_scores):
1884
+ if trial_num not in best_so_far or score > best_so_far[trial_num]:
1885
+ best_so_far[trial_num] = score
1886
+ optimization_curve = sorted(best_so_far.items())
1887
+
1888
+ summary_text, curve_text = _generate_summary_text(
1889
+ events=events,
1890
+ algorithm=algorithm_name.lower() if algorithm_name else None,
1891
+ optimization_curve=optimization_curve,
1892
+ )
1893
+ if summary_text:
1894
+ lines.append(summary_text)
1895
+ if curve_text:
1896
+ lines.append("")
1897
+ lines.append(curve_text)
1898
+ except Exception as e:
1899
+ lines.append(f"⚠️ Could not generate summary: {e}")
1900
+
1901
+ lines.append("=" * 80)
1902
+ lines.append("END OF REPORT")
1903
+ lines.append("=" * 80)
1904
+
1905
+ # Determine save location
1906
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1907
+
1908
+ # Use results_folder from config (create if it doesn't exist)
1909
+ output_dir = results_folder
1910
+ output_dir.mkdir(parents=True, exist_ok=True)
1911
+
1912
+ # Use algorithm-specific filename
1913
+ algorithm_prefix = algorithm_name.lower() if algorithm_name else "prompt_learning"
1914
+ output_file = output_dir / f"{algorithm_prefix}_results_{job_id}_{timestamp}.txt"
1915
+
1916
+ with open(output_file, "w", encoding="utf-8") as f:
1917
+ f.write("\n".join(lines))
1918
+
1919
+ click.echo(f"\n📄 Results saved locally to: {output_file}")
1920
+
1921
+ # Also save verbose log file with all events (append summary if log was streamed live)
1922
+ log_file = output_dir / f"{algorithm_prefix}_log_{job_id}_{timestamp}.log"
1923
+ append_summary = log_file.exists() # If log file exists, it was streamed live, so just append summary
1924
+ _save_verbose_log_file(events, log_file, algorithm_name, job_id, append_summary=append_summary)
1925
+ click.echo(f"📋 Verbose log saved locally to: {log_file}")
1926
+
1927
+ except (PermissionError, OSError) as e:
1928
+ click.echo(f"⚠️ Could not save results file locally: {e}")
1929
+ except Exception as e:
1930
+ click.echo(f"⚠️ Unexpected error saving results file: {e}")
1931
+
1932
+
1933
+ def handle_prompt_learning(
1934
+ *,
1935
+ cfg_path: Path,
1936
+ backend_base: str,
1937
+ synth_key: str,
1938
+ task_url_override: str | None,
1939
+ allow_experimental: bool | None,
1940
+ dry_run: bool,
1941
+ poll: bool,
1942
+ poll_timeout: float,
1943
+ poll_interval: float,
1944
+ stream_format: str,
1945
+ display_config: dict[str, Any] | None = None,
1946
+ tui: bool = False,
1947
+ show_curve: bool = True,
1948
+ verbose_summary: bool = True,
1949
+ ) -> None:
1950
+ """Handle prompt learning job creation (MIPRO or GEPA)."""
1951
+ ctx: dict[str, Any] = {
1952
+ "cfg_path": str(cfg_path),
1953
+ "backend_base": backend_base,
1954
+ "task_url_override": task_url_override,
1955
+ "poll": poll,
1956
+ }
1957
+ log_info("handle_prompt_learning invoked", ctx=ctx)
1958
+ env_key = get_required_value(
1959
+ "environment_api_key",
1960
+ env_value=os.environ.get("ENVIRONMENT_API_KEY"),
1961
+ )
1962
+ os.environ["ENVIRONMENT_API_KEY"] = env_key
1963
+
1964
+ overrides: dict[str, Any] = {
1965
+ "backend": backend_base,
1966
+ "task_url": task_url_override,
1967
+ }
1968
+
1969
+ build = build_prompt_learning_payload(
1970
+ config_path=cfg_path,
1971
+ task_url=task_url_override,
1972
+ overrides=overrides,
1973
+ allow_experimental=allow_experimental,
1974
+ )
1975
+
1976
+ # Assertion: Validate task app URL is reachable from backend perspective
1977
+ # If backend is localhost and task app is localhost, they should be able to communicate
1978
+ task_app_url = build.task_url or ""
1979
+ if backend_base.startswith("http://localhost") or backend_base.startswith("http://127.0.0.1"):
1980
+ if task_app_url.startswith("http://localhost") or task_app_url.startswith("http://127.0.0.1"):
1981
+ # Both are local - this should work
1982
+ pass
1983
+ else:
1984
+ click.echo(f"⚠️ WARNING: Backend is local ({backend_base}) but task app is remote ({task_app_url})")
1985
+ click.echo(" The backend may not be able to reach the task app. Consider using a tunnel or local task app.")
1986
+
1987
+ click.echo("Performing task app health check…")
1988
+ click.echo(f"Task app URL: {build.task_url}")
1989
+ click.echo("⏳ Checking /health endpoint (timeout: 10s)...")
1990
+ health = check_local_api_health(build.task_url, env_key, timeout=10.0)
1991
+ if not health.ok:
1992
+ click.echo(f"❌ Task app health check failed: {health.detail}")
1993
+ click.echo(f" Health status: {health.health_status}")
1994
+ click.echo(f" Task info status: {health.task_info_status}")
1995
+ click.echo("💡 Troubleshooting:")
1996
+ click.echo(" 1. Ensure the task app is running: lsof -i :8102")
1997
+ click.echo(" 2. Test manually: curl -v http://127.0.0.1:8102/health")
1998
+ click.echo(" 3. Check task app logs for errors")
1999
+ click.echo(" 4. Restart the task app if it's hung")
2000
+ raise click.ClickException("Aborting due to failing health check")
2001
+ else:
2002
+ click.echo("Task app healthy")
2003
+
2004
+ # Ensure backend_base has /api prefix
2005
+ if not backend_base.endswith("/api"):
2006
+ backend_base = ensure_api_base(backend_base)
2007
+
2008
+ # Assertion: Validate backend URL before making request
2009
+ if not backend_base.startswith("http"):
2010
+ raise click.ClickException(
2011
+ f"Invalid backend URL: {backend_base}. Must start with http:// or https://"
2012
+ )
2013
+
2014
+ create_url = f"{backend_base}/prompt-learning/online/jobs"
2015
+ headers = {"Authorization": f"Bearer {synth_key}", "Content-Type": "application/json"}
2016
+
2017
+ click.echo(f"POST {create_url}")
2018
+ click.echo("Payload preview:\n" + preview_json(build.payload, limit=800))
2019
+
2020
+ # Assertion: If using local backend, verify it's actually localhost
2021
+ if (
2022
+ os.getenv("BACKEND_BASE_URL")
2023
+ and "localhost" in os.getenv("BACKEND_BASE_URL", "").lower()
2024
+ and "localhost" not in backend_base.lower()
2025
+ and "127.0.0.1" not in backend_base
2026
+ ):
2027
+ raise click.ClickException(
2028
+ f"BACKEND_BASE_URL was set to localhost but backend_base resolved to {backend_base}. "
2029
+ f"This indicates the environment variable is not being respected."
2030
+ )
2031
+
2032
+ # Increase timeout for job creation (can take longer due to validation checks)
2033
+ resp = http_post(create_url, headers=headers, json_body=build.payload, timeout=180.0)
2034
+ try:
2035
+ js = resp.json()
2036
+ except json.JSONDecodeError as e:
2037
+ click.echo(f"⚠️ Failed to parse JSON response: {e}")
2038
+ js = {"status": resp.status_code, "text": resp.text[:400]}
2039
+ click.echo(f"Response {resp.status_code}: {preview_json(js, limit=400)}")
2040
+ if resp.status_code not in (200, 201):
2041
+ raise click.ClickException("Job creation failed")
2042
+ job_id = js.get("job_id") or js.get("id")
2043
+ if not job_id:
2044
+ raise click.ClickException("Response missing job id")
2045
+
2046
+ if not poll:
2047
+ click.echo(f"Created job {job_id} (polling disabled)")
2048
+ return
2049
+
2050
+ algorithm = str(build.payload.get("algorithm") or "").lower()
2051
+ metric_names: set[str] | None = None
2052
+ if algorithm == "gepa":
2053
+ metric_names = {"gepa.transformation.mean_score"}
2054
+
2055
+ chart_mode = stream_format == "chart" and algorithm == "gepa"
2056
+ if stream_format == "chart" and not chart_mode:
2057
+ click.echo("Chart streaming is only available for GEPA jobs; showing textual updates instead.")
2058
+
2059
+ # Prepare log file path for real-time streaming
2060
+ results_folder = parse_results_folder(cfg_path)
2061
+ from datetime import datetime
2062
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
2063
+ algorithm_prefix = algorithm.lower() if algorithm else "prompt_learning"
2064
+ log_file = results_folder / f"{algorithm_prefix}_log_{job_id}_{timestamp}.log"
2065
+
2066
+ # Write initial streaming message to log file if handler will be created
2067
+ if not chart_mode:
2068
+ try:
2069
+ log_file.parent.mkdir(parents=True, exist_ok=True)
2070
+ with open(log_file, "a", encoding="utf-8") as f:
2071
+ f.write("\n=== Streaming Job Progress ===\n")
2072
+ except Exception:
2073
+ pass # Continue even if log file can't be written
2074
+
2075
+ click.echo("\n=== Streaming Job Progress ===")
2076
+
2077
+ # Create appropriate handler based on algorithm
2078
+ if algorithm == "gepa":
2079
+ if chart_mode:
2080
+ config = StreamConfig(
2081
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS},
2082
+ event_types={
2083
+ "prompt.learning.progress",
2084
+ "prompt.learning.gepa.start",
2085
+ "prompt.learning.gepa.complete",
2086
+ },
2087
+ metric_names=metric_names,
2088
+ )
2089
+ handlers = [LossCurveHandler()]
2090
+ click.echo("Using live loss chart (metric=gepa.transformation.mean_score)")
2091
+ else:
2092
+ config = StreamConfig(
2093
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS, StreamType.TIMELINE},
2094
+ metric_names=metric_names,
2095
+ max_events_per_poll=500, # Capture more events per poll
2096
+ deduplicate=True, # Still deduplicate but capture more
2097
+ # Don't filter events - show all of them
2098
+ event_types=None, # No whitelist - show all event types
2099
+ event_types_exclude=None, # No blacklist - show all events
2100
+ event_levels=None, # Show all levels
2101
+ )
2102
+ # Use PromptLearningHandler for enhanced event handling
2103
+ handler = PromptLearningHandler(
2104
+ show_trial_results=display_config.get("show_trial_results", True) if display_config else True,
2105
+ show_transformations=display_config.get("show_transformations", False) if display_config else False,
2106
+ show_validation=display_config.get("show_validation", True) if display_config else True,
2107
+ max_tokens=display_config.get("max_tokens") if display_config else None,
2108
+ max_time_seconds=display_config.get("max_time_seconds") if display_config else None,
2109
+ max_rollouts=display_config.get("max_rollouts") if display_config else None,
2110
+ log_file=log_file,
2111
+ )
2112
+ handlers = [handler]
2113
+ else:
2114
+ # Use PromptLearningHandler for MIPRO (same as GEPA)
2115
+ config = StreamConfig(
2116
+ enabled_streams={StreamType.STATUS, StreamType.EVENTS, StreamType.METRICS, StreamType.TIMELINE},
2117
+ metric_names=metric_names,
2118
+ max_events_per_poll=500, # Capture more events per poll
2119
+ deduplicate=True, # Still deduplicate but capture more
2120
+ # Don't filter events - show all of them
2121
+ event_types=None, # No whitelist - show all event types
2122
+ event_types_exclude=None, # No blacklist - show all events
2123
+ event_levels=None, # Show all levels
2124
+ )
2125
+ handler = PromptLearningHandler(
2126
+ show_trial_results=display_config.get("show_trial_results", True) if display_config else True,
2127
+ show_transformations=display_config.get("show_transformations", False) if display_config else False,
2128
+ show_validation=display_config.get("show_validation", True) if display_config else True,
2129
+ max_tokens=display_config.get("max_tokens") if display_config else None,
2130
+ max_time_seconds=display_config.get("max_time_seconds") if display_config else None,
2131
+ max_rollouts=display_config.get("max_rollouts") if display_config else None,
2132
+ log_file=log_file,
2133
+ )
2134
+ handlers = [handler]
2135
+
2136
+ streamer = JobStreamer(
2137
+ base_url=backend_base,
2138
+ api_key=synth_key,
2139
+ job_id=job_id,
2140
+ endpoints=StreamEndpoints.prompt_learning(job_id),
2141
+ config=config,
2142
+ handlers=handlers,
2143
+ interval_seconds=poll_interval,
2144
+ timeout_seconds=poll_timeout,
2145
+ )
2146
+ final_status = asyncio.run(streamer.stream_until_terminal())
2147
+
2148
+ # Write final status to log file if handler has one
2149
+ if isinstance(handlers[0], PromptLearningHandler) and handlers[0]._log_file_handle:
2150
+ handlers[0]._write_log(f"Final status: {final_status.get('status', 'unknown')}")
2151
+ handlers[0]._write_log(preview_json(final_status, limit=600))
2152
+
2153
+ click.echo(f"Final status: {final_status.get('status', 'unknown')}")
2154
+ click.echo(preview_json(final_status, limit=600))
2155
+
2156
+ # Display final summary for GEPA/MIPRO jobs if requested
2157
+ if verbose_summary and algorithm in ("gepa", "mipro"):
2158
+ optimization_curve = None
2159
+ if isinstance(handlers[0], PromptLearningHandler):
2160
+ optimization_curve = handlers[0].optimization_curve
2161
+
2162
+ from .summary import display_prompt_learning_summary
2163
+ # Pass log_writer if handler has one
2164
+ log_writer = None
2165
+ if isinstance(handlers[0], PromptLearningHandler) and handlers[0]._log_file_handle:
2166
+ log_writer = handlers[0]._write_log
2167
+ display_prompt_learning_summary(
2168
+ job_id=job_id,
2169
+ backend_base=backend_base,
2170
+ api_key=synth_key,
2171
+ optimization_curve=optimization_curve,
2172
+ show_curve=show_curve,
2173
+ algorithm=algorithm,
2174
+ log_writer=log_writer,
2175
+ )
2176
+
2177
+ # Save results file locally
2178
+ # Parse and validate results_folder from config (already done above, but ensure it's available)
2179
+ if 'results_folder' not in locals():
2180
+ results_folder = parse_results_folder(cfg_path)
2181
+
2182
+ # Close log file if handler has one (flush is already called by streamer, but ensure it's closed)
2183
+ if isinstance(handlers[0], PromptLearningHandler) and handlers[0]._log_file_handle:
2184
+ handlers[0].flush()
2185
+
2186
+ _save_prompt_learning_results_locally(
2187
+ backend_base=backend_base,
2188
+ api_key=synth_key,
2189
+ job_id=job_id,
2190
+ config_path=cfg_path,
2191
+ results_folder=results_folder,
2192
+ )
2193
+
2194
+
2195
+ def register(cli: click.Group) -> None:
2196
+ cli.add_command(train_command)