Spaces:
Sleeping
Sleeping
Pranjal Parashar commited on
Add builder-fixer simulation runtime and training path
Browse files- .dockerignore +2 -0
- .gitattributes +35 -0
- .gitignore +2 -0
- Dockerfile +2 -2
- README.md +51 -0
- baseline.py +85 -0
- client.py +5 -0
- debug.log +132 -0
- eval.py +209 -0
- graders.py +75 -0
- models.py +22 -0
- pyproject.toml +9 -0
- runtime.py +184 -0
- server/Dockerfile +4 -4
- server/developer_control_room_environment.py +21 -0
- server/requirements.txt +1 -0
- tasks.py +227 -0
- tests/test_environment_behaviors.py +177 -0
- train.py +368 -0
- training_utils.py +301 -0
- uv.lock +0 -0
.dockerignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
outputs/
|
| 2 |
+
artifacts/
|
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
CHANGED
|
@@ -6,3 +6,5 @@ __pycache__/
|
|
| 6 |
.env
|
| 7 |
.DS_Store
|
| 8 |
*.egg-info/
|
|
|
|
|
|
|
|
|
| 6 |
.env
|
| 7 |
.DS_Store
|
| 8 |
*.egg-info/
|
| 9 |
+
outputs/
|
| 10 |
+
artifacts/
|
Dockerfile
CHANGED
|
@@ -18,9 +18,9 @@ RUN if ! command -v uv >/dev/null 2>&1; then \
|
|
| 18 |
|
| 19 |
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 20 |
if [ -f uv.lock ]; then \
|
| 21 |
-
uv sync --frozen --no-editable; \
|
| 22 |
else \
|
| 23 |
-
uv sync --no-editable; \
|
| 24 |
fi
|
| 25 |
|
| 26 |
FROM ${BASE_IMAGE}
|
|
|
|
| 18 |
|
| 19 |
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 20 |
if [ -f uv.lock ]; then \
|
| 21 |
+
uv sync --frozen --no-editable --extra train --extra dev; \
|
| 22 |
else \
|
| 23 |
+
uv sync --no-editable --extra train --extra dev; \
|
| 24 |
fi
|
| 25 |
|
| 26 |
FROM ${BASE_IMAGE}
|
README.md
CHANGED
|
@@ -295,6 +295,54 @@ docker run -d --name developer_control_room -p 7860:7860 developer_control_room:
|
|
| 295 |
python inference.py
|
| 296 |
```
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
## Validation
|
| 299 |
|
| 300 |
The benchmark has also been validated against the submission-style checks:
|
|
@@ -312,11 +360,14 @@ developer_control_room/
|
|
| 312 |
├── openenv.yaml
|
| 313 |
├── pyproject.toml
|
| 314 |
├── inference.py
|
|
|
|
|
|
|
| 315 |
├── baseline.py
|
| 316 |
├── tasks.py
|
| 317 |
├── graders.py
|
| 318 |
├── models.py
|
| 319 |
├── client.py
|
|
|
|
| 320 |
└── server/
|
| 321 |
├── app.py
|
| 322 |
└── developer_control_room_environment.py
|
|
|
|
| 295 |
python inference.py
|
| 296 |
```
|
| 297 |
|
| 298 |
+
## Training
|
| 299 |
+
|
| 300 |
+
FlowOS now includes a minimal Colab-friendly GRPO training path built on HF TRL. This path is intentionally lightweight: it trains directly against the existing OpenEnv environment and uses the environment's own dense rewards and terminal scores.
|
| 301 |
+
|
| 302 |
+
### Install training dependencies
|
| 303 |
+
|
| 304 |
+
```bash
|
| 305 |
+
pip install -e ".[train]"
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
### Start the environment server
|
| 309 |
+
|
| 310 |
+
```bash
|
| 311 |
+
uv run server
|
| 312 |
+
```
|
| 313 |
+
|
| 314 |
+
### Run a small GRPO training job
|
| 315 |
+
|
| 316 |
+
```bash
|
| 317 |
+
python train.py \
|
| 318 |
+
--env-url http://localhost:7860 \
|
| 319 |
+
--model-id Qwen/Qwen2.5-1.5B-Instruct \
|
| 320 |
+
--dataset-size 24 \
|
| 321 |
+
--num-generations 4 \
|
| 322 |
+
--task-scope all \
|
| 323 |
+
--report-to none
|
| 324 |
+
```
|
| 325 |
+
|
| 326 |
+
This creates LoRA checkpoints plus a CSV reward log under `outputs/`.
|
| 327 |
+
|
| 328 |
+
### Compare base vs tuned policy
|
| 329 |
+
|
| 330 |
+
```bash
|
| 331 |
+
python eval.py \
|
| 332 |
+
--env-url http://localhost:7860 \
|
| 333 |
+
--model-id Qwen/Qwen2.5-1.5B-Instruct \
|
| 334 |
+
--checkpoint-path outputs/<run-dir>
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
`eval.py` prints a compact table with:
|
| 338 |
+
|
| 339 |
+
- average episode reward
|
| 340 |
+
- average grader score
|
| 341 |
+
- solved rate
|
| 342 |
+
- average steps used
|
| 343 |
+
|
| 344 |
+
For judging, the most useful artifact to screenshot is the before/after eval table together with the reward log produced during training.
|
| 345 |
+
|
| 346 |
## Validation
|
| 347 |
|
| 348 |
The benchmark has also been validated against the submission-style checks:
|
|
|
|
| 360 |
├── openenv.yaml
|
| 361 |
├── pyproject.toml
|
| 362 |
├── inference.py
|
| 363 |
+
├── train.py
|
| 364 |
+
├── eval.py
|
| 365 |
├── baseline.py
|
| 366 |
├── tasks.py
|
| 367 |
├── graders.py
|
| 368 |
├── models.py
|
| 369 |
├── client.py
|
| 370 |
+
├── training_utils.py
|
| 371 |
└── server/
|
| 372 |
├── app.py
|
| 373 |
└── developer_control_room_environment.py
|
baseline.py
CHANGED
|
@@ -154,6 +154,11 @@ def get_task_specific_guidance(observation: Any) -> str:
|
|
| 154 |
"For workflow creation tasks, mirror the naming, column shapes, and artifact patterns shown in the referenced files and templates. "
|
| 155 |
"Avoid inventing extra columns, fields, or file structures unless the observed standards clearly require them."
|
| 156 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
if task_id.startswith("repair_"):
|
| 158 |
return (
|
| 159 |
"For repair tasks, preserve published contracts and existing target names exactly. "
|
|
@@ -192,6 +197,10 @@ def build_user_prompt(
|
|
| 192 |
Validator status: {json.dumps(observation.validator_status)}
|
| 193 |
Last feedback: {observation.feedback}
|
| 194 |
Last action error: {observation.last_action_error or "null"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
Phase guidance: {phase_guidance}
|
| 196 |
Task-specific guidance: {task_guidance}
|
| 197 |
Return exactly one JSON action object only.
|
|
@@ -1099,4 +1108,80 @@ def fallback_action(task_name: str, observation: Any) -> dict[str, Any]:
|
|
| 1099 |
return {"action_type": "run_validator", "parameters": {"validator": validator}}
|
| 1100 |
return {"action_type": "submit_workspace", "parameters": {"summary": spec["summary"]}}
|
| 1101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1102 |
return {"action_type": "search_workspace", "parameters": {"query": observation.developer_request}}
|
|
|
|
| 154 |
"For workflow creation tasks, mirror the naming, column shapes, and artifact patterns shown in the referenced files and templates. "
|
| 155 |
"Avoid inventing extra columns, fields, or file structures unless the observed standards clearly require them."
|
| 156 |
)
|
| 157 |
+
if task_id == "simulate_csv_report_workflow":
|
| 158 |
+
return (
|
| 159 |
+
"For the simulation workflow, respect the active role. Builder should create the initial pipeline YAML and SQL artifacts. "
|
| 160 |
+
"Fixer should use runtime_status, execution_logs, and output_schema to repair the same files until the runtime checks pass."
|
| 161 |
+
)
|
| 162 |
if task_id.startswith("repair_"):
|
| 163 |
return (
|
| 164 |
"For repair tasks, preserve published contracts and existing target names exactly. "
|
|
|
|
| 197 |
Validator status: {json.dumps(observation.validator_status)}
|
| 198 |
Last feedback: {observation.feedback}
|
| 199 |
Last action error: {observation.last_action_error or "null"}
|
| 200 |
+
Active role: {getattr(observation, "active_role", "builder")}
|
| 201 |
+
Runtime status: {json.dumps(getattr(observation, "runtime_status", {}))}
|
| 202 |
+
Execution logs: {json.dumps(getattr(observation, "execution_logs", []))}
|
| 203 |
+
Output schema: {json.dumps(getattr(observation, "output_schema", []))}
|
| 204 |
Phase guidance: {phase_guidance}
|
| 205 |
Task-specific guidance: {task_guidance}
|
| 206 |
Return exactly one JSON action object only.
|
|
|
|
| 1108 |
return {"action_type": "run_validator", "parameters": {"validator": validator}}
|
| 1109 |
return {"action_type": "submit_workspace", "parameters": {"summary": spec["summary"]}}
|
| 1110 |
|
| 1111 |
+
if grader_family == "simulation":
|
| 1112 |
+
read_order = [
|
| 1113 |
+
"docs/runtime_contract.md",
|
| 1114 |
+
"templates/report_pipeline_template.yaml",
|
| 1115 |
+
"data/sales_orders.csv",
|
| 1116 |
+
]
|
| 1117 |
+
for path in read_order:
|
| 1118 |
+
if path in observation.known_files and path not in queried.get("read_file", {}):
|
| 1119 |
+
return {"action_type": "read_file", "parameters": {"path": path}}
|
| 1120 |
+
if "raw.sales_orders_csv" in observation.known_assets and "raw.sales_orders_csv" not in queried.get("inspect_schema", {}):
|
| 1121 |
+
return {"action_type": "inspect_schema", "parameters": {"asset": "raw.sales_orders_csv"}}
|
| 1122 |
+
|
| 1123 |
+
simulation_edits = [
|
| 1124 |
+
(
|
| 1125 |
+
"pipelines/report_job.yaml",
|
| 1126 |
+
"""name: customer_daily_report_job
|
| 1127 |
+
storage_path: mock_s3/staged/sales_orders.csv
|
| 1128 |
+
raw_table: raw_sales_orders
|
| 1129 |
+
load_sql: sql/load_raw.sql
|
| 1130 |
+
build_sql: sql/build_table.sql
|
| 1131 |
+
report_sql: sql/report_view.sql
|
| 1132 |
+
final_view: customer_daily_report
|
| 1133 |
+
""",
|
| 1134 |
+
),
|
| 1135 |
+
(
|
| 1136 |
+
"sql/load_raw.sql",
|
| 1137 |
+
"""create or replace view staged_sales_orders as
|
| 1138 |
+
select
|
| 1139 |
+
order_id,
|
| 1140 |
+
customer_id,
|
| 1141 |
+
cast(order_date as date) as order_date,
|
| 1142 |
+
quantity,
|
| 1143 |
+
unit_price
|
| 1144 |
+
from raw_sales_orders;
|
| 1145 |
+
""",
|
| 1146 |
+
),
|
| 1147 |
+
(
|
| 1148 |
+
"sql/build_table.sql",
|
| 1149 |
+
"""create or replace table customer_summary as
|
| 1150 |
+
select
|
| 1151 |
+
customer_id,
|
| 1152 |
+
order_date,
|
| 1153 |
+
count(*) as order_count,
|
| 1154 |
+
sum(quantity * unit_price) as gross_revenue_usd
|
| 1155 |
+
from staged_sales_orders
|
| 1156 |
+
group by 1, 2;
|
| 1157 |
+
""",
|
| 1158 |
+
),
|
| 1159 |
+
(
|
| 1160 |
+
"sql/report_view.sql",
|
| 1161 |
+
"""create or replace view customer_daily_report as
|
| 1162 |
+
select
|
| 1163 |
+
customer_id,
|
| 1164 |
+
order_date,
|
| 1165 |
+
order_count,
|
| 1166 |
+
gross_revenue_usd
|
| 1167 |
+
from customer_summary;
|
| 1168 |
+
""",
|
| 1169 |
+
),
|
| 1170 |
+
]
|
| 1171 |
+
|
| 1172 |
+
for path, content in simulation_edits:
|
| 1173 |
+
if path not in edited:
|
| 1174 |
+
return {"action_type": "edit_file", "parameters": {"path": path, "content": content}}
|
| 1175 |
+
|
| 1176 |
+
for validator in observation.available_validators:
|
| 1177 |
+
if validator not in validators:
|
| 1178 |
+
return {"action_type": "run_validator", "parameters": {"validator": validator}}
|
| 1179 |
+
|
| 1180 |
+
return {
|
| 1181 |
+
"action_type": "submit_workspace",
|
| 1182 |
+
"parameters": {
|
| 1183 |
+
"summary": "Built a DuckDB pipeline from sales_orders.csv and published customer_daily_report."
|
| 1184 |
+
},
|
| 1185 |
+
}
|
| 1186 |
+
|
| 1187 |
return {"action_type": "search_workspace", "parameters": {"query": observation.developer_request}}
|
client.py
CHANGED
|
@@ -54,6 +54,11 @@ class DeveloperControlRoomEnv(
|
|
| 54 |
queried_data=obs.get("queried_data", {}),
|
| 55 |
edited_files=obs.get("edited_files", {}),
|
| 56 |
validator_status=obs.get("validator_status", {}),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
cumulative_reward=obs.get("cumulative_reward", 0.0),
|
| 58 |
feedback=obs.get("feedback", ""),
|
| 59 |
last_action_error=obs.get("last_action_error"),
|
|
|
|
| 54 |
queried_data=obs.get("queried_data", {}),
|
| 55 |
edited_files=obs.get("edited_files", {}),
|
| 56 |
validator_status=obs.get("validator_status", {}),
|
| 57 |
+
active_role=obs.get("active_role", "builder"),
|
| 58 |
+
runtime_status=obs.get("runtime_status", {}),
|
| 59 |
+
execution_logs=obs.get("execution_logs", []),
|
| 60 |
+
output_schema=obs.get("output_schema", []),
|
| 61 |
+
report_preview=obs.get("report_preview", []),
|
| 62 |
cumulative_reward=obs.get("cumulative_reward", 0.0),
|
| 63 |
feedback=obs.get("feedback", ""),
|
| 64 |
last_action_error=obs.get("last_action_error"),
|
debug.log
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 2 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 3 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 4 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 5 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 6 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 7 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 8 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 9 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 10 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 11 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 12 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 13 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 14 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 15 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 16 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 17 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 18 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 19 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 20 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 21 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 22 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 23 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 24 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 25 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 26 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 27 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 28 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 29 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 30 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 31 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 32 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 33 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 34 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 35 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 36 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 37 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 38 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 39 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 40 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 41 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 42 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 43 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 44 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 45 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 46 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 47 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 48 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 49 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 50 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 51 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 52 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 53 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 54 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 55 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 56 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 57 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 58 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 59 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 60 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 61 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 62 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 63 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 64 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 65 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 66 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 67 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 68 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 69 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 70 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 71 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 72 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 73 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 74 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 75 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 76 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 77 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 78 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 79 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 80 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 81 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 82 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 83 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 84 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 85 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 86 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 87 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 88 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 89 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 90 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 91 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 92 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 93 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 94 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 95 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 96 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 97 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 98 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 99 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 100 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 101 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 102 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 103 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 104 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 105 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 106 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 107 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 108 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 109 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 110 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 111 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 112 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 113 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 114 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 115 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 116 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 117 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 118 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 119 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 120 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 121 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 122 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 123 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 124 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 125 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 126 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 127 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 128 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 129 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 130 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 131 |
+
BASELINE:: LLM IS BEING CALLED!
|
| 132 |
+
BASELINE:: LLM IS BEING CALLED!
|
eval.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate base and fine-tuned FlowOS policies against the OpenEnv server."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import statistics
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from .training_utils import (
|
| 11 |
+
DEFAULT_MAX_NEW_TOKENS,
|
| 12 |
+
DEFAULT_MAX_TURNS,
|
| 13 |
+
DEFAULT_TRAIN_MODEL,
|
| 14 |
+
TRAIN_SYSTEM_PROMPT,
|
| 15 |
+
build_episode_samples,
|
| 16 |
+
build_turn_prompt,
|
| 17 |
+
parse_action_json,
|
| 18 |
+
run_episode,
|
| 19 |
+
)
|
| 20 |
+
except ImportError:
|
| 21 |
+
from training_utils import (
|
| 22 |
+
DEFAULT_MAX_NEW_TOKENS,
|
| 23 |
+
DEFAULT_MAX_TURNS,
|
| 24 |
+
DEFAULT_TRAIN_MODEL,
|
| 25 |
+
TRAIN_SYSTEM_PROMPT,
|
| 26 |
+
build_episode_samples,
|
| 27 |
+
build_turn_prompt,
|
| 28 |
+
parse_action_json,
|
| 29 |
+
run_episode,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def parse_args() -> argparse.Namespace:
|
| 34 |
+
parser = argparse.ArgumentParser(description="Evaluate FlowOS policies before and after GRPO fine-tuning")
|
| 35 |
+
parser.add_argument("--model-id", default=DEFAULT_TRAIN_MODEL, help="Base model id")
|
| 36 |
+
parser.add_argument("--checkpoint-path", default=None, help="Optional fine-tuned checkpoint or LoRA adapter path")
|
| 37 |
+
parser.add_argument("--env-url", default="http://localhost:7860", help="FlowOS OpenEnv server URL")
|
| 38 |
+
parser.add_argument("--task-scope", default="all", help="Task scope: all or comma-separated task ids")
|
| 39 |
+
parser.add_argument("--episodes", type=int, default=12, help="Total evaluation episodes per policy")
|
| 40 |
+
parser.add_argument("--max-turns", type=int, default=DEFAULT_MAX_TURNS, help="Max environment turns per episode")
|
| 41 |
+
parser.add_argument("--max-new-tokens", type=int, default=DEFAULT_MAX_NEW_TOKENS, help="Max tokens per action generation")
|
| 42 |
+
parser.add_argument("--temperature", type=float, default=0.0, help="Sampling temperature for evaluation")
|
| 43 |
+
return parser.parse_args()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def apply_chat_template(tokenizer: Any, messages: list[dict[str, str]]) -> str:
|
| 47 |
+
try:
|
| 48 |
+
return tokenizer.apply_chat_template(
|
| 49 |
+
messages,
|
| 50 |
+
add_generation_prompt=True,
|
| 51 |
+
tokenize=False,
|
| 52 |
+
enable_thinking=False,
|
| 53 |
+
)
|
| 54 |
+
except TypeError:
|
| 55 |
+
return tokenizer.apply_chat_template(
|
| 56 |
+
messages,
|
| 57 |
+
add_generation_prompt=True,
|
| 58 |
+
tokenize=False,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def load_policy(model_id: str, checkpoint_path: str | None) -> tuple[Any, Any, str]:
|
| 63 |
+
import torch
|
| 64 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint_path or model_id)
|
| 68 |
+
except Exception:
|
| 69 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 70 |
+
if tokenizer.pad_token is None:
|
| 71 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 72 |
+
|
| 73 |
+
label = "base"
|
| 74 |
+
if checkpoint_path:
|
| 75 |
+
try:
|
| 76 |
+
from peft import AutoPeftModelForCausalLM
|
| 77 |
+
|
| 78 |
+
model = AutoPeftModelForCausalLM.from_pretrained(checkpoint_path)
|
| 79 |
+
label = "tuned"
|
| 80 |
+
except Exception:
|
| 81 |
+
model = AutoModelForCausalLM.from_pretrained(checkpoint_path)
|
| 82 |
+
label = "tuned"
|
| 83 |
+
else:
|
| 84 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 85 |
+
|
| 86 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 87 |
+
model.to(device)
|
| 88 |
+
model.eval()
|
| 89 |
+
return model, tokenizer, label
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def generate_action(
|
| 93 |
+
model: Any,
|
| 94 |
+
tokenizer: Any,
|
| 95 |
+
user_prompt: str,
|
| 96 |
+
max_new_tokens: int,
|
| 97 |
+
temperature: float,
|
| 98 |
+
) -> dict[str, Any] | None:
|
| 99 |
+
import torch
|
| 100 |
+
|
| 101 |
+
prompt_text = apply_chat_template(
|
| 102 |
+
tokenizer,
|
| 103 |
+
[
|
| 104 |
+
{"role": "system", "content": TRAIN_SYSTEM_PROMPT},
|
| 105 |
+
{"role": "user", "content": user_prompt},
|
| 106 |
+
],
|
| 107 |
+
)
|
| 108 |
+
device = next(model.parameters()).device
|
| 109 |
+
inputs = tokenizer(prompt_text, return_tensors="pt").to(device)
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
generated = model.generate(
|
| 112 |
+
**inputs,
|
| 113 |
+
do_sample=temperature > 0,
|
| 114 |
+
temperature=max(temperature, 1e-5),
|
| 115 |
+
max_new_tokens=max_new_tokens,
|
| 116 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 117 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 118 |
+
)
|
| 119 |
+
completion_ids = generated[0][inputs["input_ids"].shape[1] :]
|
| 120 |
+
text = tokenizer.decode(completion_ids, skip_special_tokens=True)
|
| 121 |
+
return parse_action_json(text)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def summarize(results: list[dict[str, Any]]) -> dict[str, float]:
|
| 125 |
+
return {
|
| 126 |
+
"avg_reward": statistics.fmean(result["total_reward"] for result in results) if results else 0.0,
|
| 127 |
+
"avg_score": statistics.fmean(result["score"] for result in results) if results else 0.0,
|
| 128 |
+
"solved_rate": (
|
| 129 |
+
sum(1 for result in results if result["solved"]) / len(results) if results else 0.0
|
| 130 |
+
),
|
| 131 |
+
"avg_steps": statistics.fmean(result["steps"] for result in results) if results else 0.0,
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def run_policy(
|
| 136 |
+
label: str,
|
| 137 |
+
model: Any,
|
| 138 |
+
tokenizer: Any,
|
| 139 |
+
args: argparse.Namespace,
|
| 140 |
+
) -> list[dict[str, Any]]:
|
| 141 |
+
samples = build_episode_samples(args.task_scope, args.episodes)
|
| 142 |
+
results: list[dict[str, Any]] = []
|
| 143 |
+
for sample in samples:
|
| 144 |
+
def policy(observation: Any, transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 145 |
+
user_prompt = build_turn_prompt(observation, transcript)
|
| 146 |
+
action = generate_action(
|
| 147 |
+
model=model,
|
| 148 |
+
tokenizer=tokenizer,
|
| 149 |
+
user_prompt=user_prompt,
|
| 150 |
+
max_new_tokens=args.max_new_tokens,
|
| 151 |
+
temperature=args.temperature,
|
| 152 |
+
)
|
| 153 |
+
return {"action": action, "metadata": {"text": ""}}
|
| 154 |
+
|
| 155 |
+
metrics = run_episode(
|
| 156 |
+
base_url=args.env_url,
|
| 157 |
+
sample=sample,
|
| 158 |
+
max_turns=args.max_turns,
|
| 159 |
+
policy=policy,
|
| 160 |
+
)
|
| 161 |
+
results.append(
|
| 162 |
+
{
|
| 163 |
+
"label": label,
|
| 164 |
+
"task_id": metrics.task_id,
|
| 165 |
+
"scenario_id": metrics.scenario_id,
|
| 166 |
+
"total_reward": metrics.total_reward,
|
| 167 |
+
"score": metrics.score,
|
| 168 |
+
"solved": metrics.solved,
|
| 169 |
+
"steps": metrics.steps,
|
| 170 |
+
}
|
| 171 |
+
)
|
| 172 |
+
return results
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def print_table(rows: list[dict[str, Any]]) -> None:
|
| 176 |
+
headers = ("policy", "avg_reward", "avg_score", "solved_rate", "avg_steps")
|
| 177 |
+
line = "{:<10} {:>11} {:>10} {:>12} {:>10}"
|
| 178 |
+
print(line.format(*headers))
|
| 179 |
+
print(line.format(*("-" * len(header) for header in headers)))
|
| 180 |
+
for row in rows:
|
| 181 |
+
print(
|
| 182 |
+
line.format(
|
| 183 |
+
row["policy"],
|
| 184 |
+
f"{row['avg_reward']:.3f}",
|
| 185 |
+
f"{row['avg_score']:.3f}",
|
| 186 |
+
f"{row['solved_rate']:.2%}",
|
| 187 |
+
f"{row['avg_steps']:.2f}",
|
| 188 |
+
)
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def main() -> None:
|
| 193 |
+
args = parse_args()
|
| 194 |
+
|
| 195 |
+
base_model, base_tokenizer, base_label = load_policy(args.model_id, None)
|
| 196 |
+
rows: list[dict[str, Any]] = []
|
| 197 |
+
base_results = run_policy(base_label, base_model, base_tokenizer, args)
|
| 198 |
+
rows.append({"policy": base_label, **summarize(base_results)})
|
| 199 |
+
|
| 200 |
+
if args.checkpoint_path:
|
| 201 |
+
tuned_model, tuned_tokenizer, tuned_label = load_policy(args.model_id, args.checkpoint_path)
|
| 202 |
+
tuned_results = run_policy(tuned_label, tuned_model, tuned_tokenizer, args)
|
| 203 |
+
rows.append({"policy": tuned_label, **summarize(tuned_results)})
|
| 204 |
+
|
| 205 |
+
print_table(rows)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
if __name__ == "__main__":
|
| 209 |
+
main()
|
graders.py
CHANGED
|
@@ -153,6 +153,20 @@ def evaluate_validator(
|
|
| 153 |
),
|
| 154 |
}
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
return {"passed": False, "message": f"Unhandled validator kind '{kind}'"}
|
| 157 |
|
| 158 |
|
|
@@ -339,11 +353,72 @@ def _grade_workflow_shipping(state: dict, scenario: dict) -> dict[str, Any]:
|
|
| 339 |
}
|
| 340 |
|
| 341 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
def grade(task_id: str, state: dict, scenario: dict) -> dict[str, Any]:
|
| 343 |
graders = {
|
| 344 |
"repair": _grade_pipeline_repair,
|
| 345 |
"review": _grade_llm_patch_review,
|
| 346 |
"workflow": _grade_workflow_shipping,
|
|
|
|
| 347 |
}
|
| 348 |
try:
|
| 349 |
grader_family = get_grader_family(task_id)
|
|
|
|
| 153 |
),
|
| 154 |
}
|
| 155 |
|
| 156 |
+
if kind == "runtime_check":
|
| 157 |
+
runtime_status = state.get("runtime_status", {})
|
| 158 |
+
checks = runtime_status.get("checks", {})
|
| 159 |
+
check_key = spec.get("check_key", "")
|
| 160 |
+
passed = bool(checks.get(check_key, False))
|
| 161 |
+
return {
|
| 162 |
+
"passed": passed,
|
| 163 |
+
"message": (
|
| 164 |
+
f"PASS: runtime check {check_key} satisfied."
|
| 165 |
+
if passed
|
| 166 |
+
else f"FAIL: runtime check {check_key} not satisfied."
|
| 167 |
+
),
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
return {"passed": False, "message": f"Unhandled validator kind '{kind}'"}
|
| 171 |
|
| 172 |
|
|
|
|
| 353 |
}
|
| 354 |
|
| 355 |
|
| 356 |
+
def _grade_simulation_workflow(state: dict, scenario: dict) -> dict[str, Any]:
|
| 357 |
+
files = _workspace_files(state, scenario)
|
| 358 |
+
target = scenario["workflow_target"]
|
| 359 |
+
runtime_status = state.get("runtime_status", {})
|
| 360 |
+
|
| 361 |
+
investigation_raw = _investigation_score(
|
| 362 |
+
state,
|
| 363 |
+
{(action_type, _norm(name)) for action_type, name in target.get("investigation_targets", [])},
|
| 364 |
+
)
|
| 365 |
+
investigation = 0.15 * investigation_raw
|
| 366 |
+
|
| 367 |
+
artifact_raw = _artifact_score(files, target)
|
| 368 |
+
artifact_score = 0.25 * artifact_raw
|
| 369 |
+
|
| 370 |
+
checks = runtime_status.get("checks", {})
|
| 371 |
+
runtime_targets = target.get("solve_validator_targets", [])
|
| 372 |
+
runtime_hits = sum(1 for name in runtime_targets if checks.get(name, False))
|
| 373 |
+
runtime_score_raw = runtime_hits / len(runtime_targets) if runtime_targets else 0.0
|
| 374 |
+
runtime_score = 0.35 * runtime_score_raw
|
| 375 |
+
|
| 376 |
+
summary_raw = _summary_score(state.get("submission", {}).get("summary", ""), target.get("summary_groups", []))
|
| 377 |
+
summary_score = 0.1 * summary_raw
|
| 378 |
+
|
| 379 |
+
role_bonus = 0.05 if state.get("active_role") == "fixer" and state.get("runtime_status", {}).get("ran") else 0.0
|
| 380 |
+
|
| 381 |
+
expected_columns = (
|
| 382 |
+
scenario.get("simulation_target", {})
|
| 383 |
+
or scenario.get("llm_draft", {}).get("simulation_target", {})
|
| 384 |
+
).get("required_output_columns", [])
|
| 385 |
+
output_schema = state.get("output_schema", [])
|
| 386 |
+
schema_score = 0.1 if list(output_schema) == list(expected_columns) else 0.0
|
| 387 |
+
|
| 388 |
+
solved = (
|
| 389 |
+
state.get("submitted", False)
|
| 390 |
+
and artifact_raw == 1.0
|
| 391 |
+
and runtime_score_raw == 1.0
|
| 392 |
+
and summary_raw >= (2 / 3)
|
| 393 |
+
and schema_score > 0.0
|
| 394 |
+
and runtime_status.get("succeeded", False)
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
total = _strict_score(investigation + artifact_score + runtime_score + summary_score + role_bonus + schema_score)
|
| 398 |
+
return {
|
| 399 |
+
"total": total,
|
| 400 |
+
"solved": solved,
|
| 401 |
+
"breakdown": {
|
| 402 |
+
"investigation": round(investigation, 4),
|
| 403 |
+
"artifact_score": round(artifact_score, 4),
|
| 404 |
+
"runtime_score": round(runtime_score, 4),
|
| 405 |
+
"schema_score": round(schema_score, 4),
|
| 406 |
+
"summary_score": round(summary_score, 4),
|
| 407 |
+
"role_bonus": round(role_bonus, 4),
|
| 408 |
+
},
|
| 409 |
+
"feedback": (
|
| 410 |
+
f"investigation={investigation:.2f} artifact={artifact_score:.2f} "
|
| 411 |
+
f"runtime={runtime_score:.2f} schema={schema_score:.2f}"
|
| 412 |
+
),
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
|
| 416 |
def grade(task_id: str, state: dict, scenario: dict) -> dict[str, Any]:
|
| 417 |
graders = {
|
| 418 |
"repair": _grade_pipeline_repair,
|
| 419 |
"review": _grade_llm_patch_review,
|
| 420 |
"workflow": _grade_workflow_shipping,
|
| 421 |
+
"simulation": _grade_simulation_workflow,
|
| 422 |
}
|
| 423 |
try:
|
| 424 |
grader_family = get_grader_family(task_id)
|
models.py
CHANGED
|
@@ -78,6 +78,23 @@ class DeveloperControlRoomObservation(Observation):
|
|
| 78 |
default_factory=dict,
|
| 79 |
description="Validator pass/fail status accumulated so far",
|
| 80 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
cumulative_reward: float = Field(
|
| 82 |
default=0.0,
|
| 83 |
description="Running reward across the episode",
|
|
@@ -106,6 +123,11 @@ class DeveloperControlRoomState(State):
|
|
| 106 |
validator_status: dict[str, dict[str, Any]] = Field(default_factory=dict)
|
| 107 |
submission: dict[str, Any] = Field(default_factory=dict)
|
| 108 |
submitted: bool = Field(default=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
cumulative_reward: float = Field(default=0.0)
|
| 110 |
done: bool = Field(default=False)
|
| 111 |
feedback: str = Field(default="")
|
|
|
|
| 78 |
default_factory=dict,
|
| 79 |
description="Validator pass/fail status accumulated so far",
|
| 80 |
)
|
| 81 |
+
active_role: str = Field(default="builder", description="Current active role in shared-workspace tasks")
|
| 82 |
+
runtime_status: dict[str, Any] = Field(
|
| 83 |
+
default_factory=dict,
|
| 84 |
+
description="Execution/runtime status for simulation-backed tasks",
|
| 85 |
+
)
|
| 86 |
+
execution_logs: list[str] = Field(
|
| 87 |
+
default_factory=list,
|
| 88 |
+
description="Recent execution log lines from the runtime",
|
| 89 |
+
)
|
| 90 |
+
output_schema: list[str] = Field(
|
| 91 |
+
default_factory=list,
|
| 92 |
+
description="Current output schema produced by the runtime",
|
| 93 |
+
)
|
| 94 |
+
report_preview: list[dict[str, Any]] = Field(
|
| 95 |
+
default_factory=list,
|
| 96 |
+
description="Preview rows from the final report output",
|
| 97 |
+
)
|
| 98 |
cumulative_reward: float = Field(
|
| 99 |
default=0.0,
|
| 100 |
description="Running reward across the episode",
|
|
|
|
| 123 |
validator_status: dict[str, dict[str, Any]] = Field(default_factory=dict)
|
| 124 |
submission: dict[str, Any] = Field(default_factory=dict)
|
| 125 |
submitted: bool = Field(default=False)
|
| 126 |
+
active_role: str = Field(default="builder")
|
| 127 |
+
runtime_status: dict[str, Any] = Field(default_factory=dict)
|
| 128 |
+
execution_logs: list[str] = Field(default_factory=list)
|
| 129 |
+
output_schema: list[str] = Field(default_factory=list)
|
| 130 |
+
report_preview: list[dict[str, Any]] = Field(default_factory=list)
|
| 131 |
cumulative_reward: float = Field(default=0.0)
|
| 132 |
done: bool = Field(default=False)
|
| 133 |
feedback: str = Field(default="")
|
pyproject.toml
CHANGED
|
@@ -12,6 +12,7 @@ dependencies = [
|
|
| 12 |
"openai>=1.52.0",
|
| 13 |
"requests>=2.32.0",
|
| 14 |
"python-dotenv>=1.0.1",
|
|
|
|
| 15 |
]
|
| 16 |
|
| 17 |
[project.optional-dependencies]
|
|
@@ -19,6 +20,14 @@ dev = [
|
|
| 19 |
"pytest>=8.0.0",
|
| 20 |
"pytest-cov>=4.0.0",
|
| 21 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
[project.scripts]
|
| 24 |
server = "developer_control_room.server.app:main"
|
|
|
|
| 12 |
"openai>=1.52.0",
|
| 13 |
"requests>=2.32.0",
|
| 14 |
"python-dotenv>=1.0.1",
|
| 15 |
+
"duckdb>=1.1.0",
|
| 16 |
]
|
| 17 |
|
| 18 |
[project.optional-dependencies]
|
|
|
|
| 20 |
"pytest>=8.0.0",
|
| 21 |
"pytest-cov>=4.0.0",
|
| 22 |
]
|
| 23 |
+
train = [
|
| 24 |
+
"accelerate>=0.34.0",
|
| 25 |
+
"bitsandbytes>=0.43.0",
|
| 26 |
+
"datasets>=2.21.0",
|
| 27 |
+
"peft>=0.13.0",
|
| 28 |
+
"transformers>=4.45.0",
|
| 29 |
+
"trl>=0.11.0",
|
| 30 |
+
]
|
| 31 |
|
| 32 |
[project.scripts]
|
| 33 |
server = "developer_control_room.server.app:main"
|
runtime.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local execution runtime for CSV-to-report simulation scenarios."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import csv
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
import duckdb
|
| 11 |
+
except ImportError: # pragma: no cover - exercised only when dependency missing
|
| 12 |
+
duckdb = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _parse_simple_yaml(text: str) -> dict[str, Any]:
|
| 16 |
+
data: dict[str, Any] = {}
|
| 17 |
+
current_list_key: str | None = None
|
| 18 |
+
for raw_line in text.splitlines():
|
| 19 |
+
line = raw_line.rstrip()
|
| 20 |
+
if not line or line.lstrip().startswith("#"):
|
| 21 |
+
continue
|
| 22 |
+
stripped = line.strip()
|
| 23 |
+
if stripped.startswith("- "):
|
| 24 |
+
if current_list_key is None:
|
| 25 |
+
continue
|
| 26 |
+
data.setdefault(current_list_key, []).append(stripped[2:].strip())
|
| 27 |
+
continue
|
| 28 |
+
if ":" not in stripped:
|
| 29 |
+
continue
|
| 30 |
+
key, value = stripped.split(":", 1)
|
| 31 |
+
key = key.strip()
|
| 32 |
+
value = value.strip()
|
| 33 |
+
if not value:
|
| 34 |
+
current_list_key = key
|
| 35 |
+
data[key] = []
|
| 36 |
+
else:
|
| 37 |
+
current_list_key = None
|
| 38 |
+
data[key] = value.strip("\"'")
|
| 39 |
+
return data
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _preview_rows(rows: list[tuple[Any, ...]], columns: list[str], limit: int = 3) -> list[dict[str, Any]]:
|
| 43 |
+
preview: list[dict[str, Any]] = []
|
| 44 |
+
for row in rows[:limit]:
|
| 45 |
+
preview.append({column: value for column, value in zip(columns, row)})
|
| 46 |
+
return preview
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def execute_csv_report_runtime(scenario: dict[str, Any], state: dict[str, Any]) -> dict[str, Any]:
|
| 50 |
+
files = dict(scenario.get("files", {}))
|
| 51 |
+
files.update(state.get("edited_files", {}))
|
| 52 |
+
|
| 53 |
+
result: dict[str, Any] = {
|
| 54 |
+
"ran": True,
|
| 55 |
+
"succeeded": False,
|
| 56 |
+
"checks": {
|
| 57 |
+
"storage_stage_check": False,
|
| 58 |
+
"duckdb_load_check": False,
|
| 59 |
+
"report_view_check": False,
|
| 60 |
+
"output_schema_check": False,
|
| 61 |
+
},
|
| 62 |
+
"logs": [],
|
| 63 |
+
"errors": [],
|
| 64 |
+
"output_schema": [],
|
| 65 |
+
"report_preview": [],
|
| 66 |
+
"row_count": 0,
|
| 67 |
+
"db_path": "",
|
| 68 |
+
"staged_csv_path": "",
|
| 69 |
+
"run_dir": "",
|
| 70 |
+
"materialized_files": {},
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
if duckdb is None:
|
| 74 |
+
result["errors"].append("duckdb dependency is not installed.")
|
| 75 |
+
return result
|
| 76 |
+
|
| 77 |
+
target = scenario.get("simulation_target", {}) or scenario.get("llm_draft", {}).get("simulation_target", {})
|
| 78 |
+
source_csv = str(target.get("source_csv", ""))
|
| 79 |
+
pipeline_path = str(target.get("pipeline_path", ""))
|
| 80 |
+
load_sql_path = str(target.get("load_sql_path", ""))
|
| 81 |
+
build_sql_path = str(target.get("build_sql_path", ""))
|
| 82 |
+
report_sql_path = str(target.get("report_sql_path", ""))
|
| 83 |
+
|
| 84 |
+
csv_content = files.get(source_csv, "")
|
| 85 |
+
pipeline_text = files.get(pipeline_path, "")
|
| 86 |
+
load_sql = files.get(load_sql_path, "")
|
| 87 |
+
build_sql = files.get(build_sql_path, "")
|
| 88 |
+
report_sql = files.get(report_sql_path, "")
|
| 89 |
+
if not csv_content.strip():
|
| 90 |
+
result["errors"].append(f"Missing source CSV: {source_csv}")
|
| 91 |
+
return result
|
| 92 |
+
if not pipeline_text.strip():
|
| 93 |
+
result["errors"].append(f"Missing pipeline file: {pipeline_path}")
|
| 94 |
+
return result
|
| 95 |
+
if not load_sql.strip():
|
| 96 |
+
result["errors"].append(f"Missing SQL file: {load_sql_path}")
|
| 97 |
+
return result
|
| 98 |
+
if not build_sql.strip():
|
| 99 |
+
result["errors"].append(f"Missing SQL file: {build_sql_path}")
|
| 100 |
+
return result
|
| 101 |
+
if not report_sql.strip():
|
| 102 |
+
result["errors"].append(f"Missing SQL file: {report_sql_path}")
|
| 103 |
+
return result
|
| 104 |
+
|
| 105 |
+
pipeline = _parse_simple_yaml(pipeline_text)
|
| 106 |
+
required_keys = ["storage_path", "raw_table", "load_sql", "build_sql", "report_sql", "final_view"]
|
| 107 |
+
missing_keys = [key for key in required_keys if not pipeline.get(key)]
|
| 108 |
+
if missing_keys:
|
| 109 |
+
result["errors"].append(f"Pipeline missing keys: {', '.join(missing_keys)}")
|
| 110 |
+
return result
|
| 111 |
+
|
| 112 |
+
episode_id = str(state.get("episode_id") or "unknown-episode")
|
| 113 |
+
workdir = Path.cwd() / "artifacts" / "sim_runs" / episode_id
|
| 114 |
+
staged_root = workdir / "mock_s3"
|
| 115 |
+
staged_csv = workdir / pipeline["storage_path"]
|
| 116 |
+
db_path = workdir / "runtime.duckdb"
|
| 117 |
+
pipeline_file = workdir / pipeline_path
|
| 118 |
+
load_sql_file = workdir / load_sql_path
|
| 119 |
+
build_sql_file = workdir / build_sql_path
|
| 120 |
+
report_sql_file = workdir / report_sql_path
|
| 121 |
+
workdir.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
result["db_path"] = str(db_path)
|
| 123 |
+
result["staged_csv_path"] = str(staged_csv)
|
| 124 |
+
result["run_dir"] = str(workdir)
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
staged_csv.parent.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
staged_csv.write_text(csv_content, encoding="utf-8")
|
| 129 |
+
pipeline_file.parent.mkdir(parents=True, exist_ok=True)
|
| 130 |
+
pipeline_file.write_text(pipeline_text, encoding="utf-8")
|
| 131 |
+
load_sql_file.parent.mkdir(parents=True, exist_ok=True)
|
| 132 |
+
load_sql_file.write_text(load_sql, encoding="utf-8")
|
| 133 |
+
build_sql_file.parent.mkdir(parents=True, exist_ok=True)
|
| 134 |
+
build_sql_file.write_text(build_sql, encoding="utf-8")
|
| 135 |
+
report_sql_file.parent.mkdir(parents=True, exist_ok=True)
|
| 136 |
+
report_sql_file.write_text(report_sql, encoding="utf-8")
|
| 137 |
+
result["materialized_files"] = {
|
| 138 |
+
"pipeline": str(pipeline_file),
|
| 139 |
+
"load_sql": str(load_sql_file),
|
| 140 |
+
"build_sql": str(build_sql_file),
|
| 141 |
+
"report_sql": str(report_sql_file),
|
| 142 |
+
"staged_csv": str(staged_csv),
|
| 143 |
+
}
|
| 144 |
+
result["checks"]["storage_stage_check"] = True
|
| 145 |
+
result["logs"].append(f"persisted run artifacts to {workdir}")
|
| 146 |
+
result["logs"].append(f"staged csv to {staged_csv}")
|
| 147 |
+
|
| 148 |
+
con = duckdb.connect(str(db_path))
|
| 149 |
+
raw_table = str(pipeline["raw_table"])
|
| 150 |
+
quoted_csv_path = str(staged_csv).replace("'", "''")
|
| 151 |
+
con.execute(
|
| 152 |
+
f"create or replace table {raw_table} as "
|
| 153 |
+
f"select * from read_csv_auto('{quoted_csv_path}', header=true)"
|
| 154 |
+
)
|
| 155 |
+
result["checks"]["duckdb_load_check"] = True
|
| 156 |
+
result["logs"].append(f"loaded raw table {raw_table}")
|
| 157 |
+
|
| 158 |
+
con.execute(load_sql)
|
| 159 |
+
result["logs"].append(f"executed {load_sql_path}")
|
| 160 |
+
|
| 161 |
+
con.execute(build_sql)
|
| 162 |
+
result["logs"].append(f"executed {build_sql_path}")
|
| 163 |
+
|
| 164 |
+
con.execute(report_sql)
|
| 165 |
+
final_view = str(pipeline["final_view"])
|
| 166 |
+
columns = [row[1] for row in con.execute(f"pragma table_info('{final_view}')").fetchall()]
|
| 167 |
+
result["output_schema"] = columns
|
| 168 |
+
result["checks"]["report_view_check"] = bool(columns)
|
| 169 |
+
|
| 170 |
+
expected_columns = list(target.get("required_output_columns", []))
|
| 171 |
+
if columns == expected_columns:
|
| 172 |
+
result["checks"]["output_schema_check"] = True
|
| 173 |
+
|
| 174 |
+
rows = con.execute(f"select * from {final_view} order by 1, 2 limit 3").fetchall()
|
| 175 |
+
count = con.execute(f"select count(*) from {final_view}").fetchone()
|
| 176 |
+
result["report_preview"] = _preview_rows(rows, columns)
|
| 177 |
+
result["row_count"] = int(count[0]) if count else 0
|
| 178 |
+
result["succeeded"] = all(result["checks"].values())
|
| 179 |
+
result["logs"].append(f"queried {final_view} rows={result['row_count']}")
|
| 180 |
+
con.close()
|
| 181 |
+
return result
|
| 182 |
+
except Exception as exc:
|
| 183 |
+
result["errors"].append(str(exc))
|
| 184 |
+
return result
|
server/Dockerfile
CHANGED
|
@@ -42,16 +42,16 @@ RUN if ! command -v uv >/dev/null 2>&1; then \
|
|
| 42 |
# If uv.lock exists, use it; otherwise resolve on the fly
|
| 43 |
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 44 |
if [ -f uv.lock ]; then \
|
| 45 |
-
uv sync --frozen --no-install-project --no-editable; \
|
| 46 |
else \
|
| 47 |
-
uv sync --no-install-project --no-editable; \
|
| 48 |
fi
|
| 49 |
|
| 50 |
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 51 |
if [ -f uv.lock ]; then \
|
| 52 |
-
uv sync --frozen --no-editable; \
|
| 53 |
else \
|
| 54 |
-
uv sync --no-editable; \
|
| 55 |
fi
|
| 56 |
|
| 57 |
# Final runtime stage
|
|
|
|
| 42 |
# If uv.lock exists, use it; otherwise resolve on the fly
|
| 43 |
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 44 |
if [ -f uv.lock ]; then \
|
| 45 |
+
uv sync --frozen --no-install-project --no-editable --extra train --extra dev; \
|
| 46 |
else \
|
| 47 |
+
uv sync --no-install-project --no-editable --extra train --extra dev; \
|
| 48 |
fi
|
| 49 |
|
| 50 |
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 51 |
if [ -f uv.lock ]; then \
|
| 52 |
+
uv sync --frozen --no-editable --extra train --extra dev; \
|
| 53 |
else \
|
| 54 |
+
uv sync --no-editable --extra train --extra dev; \
|
| 55 |
fi
|
| 56 |
|
| 57 |
# Final runtime stage
|
server/developer_control_room_environment.py
CHANGED
|
@@ -16,6 +16,7 @@ try:
|
|
| 16 |
DeveloperControlRoomObservation,
|
| 17 |
DeveloperControlRoomState,
|
| 18 |
)
|
|
|
|
| 19 |
from ..tasks import get_scenario, get_task, scenario_count
|
| 20 |
except ImportError:
|
| 21 |
from graders import evaluate_validator, grade
|
|
@@ -24,6 +25,7 @@ except ImportError:
|
|
| 24 |
DeveloperControlRoomObservation,
|
| 25 |
DeveloperControlRoomState,
|
| 26 |
)
|
|
|
|
| 27 |
from tasks import get_scenario, get_task, scenario_count
|
| 28 |
|
| 29 |
|
|
@@ -105,6 +107,11 @@ class DeveloperControlRoomEnvironment(
|
|
| 105 |
validator_status={},
|
| 106 |
submission={},
|
| 107 |
submitted=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
cumulative_reward=0.0,
|
| 109 |
done=False,
|
| 110 |
feedback="Episode started.",
|
|
@@ -282,6 +289,15 @@ class DeveloperControlRoomEnvironment(
|
|
| 282 |
"preview": content[:200],
|
| 283 |
"length": len(content),
|
| 284 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
return -0.01, f"edited {path}"
|
| 286 |
|
| 287 |
if action_type == "run_validator":
|
|
@@ -381,6 +397,11 @@ class DeveloperControlRoomEnvironment(
|
|
| 381 |
queried_data=self._state.queried_data,
|
| 382 |
edited_files=self._state.edited_files,
|
| 383 |
validator_status=self._state.validator_status,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
cumulative_reward=self._state.cumulative_reward,
|
| 385 |
feedback=feedback or self._state.feedback,
|
| 386 |
last_action_error=self._state.last_action_error,
|
|
|
|
| 16 |
DeveloperControlRoomObservation,
|
| 17 |
DeveloperControlRoomState,
|
| 18 |
)
|
| 19 |
+
from ..runtime import execute_csv_report_runtime
|
| 20 |
from ..tasks import get_scenario, get_task, scenario_count
|
| 21 |
except ImportError:
|
| 22 |
from graders import evaluate_validator, grade
|
|
|
|
| 25 |
DeveloperControlRoomObservation,
|
| 26 |
DeveloperControlRoomState,
|
| 27 |
)
|
| 28 |
+
from runtime import execute_csv_report_runtime
|
| 29 |
from tasks import get_scenario, get_task, scenario_count
|
| 30 |
|
| 31 |
|
|
|
|
| 107 |
validator_status={},
|
| 108 |
submission={},
|
| 109 |
submitted=False,
|
| 110 |
+
active_role="builder",
|
| 111 |
+
runtime_status={},
|
| 112 |
+
execution_logs=[],
|
| 113 |
+
output_schema=[],
|
| 114 |
+
report_preview=[],
|
| 115 |
cumulative_reward=0.0,
|
| 116 |
done=False,
|
| 117 |
feedback="Episode started.",
|
|
|
|
| 289 |
"preview": content[:200],
|
| 290 |
"length": len(content),
|
| 291 |
}
|
| 292 |
+
if self._state.task_id == "simulate_csv_report_workflow":
|
| 293 |
+
runtime_status = execute_csv_report_runtime(self._scenario, self._state.model_dump())
|
| 294 |
+
self._state.runtime_status = runtime_status
|
| 295 |
+
self._state.execution_logs = list(runtime_status.get("logs", [])) + list(runtime_status.get("errors", []))
|
| 296 |
+
self._state.output_schema = list(runtime_status.get("output_schema", []))
|
| 297 |
+
self._state.report_preview = list(runtime_status.get("report_preview", []))
|
| 298 |
+
if runtime_status.get("errors"):
|
| 299 |
+
self._state.last_action_error = runtime_status["errors"][-1]
|
| 300 |
+
self._state.active_role = "fixer"
|
| 301 |
return -0.01, f"edited {path}"
|
| 302 |
|
| 303 |
if action_type == "run_validator":
|
|
|
|
| 397 |
queried_data=self._state.queried_data,
|
| 398 |
edited_files=self._state.edited_files,
|
| 399 |
validator_status=self._state.validator_status,
|
| 400 |
+
active_role=self._state.active_role,
|
| 401 |
+
runtime_status=self._state.runtime_status,
|
| 402 |
+
execution_logs=self._state.execution_logs,
|
| 403 |
+
output_schema=self._state.output_schema,
|
| 404 |
+
report_preview=self._state.report_preview,
|
| 405 |
cumulative_reward=self._state.cumulative_reward,
|
| 406 |
feedback=feedback or self._state.feedback,
|
| 407 |
last_action_error=self._state.last_action_error,
|
server/requirements.txt
CHANGED
|
@@ -4,3 +4,4 @@ uvicorn>=0.24.0
|
|
| 4 |
openai>=1.52.0
|
| 5 |
requests>=2.32.0
|
| 6 |
python-dotenv>=1.0.1
|
|
|
|
|
|
| 4 |
openai>=1.52.0
|
| 5 |
requests>=2.32.0
|
| 6 |
python-dotenv>=1.0.1
|
| 7 |
+
duckdb>=1.1.0
|
tasks.py
CHANGED
|
@@ -290,6 +290,28 @@ TASK_DEFINITIONS: dict[str, dict] = {
|
|
| 290 |
"grader_family": "workflow",
|
| 291 |
"scenario_ids": ["WS-001", "WS-003"],
|
| 292 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
}
|
| 294 |
|
| 295 |
ALL_TASKS = TASK_DEFINITIONS
|
|
@@ -2340,6 +2362,211 @@ required_columns:
|
|
| 2340 |
},
|
| 2341 |
),
|
| 2342 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2343 |
}
|
| 2344 |
|
| 2345 |
SCENARIO_REGISTRY: dict[str, dict] = {
|
|
|
|
| 290 |
"grader_family": "workflow",
|
| 291 |
"scenario_ids": ["WS-001", "WS-003"],
|
| 292 |
},
|
| 293 |
+
"simulate_csv_report_workflow": {
|
| 294 |
+
"id": "simulate_csv_report_workflow",
|
| 295 |
+
"name": "Task 7: Simulate CSV Report Workflow",
|
| 296 |
+
"difficulty": "hard",
|
| 297 |
+
"max_steps": 12,
|
| 298 |
+
"score_range": [0.0, 1.0],
|
| 299 |
+
"description": (
|
| 300 |
+
"Generate and repair a small CSV-to-report data workflow that stages "
|
| 301 |
+
"source data, loads it into DuckDB, and publishes a final report view."
|
| 302 |
+
),
|
| 303 |
+
"available_actions": [
|
| 304 |
+
"search_workspace",
|
| 305 |
+
"read_file",
|
| 306 |
+
"inspect_schema",
|
| 307 |
+
"edit_file",
|
| 308 |
+
"run_validator",
|
| 309 |
+
"submit_workspace",
|
| 310 |
+
],
|
| 311 |
+
"submission_action": "submit_workspace",
|
| 312 |
+
"grader_family": "simulation",
|
| 313 |
+
"scenario_ids": ["SIM-001"],
|
| 314 |
+
},
|
| 315 |
}
|
| 316 |
|
| 317 |
ALL_TASKS = TASK_DEFINITIONS
|
|
|
|
| 2362 |
},
|
| 2363 |
),
|
| 2364 |
],
|
| 2365 |
+
"simulation_workflow": [
|
| 2366 |
+
workflow_scenario(
|
| 2367 |
+
scenario_id="SIM-001",
|
| 2368 |
+
developer_request=(
|
| 2369 |
+
"Create a report out of this CSV file. The workflow should stage the raw data, "
|
| 2370 |
+
"load it into the warehouse, and publish a view the user can query."
|
| 2371 |
+
),
|
| 2372 |
+
workspace_summary=(
|
| 2373 |
+
"This experimental workspace simulates a tiny data platform. Generate the "
|
| 2374 |
+
"pipeline YAML and SQL needed to stage the CSV into mock S3, load it into "
|
| 2375 |
+
"DuckDB, build a customer summary table, and publish the final report view. "
|
| 2376 |
+
"You share the workspace with two roles: Builder starts, Fixer repairs after runtime failures."
|
| 2377 |
+
),
|
| 2378 |
+
known_files=[
|
| 2379 |
+
"data/sales_orders.csv",
|
| 2380 |
+
"docs/runtime_contract.md",
|
| 2381 |
+
"templates/report_pipeline_template.yaml",
|
| 2382 |
+
"schemas/raw_sales_orders.json",
|
| 2383 |
+
],
|
| 2384 |
+
editable_targets=[
|
| 2385 |
+
"pipelines/report_job.yaml",
|
| 2386 |
+
"sql/load_raw.sql",
|
| 2387 |
+
"sql/build_table.sql",
|
| 2388 |
+
"sql/report_view.sql",
|
| 2389 |
+
],
|
| 2390 |
+
known_assets=[
|
| 2391 |
+
"raw.sales_orders_csv",
|
| 2392 |
+
"mart.customer_daily_report",
|
| 2393 |
+
],
|
| 2394 |
+
available_validators=[
|
| 2395 |
+
"storage_stage_check",
|
| 2396 |
+
"duckdb_load_check",
|
| 2397 |
+
"report_view_check",
|
| 2398 |
+
"output_schema_check",
|
| 2399 |
+
],
|
| 2400 |
+
files={
|
| 2401 |
+
"data/sales_orders.csv": """order_id,customer_id,order_date,product_category,quantity,unit_price
|
| 2402 |
+
1001,C001,2026-04-01,books,2,15.00
|
| 2403 |
+
1002,C001,2026-04-01,games,1,25.00
|
| 2404 |
+
1003,C002,2026-04-02,books,3,12.50
|
| 2405 |
+
1004,C003,2026-04-02,gadgets,1,99.99
|
| 2406 |
+
1005,C002,2026-04-03,games,2,30.00
|
| 2407 |
+
""",
|
| 2408 |
+
"docs/runtime_contract.md": """# Runtime contract
|
| 2409 |
+
|
| 2410 |
+
- The runtime stages `data/sales_orders.csv` into a local mock S3 path.
|
| 2411 |
+
- `pipelines/report_job.yaml` must define:
|
| 2412 |
+
- storage_path
|
| 2413 |
+
- raw_table
|
| 2414 |
+
- load_sql
|
| 2415 |
+
- build_sql
|
| 2416 |
+
- report_sql
|
| 2417 |
+
- final_view
|
| 2418 |
+
- The runtime auto-loads the staged CSV into the `raw_table`.
|
| 2419 |
+
- `sql/load_raw.sql` must create a staged view named `staged_sales_orders`.
|
| 2420 |
+
- `sql/build_table.sql` must create a customer-level summary table named `customer_summary`.
|
| 2421 |
+
- `sql/report_view.sql` must create a final view named `customer_daily_report`.
|
| 2422 |
+
- The final view must expose columns:
|
| 2423 |
+
customer_id, order_date, order_count, gross_revenue_usd
|
| 2424 |
+
""",
|
| 2425 |
+
"templates/report_pipeline_template.yaml": """name: customer_daily_report_job
|
| 2426 |
+
storage_path: mock_s3/staged/sales_orders.csv
|
| 2427 |
+
raw_table: raw_sales_orders
|
| 2428 |
+
load_sql: sql/load_raw.sql
|
| 2429 |
+
build_sql: sql/build_table.sql
|
| 2430 |
+
report_sql: sql/report_view.sql
|
| 2431 |
+
final_view: customer_daily_report
|
| 2432 |
+
""",
|
| 2433 |
+
"schemas/raw_sales_orders.json": """{
|
| 2434 |
+
"name": "raw_sales_orders",
|
| 2435 |
+
"columns": [
|
| 2436 |
+
{"name": "order_id", "type": "string"},
|
| 2437 |
+
{"name": "customer_id", "type": "string"},
|
| 2438 |
+
{"name": "order_date", "type": "date"},
|
| 2439 |
+
{"name": "product_category", "type": "string"},
|
| 2440 |
+
{"name": "quantity", "type": "integer"},
|
| 2441 |
+
{"name": "unit_price", "type": "float"}
|
| 2442 |
+
]
|
| 2443 |
+
}
|
| 2444 |
+
""",
|
| 2445 |
+
},
|
| 2446 |
+
schema_registry={
|
| 2447 |
+
"raw.sales_orders_csv": """asset: raw.sales_orders_csv
|
| 2448 |
+
columns:
|
| 2449 |
+
- order_id: string
|
| 2450 |
+
- customer_id: string
|
| 2451 |
+
- order_date: date
|
| 2452 |
+
- product_category: string
|
| 2453 |
+
- quantity: integer
|
| 2454 |
+
- unit_price: float
|
| 2455 |
+
""",
|
| 2456 |
+
"mart.customer_daily_report": """asset: mart.customer_daily_report
|
| 2457 |
+
required_columns:
|
| 2458 |
+
- customer_id
|
| 2459 |
+
- order_date
|
| 2460 |
+
- order_count
|
| 2461 |
+
- gross_revenue_usd
|
| 2462 |
+
""",
|
| 2463 |
+
},
|
| 2464 |
+
workflow_target={
|
| 2465 |
+
"required_artifacts": ["pipeline_yaml", "load_sql", "build_sql", "report_sql"],
|
| 2466 |
+
"artifacts": {
|
| 2467 |
+
"pipeline_yaml": workflow_artifact(
|
| 2468 |
+
"pipelines/report_job.yaml",
|
| 2469 |
+
required_groups=[
|
| 2470 |
+
["storage_path: mock_s3/staged/sales_orders.csv"],
|
| 2471 |
+
["raw_table: raw_sales_orders"],
|
| 2472 |
+
["load_sql: sql/load_raw.sql"],
|
| 2473 |
+
["build_sql: sql/build_table.sql"],
|
| 2474 |
+
["report_sql: sql/report_view.sql"],
|
| 2475 |
+
["final_view: customer_daily_report"],
|
| 2476 |
+
],
|
| 2477 |
+
weight=1.0,
|
| 2478 |
+
),
|
| 2479 |
+
"load_sql": workflow_artifact(
|
| 2480 |
+
"sql/load_raw.sql",
|
| 2481 |
+
required_groups=[
|
| 2482 |
+
["create", "staged_sales_orders"],
|
| 2483 |
+
["raw_sales_orders"],
|
| 2484 |
+
["cast(order_date as date)", "try_cast(order_date as date)"],
|
| 2485 |
+
],
|
| 2486 |
+
weight=1.0,
|
| 2487 |
+
),
|
| 2488 |
+
"build_sql": workflow_artifact(
|
| 2489 |
+
"sql/build_table.sql",
|
| 2490 |
+
required_groups=[
|
| 2491 |
+
["create", "customer_summary"],
|
| 2492 |
+
["staged_sales_orders"],
|
| 2493 |
+
["quantity * unit_price", "unit_price * quantity"],
|
| 2494 |
+
],
|
| 2495 |
+
weight=1.2,
|
| 2496 |
+
),
|
| 2497 |
+
"report_sql": workflow_artifact(
|
| 2498 |
+
"sql/report_view.sql",
|
| 2499 |
+
required_groups=[
|
| 2500 |
+
["create", "customer_daily_report"],
|
| 2501 |
+
["customer_summary"],
|
| 2502 |
+
["order_count"],
|
| 2503 |
+
["gross_revenue_usd"],
|
| 2504 |
+
],
|
| 2505 |
+
weight=1.2,
|
| 2506 |
+
),
|
| 2507 |
+
},
|
| 2508 |
+
"validator_targets": [
|
| 2509 |
+
"storage_stage_check",
|
| 2510 |
+
"duckdb_load_check",
|
| 2511 |
+
"report_view_check",
|
| 2512 |
+
"output_schema_check",
|
| 2513 |
+
],
|
| 2514 |
+
"solve_validator_targets": [
|
| 2515 |
+
"storage_stage_check",
|
| 2516 |
+
"duckdb_load_check",
|
| 2517 |
+
"report_view_check",
|
| 2518 |
+
"output_schema_check",
|
| 2519 |
+
],
|
| 2520 |
+
"summary_groups": [
|
| 2521 |
+
["sales_orders.csv"],
|
| 2522 |
+
["customer_daily_report"],
|
| 2523 |
+
["DuckDB", "warehouse"],
|
| 2524 |
+
],
|
| 2525 |
+
"investigation_targets": [
|
| 2526 |
+
("read_file", "docs/runtime_contract.md"),
|
| 2527 |
+
("read_file", "data/sales_orders.csv"),
|
| 2528 |
+
("inspect_schema", "raw.sales_orders_csv"),
|
| 2529 |
+
],
|
| 2530 |
+
},
|
| 2531 |
+
validators={
|
| 2532 |
+
"storage_stage_check": {
|
| 2533 |
+
"description": "Checks that the CSV could be staged into mock storage.",
|
| 2534 |
+
"kind": "runtime_check",
|
| 2535 |
+
"check_key": "storage_stage_check",
|
| 2536 |
+
},
|
| 2537 |
+
"duckdb_load_check": {
|
| 2538 |
+
"description": "Checks that the staged CSV loads into DuckDB.",
|
| 2539 |
+
"kind": "runtime_check",
|
| 2540 |
+
"check_key": "duckdb_load_check",
|
| 2541 |
+
},
|
| 2542 |
+
"report_view_check": {
|
| 2543 |
+
"description": "Checks that the final report view compiles.",
|
| 2544 |
+
"kind": "runtime_check",
|
| 2545 |
+
"check_key": "report_view_check",
|
| 2546 |
+
},
|
| 2547 |
+
"output_schema_check": {
|
| 2548 |
+
"description": "Checks that the final report view exposes the expected schema.",
|
| 2549 |
+
"kind": "runtime_check",
|
| 2550 |
+
"check_key": "output_schema_check",
|
| 2551 |
+
},
|
| 2552 |
+
},
|
| 2553 |
+
llm_draft={
|
| 2554 |
+
"simulation_target": {
|
| 2555 |
+
"source_csv": "data/sales_orders.csv",
|
| 2556 |
+
"pipeline_path": "pipelines/report_job.yaml",
|
| 2557 |
+
"load_sql_path": "sql/load_raw.sql",
|
| 2558 |
+
"build_sql_path": "sql/build_table.sql",
|
| 2559 |
+
"report_sql_path": "sql/report_view.sql",
|
| 2560 |
+
"required_output_columns": [
|
| 2561 |
+
"customer_id",
|
| 2562 |
+
"order_date",
|
| 2563 |
+
"order_count",
|
| 2564 |
+
"gross_revenue_usd",
|
| 2565 |
+
],
|
| 2566 |
+
}
|
| 2567 |
+
},
|
| 2568 |
+
),
|
| 2569 |
+
],
|
| 2570 |
}
|
| 2571 |
|
| 2572 |
SCENARIO_REGISTRY: dict[str, dict] = {
|
tests/test_environment_behaviors.py
CHANGED
|
@@ -3,6 +3,8 @@ from __future__ import annotations
|
|
| 3 |
from pathlib import Path
|
| 4 |
import sys
|
| 5 |
|
|
|
|
|
|
|
| 6 |
ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
if str(ROOT) not in sys.path:
|
| 8 |
sys.path.insert(0, str(ROOT))
|
|
@@ -13,6 +15,45 @@ from server.developer_control_room_environment import DeveloperControlRoomEnviro
|
|
| 13 |
from tasks import get_scenario
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def run_episode_with_fallback(task_id: str, scenario_index: int) -> dict:
|
| 17 |
env = DeveloperControlRoomEnvironment()
|
| 18 |
observation = env.reset(task_id=task_id, scenario_index=scenario_index)
|
|
@@ -26,6 +67,33 @@ def run_episode_with_fallback(task_id: str, scenario_index: int) -> dict:
|
|
| 26 |
}
|
| 27 |
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
def test_repeated_file_reads_are_penalized() -> None:
|
| 30 |
env = DeveloperControlRoomEnvironment()
|
| 31 |
env.reset(task_id="repair_pipeline_execution", scenario_index=0)
|
|
@@ -255,3 +323,112 @@ def test_solved_episode_gets_terminal_bonus() -> None:
|
|
| 255 |
|
| 256 |
assert observation.done is True
|
| 257 |
assert observation.reward >= DeveloperControlRoomEnvironment.SOLVED_TERMINAL_REWARD_BONUS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from pathlib import Path
|
| 4 |
import sys
|
| 5 |
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
ROOT = Path(__file__).resolve().parents[1]
|
| 9 |
if str(ROOT) not in sys.path:
|
| 10 |
sys.path.insert(0, str(ROOT))
|
|
|
|
| 15 |
from tasks import get_scenario
|
| 16 |
|
| 17 |
|
| 18 |
+
SIMULATION_PIPELINE_YAML = """name: customer_daily_report_job
|
| 19 |
+
storage_path: mock_s3/staged/sales_orders.csv
|
| 20 |
+
raw_table: raw_sales_orders
|
| 21 |
+
load_sql: sql/load_raw.sql
|
| 22 |
+
build_sql: sql/build_table.sql
|
| 23 |
+
report_sql: sql/report_view.sql
|
| 24 |
+
final_view: customer_daily_report
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
SIMULATION_LOAD_SQL = """create or replace view staged_sales_orders as
|
| 28 |
+
select
|
| 29 |
+
order_id,
|
| 30 |
+
customer_id,
|
| 31 |
+
cast(order_date as date) as order_date,
|
| 32 |
+
quantity,
|
| 33 |
+
unit_price
|
| 34 |
+
from raw_sales_orders;
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
SIMULATION_BUILD_SQL = """create or replace table customer_summary as
|
| 38 |
+
select
|
| 39 |
+
customer_id,
|
| 40 |
+
order_date,
|
| 41 |
+
count(*) as order_count,
|
| 42 |
+
sum(quantity * unit_price) as gross_revenue_usd
|
| 43 |
+
from staged_sales_orders
|
| 44 |
+
group by 1, 2;
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
SIMULATION_REPORT_SQL = """create or replace view customer_daily_report as
|
| 48 |
+
select
|
| 49 |
+
customer_id,
|
| 50 |
+
order_date,
|
| 51 |
+
order_count,
|
| 52 |
+
gross_revenue_usd
|
| 53 |
+
from customer_summary;
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
def run_episode_with_fallback(task_id: str, scenario_index: int) -> dict:
|
| 58 |
env = DeveloperControlRoomEnvironment()
|
| 59 |
observation = env.reset(task_id=task_id, scenario_index=scenario_index)
|
|
|
|
| 67 |
}
|
| 68 |
|
| 69 |
|
| 70 |
+
def _run_simulation_sequence(report_sql: str = SIMULATION_REPORT_SQL) -> dict:
|
| 71 |
+
env = DeveloperControlRoomEnvironment()
|
| 72 |
+
observation = env.reset(task_id="simulate_csv_report_workflow", scenario_index=0)
|
| 73 |
+
|
| 74 |
+
for action in (
|
| 75 |
+
{
|
| 76 |
+
"action_type": "edit_file",
|
| 77 |
+
"parameters": {"path": "pipelines/report_job.yaml", "content": SIMULATION_PIPELINE_YAML},
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"action_type": "edit_file",
|
| 81 |
+
"parameters": {"path": "sql/load_raw.sql", "content": SIMULATION_LOAD_SQL},
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"action_type": "edit_file",
|
| 85 |
+
"parameters": {"path": "sql/build_table.sql", "content": SIMULATION_BUILD_SQL},
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"action_type": "edit_file",
|
| 89 |
+
"parameters": {"path": "sql/report_view.sql", "content": report_sql},
|
| 90 |
+
},
|
| 91 |
+
):
|
| 92 |
+
observation = env.step(build_action(action))
|
| 93 |
+
|
| 94 |
+
return {"env": env, "observation": observation}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
def test_repeated_file_reads_are_penalized() -> None:
|
| 98 |
env = DeveloperControlRoomEnvironment()
|
| 99 |
env.reset(task_id="repair_pipeline_execution", scenario_index=0)
|
|
|
|
| 323 |
|
| 324 |
assert observation.done is True
|
| 325 |
assert observation.reward >= DeveloperControlRoomEnvironment.SOLVED_TERMINAL_REWARD_BONUS
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def test_simulation_reset_exposes_runtime_context() -> None:
|
| 329 |
+
env = DeveloperControlRoomEnvironment()
|
| 330 |
+
observation = env.reset(task_id="simulate_csv_report_workflow", scenario_index=0)
|
| 331 |
+
|
| 332 |
+
assert observation.active_role == "builder"
|
| 333 |
+
assert "data/sales_orders.csv" in observation.known_files
|
| 334 |
+
assert "pipelines/report_job.yaml" in observation.editable_targets
|
| 335 |
+
assert "storage_stage_check" in observation.available_validators
|
| 336 |
+
assert observation.runtime_status == {}
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def test_simulation_runtime_happy_path_executes_end_to_end() -> None:
|
| 340 |
+
pytest.importorskip("duckdb")
|
| 341 |
+
run = _run_simulation_sequence()
|
| 342 |
+
env = run["env"]
|
| 343 |
+
observation = run["observation"]
|
| 344 |
+
|
| 345 |
+
assert observation.active_role == "fixer"
|
| 346 |
+
assert observation.runtime_status.get("succeeded") is True
|
| 347 |
+
assert observation.output_schema == [
|
| 348 |
+
"customer_id",
|
| 349 |
+
"order_date",
|
| 350 |
+
"order_count",
|
| 351 |
+
"gross_revenue_usd",
|
| 352 |
+
]
|
| 353 |
+
assert observation.report_preview
|
| 354 |
+
|
| 355 |
+
for validator in (
|
| 356 |
+
"storage_stage_check",
|
| 357 |
+
"duckdb_load_check",
|
| 358 |
+
"report_view_check",
|
| 359 |
+
"output_schema_check",
|
| 360 |
+
):
|
| 361 |
+
observation = env.step(
|
| 362 |
+
build_action(
|
| 363 |
+
{
|
| 364 |
+
"action_type": "run_validator",
|
| 365 |
+
"parameters": {"validator": validator},
|
| 366 |
+
}
|
| 367 |
+
)
|
| 368 |
+
)
|
| 369 |
+
assert observation.validator_status[validator]["passed"] is True
|
| 370 |
+
|
| 371 |
+
observation = env.step(
|
| 372 |
+
build_action(
|
| 373 |
+
{
|
| 374 |
+
"action_type": "submit_workspace",
|
| 375 |
+
"parameters": {
|
| 376 |
+
"summary": "Built a DuckDB pipeline from sales_orders.csv and published customer_daily_report."
|
| 377 |
+
},
|
| 378 |
+
}
|
| 379 |
+
)
|
| 380 |
+
)
|
| 381 |
+
final_grade = grade("simulate_csv_report_workflow", env._state.model_dump(), env._scenario)
|
| 382 |
+
|
| 383 |
+
assert observation.done is True
|
| 384 |
+
assert final_grade["solved"] is True
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def test_simulation_fixer_can_repair_broken_report_view() -> None:
|
| 388 |
+
pytest.importorskip("duckdb")
|
| 389 |
+
broken_report_sql = """create or replace view customer_daily_report as
|
| 390 |
+
select
|
| 391 |
+
customer_id,
|
| 392 |
+
order_date,
|
| 393 |
+
order_count,
|
| 394 |
+
gross_revenue_usd as gross_revenue
|
| 395 |
+
from customer_summary;
|
| 396 |
+
"""
|
| 397 |
+
|
| 398 |
+
run = _run_simulation_sequence(report_sql=broken_report_sql)
|
| 399 |
+
env = run["env"]
|
| 400 |
+
observation = run["observation"]
|
| 401 |
+
|
| 402 |
+
assert observation.active_role == "fixer"
|
| 403 |
+
assert observation.runtime_status.get("checks", {}).get("report_view_check") is True
|
| 404 |
+
assert observation.runtime_status.get("checks", {}).get("output_schema_check") is False
|
| 405 |
+
|
| 406 |
+
observation = env.step(
|
| 407 |
+
build_action(
|
| 408 |
+
{
|
| 409 |
+
"action_type": "edit_file",
|
| 410 |
+
"parameters": {"path": "sql/report_view.sql", "content": SIMULATION_REPORT_SQL},
|
| 411 |
+
}
|
| 412 |
+
)
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
assert observation.runtime_status.get("succeeded") is True
|
| 416 |
+
assert observation.output_schema[-1] == "gross_revenue_usd"
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def test_simulation_sequence_replays_deterministically() -> None:
|
| 420 |
+
pytest.importorskip("duckdb")
|
| 421 |
+
first = _run_simulation_sequence()
|
| 422 |
+
second = _run_simulation_sequence()
|
| 423 |
+
|
| 424 |
+
first_env = first["env"]
|
| 425 |
+
second_env = second["env"]
|
| 426 |
+
|
| 427 |
+
assert first_env._state.action_history == second_env._state.action_history
|
| 428 |
+
assert first_env._state.runtime_status == second_env._state.runtime_status
|
| 429 |
+
assert first_env._state.report_preview == second_env._state.report_preview
|
| 430 |
+
assert grade("simulate_csv_report_workflow", first_env._state.model_dump(), first_env._scenario) == grade(
|
| 431 |
+
"simulate_csv_report_workflow",
|
| 432 |
+
second_env._state.model_dump(),
|
| 433 |
+
second_env._scenario,
|
| 434 |
+
)
|
train.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Minimal GRPO training entrypoint for FlowOS."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import csv
|
| 7 |
+
import logging
|
| 8 |
+
import re
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from .baseline import action_is_valid, fallback_action
|
| 15 |
+
from .training_utils import (
|
| 16 |
+
DEFAULT_MAX_NEW_TOKENS,
|
| 17 |
+
DEFAULT_MAX_TURNS,
|
| 18 |
+
DEFAULT_TRAIN_MODEL,
|
| 19 |
+
TRAIN_SYSTEM_PROMPT,
|
| 20 |
+
build_episode_samples,
|
| 21 |
+
build_turn_prompt,
|
| 22 |
+
parse_action_json,
|
| 23 |
+
parse_sample_prompt,
|
| 24 |
+
run_episode,
|
| 25 |
+
samples_to_dataset_prompts,
|
| 26 |
+
)
|
| 27 |
+
except ImportError:
|
| 28 |
+
from baseline import action_is_valid, fallback_action
|
| 29 |
+
from training_utils import (
|
| 30 |
+
DEFAULT_MAX_NEW_TOKENS,
|
| 31 |
+
DEFAULT_MAX_TURNS,
|
| 32 |
+
DEFAULT_TRAIN_MODEL,
|
| 33 |
+
TRAIN_SYSTEM_PROMPT,
|
| 34 |
+
build_episode_samples,
|
| 35 |
+
build_turn_prompt,
|
| 36 |
+
parse_action_json,
|
| 37 |
+
parse_sample_prompt,
|
| 38 |
+
run_episode,
|
| 39 |
+
samples_to_dataset_prompts,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
logger = logging.getLogger(__name__)
|
| 43 |
+
DEBUG_GENERATION_LOG_LIMIT = 8
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _clean_preview(text: str, limit: int = 220) -> str:
|
| 47 |
+
normalized = text.replace("\u00a0", " ")
|
| 48 |
+
normalized = re.sub(r"\s+", " ", normalized).strip()
|
| 49 |
+
if not normalized:
|
| 50 |
+
return "<empty>"
|
| 51 |
+
if len(normalized) > limit:
|
| 52 |
+
return normalized[:limit] + "..."
|
| 53 |
+
return normalized
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def parse_args() -> argparse.Namespace:
|
| 57 |
+
parser = argparse.ArgumentParser(description="Minimal Colab-first GRPO training for FlowOS")
|
| 58 |
+
parser.add_argument("--model-id", default=DEFAULT_TRAIN_MODEL, help="Base instruct model to fine-tune")
|
| 59 |
+
parser.add_argument("--env-url", default="http://localhost:7860", help="FlowOS OpenEnv server URL")
|
| 60 |
+
parser.add_argument("--dataset-size", type=int, default=24, help="Number of training episode prompts")
|
| 61 |
+
parser.add_argument("--num-generations", type=int, default=4, help="GRPO generations per prompt")
|
| 62 |
+
parser.add_argument("--max-turns", type=int, default=DEFAULT_MAX_TURNS, help="Max environment turns per episode")
|
| 63 |
+
parser.add_argument("--max-new-tokens", type=int, default=DEFAULT_MAX_NEW_TOKENS, help="Max tokens per action generation")
|
| 64 |
+
parser.add_argument("--learning-rate", type=float, default=2e-6, help="Trainer learning rate")
|
| 65 |
+
parser.add_argument("--output-dir", default=None, help="Checkpoint output directory")
|
| 66 |
+
parser.add_argument("--task-scope", default="all", help="Task scope: all or comma-separated task ids")
|
| 67 |
+
parser.add_argument("--report-to", default="none", choices=("none", "tensorboard", "wandb"), help="Logging backend")
|
| 68 |
+
parser.add_argument("--num-epochs", type=int, default=1, help="Number of GRPO epochs")
|
| 69 |
+
parser.add_argument("--max-steps", type=int, default=-1, help="Max trainer steps; -1 lets TRL infer from epochs")
|
| 70 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=4, help="Gradient accumulation")
|
| 71 |
+
parser.add_argument("--per-device-train-batch-size", type=int, default=1, help="Per-device batch size")
|
| 72 |
+
parser.add_argument("--save-steps", type=int, default=10, help="Checkpoint save interval")
|
| 73 |
+
parser.add_argument("--logging-steps", type=int, default=1, help="Logging interval")
|
| 74 |
+
parser.add_argument("--temperature", type=float, default=0.7, help="Sampling temperature")
|
| 75 |
+
parser.add_argument("--lora-r", type=int, default=16, help="LoRA rank")
|
| 76 |
+
parser.add_argument("--lora-alpha", type=int, default=32, help="LoRA alpha")
|
| 77 |
+
parser.add_argument("--lora-dropout", type=float, default=0.05, help="LoRA dropout")
|
| 78 |
+
parser.add_argument("--reward-log", default="reward_log.csv", help="CSV filename for episode rewards")
|
| 79 |
+
return parser.parse_args()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def apply_chat_template(tokenizer: Any, messages: list[dict[str, str]]) -> str:
|
| 83 |
+
try:
|
| 84 |
+
return tokenizer.apply_chat_template(
|
| 85 |
+
messages,
|
| 86 |
+
add_generation_prompt=True,
|
| 87 |
+
tokenize=False,
|
| 88 |
+
enable_thinking=False,
|
| 89 |
+
)
|
| 90 |
+
except TypeError:
|
| 91 |
+
return tokenizer.apply_chat_template(
|
| 92 |
+
messages,
|
| 93 |
+
add_generation_prompt=True,
|
| 94 |
+
tokenize=False,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def generate_with_trainer(
|
| 99 |
+
trainer: Any,
|
| 100 |
+
tokenizer: Any,
|
| 101 |
+
prompt_text: str,
|
| 102 |
+
max_new_tokens: int,
|
| 103 |
+
temperature: float,
|
| 104 |
+
) -> dict[str, Any]:
|
| 105 |
+
try:
|
| 106 |
+
from trl.experimental.openenv import generate_rollout_completions
|
| 107 |
+
|
| 108 |
+
episode = generate_rollout_completions(trainer, [prompt_text], max_new_tokens=max_new_tokens)[0]
|
| 109 |
+
return {
|
| 110 |
+
"prompt_ids": list(episode.get("prompt_ids", [])),
|
| 111 |
+
"completion_ids": list(episode.get("completion_ids", [])),
|
| 112 |
+
"logprobs": list(episode.get("logprobs", [])),
|
| 113 |
+
"text": episode.get("text") or tokenizer.decode(episode.get("completion_ids", []), skip_special_tokens=True),
|
| 114 |
+
}
|
| 115 |
+
except Exception:
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
import torch
|
| 119 |
+
|
| 120 |
+
model = getattr(trainer, "model_wrapped", None) or getattr(trainer, "model", None)
|
| 121 |
+
if model is None:
|
| 122 |
+
raise RuntimeError("Could not access trainer model for fallback generation.")
|
| 123 |
+
|
| 124 |
+
device = next(model.parameters()).device
|
| 125 |
+
inputs = tokenizer(prompt_text, return_tensors="pt").to(device)
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
generated = model.generate(
|
| 128 |
+
**inputs,
|
| 129 |
+
do_sample=temperature > 0,
|
| 130 |
+
temperature=max(temperature, 1e-5),
|
| 131 |
+
max_new_tokens=max_new_tokens,
|
| 132 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 133 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
prompt_ids = inputs["input_ids"][0].tolist()
|
| 137 |
+
full_ids = generated[0]
|
| 138 |
+
completion_ids = full_ids[len(prompt_ids) :].tolist()
|
| 139 |
+
|
| 140 |
+
with torch.no_grad():
|
| 141 |
+
logits = model(full_ids.unsqueeze(0)).logits[0]
|
| 142 |
+
token_logprobs: list[float] = []
|
| 143 |
+
for offset, token_id in enumerate(completion_ids):
|
| 144 |
+
logit_index = len(prompt_ids) - 1 + offset
|
| 145 |
+
distribution = torch.log_softmax(logits[logit_index], dim=-1)
|
| 146 |
+
token_logprobs.append(float(distribution[token_id].item()))
|
| 147 |
+
|
| 148 |
+
return {
|
| 149 |
+
"prompt_ids": prompt_ids,
|
| 150 |
+
"completion_ids": completion_ids,
|
| 151 |
+
"logprobs": token_logprobs,
|
| 152 |
+
"text": tokenizer.decode(completion_ids, skip_special_tokens=True),
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def reward_total(completions: list[str], **kwargs: Any) -> list[float]:
|
| 157 |
+
rewards = kwargs.get("total_reward", [])
|
| 158 |
+
return [float(value) for value in rewards] if rewards else [0.0] * len(completions)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def reward_score(completions: list[str], **kwargs: Any) -> list[float]:
|
| 162 |
+
rewards = kwargs.get("score_reward", [])
|
| 163 |
+
return [float(value) for value in rewards] if rewards else [0.0] * len(completions)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def reward_solved(completions: list[str], **kwargs: Any) -> list[float]:
|
| 167 |
+
solved = kwargs.get("solved_reward", [])
|
| 168 |
+
return [float(value) for value in solved] if solved else [0.0] * len(completions)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def main() -> None:
|
| 172 |
+
args = parse_args()
|
| 173 |
+
|
| 174 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 175 |
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
| 176 |
+
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
| 177 |
+
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
|
| 178 |
+
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
| 179 |
+
|
| 180 |
+
try:
|
| 181 |
+
from datasets import Dataset
|
| 182 |
+
from peft import LoraConfig
|
| 183 |
+
from transformers import AutoTokenizer
|
| 184 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 185 |
+
except ImportError as exc:
|
| 186 |
+
raise SystemExit(
|
| 187 |
+
"Training dependencies are missing. Install them with `pip install -e \".[train]\"`."
|
| 188 |
+
) from exc
|
| 189 |
+
|
| 190 |
+
samples = build_episode_samples(args.task_scope, args.dataset_size)
|
| 191 |
+
dataset = Dataset.from_dict({"prompt": samples_to_dataset_prompts(samples)})
|
| 192 |
+
|
| 193 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_id)
|
| 194 |
+
if tokenizer.pad_token is None:
|
| 195 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 196 |
+
|
| 197 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 198 |
+
output_dir = Path(args.output_dir or Path("outputs") / f"flowos-grpo-{timestamp}")
|
| 199 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 200 |
+
|
| 201 |
+
reward_log_path = output_dir / args.reward_log
|
| 202 |
+
with reward_log_path.open("w", newline="") as handle:
|
| 203 |
+
writer = csv.writer(handle)
|
| 204 |
+
writer.writerow(["episode", "task_id", "scenario_id", "total_reward", "score", "solved", "steps"])
|
| 205 |
+
|
| 206 |
+
episode_counter = [0]
|
| 207 |
+
generation_debug_counter = [0]
|
| 208 |
+
|
| 209 |
+
def log_episode(metrics: dict[str, Any]) -> None:
|
| 210 |
+
episode_counter[0] += 1
|
| 211 |
+
with reward_log_path.open("a", newline="") as handle:
|
| 212 |
+
writer = csv.writer(handle)
|
| 213 |
+
writer.writerow(
|
| 214 |
+
[
|
| 215 |
+
episode_counter[0],
|
| 216 |
+
metrics["task_id"],
|
| 217 |
+
metrics["scenario_id"],
|
| 218 |
+
f"{metrics['total_reward']:.4f}",
|
| 219 |
+
f"{metrics['score']:.4f}",
|
| 220 |
+
str(bool(metrics["solved"])).lower(),
|
| 221 |
+
metrics["steps"],
|
| 222 |
+
]
|
| 223 |
+
)
|
| 224 |
+
logger.info(
|
| 225 |
+
"Episode %s task=%s scenario=%s reward=%.3f score=%.3f solved=%s steps=%s",
|
| 226 |
+
episode_counter[0],
|
| 227 |
+
metrics["task_id"],
|
| 228 |
+
metrics["scenario_id"],
|
| 229 |
+
metrics["total_reward"],
|
| 230 |
+
metrics["score"],
|
| 231 |
+
metrics["solved"],
|
| 232 |
+
metrics["steps"],
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def rollout_func(prompts: list[str], trainer: Any) -> dict[str, list]:
|
| 236 |
+
prompt_batches: list[list[int]] = []
|
| 237 |
+
completion_batches: list[list[int]] = []
|
| 238 |
+
logprob_batches: list[list[float]] = []
|
| 239 |
+
total_rewards: list[float] = []
|
| 240 |
+
score_rewards: list[float] = []
|
| 241 |
+
solved_rewards: list[float] = []
|
| 242 |
+
|
| 243 |
+
for prompt in prompts:
|
| 244 |
+
sample = parse_sample_prompt(prompt)
|
| 245 |
+
|
| 246 |
+
def policy(observation: Any, transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 247 |
+
user_prompt = build_turn_prompt(observation, transcript)
|
| 248 |
+
prompt_text = apply_chat_template(
|
| 249 |
+
tokenizer,
|
| 250 |
+
[
|
| 251 |
+
{"role": "system", "content": TRAIN_SYSTEM_PROMPT},
|
| 252 |
+
{"role": "user", "content": user_prompt},
|
| 253 |
+
],
|
| 254 |
+
)
|
| 255 |
+
generation = generate_with_trainer(
|
| 256 |
+
trainer=trainer,
|
| 257 |
+
tokenizer=tokenizer,
|
| 258 |
+
prompt_text=prompt_text,
|
| 259 |
+
max_new_tokens=args.max_new_tokens,
|
| 260 |
+
temperature=args.temperature,
|
| 261 |
+
)
|
| 262 |
+
parsed_action = parse_action_json(generation["text"])
|
| 263 |
+
if generation_debug_counter[0] < DEBUG_GENERATION_LOG_LIMIT:
|
| 264 |
+
logger.info(
|
| 265 |
+
"Raw rollout completion %s task=%s step=%s text=%s parsed=%s",
|
| 266 |
+
generation_debug_counter[0] + 1,
|
| 267 |
+
sample.task_id,
|
| 268 |
+
observation.step_count + 1,
|
| 269 |
+
_clean_preview(generation["text"]),
|
| 270 |
+
parsed_action,
|
| 271 |
+
)
|
| 272 |
+
generation_debug_counter[0] += 1
|
| 273 |
+
if not action_is_valid(parsed_action, observation):
|
| 274 |
+
fallback = fallback_action(sample.task_id, observation)
|
| 275 |
+
logger.info(
|
| 276 |
+
"Using fallback action task=%s step=%s fallback=%s",
|
| 277 |
+
sample.task_id,
|
| 278 |
+
observation.step_count + 1,
|
| 279 |
+
fallback,
|
| 280 |
+
)
|
| 281 |
+
parsed_action = fallback
|
| 282 |
+
return {
|
| 283 |
+
"action": parsed_action,
|
| 284 |
+
"metadata": generation,
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
metrics = run_episode(
|
| 288 |
+
base_url=args.env_url,
|
| 289 |
+
sample=sample,
|
| 290 |
+
max_turns=args.max_turns,
|
| 291 |
+
policy=policy,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
prompt_batches.append(metrics.prompt_ids or [])
|
| 295 |
+
completion_batches.append(metrics.completion_ids or [])
|
| 296 |
+
logprob_batches.append(metrics.logprobs or [])
|
| 297 |
+
total_rewards.append(metrics.total_reward)
|
| 298 |
+
score_rewards.append(metrics.score)
|
| 299 |
+
solved_rewards.append(1.0 if metrics.solved else 0.0)
|
| 300 |
+
log_episode(
|
| 301 |
+
{
|
| 302 |
+
"task_id": metrics.task_id,
|
| 303 |
+
"scenario_id": metrics.scenario_id,
|
| 304 |
+
"total_reward": metrics.total_reward,
|
| 305 |
+
"score": metrics.score,
|
| 306 |
+
"solved": metrics.solved,
|
| 307 |
+
"steps": metrics.steps,
|
| 308 |
+
}
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
return {
|
| 312 |
+
"prompt_ids": prompt_batches,
|
| 313 |
+
"completion_ids": completion_batches,
|
| 314 |
+
"logprobs": logprob_batches,
|
| 315 |
+
"total_reward": total_rewards,
|
| 316 |
+
"score_reward": score_rewards,
|
| 317 |
+
"solved_reward": solved_rewards,
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
peft_config = LoraConfig(
|
| 321 |
+
r=args.lora_r,
|
| 322 |
+
lora_alpha=args.lora_alpha,
|
| 323 |
+
lora_dropout=args.lora_dropout,
|
| 324 |
+
bias="none",
|
| 325 |
+
task_type="CAUSAL_LM",
|
| 326 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
grpo_config = GRPOConfig(
|
| 330 |
+
output_dir=str(output_dir),
|
| 331 |
+
use_vllm=False,
|
| 332 |
+
learning_rate=args.learning_rate,
|
| 333 |
+
num_train_epochs=args.num_epochs,
|
| 334 |
+
max_steps=args.max_steps,
|
| 335 |
+
per_device_train_batch_size=args.per_device_train_batch_size,
|
| 336 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 337 |
+
num_generations=args.num_generations,
|
| 338 |
+
generation_batch_size=args.num_generations,
|
| 339 |
+
max_completion_length=args.max_new_tokens,
|
| 340 |
+
logging_steps=args.logging_steps,
|
| 341 |
+
save_strategy="steps",
|
| 342 |
+
save_steps=args.save_steps,
|
| 343 |
+
report_to=args.report_to,
|
| 344 |
+
temperature=args.temperature,
|
| 345 |
+
gradient_checkpointing=True,
|
| 346 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
trainer = GRPOTrainer(
|
| 350 |
+
model=args.model_id,
|
| 351 |
+
processing_class=tokenizer,
|
| 352 |
+
reward_funcs=[reward_total, reward_score, reward_solved],
|
| 353 |
+
train_dataset=dataset,
|
| 354 |
+
args=grpo_config,
|
| 355 |
+
rollout_func=rollout_func,
|
| 356 |
+
peft_config=peft_config,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
logger.info("Starting FlowOS GRPO training")
|
| 360 |
+
logger.info("model=%s env=%s dataset_size=%s task_scope=%s", args.model_id, args.env_url, args.dataset_size, args.task_scope)
|
| 361 |
+
trainer.train()
|
| 362 |
+
trainer.save_model(str(output_dir))
|
| 363 |
+
logger.info("Training finished. Model saved to %s", output_dir)
|
| 364 |
+
logger.info("Reward log written to %s", reward_log_path)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
if __name__ == "__main__":
|
| 368 |
+
main()
|
training_utils.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers for FlowOS training and evaluation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import json
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from itertools import cycle, islice
|
| 9 |
+
from typing import Any, Callable
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from .client import DeveloperControlRoomEnv
|
| 15 |
+
from .models import ActionParameters, DeveloperControlRoomAction, DeveloperControlRoomObservation
|
| 16 |
+
from .tasks import TASK_DEFINITIONS, scenario_count
|
| 17 |
+
except ImportError:
|
| 18 |
+
from client import DeveloperControlRoomEnv
|
| 19 |
+
from models import ActionParameters, DeveloperControlRoomAction, DeveloperControlRoomObservation
|
| 20 |
+
from tasks import TASK_DEFINITIONS, scenario_count
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
DEFAULT_TRAIN_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 24 |
+
DEFAULT_MAX_TURNS = 12
|
| 25 |
+
DEFAULT_MAX_NEW_TOKENS = 200
|
| 26 |
+
|
| 27 |
+
TRAIN_SYSTEM_PROMPT = """You are operating the FlowOS benchmark as a production engineering agent.
|
| 28 |
+
Reply with exactly one JSON object with keys "action_type" and "parameters".
|
| 29 |
+
Do not include markdown, explanations, or code fences.
|
| 30 |
+
|
| 31 |
+
Allowed action shapes:
|
| 32 |
+
{"action_type":"search_workspace","parameters":{"query":"..."}}
|
| 33 |
+
{"action_type":"read_file","parameters":{"path":"..."}}
|
| 34 |
+
{"action_type":"inspect_schema","parameters":{"asset":"..."}}
|
| 35 |
+
{"action_type":"inspect_lineage","parameters":{"asset":"..."}}
|
| 36 |
+
{"action_type":"inspect_llm_draft","parameters":{"draft_id":"primary"}}
|
| 37 |
+
{"action_type":"edit_file","parameters":{"path":"...","content":"..."}}
|
| 38 |
+
{"action_type":"run_validator","parameters":{"validator":"..."}}
|
| 39 |
+
{"action_type":"submit_repair","parameters":{"root_cause":"...","fix_path":"...","summary":"..."}}
|
| 40 |
+
{"action_type":"submit_review","parameters":{"verdict":"approve|reject","issue_type":"...","summary":"..."}}
|
| 41 |
+
{"action_type":"submit_workspace","parameters":{"summary":"..."}}
|
| 42 |
+
|
| 43 |
+
Use exact file paths, asset names, and validator names from the observation.
|
| 44 |
+
Good examples:
|
| 45 |
+
{"action_type":"read_file","parameters":{"path":"docs/runtime_contract.md"}}
|
| 46 |
+
{"action_type":"inspect_schema","parameters":{"asset":"raw.sales_orders_csv"}}
|
| 47 |
+
{"action_type":"edit_file","parameters":{"path":"pipelines/report_job.yaml","content":"name: customer_daily_report_job\\nstorage_path: mock_s3/staged/sales_orders.csv\\nraw_table: raw_sales_orders\\nload_sql: sql/load_raw.sql\\nbuild_sql: sql/build_table.sql\\nreport_sql: sql/report_view.sql\\nfinal_view: customer_daily_report\\n"}}
|
| 48 |
+
For simulate_csv_report_workflow, prefer starting with read_file on docs/runtime_contract.md or templates/report_pipeline_template.yaml.
|
| 49 |
+
Return only one action per turn."""
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class EpisodeSample:
|
| 54 |
+
task_id: str
|
| 55 |
+
scenario_index: int
|
| 56 |
+
seed: int
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class EpisodeMetrics:
|
| 61 |
+
task_id: str
|
| 62 |
+
scenario_id: str
|
| 63 |
+
rewards: list[float]
|
| 64 |
+
total_reward: float
|
| 65 |
+
score: float
|
| 66 |
+
solved: bool
|
| 67 |
+
steps: int
|
| 68 |
+
transcript: list[dict[str, Any]]
|
| 69 |
+
prompt_ids: list[int] | None = None
|
| 70 |
+
completion_ids: list[int] | None = None
|
| 71 |
+
logprobs: list[float] | None = None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def resolve_task_scope(task_scope: str) -> list[str]:
|
| 75 |
+
if not task_scope or task_scope == "all":
|
| 76 |
+
return list(TASK_DEFINITIONS)
|
| 77 |
+
task_ids = [task.strip() for task in task_scope.split(",") if task.strip()]
|
| 78 |
+
unknown = [task for task in task_ids if task not in TASK_DEFINITIONS]
|
| 79 |
+
if unknown:
|
| 80 |
+
raise ValueError(f"Unknown task ids in --task-scope: {', '.join(unknown)}")
|
| 81 |
+
return task_ids
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def build_episode_samples(task_scope: str, dataset_size: int) -> list[EpisodeSample]:
|
| 85 |
+
task_ids = resolve_task_scope(task_scope)
|
| 86 |
+
universe: list[EpisodeSample] = []
|
| 87 |
+
seed = 0
|
| 88 |
+
for task_id in task_ids:
|
| 89 |
+
for scenario_index in range(scenario_count(task_id)):
|
| 90 |
+
universe.append(EpisodeSample(task_id=task_id, scenario_index=scenario_index, seed=seed))
|
| 91 |
+
seed += 1
|
| 92 |
+
if not universe:
|
| 93 |
+
return []
|
| 94 |
+
return list(islice(cycle(universe), dataset_size))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def samples_to_dataset_prompts(samples: list[EpisodeSample]) -> list[str]:
|
| 98 |
+
return [
|
| 99 |
+
json.dumps(
|
| 100 |
+
{
|
| 101 |
+
"task_id": sample.task_id,
|
| 102 |
+
"scenario_index": sample.scenario_index,
|
| 103 |
+
"seed": sample.seed,
|
| 104 |
+
},
|
| 105 |
+
separators=(",", ":"),
|
| 106 |
+
)
|
| 107 |
+
for sample in samples
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def parse_sample_prompt(prompt: str) -> EpisodeSample:
|
| 112 |
+
payload = json.loads(prompt)
|
| 113 |
+
return EpisodeSample(
|
| 114 |
+
task_id=str(payload["task_id"]),
|
| 115 |
+
scenario_index=int(payload["scenario_index"]),
|
| 116 |
+
seed=int(payload.get("seed", 0)),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def parse_action_json(response_text: str) -> dict[str, Any] | None:
|
| 121 |
+
text = (response_text or "").strip()
|
| 122 |
+
if not text:
|
| 123 |
+
return None
|
| 124 |
+
if text.startswith("```"):
|
| 125 |
+
text = "\n".join(
|
| 126 |
+
line for line in text.splitlines() if not line.strip().startswith("```")
|
| 127 |
+
).strip()
|
| 128 |
+
try:
|
| 129 |
+
parsed = json.loads(text)
|
| 130 |
+
return parsed if isinstance(parsed, dict) else None
|
| 131 |
+
except json.JSONDecodeError:
|
| 132 |
+
decoder = json.JSONDecoder()
|
| 133 |
+
for idx, char in enumerate(text):
|
| 134 |
+
if char != "{":
|
| 135 |
+
continue
|
| 136 |
+
try:
|
| 137 |
+
parsed, _ = decoder.raw_decode(text[idx:])
|
| 138 |
+
except json.JSONDecodeError:
|
| 139 |
+
continue
|
| 140 |
+
if isinstance(parsed, dict):
|
| 141 |
+
return parsed
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def coerce_action(action_dict: dict[str, Any] | None) -> DeveloperControlRoomAction:
|
| 146 |
+
if not isinstance(action_dict, dict):
|
| 147 |
+
return DeveloperControlRoomAction(
|
| 148 |
+
action_type="invalid_action",
|
| 149 |
+
parameters=ActionParameters(),
|
| 150 |
+
)
|
| 151 |
+
action_type = str(action_dict.get("action_type") or "").strip() or "invalid_action"
|
| 152 |
+
params = action_dict.get("parameters", {})
|
| 153 |
+
if not isinstance(params, dict):
|
| 154 |
+
params = {}
|
| 155 |
+
return DeveloperControlRoomAction(
|
| 156 |
+
action_type=action_type,
|
| 157 |
+
parameters=ActionParameters(**params),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def format_history(transcript: list[dict[str, Any]]) -> str:
|
| 162 |
+
if not transcript:
|
| 163 |
+
return "None"
|
| 164 |
+
lines: list[str] = []
|
| 165 |
+
for entry in transcript[-4:]:
|
| 166 |
+
lines.append(
|
| 167 |
+
"Action: {action}\nReward: {reward:.2f}\nFeedback: {feedback}\nError: {error}".format(
|
| 168 |
+
action=entry.get("action_text", "invalid_action()"),
|
| 169 |
+
reward=float(entry.get("reward", 0.0)),
|
| 170 |
+
feedback=entry.get("feedback") or "none",
|
| 171 |
+
error=entry.get("error") or "null",
|
| 172 |
+
)
|
| 173 |
+
)
|
| 174 |
+
return "\n\n".join(lines)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def format_observation(observation: DeveloperControlRoomObservation) -> str:
|
| 178 |
+
return (
|
| 179 |
+
f"Task: {observation.task_id}\n"
|
| 180 |
+
f"Scenario: {observation.scenario_id}\n"
|
| 181 |
+
f"Step: {observation.step_count}/{observation.max_steps}\n"
|
| 182 |
+
f"Active role: {observation.active_role}\n"
|
| 183 |
+
f"Request: {observation.developer_request}\n"
|
| 184 |
+
f"Workspace summary: {observation.workspace_summary}\n"
|
| 185 |
+
f"Known files: {json.dumps(observation.known_files)}\n"
|
| 186 |
+
f"Editable targets: {json.dumps(observation.editable_targets)}\n"
|
| 187 |
+
f"Known assets: {json.dumps(observation.known_assets)}\n"
|
| 188 |
+
f"Validators: {json.dumps(observation.available_validators)}\n"
|
| 189 |
+
f"Queried data keys: {json.dumps(sorted(observation.queried_data.keys()))}\n"
|
| 190 |
+
f"Edited files: {json.dumps(sorted(observation.edited_files.keys()))}\n"
|
| 191 |
+
f"Validator status: {json.dumps(observation.validator_status)}\n"
|
| 192 |
+
f"Runtime status: {json.dumps(observation.runtime_status)}\n"
|
| 193 |
+
f"Execution logs: {json.dumps(observation.execution_logs)}\n"
|
| 194 |
+
f"Output schema: {json.dumps(observation.output_schema)}\n"
|
| 195 |
+
f"Feedback: {observation.feedback or 'none'}\n"
|
| 196 |
+
f"Last action error: {observation.last_action_error or 'null'}"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def build_turn_prompt(
|
| 201 |
+
observation: DeveloperControlRoomObservation,
|
| 202 |
+
transcript: list[dict[str, Any]],
|
| 203 |
+
) -> str:
|
| 204 |
+
return (
|
| 205 |
+
"Current observation:\n"
|
| 206 |
+
f"{format_observation(observation)}\n\n"
|
| 207 |
+
"Recent action history:\n"
|
| 208 |
+
f"{format_history(transcript)}\n\n"
|
| 209 |
+
"Choose exactly one next JSON action."
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def format_action_text(action: DeveloperControlRoomAction) -> str:
|
| 214 |
+
payload = action.parameters.model_dump(exclude_none=True)
|
| 215 |
+
if not payload:
|
| 216 |
+
return f"{action.action_type}()"
|
| 217 |
+
parts = [f"{key}={payload[key]!r}" for key in sorted(payload)]
|
| 218 |
+
return f"{action.action_type}({','.join(parts)})"
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def fetch_grader_result(base_url: str) -> dict[str, Any]:
|
| 222 |
+
response = requests.get(f"{base_url.rstrip('/')}/grader", timeout=20)
|
| 223 |
+
response.raise_for_status()
|
| 224 |
+
payload = response.json()
|
| 225 |
+
return {
|
| 226 |
+
"total": float(payload.get("total", 0.0)),
|
| 227 |
+
"solved": bool(payload.get("solved", False)),
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
async def run_episode_async(
|
| 232 |
+
base_url: str,
|
| 233 |
+
sample: EpisodeSample,
|
| 234 |
+
max_turns: int,
|
| 235 |
+
policy: Callable[[DeveloperControlRoomObservation, list[dict[str, Any]]], dict[str, Any]],
|
| 236 |
+
) -> EpisodeMetrics:
|
| 237 |
+
env = DeveloperControlRoomEnv(base_url=base_url)
|
| 238 |
+
await env.connect()
|
| 239 |
+
transcript: list[dict[str, Any]] = []
|
| 240 |
+
rewards: list[float] = []
|
| 241 |
+
prompt_ids: list[int] = []
|
| 242 |
+
completion_ids: list[int] = []
|
| 243 |
+
logprobs: list[float] = []
|
| 244 |
+
try:
|
| 245 |
+
result = await env.reset(
|
| 246 |
+
task_id=sample.task_id,
|
| 247 |
+
scenario_index=sample.scenario_index,
|
| 248 |
+
seed=sample.seed,
|
| 249 |
+
)
|
| 250 |
+
observation = result.observation
|
| 251 |
+
for _ in range(max_turns):
|
| 252 |
+
if result.done:
|
| 253 |
+
break
|
| 254 |
+
action_payload = policy(observation, transcript)
|
| 255 |
+
action = coerce_action(action_payload.get("action"))
|
| 256 |
+
metadata = action_payload.get("metadata", {})
|
| 257 |
+
prompt_ids.extend(metadata.get("prompt_ids", []))
|
| 258 |
+
completion_ids.extend(metadata.get("completion_ids", []))
|
| 259 |
+
logprobs.extend(metadata.get("logprobs", []))
|
| 260 |
+
|
| 261 |
+
result = await env.step(action)
|
| 262 |
+
observation = result.observation
|
| 263 |
+
reward = float(result.reward or 0.0)
|
| 264 |
+
rewards.append(reward)
|
| 265 |
+
transcript.append(
|
| 266 |
+
{
|
| 267 |
+
"action_text": format_action_text(action),
|
| 268 |
+
"reward": reward,
|
| 269 |
+
"feedback": observation.feedback,
|
| 270 |
+
"error": observation.last_action_error,
|
| 271 |
+
"raw_model_text": metadata.get("text", ""),
|
| 272 |
+
}
|
| 273 |
+
)
|
| 274 |
+
if result.done:
|
| 275 |
+
break
|
| 276 |
+
|
| 277 |
+
grader = fetch_grader_result(base_url)
|
| 278 |
+
return EpisodeMetrics(
|
| 279 |
+
task_id=sample.task_id,
|
| 280 |
+
scenario_id=observation.scenario_id,
|
| 281 |
+
rewards=rewards,
|
| 282 |
+
total_reward=sum(rewards),
|
| 283 |
+
score=float(grader["total"]),
|
| 284 |
+
solved=bool(grader["solved"]),
|
| 285 |
+
steps=len(rewards),
|
| 286 |
+
transcript=transcript,
|
| 287 |
+
prompt_ids=prompt_ids,
|
| 288 |
+
completion_ids=completion_ids,
|
| 289 |
+
logprobs=logprobs,
|
| 290 |
+
)
|
| 291 |
+
finally:
|
| 292 |
+
await env.close()
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def run_episode(
|
| 296 |
+
base_url: str,
|
| 297 |
+
sample: EpisodeSample,
|
| 298 |
+
max_turns: int,
|
| 299 |
+
policy: Callable[[DeveloperControlRoomObservation, list[dict[str, Any]]], dict[str, Any]],
|
| 300 |
+
) -> EpisodeMetrics:
|
| 301 |
+
return asyncio.run(run_episode_async(base_url, sample, max_turns, policy))
|
uv.lock
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|