synth-ai 0.2.13.dev2__py3-none-any.whl → 0.2.16__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.
- examples/README.md +1 -0
- examples/multi_step/SFT_README.md +147 -0
- examples/multi_step/configs/README_verilog_rl.md +77 -0
- examples/multi_step/configs/VERILOG_REWARDS.md +90 -0
- examples/multi_step/configs/VERILOG_RL_CHECKLIST.md +183 -0
- examples/multi_step/configs/crafter_eval_synth_qwen4b.toml +35 -0
- examples/multi_step/configs/crafter_eval_text_only_groq_qwen32b.toml +36 -0
- examples/multi_step/configs/crafter_rl_stepwise_hosted_judge.toml +12 -11
- examples/multi_step/configs/crafter_sft_qwen30b_lora.toml +62 -0
- examples/multi_step/configs/crafter_synth_backend.md +40 -0
- examples/multi_step/configs/verilog_eval_groq_qwen32b.toml +31 -0
- examples/multi_step/configs/verilog_eval_synth_qwen8b.toml +33 -0
- examples/multi_step/configs/verilog_rl_lora.toml +190 -0
- examples/multi_step/convert_traces_to_sft.py +84 -0
- examples/multi_step/judges/crafter_backend_judge.py +220 -0
- examples/multi_step/judges/verilog_backend_judge.py +234 -0
- examples/multi_step/readme.md +48 -0
- examples/multi_step/run_sft_qwen30b.sh +45 -0
- examples/multi_step/verilog_rl_lora.md +218 -0
- examples/qwen_coder/configs/coder_lora_30b.toml +3 -2
- examples/qwen_coder/configs/coder_lora_4b.toml +2 -1
- examples/qwen_coder/configs/coder_lora_small.toml +2 -1
- examples/qwen_vl/BUGS_AND_FIXES.md +232 -0
- examples/qwen_vl/IMAGE_VALIDATION_COMPLETE.md +271 -0
- examples/qwen_vl/IMAGE_VALIDATION_SUMMARY.md +260 -0
- examples/qwen_vl/INFERENCE_SFT_TESTS.md +412 -0
- examples/qwen_vl/NEXT_STEPS_2B.md +325 -0
- examples/qwen_vl/QUICKSTART.md +327 -0
- examples/qwen_vl/QUICKSTART_RL_VISION.md +110 -0
- examples/qwen_vl/README.md +154 -0
- examples/qwen_vl/RL_VISION_COMPLETE.md +475 -0
- examples/qwen_vl/RL_VISION_TESTING.md +333 -0
- examples/qwen_vl/SDK_VISION_INTEGRATION.md +328 -0
- examples/qwen_vl/SETUP_COMPLETE.md +275 -0
- examples/qwen_vl/VISION_TESTS_COMPLETE.md +490 -0
- examples/qwen_vl/VLM_PIPELINE_COMPLETE.md +242 -0
- examples/qwen_vl/__init__.py +2 -0
- examples/qwen_vl/collect_data_via_cli.md +423 -0
- examples/qwen_vl/collect_vision_traces.py +368 -0
- examples/qwen_vl/configs/crafter_rl_vision_qwen3vl4b.toml +127 -0
- examples/qwen_vl/configs/crafter_vlm_sft_example.toml +60 -0
- examples/qwen_vl/configs/eval_gpt4o_mini_vision.toml +43 -0
- examples/qwen_vl/configs/eval_gpt4o_vision_proper.toml +29 -0
- examples/qwen_vl/configs/eval_gpt5nano_vision.toml +45 -0
- examples/qwen_vl/configs/eval_qwen2vl_vision.toml +44 -0
- examples/qwen_vl/configs/filter_qwen2vl_sft.toml +50 -0
- examples/qwen_vl/configs/filter_vision_sft.toml +53 -0
- examples/qwen_vl/configs/filter_vision_test.toml +8 -0
- examples/qwen_vl/configs/sft_qwen3_vl_2b_test.toml +54 -0
- examples/qwen_vl/crafter_gpt5nano_agent.py +308 -0
- examples/qwen_vl/crafter_qwen_vl_agent.py +300 -0
- examples/qwen_vl/run_vision_comparison.sh +62 -0
- examples/qwen_vl/run_vision_sft_pipeline.sh +175 -0
- examples/qwen_vl/test_image_validation.py +201 -0
- examples/qwen_vl/test_sft_vision_data.py +110 -0
- examples/rl/README.md +1 -1
- examples/rl/configs/eval_base_qwen.toml +17 -0
- examples/rl/configs/eval_rl_qwen.toml +13 -0
- examples/rl/configs/rl_from_base_qwen.toml +37 -0
- examples/rl/configs/rl_from_base_qwen17.toml +76 -0
- examples/rl/configs/rl_from_ft_qwen.toml +37 -0
- examples/rl/run_eval.py +436 -0
- examples/rl/run_rl_and_save.py +111 -0
- examples/rl/task_app/README.md +22 -0
- examples/rl/task_app/math_single_step.py +990 -0
- examples/rl/task_app/math_task_app.py +111 -0
- examples/sft/README.md +5 -5
- examples/sft/configs/crafter_fft_qwen0p6b.toml +4 -2
- examples/sft/configs/crafter_lora_qwen0p6b.toml +4 -3
- examples/sft/evaluate.py +4 -4
- examples/sft/export_dataset.py +7 -4
- examples/sft/generate_traces.py +2 -0
- examples/swe/task_app/README.md +1 -1
- examples/swe/task_app/grpo_swe_mini.py +1 -1
- examples/swe/task_app/grpo_swe_mini_task_app.py +0 -12
- examples/swe/task_app/hosted/envs/mini_swe/environment.py +13 -13
- examples/swe/task_app/hosted/policy_routes.py +0 -2
- examples/swe/task_app/hosted/rollout.py +2 -8
- examples/task_apps/IMAGE_ONLY_EVAL_QUICKSTART.md +258 -0
- examples/task_apps/crafter/CREATE_SFT_DATASET.md +273 -0
- examples/task_apps/crafter/EVAL_IMAGE_ONLY_RESULTS.md +152 -0
- examples/task_apps/crafter/FILTER_COMMAND_STATUS.md +174 -0
- examples/task_apps/crafter/FILTER_COMMAND_SUCCESS.md +268 -0
- examples/task_apps/crafter/QUERY_EXAMPLES.md +203 -0
- examples/task_apps/crafter/README_IMAGE_ONLY_EVAL.md +316 -0
- examples/task_apps/crafter/eval_image_only_gpt4o.toml +28 -0
- examples/task_apps/crafter/eval_text_only_groq_llama.toml +36 -0
- examples/task_apps/crafter/filter_sft_dataset.toml +16 -0
- examples/task_apps/crafter/task_app/__init__.py +3 -0
- examples/task_apps/crafter/task_app/grpo_crafter.py +309 -14
- examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/environment.py +10 -0
- examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/policy.py +75 -4
- examples/task_apps/crafter/task_app/synth_envs_hosted/envs/crafter/react_agent.py +17 -2
- examples/task_apps/crafter/task_app/synth_envs_hosted/inference/openai_client.py +55 -3
- examples/task_apps/crafter/task_app/synth_envs_hosted/policy_routes.py +114 -32
- examples/task_apps/crafter/task_app/synth_envs_hosted/rollout.py +127 -27
- examples/task_apps/crafter/task_app/synth_envs_hosted/utils.py +156 -0
- examples/task_apps/enron/__init__.py +1 -0
- examples/task_apps/enron/filter_sft.toml +5 -0
- examples/task_apps/enron/tests/__init__.py +2 -0
- examples/task_apps/enron/tests/integration/__init__.py +2 -0
- examples/task_apps/enron/tests/integration/test_enron_eval.py +2 -0
- examples/task_apps/enron/tests/unit/__init__.py +2 -0
- examples/task_apps/pokemon_red/EVAL_IMAGE_ONLY_COMPLETE.md +283 -0
- examples/task_apps/pokemon_red/EVAL_IMAGE_ONLY_STATUS.md +155 -0
- examples/task_apps/pokemon_red/README_IMAGE_ONLY_EVAL.md +415 -0
- examples/task_apps/pokemon_red/eval_image_only_gpt4o.toml +29 -0
- examples/task_apps/pokemon_red/pallet_town_rl_config.toml +2 -0
- examples/task_apps/pokemon_red/task_app.py +199 -6
- examples/task_apps/pokemon_red/test_pallet_town_rewards.py +2 -0
- examples/task_apps/sokoban/filter_sft.toml +5 -0
- examples/task_apps/sokoban/tests/__init__.py +2 -0
- examples/task_apps/sokoban/tests/integration/__init__.py +2 -0
- examples/task_apps/sokoban/tests/unit/__init__.py +2 -0
- examples/task_apps/verilog/eval_groq_qwen32b.toml +8 -4
- examples/task_apps/verilog/filter_sft.toml +5 -0
- examples/task_apps/verilog/task_app/grpo_verilog.py +258 -23
- examples/task_apps/verilog/tests/__init__.py +2 -0
- examples/task_apps/verilog/tests/integration/__init__.py +2 -0
- examples/task_apps/verilog/tests/integration/test_verilog_eval.py +2 -0
- examples/task_apps/verilog/tests/unit/__init__.py +2 -0
- examples/vlm/README.md +3 -3
- examples/vlm/configs/crafter_vlm_gpt4o.toml +2 -0
- examples/vlm/crafter_openai_vlm_agent.py +3 -5
- examples/vlm/filter_image_rows.py +1 -1
- examples/vlm/run_crafter_vlm_benchmark.py +2 -2
- examples/warming_up_to_rl/_utils.py +92 -0
- examples/warming_up_to_rl/analyze_trace_db.py +1 -1
- examples/warming_up_to_rl/configs/crafter_fft.toml +2 -0
- examples/warming_up_to_rl/configs/crafter_fft_4b.toml +2 -0
- examples/warming_up_to_rl/configs/eval_fft_qwen4b.toml +2 -0
- examples/warming_up_to_rl/configs/eval_groq_qwen32b.toml +2 -0
- examples/warming_up_to_rl/configs/eval_modal_qwen4b.toml +2 -1
- examples/warming_up_to_rl/configs/rl_from_base_qwen4b.toml +2 -1
- examples/warming_up_to_rl/configs/rl_from_ft.toml +2 -0
- examples/warming_up_to_rl/export_trace_sft.py +174 -60
- examples/warming_up_to_rl/groq_test.py +2 -0
- examples/warming_up_to_rl/readme.md +63 -132
- examples/warming_up_to_rl/run_fft_and_save.py +1 -1
- examples/warming_up_to_rl/run_local_rollout.py +2 -0
- examples/warming_up_to_rl/run_local_rollout_modal.py +2 -0
- examples/warming_up_to_rl/run_local_rollout_parallel.py +2 -0
- examples/warming_up_to_rl/run_local_rollout_traced.py +2 -0
- examples/warming_up_to_rl/run_rl_and_save.py +1 -1
- examples/warming_up_to_rl/run_rollout_remote.py +2 -0
- examples/warming_up_to_rl/task_app/README.md +42 -0
- examples/warming_up_to_rl/task_app/grpo_crafter.py +696 -0
- examples/warming_up_to_rl/task_app/grpo_crafter_task_app.py +135 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/README.md +173 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/__init__.py +5 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/branching.py +143 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/environment_routes.py +1226 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/__init__.py +1 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/__init__.py +6 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/app.py +1 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/environment.py +522 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/policy.py +478 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/react_agent.py +108 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/shared.py +305 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/envs/crafter/tools.py +47 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/hosted_app.py +204 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/inference/__init__.py +5 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/inference/openai_client.py +618 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/main.py +100 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/policy_routes.py +1081 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/registry.py +195 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/rollout.py +1861 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/storage/__init__.py +5 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/storage/volume.py +211 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/test_agents.py +161 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/test_service.py +137 -0
- examples/warming_up_to_rl/task_app/synth_envs_hosted/utils.py +62 -0
- synth_ai/__init__.py +44 -30
- synth_ai/_utils/__init__.py +47 -0
- synth_ai/_utils/base_url.py +10 -0
- synth_ai/_utils/http.py +10 -0
- synth_ai/_utils/prompts.py +10 -0
- synth_ai/_utils/task_app_state.py +12 -0
- synth_ai/_utils/user_config.py +10 -0
- synth_ai/api/models/supported.py +145 -7
- synth_ai/api/train/__init__.py +13 -1
- synth_ai/api/train/cli.py +30 -7
- synth_ai/api/train/config_finder.py +18 -11
- synth_ai/api/train/env_resolver.py +13 -10
- synth_ai/cli/__init__.py +66 -49
- synth_ai/cli/_modal_wrapper.py +9 -6
- synth_ai/cli/_typer_patch.py +0 -2
- synth_ai/cli/_validate_task_app.py +22 -4
- synth_ai/cli/legacy_root_backup.py +3 -1
- synth_ai/cli/lib/__init__.py +10 -0
- synth_ai/cli/lib/task_app_discovery.py +7 -0
- synth_ai/cli/lib/task_app_env.py +518 -0
- synth_ai/cli/recent.py +1 -0
- synth_ai/cli/setup.py +266 -0
- synth_ai/cli/task_app_deploy.py +16 -0
- synth_ai/cli/task_app_list.py +25 -0
- synth_ai/cli/task_app_modal_serve.py +16 -0
- synth_ai/cli/task_app_serve.py +18 -0
- synth_ai/cli/task_apps.py +392 -141
- synth_ai/cli/train.py +18 -0
- synth_ai/cli/tui.py +62 -0
- synth_ai/demos/__init__.py +10 -0
- synth_ai/demos/core/__init__.py +28 -1
- synth_ai/demos/crafter/__init__.py +1 -0
- synth_ai/demos/crafter/crafter_fft_4b.toml +55 -0
- synth_ai/demos/crafter/grpo_crafter_task_app.py +185 -0
- synth_ai/demos/crafter/rl_from_base_qwen4b.toml +74 -0
- synth_ai/demos/demo_registry.py +176 -0
- synth_ai/demos/demo_task_apps/crafter/grpo_crafter_task_app.py +1 -1
- synth_ai/demos/math/__init__.py +1 -0
- synth_ai/demos/math/_common.py +16 -0
- synth_ai/demos/math/app.py +38 -0
- synth_ai/demos/math/config.toml +76 -0
- synth_ai/demos/math/deploy_modal.py +54 -0
- synth_ai/demos/math/modal_task_app.py +702 -0
- synth_ai/demos/math/task_app_entry.py +51 -0
- synth_ai/environments/environment/core.py +7 -1
- synth_ai/environments/examples/bandit/engine.py +0 -1
- synth_ai/environments/examples/bandit/environment.py +0 -1
- synth_ai/environments/examples/crafter_classic/environment.py +1 -1
- synth_ai/environments/examples/verilog/engine.py +76 -10
- synth_ai/environments/examples/wordle/environment.py +0 -1
- synth_ai/evals/base.py +16 -5
- synth_ai/evals/client.py +1 -1
- synth_ai/inference/client.py +1 -1
- synth_ai/learning/client.py +1 -1
- synth_ai/learning/health.py +1 -1
- synth_ai/learning/jobs.py +1 -1
- synth_ai/learning/rl/client.py +1 -1
- synth_ai/learning/rl/env_keys.py +1 -1
- synth_ai/learning/rl/secrets.py +1 -1
- synth_ai/learning/sft/client.py +1 -1
- synth_ai/learning/sft/data.py +407 -4
- synth_ai/learning/validators.py +4 -1
- synth_ai/task/__init__.py +11 -1
- synth_ai/task/apps/__init__.py +5 -2
- synth_ai/task/config.py +259 -0
- synth_ai/task/contracts.py +15 -2
- synth_ai/task/rubrics/__init__.py +4 -2
- synth_ai/task/rubrics/loaders.py +27 -4
- synth_ai/task/rubrics/scoring.py +3 -0
- synth_ai/task/rubrics.py +219 -0
- synth_ai/task/trace_correlation_helpers.py +328 -0
- synth_ai/task/tracing_utils.py +14 -3
- synth_ai/task/validators.py +145 -2
- synth_ai/tracing_v3/config.py +15 -13
- synth_ai/tracing_v3/constants.py +21 -0
- synth_ai/tracing_v3/db_config.py +3 -1
- synth_ai/tracing_v3/decorators.py +10 -7
- synth_ai/tracing_v3/session_tracer.py +10 -0
- synth_ai/tracing_v3/turso/daemon.py +2 -2
- synth_ai/tracing_v3/turso/native_manager.py +108 -77
- synth_ai/tracing_v3/utils.py +1 -1
- synth_ai/tui/__init__.py +5 -0
- synth_ai/tui/__main__.py +13 -0
- synth_ai/tui/cli/__init__.py +1 -0
- synth_ai/tui/cli/query_experiments.py +164 -0
- synth_ai/tui/cli/query_experiments_v3.py +164 -0
- synth_ai/tui/dashboard.py +911 -0
- synth_ai/utils/__init__.py +101 -0
- synth_ai/utils/base_url.py +94 -0
- synth_ai/utils/cli.py +131 -0
- synth_ai/utils/env.py +287 -0
- synth_ai/utils/http.py +169 -0
- synth_ai/utils/modal.py +308 -0
- synth_ai/utils/process.py +212 -0
- synth_ai/utils/prompts.py +39 -0
- synth_ai/utils/sqld.py +122 -0
- synth_ai/utils/task_app_discovery.py +882 -0
- synth_ai/utils/task_app_env.py +186 -0
- synth_ai/utils/task_app_state.py +318 -0
- synth_ai/utils/user_config.py +137 -0
- synth_ai/v0/config/__init__.py +1 -5
- synth_ai/v0/config/base_url.py +1 -7
- synth_ai/v0/tracing/config.py +1 -1
- synth_ai/v0/tracing/decorators.py +1 -1
- synth_ai/v0/tracing/upload.py +1 -1
- synth_ai/v0/tracing_v1/config.py +1 -1
- synth_ai/v0/tracing_v1/decorators.py +1 -1
- synth_ai/v0/tracing_v1/upload.py +1 -1
- {synth_ai-0.2.13.dev2.dist-info → synth_ai-0.2.16.dist-info}/METADATA +85 -31
- {synth_ai-0.2.13.dev2.dist-info → synth_ai-0.2.16.dist-info}/RECORD +286 -135
- synth_ai/cli/man.py +0 -106
- synth_ai/compound/cais.py +0 -0
- synth_ai/core/experiment.py +0 -13
- synth_ai/core/system.py +0 -15
- synth_ai/demo_registry.py +0 -295
- synth_ai/handshake.py +0 -109
- synth_ai/http.py +0 -26
- {synth_ai-0.2.13.dev2.dist-info → synth_ai-0.2.16.dist-info}/WHEEL +0 -0
- {synth_ai-0.2.13.dev2.dist-info → synth_ai-0.2.16.dist-info}/entry_points.txt +0 -0
- {synth_ai-0.2.13.dev2.dist-info → synth_ai-0.2.16.dist-info}/licenses/LICENSE +0 -0
- {synth_ai-0.2.13.dev2.dist-info → synth_ai-0.2.16.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,1226 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter, HTTPException
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
# Import the actual classes from synth-ai
|
|
13
|
+
from synth_ai.environments.examples.crafter_classic.environment import (
|
|
14
|
+
CrafterClassicEnvironment,
|
|
15
|
+
)
|
|
16
|
+
from synth_ai.environments.examples.crafter_classic.taskset import (
|
|
17
|
+
CrafterTaskInstance,
|
|
18
|
+
CrafterTaskInstanceMetadata,
|
|
19
|
+
)
|
|
20
|
+
from synth_ai.environments.tasks.core import Impetus, Intent
|
|
21
|
+
|
|
22
|
+
from .envs.crafter.environment import CrafterEnvironmentWrapper
|
|
23
|
+
from .registry import registry
|
|
24
|
+
from .storage.volume import storage
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
router = APIRouter()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def validate_environment_observation(observation: Any, context: str) -> None:
|
|
32
|
+
"""
|
|
33
|
+
Validate that an environment observation has the correct structure.
|
|
34
|
+
This ensures the environment wrapper is producing valid observations.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
observation: The observation to validate
|
|
38
|
+
context: Context string for logging (e.g., "initialize", "step")
|
|
39
|
+
"""
|
|
40
|
+
if observation is None:
|
|
41
|
+
raise ValueError(f"Environment observation cannot be None in {context}")
|
|
42
|
+
|
|
43
|
+
if not isinstance(observation, dict):
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"Environment observation must be dict in {context}, got {type(observation)}"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# For Wordle environments, validate specific structure
|
|
49
|
+
# Check if this looks like a Wordle observation by looking for Wordle-specific keys
|
|
50
|
+
wordle_keys = {
|
|
51
|
+
"text",
|
|
52
|
+
"status",
|
|
53
|
+
"remaining_guesses",
|
|
54
|
+
"guesses",
|
|
55
|
+
"feedback",
|
|
56
|
+
"reward_last",
|
|
57
|
+
"total_reward",
|
|
58
|
+
"terminated",
|
|
59
|
+
}
|
|
60
|
+
if wordle_keys.issubset(set(observation.keys())):
|
|
61
|
+
logger.info(f"🔍 ENV_ROUTES: Validating Wordle observation structure in {context}")
|
|
62
|
+
logger.info(f"🔍 ENV_ROUTES: Observation keys: {list(observation.keys())}")
|
|
63
|
+
|
|
64
|
+
missing_keys = wordle_keys - set(observation.keys())
|
|
65
|
+
if missing_keys:
|
|
66
|
+
logger.error(
|
|
67
|
+
f"❌ ENV_ROUTES: Wordle observation missing required keys in {context}: {missing_keys}"
|
|
68
|
+
)
|
|
69
|
+
logger.error(f"❌ ENV_ROUTES: Full observation: {observation}")
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"Wordle observation missing required keys in {context}: {missing_keys}"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# Validate data types
|
|
75
|
+
if not isinstance(observation.get("text"), str):
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"Wordle observation 'text' must be string in {context}, got {type(observation.get('text'))}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
if not isinstance(observation.get("guesses"), list):
|
|
81
|
+
raise ValueError(
|
|
82
|
+
f"Wordle observation 'guesses' must be list in {context}, got {type(observation.get('guesses'))}"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if not isinstance(observation.get("feedback"), list):
|
|
86
|
+
raise ValueError(
|
|
87
|
+
f"Wordle observation 'feedback' must be list in {context}, got {type(observation.get('feedback'))}"
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
logger.info(
|
|
91
|
+
f"✅ ENV_ROUTES: Wordle observation structure validated successfully in {context}"
|
|
92
|
+
)
|
|
93
|
+
else:
|
|
94
|
+
logger.debug(
|
|
95
|
+
f"🔍 ENV_ROUTES: Observation doesn't appear to be Wordle in {context}, skipping validation"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class EnvCreateRequest(BaseModel):
|
|
100
|
+
env_name: str
|
|
101
|
+
config: dict[str, Any] = {}
|
|
102
|
+
seed: int | None = None
|
|
103
|
+
parent_env_id: str | None = None
|
|
104
|
+
rl_run_id: str
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class EnvCreateResponse(BaseModel):
|
|
108
|
+
env_id: str
|
|
109
|
+
observation: dict[str, Any]
|
|
110
|
+
info: dict[str, Any] | None = None
|
|
111
|
+
step_idx: int
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class EnvResetRequest(BaseModel):
|
|
115
|
+
env_id: str
|
|
116
|
+
seed: int | None = None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class EnvResetResponse(BaseModel):
|
|
120
|
+
observation: dict[str, Any]
|
|
121
|
+
info: dict[str, Any] | None = None
|
|
122
|
+
step_idx: int
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class EnvStepRequest(BaseModel):
|
|
126
|
+
env_id: str
|
|
127
|
+
tool_calls: list[dict[str, Any]]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class EnvStepResponse(BaseModel):
|
|
131
|
+
observation: dict[str, Any]
|
|
132
|
+
done: bool
|
|
133
|
+
info: dict[str, Any] | None = None
|
|
134
|
+
reward: float | None = None
|
|
135
|
+
truncated: bool | None = None
|
|
136
|
+
step_idx: int
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class EnvSnapshotRequest(BaseModel):
|
|
140
|
+
env_id: str
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class EnvSnapshotResponse(BaseModel):
|
|
144
|
+
snapshot_id: str
|
|
145
|
+
path: str
|
|
146
|
+
rl_run_id: str
|
|
147
|
+
size: int
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class EnvRestoreRequest(BaseModel):
|
|
151
|
+
snapshot_id: str
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class EnvRestoreResponse(BaseModel):
|
|
155
|
+
env_id: str
|
|
156
|
+
observation: dict[str, Any]
|
|
157
|
+
info: dict[str, Any] | None = None
|
|
158
|
+
step_idx: int
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class EnvTerminateRequest(BaseModel):
|
|
162
|
+
env_id: str
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class EnvTerminateResponse(BaseModel):
|
|
166
|
+
ok: bool
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@router.post("/create", response_model=EnvCreateResponse)
|
|
170
|
+
async def create_environment(request: EnvCreateRequest) -> EnvCreateResponse:
|
|
171
|
+
"""Create a new environment instance."""
|
|
172
|
+
try:
|
|
173
|
+
# Create the underlying synth-ai environment
|
|
174
|
+
env_name_lower = request.env_name.lower()
|
|
175
|
+
if env_name_lower == "crafter":
|
|
176
|
+
# Build a minimal Crafter task instance
|
|
177
|
+
difficulty = (request.config or {}).get("difficulty", "normal")
|
|
178
|
+
seed_value = request.seed if request.seed is not None else 0
|
|
179
|
+
# Task object is part of the ecosystem; not required for instantiation here
|
|
180
|
+
impetus = Impetus(instructions="Survive and unlock achievements.")
|
|
181
|
+
intent = Intent(
|
|
182
|
+
rubric={"goal": "Unlock achievements"},
|
|
183
|
+
gold_trajectories=None,
|
|
184
|
+
gold_state_diff={},
|
|
185
|
+
)
|
|
186
|
+
metadata = CrafterTaskInstanceMetadata(
|
|
187
|
+
difficulty=difficulty,
|
|
188
|
+
seed=seed_value,
|
|
189
|
+
num_trees_radius=0,
|
|
190
|
+
num_cows_radius=0,
|
|
191
|
+
num_hostiles_radius=0,
|
|
192
|
+
)
|
|
193
|
+
instance = CrafterTaskInstance(
|
|
194
|
+
id=uuid4(),
|
|
195
|
+
impetus=impetus,
|
|
196
|
+
intent=intent,
|
|
197
|
+
metadata=metadata,
|
|
198
|
+
is_reproducible=True,
|
|
199
|
+
initial_engine_snapshot=None,
|
|
200
|
+
)
|
|
201
|
+
# Create CrafterClassicEnvironment from task instance
|
|
202
|
+
base_env = CrafterClassicEnvironment(task_instance=instance)
|
|
203
|
+
|
|
204
|
+
# Wrap it for our API
|
|
205
|
+
wrapper = CrafterEnvironmentWrapper(
|
|
206
|
+
env=base_env,
|
|
207
|
+
seed=request.seed,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
# Initialize the environment
|
|
211
|
+
result = await wrapper.initialize()
|
|
212
|
+
|
|
213
|
+
# Log a world signature for sanity: seed + starting public state hash
|
|
214
|
+
try:
|
|
215
|
+
pub_state = base_env.engine._get_public_state_from_env() # type: ignore[attr-defined]
|
|
216
|
+
import hashlib
|
|
217
|
+
import json as _json
|
|
218
|
+
|
|
219
|
+
sig_src = {
|
|
220
|
+
"player_position": list(pub_state.player_position),
|
|
221
|
+
"player_direction": pub_state.player_direction,
|
|
222
|
+
"semantic_map": pub_state.semantic_map,
|
|
223
|
+
"inventory": {k: v for k, v in pub_state.inventory.items() if v},
|
|
224
|
+
}
|
|
225
|
+
sig_str = _json.dumps(sig_src, sort_keys=True)
|
|
226
|
+
sig = hashlib.md5(sig_str.encode("utf-8")).hexdigest()[:12]
|
|
227
|
+
logger.info(
|
|
228
|
+
"Crafter init signature: seed=%s sig=%s pos=%s inv=%s",
|
|
229
|
+
str(seed_value),
|
|
230
|
+
sig,
|
|
231
|
+
list(pub_state.player_position),
|
|
232
|
+
{k: v for k, v in pub_state.inventory.items() if v},
|
|
233
|
+
)
|
|
234
|
+
except Exception as _e:
|
|
235
|
+
pass
|
|
236
|
+
|
|
237
|
+
# Handle the observation structure consistently
|
|
238
|
+
# For Crafter, the result might still have the old nested structure, so we need to handle both
|
|
239
|
+
if isinstance(result, dict) and "observation" in result:
|
|
240
|
+
# Old nested structure - extract the inner observation
|
|
241
|
+
observation_for_registry = result["observation"].copy()
|
|
242
|
+
else:
|
|
243
|
+
# New flat structure - remove non-observation fields
|
|
244
|
+
observation_for_registry = result.copy()
|
|
245
|
+
for key in ["step_idx", "info"]:
|
|
246
|
+
if key in observation_for_registry:
|
|
247
|
+
del observation_for_registry[key]
|
|
248
|
+
|
|
249
|
+
# Register in memory
|
|
250
|
+
env_id = registry.register_env(
|
|
251
|
+
env=wrapper,
|
|
252
|
+
seed=request.seed,
|
|
253
|
+
rl_run_id=request.rl_run_id,
|
|
254
|
+
last_observation=observation_for_registry,
|
|
255
|
+
last_info=result.get("info"),
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
# Update step index in registry
|
|
259
|
+
handle = registry.get_env(env_id)
|
|
260
|
+
if handle:
|
|
261
|
+
handle.step_idx = result["step_idx"]
|
|
262
|
+
|
|
263
|
+
return EnvCreateResponse(
|
|
264
|
+
env_id=env_id,
|
|
265
|
+
observation=observation_for_registry,
|
|
266
|
+
info=result.get("info"),
|
|
267
|
+
step_idx=result["step_idx"],
|
|
268
|
+
)
|
|
269
|
+
elif env_name_lower == "wordle":
|
|
270
|
+
# Defer imports to avoid hard dependency when not used
|
|
271
|
+
try:
|
|
272
|
+
from synth_ai.environments.examples.wordle.environment import (
|
|
273
|
+
WordleEnvironment,
|
|
274
|
+
)
|
|
275
|
+
from synth_ai.environments.examples.wordle.taskset import (
|
|
276
|
+
WordleTaskInstance,
|
|
277
|
+
WordleTaskInstanceMetadata,
|
|
278
|
+
)
|
|
279
|
+
except Exception as e:
|
|
280
|
+
raise HTTPException(
|
|
281
|
+
status_code=500, detail=f"Wordle modules unavailable: {e}"
|
|
282
|
+
) from e
|
|
283
|
+
|
|
284
|
+
# Lazy import of wrapper within branch
|
|
285
|
+
try:
|
|
286
|
+
from .envs.wordle.environment import WordleEnvironmentWrapper
|
|
287
|
+
except Exception as e:
|
|
288
|
+
raise HTTPException(
|
|
289
|
+
status_code=500, detail=f"Wordle wrapper unavailable: {e}"
|
|
290
|
+
) from e
|
|
291
|
+
else:
|
|
292
|
+
wordle_wrapper_cls = WordleEnvironmentWrapper
|
|
293
|
+
|
|
294
|
+
cfg = request.config or {}
|
|
295
|
+
word_length = int(cfg.get("word_length", 5))
|
|
296
|
+
max_guesses = int(cfg.get("max_guesses", 6))
|
|
297
|
+
|
|
298
|
+
# Build a single Wordle task instance with proper seed usage
|
|
299
|
+
md = WordleTaskInstanceMetadata(
|
|
300
|
+
word_length=word_length,
|
|
301
|
+
max_guesses=max_guesses,
|
|
302
|
+
target_word=None, # Let seed determine the word
|
|
303
|
+
enforce_wordlist=True,
|
|
304
|
+
seed=request.seed,
|
|
305
|
+
consume_invalid_attempts=True,
|
|
306
|
+
)
|
|
307
|
+
instance = WordleTaskInstance(
|
|
308
|
+
id=uuid4(),
|
|
309
|
+
impetus=Impetus(instructions="Play Wordle. Submit one 5-letter word per turn."),
|
|
310
|
+
intent=Intent(rubric="guess the word", gold_trajectories=None, gold_state_diff={}),
|
|
311
|
+
metadata=md,
|
|
312
|
+
is_reproducible=True,
|
|
313
|
+
initial_engine_snapshot=None,
|
|
314
|
+
)
|
|
315
|
+
base_env = WordleEnvironment(task_instance=instance)
|
|
316
|
+
|
|
317
|
+
# Try to preserve the exact puzzle snapshot for reproducibility
|
|
318
|
+
init_snap = getattr(instance, "initial_engine_snapshot", None)
|
|
319
|
+
|
|
320
|
+
wrapper = wordle_wrapper_cls(
|
|
321
|
+
env=base_env,
|
|
322
|
+
seed=request.seed,
|
|
323
|
+
word_length=word_length,
|
|
324
|
+
max_guesses=max_guesses,
|
|
325
|
+
initial_engine_snapshot=init_snap,
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
result = await wrapper.initialize()
|
|
329
|
+
|
|
330
|
+
# Validate Wordle observation structure
|
|
331
|
+
# After our fix, the result is now flat, so we need to extract the observation fields
|
|
332
|
+
# that should be passed to the registry and response
|
|
333
|
+
if isinstance(result, dict) and "observation" in result:
|
|
334
|
+
# Old nested structure - extract the inner observation
|
|
335
|
+
observation_for_registry = result["observation"].copy()
|
|
336
|
+
else:
|
|
337
|
+
# New flat structure - remove non-observation fields
|
|
338
|
+
observation_for_registry = result.copy()
|
|
339
|
+
for key in ["step_idx", "info"]:
|
|
340
|
+
if key in observation_for_registry:
|
|
341
|
+
del observation_for_registry[key]
|
|
342
|
+
|
|
343
|
+
await validate_environment_observation(observation_for_registry, "initialize")
|
|
344
|
+
|
|
345
|
+
env_id = registry.register_env(
|
|
346
|
+
env=wrapper,
|
|
347
|
+
seed=request.seed,
|
|
348
|
+
rl_run_id=request.rl_run_id,
|
|
349
|
+
last_observation=observation_for_registry,
|
|
350
|
+
last_info=result.get("info"),
|
|
351
|
+
)
|
|
352
|
+
handle = registry.get_env(env_id)
|
|
353
|
+
if handle:
|
|
354
|
+
handle.step_idx = result["step_idx"]
|
|
355
|
+
return EnvCreateResponse(
|
|
356
|
+
env_id=env_id,
|
|
357
|
+
observation=observation_for_registry,
|
|
358
|
+
info=result.get("info"),
|
|
359
|
+
step_idx=result["step_idx"],
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
elif env_name_lower == "sokoban":
|
|
363
|
+
try:
|
|
364
|
+
from synth_ai.environments.examples.sokoban.environment import (
|
|
365
|
+
SokobanEnvironment,
|
|
366
|
+
)
|
|
367
|
+
from synth_ai.environments.examples.sokoban.taskset import (
|
|
368
|
+
SokobanTaskInstance,
|
|
369
|
+
SokobanTaskInstanceMetadata,
|
|
370
|
+
)
|
|
371
|
+
except Exception as e:
|
|
372
|
+
raise HTTPException(
|
|
373
|
+
status_code=500, detail=f"Sokoban modules unavailable: {e}"
|
|
374
|
+
) from e
|
|
375
|
+
|
|
376
|
+
# Lazy import of wrapper within branch
|
|
377
|
+
try:
|
|
378
|
+
from .envs.sokoban.environment import SokobanEnvironmentWrapper
|
|
379
|
+
except Exception as e:
|
|
380
|
+
raise HTTPException(
|
|
381
|
+
status_code=500, detail=f"Sokoban wrapper unavailable: {e}"
|
|
382
|
+
) from e
|
|
383
|
+
|
|
384
|
+
cfg = request.config or {}
|
|
385
|
+
difficulty = cfg.get("difficulty", "easy")
|
|
386
|
+
initial_state = cfg.get("initial_state") # Optional engine snapshot
|
|
387
|
+
|
|
388
|
+
metadata = SokobanTaskInstanceMetadata(
|
|
389
|
+
difficulty=difficulty,
|
|
390
|
+
)
|
|
391
|
+
instance = SokobanTaskInstance(
|
|
392
|
+
id=uuid4(),
|
|
393
|
+
impetus=Impetus(instructions="Push boxes to targets."),
|
|
394
|
+
intent=Intent(
|
|
395
|
+
rubric={"goal": "Solve the Sokoban puzzle"},
|
|
396
|
+
gold_trajectories=None,
|
|
397
|
+
gold_state_diff={},
|
|
398
|
+
),
|
|
399
|
+
metadata=metadata,
|
|
400
|
+
is_reproducible=True,
|
|
401
|
+
initial_engine_snapshot=initial_state,
|
|
402
|
+
)
|
|
403
|
+
base_env = SokobanEnvironment(task_instance=instance)
|
|
404
|
+
|
|
405
|
+
wrapper = SokobanEnvironmentWrapper(env=base_env, seed=request.seed, config=cfg)
|
|
406
|
+
result = await wrapper.initialize()
|
|
407
|
+
|
|
408
|
+
# Handle the observation structure consistently for Sokoban
|
|
409
|
+
if isinstance(result, dict) and "observation" in result:
|
|
410
|
+
# Old nested structure - extract the inner observation
|
|
411
|
+
observation_for_registry = result["observation"].copy()
|
|
412
|
+
else:
|
|
413
|
+
# New flat structure - remove non-observation fields
|
|
414
|
+
observation_for_registry = result.copy()
|
|
415
|
+
for key in ["step_idx", "info"]:
|
|
416
|
+
if key in observation_for_registry:
|
|
417
|
+
del observation_for_registry[key]
|
|
418
|
+
|
|
419
|
+
env_id = registry.register_env(
|
|
420
|
+
env=wrapper,
|
|
421
|
+
seed=request.seed,
|
|
422
|
+
rl_run_id=request.rl_run_id,
|
|
423
|
+
last_observation=observation_for_registry,
|
|
424
|
+
last_info=result.get("info"),
|
|
425
|
+
)
|
|
426
|
+
handle = registry.get_env(env_id)
|
|
427
|
+
if handle:
|
|
428
|
+
handle.step_idx = result["step_idx"]
|
|
429
|
+
return EnvCreateResponse(
|
|
430
|
+
env_id=env_id,
|
|
431
|
+
observation=observation_for_registry,
|
|
432
|
+
info=result.get("info"),
|
|
433
|
+
step_idx=result["step_idx"],
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
elif env_name_lower == "math":
|
|
437
|
+
# Single-step math env (GSM8K-style)
|
|
438
|
+
cfg = request.config or {}
|
|
439
|
+
# Lazy import of wrapper within branch
|
|
440
|
+
try:
|
|
441
|
+
from .envs.math.environment import MathEnvironmentWrapper
|
|
442
|
+
except Exception as e:
|
|
443
|
+
raise HTTPException(status_code=500, detail=f"Math wrapper unavailable: {e}") from e
|
|
444
|
+
|
|
445
|
+
wrapper = MathEnvironmentWrapper(
|
|
446
|
+
seed=request.seed,
|
|
447
|
+
problem_id=cfg.get("problem_id"),
|
|
448
|
+
problem_text=cfg.get("problem_text"),
|
|
449
|
+
)
|
|
450
|
+
result = await wrapper.initialize()
|
|
451
|
+
|
|
452
|
+
observation_for_registry = (
|
|
453
|
+
result["observation"].copy()
|
|
454
|
+
if isinstance(result, dict) and "observation" in result
|
|
455
|
+
else result.copy()
|
|
456
|
+
)
|
|
457
|
+
for key in ["step_idx", "info"]:
|
|
458
|
+
if key in observation_for_registry:
|
|
459
|
+
del observation_for_registry[key]
|
|
460
|
+
|
|
461
|
+
env_id = registry.register_env(
|
|
462
|
+
env=wrapper,
|
|
463
|
+
seed=request.seed,
|
|
464
|
+
rl_run_id=request.rl_run_id,
|
|
465
|
+
last_observation=observation_for_registry,
|
|
466
|
+
last_info=result.get("info"),
|
|
467
|
+
)
|
|
468
|
+
handle = registry.get_env(env_id)
|
|
469
|
+
if handle:
|
|
470
|
+
handle.step_idx = result["step_idx"]
|
|
471
|
+
return EnvCreateResponse(
|
|
472
|
+
env_id=env_id,
|
|
473
|
+
observation=observation_for_registry,
|
|
474
|
+
info=result.get("info"),
|
|
475
|
+
step_idx=result["step_idx"],
|
|
476
|
+
)
|
|
477
|
+
else:
|
|
478
|
+
raise HTTPException(
|
|
479
|
+
status_code=422,
|
|
480
|
+
detail=f"Unknown environment name: {request.env_name}",
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
except Exception as e:
|
|
484
|
+
logger.error(f"Failed to create environment: {e}")
|
|
485
|
+
raise HTTPException(status_code=500, detail=str(e)) from e
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
# --- Compatibility routes for existing eval scripts that expect CrafterClassic paths ---
|
|
489
|
+
@router.post("/CrafterClassic/initialize", response_model=EnvCreateResponse)
|
|
490
|
+
async def compat_initialize(payload: dict) -> EnvCreateResponse:
|
|
491
|
+
seed = payload.get("seed")
|
|
492
|
+
wc = payload.get("world_config")
|
|
493
|
+
cfg = payload.get("config")
|
|
494
|
+
difficulty: str = "normal"
|
|
495
|
+
if isinstance(wc, str) and wc:
|
|
496
|
+
difficulty = wc
|
|
497
|
+
elif isinstance(wc, dict) and wc.get("difficulty"):
|
|
498
|
+
difficulty = str(wc.get("difficulty"))
|
|
499
|
+
elif isinstance(cfg, dict) and cfg.get("difficulty"):
|
|
500
|
+
difficulty = str(cfg.get("difficulty"))
|
|
501
|
+
req = EnvCreateRequest(
|
|
502
|
+
env_name="crafter", config={"difficulty": difficulty}, seed=seed, rl_run_id="eval"
|
|
503
|
+
)
|
|
504
|
+
return await create_environment(req)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
@router.post("/CrafterClassic/step", response_model=EnvStepResponse)
|
|
508
|
+
async def compat_step(payload: dict) -> EnvStepResponse:
|
|
509
|
+
env_id = payload.get("env_id")
|
|
510
|
+
# eval script wraps action as {"tool_calls":[{"tool":"interact","args":{"action": <id>}}]}
|
|
511
|
+
action = payload.get("action") or {}
|
|
512
|
+
tool_calls = action.get("tool_calls") if isinstance(action, dict) else None
|
|
513
|
+
if not isinstance(tool_calls, list):
|
|
514
|
+
tool_calls = []
|
|
515
|
+
# Fallback: support {action: {actions: [..]}} by expanding into tool_calls
|
|
516
|
+
actions_list = action.get("actions") if isinstance(action, dict) else None
|
|
517
|
+
if isinstance(actions_list, list) and actions_list:
|
|
518
|
+
for a in actions_list:
|
|
519
|
+
tool_calls.append(
|
|
520
|
+
{
|
|
521
|
+
"tool": "interact",
|
|
522
|
+
"args": {"action": a},
|
|
523
|
+
}
|
|
524
|
+
)
|
|
525
|
+
req = EnvStepRequest(env_id=env_id, tool_calls=tool_calls)
|
|
526
|
+
return await step_environment(req)
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
@router.post("/CrafterClassic/terminate", response_model=EnvTerminateResponse)
|
|
530
|
+
async def compat_terminate(payload: dict) -> EnvTerminateResponse:
|
|
531
|
+
env_id = payload.get("env_id")
|
|
532
|
+
req = EnvTerminateRequest(env_id=env_id)
|
|
533
|
+
return await terminate_environment(req)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
@router.post("/reset", response_model=EnvResetResponse)
|
|
537
|
+
async def reset_environment(request: EnvResetRequest) -> EnvResetResponse:
|
|
538
|
+
"""Reset an environment to its initial state."""
|
|
539
|
+
handle = registry.get_env(request.env_id)
|
|
540
|
+
if not handle:
|
|
541
|
+
raise HTTPException(status_code=404, detail=f"Environment {request.env_id} not found")
|
|
542
|
+
|
|
543
|
+
try:
|
|
544
|
+
# Determine wrapper type and rebuild base env if a new seed is provided
|
|
545
|
+
wrapper = handle.env
|
|
546
|
+
if isinstance(wrapper, CrafterEnvironmentWrapper):
|
|
547
|
+
if request.seed is not None:
|
|
548
|
+
try:
|
|
549
|
+
difficulty = "normal"
|
|
550
|
+
seed_value = int(request.seed)
|
|
551
|
+
metadata = CrafterTaskInstanceMetadata(
|
|
552
|
+
difficulty=difficulty,
|
|
553
|
+
seed=seed_value,
|
|
554
|
+
num_trees_radius=0,
|
|
555
|
+
num_cows_radius=0,
|
|
556
|
+
num_hostiles_radius=0,
|
|
557
|
+
)
|
|
558
|
+
instance = CrafterTaskInstance(
|
|
559
|
+
id=uuid4(),
|
|
560
|
+
impetus=Impetus(instructions="Reset"),
|
|
561
|
+
intent=Intent(
|
|
562
|
+
rubric={"goal": "Reset"},
|
|
563
|
+
gold_trajectories=None,
|
|
564
|
+
gold_state_diff={},
|
|
565
|
+
),
|
|
566
|
+
metadata=metadata,
|
|
567
|
+
is_reproducible=True,
|
|
568
|
+
initial_engine_snapshot=None,
|
|
569
|
+
)
|
|
570
|
+
new_base_env = CrafterClassicEnvironment(task_instance=instance)
|
|
571
|
+
wrapper.env = new_base_env
|
|
572
|
+
wrapper.seed = seed_value
|
|
573
|
+
handle.seed = seed_value
|
|
574
|
+
except Exception:
|
|
575
|
+
wrapper.seed = request.seed
|
|
576
|
+
handle.seed = request.seed
|
|
577
|
+
|
|
578
|
+
elif True:
|
|
579
|
+
# Try to dynamically import Wordle wrapper and check instance safely
|
|
580
|
+
wordle_wrapper_cls = None
|
|
581
|
+
with contextlib.suppress(Exception):
|
|
582
|
+
from .envs.wordle.environment import WordleEnvironmentWrapper
|
|
583
|
+
|
|
584
|
+
wordle_wrapper_cls = WordleEnvironmentWrapper # type: ignore[assignment]
|
|
585
|
+
|
|
586
|
+
if wordle_wrapper_cls is not None and isinstance(wrapper, wordle_wrapper_cls):
|
|
587
|
+
# Rebuild Wordle env with the same configuration; if we have a preserved
|
|
588
|
+
# initial_engine_snapshot, prefer constructing the instance directly.
|
|
589
|
+
try:
|
|
590
|
+
from synth_ai.environments.examples.wordle.environment import (
|
|
591
|
+
WordleEnvironment,
|
|
592
|
+
)
|
|
593
|
+
from synth_ai.environments.examples.wordle.taskset import (
|
|
594
|
+
WordleTaskInstance,
|
|
595
|
+
WordleTaskInstanceMetadata,
|
|
596
|
+
create_wordle_taskset,
|
|
597
|
+
)
|
|
598
|
+
except Exception as e:
|
|
599
|
+
raise HTTPException(
|
|
600
|
+
status_code=500, detail=f"Wordle modules unavailable: {e}"
|
|
601
|
+
) from e
|
|
602
|
+
|
|
603
|
+
init_snap = getattr(wrapper, "initial_engine_snapshot", None)
|
|
604
|
+
if init_snap is not None:
|
|
605
|
+
metadata = WordleTaskInstanceMetadata(
|
|
606
|
+
word_length=int(wrapper.word_length),
|
|
607
|
+
max_guesses=int(wrapper.max_guesses),
|
|
608
|
+
)
|
|
609
|
+
instance = WordleTaskInstance(
|
|
610
|
+
id=uuid4(),
|
|
611
|
+
impetus=Impetus(instructions="Reset"),
|
|
612
|
+
intent=Intent(
|
|
613
|
+
rubric={"goal": "Reset"},
|
|
614
|
+
gold_trajectories=None,
|
|
615
|
+
gold_state_diff={},
|
|
616
|
+
),
|
|
617
|
+
metadata=metadata,
|
|
618
|
+
is_reproducible=True,
|
|
619
|
+
initial_engine_snapshot=init_snap,
|
|
620
|
+
)
|
|
621
|
+
new_base_env = WordleEnvironment(task_instance=instance)
|
|
622
|
+
else:
|
|
623
|
+
ts = await create_wordle_taskset(
|
|
624
|
+
sample_size=1,
|
|
625
|
+
word_length=int(wrapper.word_length),
|
|
626
|
+
max_guesses=int(wrapper.max_guesses),
|
|
627
|
+
)
|
|
628
|
+
instance = ts.instances[0]
|
|
629
|
+
new_base_env = WordleEnvironment(task_instance=instance)
|
|
630
|
+
wrapper.env = new_base_env
|
|
631
|
+
if request.seed is not None:
|
|
632
|
+
wrapper.seed = int(request.seed)
|
|
633
|
+
handle.seed = int(request.seed)
|
|
634
|
+
else:
|
|
635
|
+
pass
|
|
636
|
+
# Rebuild Wordle env with the same configuration; if we have a preserved
|
|
637
|
+
# initial_engine_snapshot, prefer constructing the instance directly.
|
|
638
|
+
try:
|
|
639
|
+
from synth_ai.environments.examples.wordle.environment import (
|
|
640
|
+
WordleEnvironment,
|
|
641
|
+
)
|
|
642
|
+
from synth_ai.environments.examples.wordle.taskset import (
|
|
643
|
+
WordleTaskInstance,
|
|
644
|
+
WordleTaskInstanceMetadata,
|
|
645
|
+
create_wordle_taskset,
|
|
646
|
+
)
|
|
647
|
+
except Exception as e:
|
|
648
|
+
raise HTTPException(
|
|
649
|
+
status_code=500, detail=f"Wordle modules unavailable: {e}"
|
|
650
|
+
) from e
|
|
651
|
+
|
|
652
|
+
init_snap = getattr(wrapper, "initial_engine_snapshot", None)
|
|
653
|
+
if init_snap is not None:
|
|
654
|
+
metadata = WordleTaskInstanceMetadata(
|
|
655
|
+
word_length=int(wrapper.word_length),
|
|
656
|
+
max_guesses=int(wrapper.max_guesses),
|
|
657
|
+
)
|
|
658
|
+
instance = WordleTaskInstance(
|
|
659
|
+
id=uuid4(),
|
|
660
|
+
impetus=Impetus(instructions="Reset"),
|
|
661
|
+
intent=Intent(
|
|
662
|
+
rubric={"goal": "Reset"},
|
|
663
|
+
gold_trajectories=None,
|
|
664
|
+
gold_state_diff={},
|
|
665
|
+
),
|
|
666
|
+
metadata=metadata,
|
|
667
|
+
is_reproducible=True,
|
|
668
|
+
initial_engine_snapshot=init_snap,
|
|
669
|
+
)
|
|
670
|
+
new_base_env = WordleEnvironment(task_instance=instance)
|
|
671
|
+
else:
|
|
672
|
+
ts = await create_wordle_taskset(
|
|
673
|
+
sample_size=1,
|
|
674
|
+
word_length=int(wrapper.word_length),
|
|
675
|
+
max_guesses=int(wrapper.max_guesses),
|
|
676
|
+
)
|
|
677
|
+
instance = ts.instances[0]
|
|
678
|
+
new_base_env = WordleEnvironment(task_instance=instance)
|
|
679
|
+
wrapper.env = new_base_env
|
|
680
|
+
if request.seed is not None:
|
|
681
|
+
wrapper.seed = int(request.seed)
|
|
682
|
+
handle.seed = int(request.seed)
|
|
683
|
+
|
|
684
|
+
elif True:
|
|
685
|
+
# Try to dynamically import Sokoban wrapper and check instance safely
|
|
686
|
+
sokoban_wrapper_cls = None
|
|
687
|
+
with contextlib.suppress(Exception):
|
|
688
|
+
from .envs.sokoban.environment import SokobanEnvironmentWrapper
|
|
689
|
+
|
|
690
|
+
sokoban_wrapper_cls = SokobanEnvironmentWrapper # type: ignore[assignment]
|
|
691
|
+
|
|
692
|
+
if sokoban_wrapper_cls is not None and isinstance(wrapper, sokoban_wrapper_cls):
|
|
693
|
+
# Rebuild Sokoban env using stored config snapshot
|
|
694
|
+
try:
|
|
695
|
+
from synth_ai.environments.examples.sokoban.environment import (
|
|
696
|
+
SokobanEnvironment,
|
|
697
|
+
)
|
|
698
|
+
from synth_ai.environments.examples.sokoban.taskset import (
|
|
699
|
+
SokobanTaskInstance,
|
|
700
|
+
SokobanTaskInstanceMetadata,
|
|
701
|
+
)
|
|
702
|
+
except Exception as e:
|
|
703
|
+
raise HTTPException(
|
|
704
|
+
status_code=500, detail=f"Sokoban modules unavailable: {e}"
|
|
705
|
+
) from e
|
|
706
|
+
|
|
707
|
+
cfg = dict(wrapper.config or {})
|
|
708
|
+
metadata = SokobanTaskInstanceMetadata(
|
|
709
|
+
difficulty=cfg.get("difficulty", "easy"),
|
|
710
|
+
)
|
|
711
|
+
instance = SokobanTaskInstance(
|
|
712
|
+
id=uuid4(),
|
|
713
|
+
impetus=Impetus(instructions="Reset"),
|
|
714
|
+
intent=Intent(
|
|
715
|
+
rubric={"goal": "Reset"}, gold_trajectories=None, gold_state_diff={}
|
|
716
|
+
),
|
|
717
|
+
metadata=metadata,
|
|
718
|
+
is_reproducible=True,
|
|
719
|
+
initial_engine_snapshot=cfg.get("initial_state"),
|
|
720
|
+
)
|
|
721
|
+
new_base_env = SokobanEnvironment(task_instance=instance)
|
|
722
|
+
wrapper.env = new_base_env
|
|
723
|
+
if request.seed is not None:
|
|
724
|
+
wrapper.seed = int(request.seed)
|
|
725
|
+
handle.seed = int(request.seed)
|
|
726
|
+
else:
|
|
727
|
+
pass
|
|
728
|
+
# Rebuild Sokoban env using stored config snapshot
|
|
729
|
+
try:
|
|
730
|
+
from synth_ai.environments.examples.sokoban.environment import (
|
|
731
|
+
SokobanEnvironment,
|
|
732
|
+
)
|
|
733
|
+
from synth_ai.environments.examples.sokoban.taskset import (
|
|
734
|
+
SokobanTaskInstance,
|
|
735
|
+
SokobanTaskInstanceMetadata,
|
|
736
|
+
)
|
|
737
|
+
except Exception as e:
|
|
738
|
+
raise HTTPException(
|
|
739
|
+
status_code=500, detail=f"Sokoban modules unavailable: {e}"
|
|
740
|
+
) from e
|
|
741
|
+
|
|
742
|
+
cfg = dict(wrapper.config or {})
|
|
743
|
+
metadata = SokobanTaskInstanceMetadata(
|
|
744
|
+
difficulty=cfg.get("difficulty", "easy"),
|
|
745
|
+
)
|
|
746
|
+
instance = SokobanTaskInstance(
|
|
747
|
+
id=uuid4(),
|
|
748
|
+
impetus=Impetus(instructions="Reset"),
|
|
749
|
+
intent=Intent(rubric={"goal": "Reset"}, gold_trajectories=None, gold_state_diff={}),
|
|
750
|
+
metadata=metadata,
|
|
751
|
+
is_reproducible=True,
|
|
752
|
+
initial_engine_snapshot=cfg.get("initial_state"),
|
|
753
|
+
)
|
|
754
|
+
new_base_env = SokobanEnvironment(task_instance=instance)
|
|
755
|
+
wrapper.env = new_base_env
|
|
756
|
+
if request.seed is not None:
|
|
757
|
+
wrapper.seed = int(request.seed)
|
|
758
|
+
handle.seed = int(request.seed)
|
|
759
|
+
|
|
760
|
+
# Reset the environment regardless of type
|
|
761
|
+
result = await wrapper.initialize()
|
|
762
|
+
|
|
763
|
+
# Log a world signature after reset for sanity
|
|
764
|
+
try:
|
|
765
|
+
base_env = handle.env.env # type: ignore[attr-defined]
|
|
766
|
+
pub_state = base_env.engine._get_public_state_from_env() # type: ignore[attr-defined]
|
|
767
|
+
import hashlib
|
|
768
|
+
import json as _json
|
|
769
|
+
|
|
770
|
+
sig_src = {
|
|
771
|
+
"player_position": list(pub_state.player_position),
|
|
772
|
+
"player_direction": pub_state.player_direction,
|
|
773
|
+
"semantic_map": pub_state.semantic_map,
|
|
774
|
+
"inventory": {k: v for k, v in pub_state.inventory.items() if v},
|
|
775
|
+
}
|
|
776
|
+
sig_str = _json.dumps(sig_src, sort_keys=True)
|
|
777
|
+
sig = hashlib.md5(sig_str.encode("utf-8")).hexdigest()[:12]
|
|
778
|
+
logger.info(
|
|
779
|
+
"Crafter reset signature: seed=%s sig=%s pos=%s inv=%s",
|
|
780
|
+
str(handle.seed),
|
|
781
|
+
sig,
|
|
782
|
+
list(pub_state.player_position),
|
|
783
|
+
{k: v for k, v in pub_state.inventory.items() if v},
|
|
784
|
+
)
|
|
785
|
+
except Exception as _:
|
|
786
|
+
pass
|
|
787
|
+
|
|
788
|
+
# Update registry
|
|
789
|
+
handle.step_idx = result["step_idx"]
|
|
790
|
+
handle.last_observation = result["observation"]
|
|
791
|
+
handle.last_info = result.get("info")
|
|
792
|
+
|
|
793
|
+
return EnvResetResponse(
|
|
794
|
+
observation=result["observation"],
|
|
795
|
+
info=result.get("info"),
|
|
796
|
+
step_idx=result["step_idx"],
|
|
797
|
+
)
|
|
798
|
+
|
|
799
|
+
except Exception as e:
|
|
800
|
+
logger.error(f"Failed to reset environment {request.env_id}: {e}")
|
|
801
|
+
raise HTTPException(status_code=500, detail=str(e)) from e
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
@router.post("/step", response_model=EnvStepResponse)
|
|
805
|
+
async def step_environment(request: EnvStepRequest) -> EnvStepResponse:
|
|
806
|
+
"""Execute a step in the environment."""
|
|
807
|
+
handle = registry.get_env(request.env_id)
|
|
808
|
+
if not handle:
|
|
809
|
+
raise HTTPException(status_code=404, detail=f"Environment {request.env_id} not found")
|
|
810
|
+
|
|
811
|
+
try:
|
|
812
|
+
# Execute the step, pre-normalizing invalid Wordle guesses to avoid hard failures
|
|
813
|
+
wrapper = handle.env
|
|
814
|
+
wordle_wrapper_cls = None
|
|
815
|
+
with contextlib.suppress(Exception):
|
|
816
|
+
from .envs.wordle.environment import WordleEnvironmentWrapper
|
|
817
|
+
|
|
818
|
+
wordle_wrapper_cls = WordleEnvironmentWrapper # type: ignore[assignment]
|
|
819
|
+
|
|
820
|
+
if wordle_wrapper_cls is not None and isinstance(wrapper, wordle_wrapper_cls):
|
|
821
|
+
expected_len = int(getattr(wrapper, "word_length", 5))
|
|
822
|
+
normalized: list[dict[str, Any]] = []
|
|
823
|
+
for tc in request.tool_calls or []:
|
|
824
|
+
tool = tc.get("tool") or tc.get("tool_name") or tc.get("name") or "interact"
|
|
825
|
+
args = tc.get("arguments") or tc.get("args") or {}
|
|
826
|
+
if isinstance(args, str):
|
|
827
|
+
try:
|
|
828
|
+
args = json.loads(args)
|
|
829
|
+
except Exception:
|
|
830
|
+
args = {}
|
|
831
|
+
guess = None
|
|
832
|
+
if isinstance(args, dict):
|
|
833
|
+
guess = args.get("guess") or args.get("word")
|
|
834
|
+
if isinstance(guess, str):
|
|
835
|
+
g = guess.strip().lower()
|
|
836
|
+
if (not g.isalpha()) or (len(g) != expected_len):
|
|
837
|
+
normalized.append(
|
|
838
|
+
{"tool": "invalid_guess", "args": {"original_guess": guess}}
|
|
839
|
+
)
|
|
840
|
+
else:
|
|
841
|
+
# Preserve the original tool name (interact or submit) for the environment to handle
|
|
842
|
+
normalized.append({"tool": tool, "args": {"guess": g}})
|
|
843
|
+
else:
|
|
844
|
+
normalized.append({"tool": "invalid_guess", "args": {"original_guess": guess}})
|
|
845
|
+
result = await wrapper.step(normalized)
|
|
846
|
+
else:
|
|
847
|
+
result = await handle.env.step(request.tool_calls)
|
|
848
|
+
|
|
849
|
+
# Validate observation structure for Wordle environments
|
|
850
|
+
env_name = getattr(handle.env, "env", None)
|
|
851
|
+
if (
|
|
852
|
+
env_name
|
|
853
|
+
and hasattr(env_name, "__class__")
|
|
854
|
+
and "wordle" in env_name.__class__.__name__.lower()
|
|
855
|
+
):
|
|
856
|
+
# Extract observation fields from the flat result structure for validation
|
|
857
|
+
observation_for_validation = result.copy()
|
|
858
|
+
# Remove step_idx, done, info, reward, truncated from the observation since they're separate fields
|
|
859
|
+
for key in ["step_idx", "done", "info", "reward", "truncated"]:
|
|
860
|
+
if key in observation_for_validation:
|
|
861
|
+
del observation_for_validation[key]
|
|
862
|
+
await validate_environment_observation(observation_for_validation, "step")
|
|
863
|
+
|
|
864
|
+
# Update registry
|
|
865
|
+
handle.step_idx = result["step_idx"]
|
|
866
|
+
|
|
867
|
+
# Extract the observation fields from the result structure (handle both old nested and new flat)
|
|
868
|
+
if isinstance(result, dict) and "observation" in result:
|
|
869
|
+
# Old nested structure - extract the inner observation
|
|
870
|
+
observation_for_registry = result["observation"].copy()
|
|
871
|
+
else:
|
|
872
|
+
# New flat structure - remove non-observation fields
|
|
873
|
+
observation_for_registry = result.copy()
|
|
874
|
+
for key in ["step_idx", "done", "info", "reward", "truncated"]:
|
|
875
|
+
if key in observation_for_registry:
|
|
876
|
+
del observation_for_registry[key]
|
|
877
|
+
|
|
878
|
+
handle.last_observation = observation_for_registry
|
|
879
|
+
handle.last_info = result.get("info")
|
|
880
|
+
|
|
881
|
+
return EnvStepResponse(
|
|
882
|
+
observation=observation_for_registry,
|
|
883
|
+
done=result["done"],
|
|
884
|
+
info=result.get("info"),
|
|
885
|
+
reward=result.get("reward"),
|
|
886
|
+
truncated=result.get("truncated"),
|
|
887
|
+
step_idx=result["step_idx"],
|
|
888
|
+
)
|
|
889
|
+
|
|
890
|
+
except Exception as e:
|
|
891
|
+
logger.error(f"Failed to step environment {request.env_id}: {e}")
|
|
892
|
+
# Fallback for Wordle: convert invalid guesses into 'invalid_guess' tool calls and retry once
|
|
893
|
+
try:
|
|
894
|
+
wordle_wrapper_cls = None
|
|
895
|
+
with contextlib.suppress(Exception):
|
|
896
|
+
from .envs.wordle.environment import WordleEnvironmentWrapper
|
|
897
|
+
|
|
898
|
+
wordle_wrapper_cls = WordleEnvironmentWrapper # type: ignore[assignment]
|
|
899
|
+
|
|
900
|
+
wrapper = handle.env
|
|
901
|
+
if wordle_wrapper_cls is not None and isinstance(wrapper, wordle_wrapper_cls):
|
|
902
|
+
expected_len = int(getattr(wrapper, "word_length", 5))
|
|
903
|
+
normalized: list[dict[str, Any]] = []
|
|
904
|
+
for tc in request.tool_calls or []:
|
|
905
|
+
tool = tc.get("tool") or tc.get("tool_name") or tc.get("name") or "interact"
|
|
906
|
+
args = tc.get("arguments") or tc.get("args") or {}
|
|
907
|
+
if isinstance(args, str):
|
|
908
|
+
try:
|
|
909
|
+
args = json.loads(args)
|
|
910
|
+
except Exception:
|
|
911
|
+
args = {}
|
|
912
|
+
guess = None
|
|
913
|
+
if isinstance(args, dict):
|
|
914
|
+
guess = args.get("guess") or args.get("word")
|
|
915
|
+
if isinstance(guess, str):
|
|
916
|
+
g = guess.strip().lower()
|
|
917
|
+
if (not g.isalpha()) or (len(g) != expected_len):
|
|
918
|
+
normalized.append(
|
|
919
|
+
{
|
|
920
|
+
"tool": "invalid_guess",
|
|
921
|
+
"args": {"original_guess": guess},
|
|
922
|
+
}
|
|
923
|
+
)
|
|
924
|
+
else:
|
|
925
|
+
normalized.append({"tool": "interact", "args": {"guess": g}})
|
|
926
|
+
else:
|
|
927
|
+
normalized.append(
|
|
928
|
+
{"tool": "invalid_guess", "args": {"original_guess": guess}}
|
|
929
|
+
)
|
|
930
|
+
|
|
931
|
+
# Retry with normalized calls, allowing the wrapper to synthesize an observation
|
|
932
|
+
result = await wrapper.step(normalized)
|
|
933
|
+
|
|
934
|
+
# Update registry and return as usual
|
|
935
|
+
handle.step_idx = result["step_idx"]
|
|
936
|
+
if isinstance(result, dict) and "observation" in result:
|
|
937
|
+
observation_for_registry = result["observation"].copy()
|
|
938
|
+
else:
|
|
939
|
+
observation_for_registry = result.copy()
|
|
940
|
+
for key in ["step_idx", "done", "info", "reward", "truncated"]:
|
|
941
|
+
if key in observation_for_registry:
|
|
942
|
+
del observation_for_registry[key]
|
|
943
|
+
handle.last_observation = observation_for_registry
|
|
944
|
+
handle.last_info = result.get("info")
|
|
945
|
+
return EnvStepResponse(
|
|
946
|
+
observation=observation_for_registry,
|
|
947
|
+
done=result["done"],
|
|
948
|
+
info=result.get("info"),
|
|
949
|
+
reward=result.get("reward"),
|
|
950
|
+
truncated=result.get("truncated"),
|
|
951
|
+
step_idx=result["step_idx"],
|
|
952
|
+
)
|
|
953
|
+
except Exception:
|
|
954
|
+
# Ignore fallback errors; fall through to generic error
|
|
955
|
+
pass
|
|
956
|
+
|
|
957
|
+
raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {e}") from e
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
@router.post("/snapshot", response_model=EnvSnapshotResponse)
|
|
961
|
+
async def snapshot_environment(request: EnvSnapshotRequest) -> EnvSnapshotResponse:
|
|
962
|
+
"""Create a snapshot of the environment state."""
|
|
963
|
+
handle = registry.get_env(request.env_id)
|
|
964
|
+
if not handle:
|
|
965
|
+
raise HTTPException(status_code=404, detail=f"Environment {request.env_id} not found")
|
|
966
|
+
|
|
967
|
+
try:
|
|
968
|
+
# Serialize environment state
|
|
969
|
+
state_dict = await handle.env.serialize()
|
|
970
|
+
|
|
971
|
+
# Save to volume
|
|
972
|
+
snapshot_id, path, size = storage.save_snapshot(
|
|
973
|
+
rl_run_id=handle.rl_run_id,
|
|
974
|
+
kind="env",
|
|
975
|
+
state_dict=state_dict,
|
|
976
|
+
config={"seed": handle.seed},
|
|
977
|
+
)
|
|
978
|
+
|
|
979
|
+
# Register snapshot
|
|
980
|
+
registry.register_snapshot(
|
|
981
|
+
kind="env",
|
|
982
|
+
rl_run_id=handle.rl_run_id,
|
|
983
|
+
size=size,
|
|
984
|
+
path=path,
|
|
985
|
+
)
|
|
986
|
+
|
|
987
|
+
return EnvSnapshotResponse(
|
|
988
|
+
snapshot_id=snapshot_id,
|
|
989
|
+
path=path,
|
|
990
|
+
rl_run_id=handle.rl_run_id,
|
|
991
|
+
size=size,
|
|
992
|
+
)
|
|
993
|
+
|
|
994
|
+
except Exception as e:
|
|
995
|
+
logger.error(f"Failed to snapshot environment {request.env_id}: {e}")
|
|
996
|
+
raise HTTPException(status_code=500, detail=str(e)) from e
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
@router.post("/restore", response_model=EnvRestoreResponse)
|
|
1000
|
+
async def restore_environment(request: EnvRestoreRequest) -> EnvRestoreResponse:
|
|
1001
|
+
"""Restore an environment from a snapshot."""
|
|
1002
|
+
snapshot = registry.get_snapshot(request.snapshot_id)
|
|
1003
|
+
if not snapshot:
|
|
1004
|
+
raise HTTPException(status_code=404, detail=f"Snapshot {request.snapshot_id} not found")
|
|
1005
|
+
|
|
1006
|
+
if snapshot.kind != "env":
|
|
1007
|
+
raise HTTPException(
|
|
1008
|
+
status_code=422,
|
|
1009
|
+
detail=f"Snapshot {request.snapshot_id} is not an environment snapshot",
|
|
1010
|
+
)
|
|
1011
|
+
|
|
1012
|
+
try:
|
|
1013
|
+
# Load snapshot from volume
|
|
1014
|
+
state_dict, meta = storage.load_snapshot(
|
|
1015
|
+
rl_run_id=snapshot.rl_run_id,
|
|
1016
|
+
kind="env",
|
|
1017
|
+
snapshot_id=request.snapshot_id,
|
|
1018
|
+
)
|
|
1019
|
+
|
|
1020
|
+
# Recreate environment
|
|
1021
|
+
env_name = state_dict.get("name", "crafter")
|
|
1022
|
+
name_lower = str(env_name).lower()
|
|
1023
|
+
if name_lower == "crafter":
|
|
1024
|
+
# Create base environment
|
|
1025
|
+
# Recreate classic env from snapshot metadata
|
|
1026
|
+
seed_value = state_dict["config"]["seed"]
|
|
1027
|
+
metadata = CrafterTaskInstanceMetadata(
|
|
1028
|
+
difficulty="normal",
|
|
1029
|
+
seed=seed_value,
|
|
1030
|
+
num_trees_radius=0,
|
|
1031
|
+
num_cows_radius=0,
|
|
1032
|
+
num_hostiles_radius=0,
|
|
1033
|
+
)
|
|
1034
|
+
instance = CrafterTaskInstance(
|
|
1035
|
+
id=uuid4(),
|
|
1036
|
+
impetus=Impetus(instructions="Restore"),
|
|
1037
|
+
intent=Intent(
|
|
1038
|
+
rubric={"goal": "Restore"},
|
|
1039
|
+
gold_trajectories=None,
|
|
1040
|
+
gold_state_diff={},
|
|
1041
|
+
),
|
|
1042
|
+
metadata=metadata,
|
|
1043
|
+
is_reproducible=True,
|
|
1044
|
+
initial_engine_snapshot=None,
|
|
1045
|
+
)
|
|
1046
|
+
base_env = CrafterClassicEnvironment(task_instance=instance)
|
|
1047
|
+
|
|
1048
|
+
# Deserialize into wrapper
|
|
1049
|
+
wrapper = await CrafterEnvironmentWrapper.deserialize(
|
|
1050
|
+
payload=state_dict,
|
|
1051
|
+
env=base_env,
|
|
1052
|
+
)
|
|
1053
|
+
|
|
1054
|
+
# Register new instance
|
|
1055
|
+
env_id = registry.register_env(
|
|
1056
|
+
env=wrapper,
|
|
1057
|
+
seed=wrapper.seed,
|
|
1058
|
+
rl_run_id=snapshot.rl_run_id,
|
|
1059
|
+
last_observation=wrapper.last_observation,
|
|
1060
|
+
last_info=wrapper.last_info,
|
|
1061
|
+
)
|
|
1062
|
+
|
|
1063
|
+
# Update step index
|
|
1064
|
+
handle = registry.get_env(env_id)
|
|
1065
|
+
if handle:
|
|
1066
|
+
handle.step_idx = wrapper.step_idx
|
|
1067
|
+
|
|
1068
|
+
return EnvRestoreResponse(
|
|
1069
|
+
env_id=env_id,
|
|
1070
|
+
observation=wrapper.last_observation or {},
|
|
1071
|
+
info=wrapper.last_info,
|
|
1072
|
+
step_idx=wrapper.step_idx,
|
|
1073
|
+
)
|
|
1074
|
+
elif name_lower == "wordle":
|
|
1075
|
+
try:
|
|
1076
|
+
from synth_ai.environments.examples.wordle.environment import (
|
|
1077
|
+
WordleEnvironment,
|
|
1078
|
+
)
|
|
1079
|
+
from synth_ai.environments.examples.wordle.taskset import (
|
|
1080
|
+
WordleTaskInstance,
|
|
1081
|
+
WordleTaskInstanceMetadata,
|
|
1082
|
+
create_wordle_taskset,
|
|
1083
|
+
)
|
|
1084
|
+
except Exception as e:
|
|
1085
|
+
raise HTTPException(
|
|
1086
|
+
status_code=500, detail=f"Wordle modules unavailable: {e}"
|
|
1087
|
+
) from e
|
|
1088
|
+
|
|
1089
|
+
cfg = state_dict.get("config", {}) or {}
|
|
1090
|
+
word_length = int(cfg.get("word_length", 5))
|
|
1091
|
+
max_guesses = int(cfg.get("max_guesses", 6))
|
|
1092
|
+
init_snap = cfg.get("initial_engine_snapshot")
|
|
1093
|
+
if init_snap is not None:
|
|
1094
|
+
metadata = WordleTaskInstanceMetadata(
|
|
1095
|
+
word_length=word_length, max_guesses=max_guesses
|
|
1096
|
+
)
|
|
1097
|
+
instance = WordleTaskInstance(
|
|
1098
|
+
id=uuid4(),
|
|
1099
|
+
impetus=Impetus(instructions="Restore"),
|
|
1100
|
+
intent=Intent(
|
|
1101
|
+
rubric={"goal": "Restore"},
|
|
1102
|
+
gold_trajectories=None,
|
|
1103
|
+
gold_state_diff={},
|
|
1104
|
+
),
|
|
1105
|
+
metadata=metadata,
|
|
1106
|
+
is_reproducible=True,
|
|
1107
|
+
initial_engine_snapshot=init_snap,
|
|
1108
|
+
)
|
|
1109
|
+
base_env = WordleEnvironment(task_instance=instance)
|
|
1110
|
+
else:
|
|
1111
|
+
ts = await create_wordle_taskset(
|
|
1112
|
+
sample_size=1, word_length=word_length, max_guesses=max_guesses
|
|
1113
|
+
)
|
|
1114
|
+
instance = ts.instances[0]
|
|
1115
|
+
base_env = WordleEnvironment(task_instance=instance)
|
|
1116
|
+
# Lazy import of wrapper only when needed
|
|
1117
|
+
try:
|
|
1118
|
+
from .envs.wordle.environment import WordleEnvironmentWrapper
|
|
1119
|
+
except Exception as e:
|
|
1120
|
+
raise HTTPException(
|
|
1121
|
+
status_code=500, detail=f"Wordle wrapper unavailable: {e}"
|
|
1122
|
+
) from e
|
|
1123
|
+
wrapper = await WordleEnvironmentWrapper.deserialize(payload=state_dict, env=base_env)
|
|
1124
|
+
|
|
1125
|
+
env_id = registry.register_env(
|
|
1126
|
+
env=wrapper,
|
|
1127
|
+
seed=wrapper.seed,
|
|
1128
|
+
rl_run_id=snapshot.rl_run_id,
|
|
1129
|
+
last_observation=wrapper.last_observation,
|
|
1130
|
+
last_info=wrapper.last_info,
|
|
1131
|
+
)
|
|
1132
|
+
handle = registry.get_env(env_id)
|
|
1133
|
+
if handle:
|
|
1134
|
+
handle.step_idx = wrapper.step_idx
|
|
1135
|
+
return EnvRestoreResponse(
|
|
1136
|
+
env_id=env_id,
|
|
1137
|
+
observation=wrapper.last_observation or {},
|
|
1138
|
+
info=wrapper.last_info,
|
|
1139
|
+
step_idx=wrapper.step_idx,
|
|
1140
|
+
)
|
|
1141
|
+
|
|
1142
|
+
elif name_lower == "sokoban":
|
|
1143
|
+
try:
|
|
1144
|
+
from synth_ai.environments.examples.sokoban.environment import (
|
|
1145
|
+
SokobanEnvironment,
|
|
1146
|
+
)
|
|
1147
|
+
from synth_ai.environments.examples.sokoban.taskset import (
|
|
1148
|
+
SokobanTaskInstance,
|
|
1149
|
+
SokobanTaskInstanceMetadata,
|
|
1150
|
+
)
|
|
1151
|
+
except Exception as e:
|
|
1152
|
+
raise HTTPException(
|
|
1153
|
+
status_code=500, detail=f"Sokoban modules unavailable: {e}"
|
|
1154
|
+
) from e
|
|
1155
|
+
|
|
1156
|
+
cfg = state_dict.get("config", {}) or {}
|
|
1157
|
+
metadata = SokobanTaskInstanceMetadata(difficulty=cfg.get("difficulty", "easy"))
|
|
1158
|
+
instance = SokobanTaskInstance(
|
|
1159
|
+
id=uuid4(),
|
|
1160
|
+
impetus=Impetus(instructions="Restore"),
|
|
1161
|
+
intent=Intent(
|
|
1162
|
+
rubric={"goal": "Restore"},
|
|
1163
|
+
gold_trajectories=None,
|
|
1164
|
+
gold_state_diff={},
|
|
1165
|
+
),
|
|
1166
|
+
metadata=metadata,
|
|
1167
|
+
is_reproducible=True,
|
|
1168
|
+
initial_engine_snapshot=cfg.get("initial_state"),
|
|
1169
|
+
)
|
|
1170
|
+
base_env = SokobanEnvironment(task_instance=instance)
|
|
1171
|
+
# Lazy import of wrapper only when needed
|
|
1172
|
+
try:
|
|
1173
|
+
from .envs.sokoban.environment import SokobanEnvironmentWrapper
|
|
1174
|
+
except Exception as e:
|
|
1175
|
+
raise HTTPException(
|
|
1176
|
+
status_code=500, detail=f"Sokoban wrapper unavailable: {e}"
|
|
1177
|
+
) from e
|
|
1178
|
+
wrapper = await SokobanEnvironmentWrapper.deserialize(payload=state_dict, env=base_env)
|
|
1179
|
+
|
|
1180
|
+
env_id = registry.register_env(
|
|
1181
|
+
env=wrapper,
|
|
1182
|
+
seed=wrapper.seed,
|
|
1183
|
+
rl_run_id=snapshot.rl_run_id,
|
|
1184
|
+
last_observation=wrapper.last_observation,
|
|
1185
|
+
last_info=wrapper.last_info,
|
|
1186
|
+
)
|
|
1187
|
+
handle = registry.get_env(env_id)
|
|
1188
|
+
if handle:
|
|
1189
|
+
handle.step_idx = wrapper.step_idx
|
|
1190
|
+
return EnvRestoreResponse(
|
|
1191
|
+
env_id=env_id,
|
|
1192
|
+
observation=wrapper.last_observation or {},
|
|
1193
|
+
info=wrapper.last_info,
|
|
1194
|
+
step_idx=wrapper.step_idx,
|
|
1195
|
+
)
|
|
1196
|
+
|
|
1197
|
+
else:
|
|
1198
|
+
raise HTTPException(
|
|
1199
|
+
status_code=422,
|
|
1200
|
+
detail=f"Unknown environment name in snapshot: {env_name}",
|
|
1201
|
+
)
|
|
1202
|
+
|
|
1203
|
+
except Exception as e:
|
|
1204
|
+
logger.error(f"Failed to restore environment from snapshot {request.snapshot_id}: {e}")
|
|
1205
|
+
raise HTTPException(status_code=500, detail=str(e)) from e
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
@router.post("/terminate", response_model=EnvTerminateResponse)
|
|
1209
|
+
async def terminate_environment(request: EnvTerminateRequest) -> EnvTerminateResponse:
|
|
1210
|
+
"""Terminate an environment and clean up resources."""
|
|
1211
|
+
handle = registry.get_env(request.env_id)
|
|
1212
|
+
if not handle:
|
|
1213
|
+
raise HTTPException(status_code=404, detail=f"Environment {request.env_id} not found")
|
|
1214
|
+
|
|
1215
|
+
try:
|
|
1216
|
+
# Call terminate on the environment
|
|
1217
|
+
await handle.env.terminate()
|
|
1218
|
+
|
|
1219
|
+
# Remove from registry
|
|
1220
|
+
registry.remove_env(request.env_id)
|
|
1221
|
+
|
|
1222
|
+
return EnvTerminateResponse(ok=True)
|
|
1223
|
+
|
|
1224
|
+
except Exception as e:
|
|
1225
|
+
logger.error(f"Failed to terminate environment {request.env_id}: {e}")
|
|
1226
|
+
raise HTTPException(status_code=500, detail=str(e)) from e
|