Spaces:
Sleeping
Sleeping
- inference.py +77 -238
inference.py
CHANGED
|
@@ -2,14 +2,8 @@ import asyncio
|
|
| 2 |
import json
|
| 3 |
import math
|
| 4 |
import os
|
| 5 |
-
import socket
|
| 6 |
-
import subprocess
|
| 7 |
-
import sys
|
| 8 |
import textwrap
|
| 9 |
-
import time
|
| 10 |
-
import traceback
|
| 11 |
from dataclasses import dataclass
|
| 12 |
-
from pathlib import Path
|
| 13 |
from typing import Any
|
| 14 |
|
| 15 |
from openai import OpenAI
|
|
@@ -31,10 +25,6 @@ BENCHMARK = os.getenv("BENCHMARK", "openenv")
|
|
| 31 |
MAX_STEPS = int(os.getenv("MAX_STEPS", "32"))
|
| 32 |
TEMPERATURE = float(os.getenv("TEMPERATURE", "0.1"))
|
| 33 |
MAX_TOKENS = int(os.getenv("MAX_TOKENS", "120"))
|
| 34 |
-
LOCAL_SERVER_HOST = os.getenv("LOCAL_SERVER_HOST", "127.0.0.1")
|
| 35 |
-
LOCAL_SERVER_STARTUP_TIMEOUT = float(os.getenv("LOCAL_SERVER_STARTUP_TIMEOUT", "15"))
|
| 36 |
-
|
| 37 |
-
_LOCAL_SERVER_PROCESS: subprocess.Popen[str] | None = None
|
| 38 |
|
| 39 |
SYSTEM_PROMPT = textwrap.dedent(
|
| 40 |
"""
|
|
@@ -62,90 +52,6 @@ SYSTEM_PROMPT = textwrap.dedent(
|
|
| 62 |
).strip()
|
| 63 |
|
| 64 |
|
| 65 |
-
def _require_env(name: str, value: str | None) -> str:
|
| 66 |
-
if value:
|
| 67 |
-
return value
|
| 68 |
-
raise RuntimeError(f"Missing required environment variable: {name}")
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def _sanitize_field(value: Any) -> str:
|
| 72 |
-
text = str(value)
|
| 73 |
-
return text.replace("\r", " ").replace("\n", " ").strip()
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def log_start(task: str, env: str, model: str) -> None:
|
| 77 |
-
print(
|
| 78 |
-
f"[START] task={_sanitize_field(task)} env={_sanitize_field(env)} model={_sanitize_field(model)}",
|
| 79 |
-
flush=True,
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def log_step(
|
| 84 |
-
step: int,
|
| 85 |
-
action: str,
|
| 86 |
-
reward: float,
|
| 87 |
-
done: bool,
|
| 88 |
-
error: str | None,
|
| 89 |
-
) -> None:
|
| 90 |
-
error_text = "null" if error in (None, "") else _sanitize_field(error)
|
| 91 |
-
print(
|
| 92 |
-
f"[STEP] step={step} action={_sanitize_field(action)} reward={reward:.2f} "
|
| 93 |
-
f"done={str(done).lower()} error={error_text}",
|
| 94 |
-
flush=True,
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def log_end(success: bool, steps: int, score: float, rewards: list[float]) -> None:
|
| 99 |
-
rewards_text = ",".join(f"{reward:.2f}" for reward in rewards)
|
| 100 |
-
print(
|
| 101 |
-
f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_text}",
|
| 102 |
-
flush=True,
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
def log_error(stage: str, error: Exception) -> None:
|
| 107 |
-
print(
|
| 108 |
-
f"[ERROR] stage={_sanitize_field(stage)} error={_sanitize_field(error)}",
|
| 109 |
-
flush=True,
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def log_traceback(stage: str, error: BaseException) -> None:
|
| 114 |
-
traceback_text = "".join(
|
| 115 |
-
traceback.format_exception(type(error), error, error.__traceback__)
|
| 116 |
-
).rstrip()
|
| 117 |
-
print(f"[TRACEBACK] stage={_sanitize_field(stage)}", flush=True)
|
| 118 |
-
print(traceback_text, flush=True)
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
def log_info(stage: str, message: str) -> None:
|
| 122 |
-
print(
|
| 123 |
-
f"[INFO] stage={_sanitize_field(stage)} message={_sanitize_field(message)}",
|
| 124 |
-
flush=True,
|
| 125 |
-
)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
def log_env_status() -> None:
|
| 129 |
-
env_fields = {
|
| 130 |
-
"API_BASE_URL": API_BASE_URL,
|
| 131 |
-
"MODEL_NAME": MODEL_NAME,
|
| 132 |
-
"HF_TOKEN": "<set>" if HF_TOKEN else "<missing>",
|
| 133 |
-
"LOCAL_IMAGE_NAME": LOCAL_IMAGE_NAME or "<missing>",
|
| 134 |
-
"OPENENV_BASE_URL": OPENENV_BASE_URL or "<missing>",
|
| 135 |
-
"TASK_NAME": TASK_NAME,
|
| 136 |
-
"BENCHMARK": BENCHMARK,
|
| 137 |
-
"MAX_STEPS": MAX_STEPS,
|
| 138 |
-
"TEMPERATURE": TEMPERATURE,
|
| 139 |
-
"MAX_TOKENS": MAX_TOKENS,
|
| 140 |
-
"LOCAL_SERVER_HOST": LOCAL_SERVER_HOST,
|
| 141 |
-
"LOCAL_SERVER_STARTUP_TIMEOUT": LOCAL_SERVER_STARTUP_TIMEOUT,
|
| 142 |
-
}
|
| 143 |
-
formatted = ", ".join(
|
| 144 |
-
f"{name}={_sanitize_field(value)}" for name, value in env_fields.items()
|
| 145 |
-
)
|
| 146 |
-
log_info("env", formatted)
|
| 147 |
-
|
| 148 |
-
|
| 149 |
@dataclass
|
| 150 |
class _EnvResult:
|
| 151 |
observation: dict[str, Any]
|
|
@@ -182,19 +88,51 @@ class _InProcessEnvClient:
|
|
| 182 |
return None
|
| 183 |
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
def estimate_max_flow_score(timeline: list[int]) -> float:
|
| 186 |
slot_count = len(timeline)
|
| 187 |
if slot_count <= 0:
|
| 188 |
return 1.0
|
| 189 |
-
|
| 190 |
-
return max(1.0, hours * hours)
|
| 191 |
|
| 192 |
|
| 193 |
def normalize_score(total_reward: float, observation: dict[str, Any]) -> float:
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
normalized = total_reward / max_score
|
| 197 |
-
return min(1.0, max(0.0, normalized))
|
| 198 |
|
| 199 |
|
| 200 |
def first_future_slot(observation: dict[str, Any], kind: int) -> int | None:
|
|
@@ -206,17 +144,12 @@ def first_future_slot(observation: dict[str, Any], kind: int) -> int | None:
|
|
| 206 |
return None
|
| 207 |
|
| 208 |
|
| 209 |
-
def first_future_empty_slot(observation: dict[str, Any]) -> int | None:
|
| 210 |
-
return first_future_slot(observation, 0)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
def build_user_prompt(
|
| 214 |
step: int,
|
| 215 |
observation: dict[str, Any],
|
| 216 |
rewards: list[float],
|
| 217 |
history: list[str],
|
| 218 |
) -> str:
|
| 219 |
-
timeline = observation.get("timeline") or []
|
| 220 |
metadata = observation.get("metadata") or {}
|
| 221 |
return textwrap.dedent(
|
| 222 |
f"""
|
|
@@ -229,10 +162,10 @@ def build_user_prompt(
|
|
| 229 |
social_debt={float(observation.get("social_debt", 0.0)):.2f}
|
| 230 |
calendar_churn={int(observation.get("calendar_churn", 0))}
|
| 231 |
recovery_state={int(observation.get("recovery_state", 0))}
|
| 232 |
-
timeline={timeline}
|
| 233 |
task_buffer={json.dumps(observation.get("task_buffer", []), separators=(",", ":"))}
|
| 234 |
last_rewards={",".join(f"{reward:.2f}" for reward in rewards[-5:]) or "none"}
|
| 235 |
-
recent_history={json.dumps(history[-5:])}
|
| 236 |
last_metadata={json.dumps(metadata, separators=(",", ":"))}
|
| 237 |
Choose the single next action.
|
| 238 |
"""
|
|
@@ -246,12 +179,12 @@ def choose_fallback_action(observation: dict[str, Any]) -> dict[str, int]:
|
|
| 246 |
if distraction_risk >= 0.2 and not mute_comms:
|
| 247 |
return {"target_slot": current_slot, "operation": 3}
|
| 248 |
|
| 249 |
-
empty_slot =
|
| 250 |
if empty_slot is not None and observation.get("task_buffer"):
|
| 251 |
return {"target_slot": empty_slot, "operation": 1}
|
| 252 |
|
| 253 |
meeting_slot = first_future_slot(observation, 2)
|
| 254 |
-
if meeting_slot is not None
|
| 255 |
return {"target_slot": meeting_slot, "operation": 2}
|
| 256 |
|
| 257 |
return {"target_slot": current_slot, "operation": 0}
|
|
@@ -259,8 +192,8 @@ def choose_fallback_action(observation: dict[str, Any]) -> dict[str, int]:
|
|
| 259 |
|
| 260 |
def coerce_action(raw_text: str, observation: dict[str, Any]) -> dict[str, int]:
|
| 261 |
timeline = observation.get("timeline") or []
|
| 262 |
-
max_slot = max(0, len(timeline) - 1)
|
| 263 |
fallback = choose_fallback_action(observation)
|
|
|
|
| 264 |
try:
|
| 265 |
data = json.loads(raw_text)
|
| 266 |
target_slot = int(data["target_slot"])
|
|
@@ -270,20 +203,16 @@ def coerce_action(raw_text: str, observation: dict[str, Any]) -> dict[str, int]:
|
|
| 270 |
|
| 271 |
if operation not in {0, 1, 2, 3}:
|
| 272 |
return fallback
|
| 273 |
-
target_slot
|
| 274 |
-
return {"target_slot": target_slot, "operation": operation}
|
| 275 |
|
| 276 |
|
| 277 |
def get_model_action(
|
| 278 |
-
client: OpenAI
|
| 279 |
step: int,
|
| 280 |
observation: dict[str, Any],
|
| 281 |
rewards: list[float],
|
| 282 |
history: list[str],
|
| 283 |
) -> dict[str, int]:
|
| 284 |
-
if client is None:
|
| 285 |
-
return choose_fallback_action(observation)
|
| 286 |
-
|
| 287 |
user_prompt = build_user_prompt(step, observation, rewards, history)
|
| 288 |
try:
|
| 289 |
completion = client.chat.completions.create(
|
|
@@ -301,101 +230,22 @@ def get_model_action(
|
|
| 301 |
return choose_fallback_action(observation)
|
| 302 |
|
| 303 |
|
| 304 |
-
def
|
| 305 |
-
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
| 306 |
-
sock.bind((host, 0))
|
| 307 |
-
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 308 |
-
return int(sock.getsockname()[1])
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
def _server_script_path() -> Path:
|
| 312 |
-
return Path(__file__).resolve().parent / "server" / "app.py"
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
async def _connect_env(base_url: str) -> GenericEnvClient:
|
| 316 |
-
env = GenericEnvClient(base_url=base_url)
|
| 317 |
-
await env.connect()
|
| 318 |
-
return env
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
def _start_local_server() -> str:
|
| 322 |
-
global _LOCAL_SERVER_PROCESS
|
| 323 |
-
|
| 324 |
-
if _LOCAL_SERVER_PROCESS is not None:
|
| 325 |
-
raise RuntimeError("Local server process is already running")
|
| 326 |
-
|
| 327 |
-
host = LOCAL_SERVER_HOST
|
| 328 |
-
port = _reserve_local_port(host)
|
| 329 |
-
script_path = _server_script_path()
|
| 330 |
-
process = subprocess.Popen(
|
| 331 |
-
[sys.executable, str(script_path), "--host", host, "--port", str(port)],
|
| 332 |
-
cwd=str(Path(__file__).resolve().parent),
|
| 333 |
-
stdout=subprocess.DEVNULL,
|
| 334 |
-
stderr=subprocess.DEVNULL,
|
| 335 |
-
text=True,
|
| 336 |
-
)
|
| 337 |
-
_LOCAL_SERVER_PROCESS = process
|
| 338 |
-
|
| 339 |
-
deadline = time.monotonic() + LOCAL_SERVER_STARTUP_TIMEOUT
|
| 340 |
-
health_url = f"http://{host}:{port}/health"
|
| 341 |
-
base_url = f"http://{host}:{port}"
|
| 342 |
-
|
| 343 |
-
while time.monotonic() < deadline:
|
| 344 |
-
if process.poll() is not None:
|
| 345 |
-
raise RuntimeError("Local server process exited before becoming healthy")
|
| 346 |
-
try:
|
| 347 |
-
import urllib.request
|
| 348 |
-
|
| 349 |
-
with urllib.request.urlopen(health_url, timeout=1.0) as response:
|
| 350 |
-
if response.status == 200:
|
| 351 |
-
return base_url
|
| 352 |
-
except Exception:
|
| 353 |
-
time.sleep(0.25)
|
| 354 |
-
|
| 355 |
-
raise RuntimeError("Timed out waiting for the local server to become healthy")
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
def stop_local_server() -> None:
|
| 359 |
-
global _LOCAL_SERVER_PROCESS
|
| 360 |
-
|
| 361 |
-
process = _LOCAL_SERVER_PROCESS
|
| 362 |
-
_LOCAL_SERVER_PROCESS = None
|
| 363 |
-
if process is None:
|
| 364 |
-
return
|
| 365 |
-
|
| 366 |
-
if process.poll() is None:
|
| 367 |
-
process.terminate()
|
| 368 |
-
try:
|
| 369 |
-
process.wait(timeout=5)
|
| 370 |
-
except subprocess.TimeoutExpired:
|
| 371 |
-
process.kill()
|
| 372 |
-
process.wait(timeout=5)
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
async def create_env() -> tuple[Any, str]:
|
| 376 |
if OPENENV_BASE_URL:
|
| 377 |
-
|
|
|
|
|
|
|
| 378 |
|
| 379 |
if LOCAL_IMAGE_NAME:
|
| 380 |
-
|
| 381 |
-
return await GenericEnvClient.from_docker_image(LOCAL_IMAGE_NAME), "docker"
|
| 382 |
-
except Exception as error:
|
| 383 |
-
log_error("docker", error)
|
| 384 |
-
log_info("docker", "Falling back to bundled local server")
|
| 385 |
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
local_env = _InProcessEnvClient()
|
| 390 |
-
await local_env.connect()
|
| 391 |
-
log_info("env", "Using in-process bundled environment")
|
| 392 |
-
return local_env, "in-process"
|
| 393 |
|
| 394 |
|
| 395 |
async def main() -> None:
|
| 396 |
-
client: OpenAI | None = None
|
| 397 |
env = None
|
| 398 |
-
env_mode = "unknown"
|
| 399 |
rewards: list[float] = []
|
| 400 |
history: list[str] = []
|
| 401 |
steps_taken = 0
|
|
@@ -404,16 +254,13 @@ async def main() -> None:
|
|
| 404 |
observation: dict[str, Any] = {}
|
| 405 |
|
| 406 |
log_start(TASK_NAME, BENCHMARK, MODEL_NAME)
|
| 407 |
-
log_env_status()
|
| 408 |
|
| 409 |
try:
|
| 410 |
-
if HF_TOKEN:
|
| 411 |
-
|
| 412 |
-
else:
|
| 413 |
-
log_error("startup", RuntimeError("Missing HF_TOKEN; using fallback policy"))
|
| 414 |
|
| 415 |
-
|
| 416 |
-
|
| 417 |
result = await env.reset()
|
| 418 |
observation = dict(result.observation)
|
| 419 |
|
|
@@ -422,52 +269,44 @@ async def main() -> None:
|
|
| 422 |
break
|
| 423 |
|
| 424 |
action = get_model_action(client, step, observation, rewards, history)
|
| 425 |
-
|
| 426 |
-
|
| 427 |
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
|
| 433 |
rewards.append(reward)
|
| 434 |
steps_taken = step
|
| 435 |
-
|
| 436 |
-
action_text = (
|
| 437 |
-
f"target_slot={int(action['target_slot'])},operation={int(action['operation'])}"
|
| 438 |
-
)
|
| 439 |
-
log_step(step, action_text, reward, done, error)
|
| 440 |
-
|
| 441 |
history.append(
|
| 442 |
-
f"step={step} action={action_text} reward={reward:.2f} "
|
| 443 |
-
f"flow={float(observation.get('flow_score', 0.0)):.2f} "
|
| 444 |
-
f"debt={float(observation.get('social_debt', 0.0)):.2f}"
|
| 445 |
)
|
| 446 |
|
| 447 |
if done:
|
| 448 |
break
|
| 449 |
|
| 450 |
-
|
| 451 |
-
score = normalize_score(total_reward, observation)
|
| 452 |
-
score = round(score, 2)
|
| 453 |
success = score > 0.0
|
| 454 |
-
except Exception
|
| 455 |
-
|
| 456 |
-
|
| 457 |
finally:
|
| 458 |
if env is not None:
|
| 459 |
try:
|
| 460 |
await env.close()
|
| 461 |
except Exception:
|
| 462 |
pass
|
| 463 |
-
stop_local_server()
|
| 464 |
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
|
| 465 |
|
| 466 |
|
| 467 |
if __name__ == "__main__":
|
| 468 |
-
|
| 469 |
-
asyncio.run(main())
|
| 470 |
-
except BaseException as error:
|
| 471 |
-
log_error("fatal", error)
|
| 472 |
-
log_traceback("fatal", error)
|
| 473 |
-
log_end(success=False, steps=0, score=0.0, rewards=[])
|
|
|
|
| 2 |
import json
|
| 3 |
import math
|
| 4 |
import os
|
|
|
|
|
|
|
|
|
|
| 5 |
import textwrap
|
|
|
|
|
|
|
| 6 |
from dataclasses import dataclass
|
|
|
|
| 7 |
from typing import Any
|
| 8 |
|
| 9 |
from openai import OpenAI
|
|
|
|
| 25 |
MAX_STEPS = int(os.getenv("MAX_STEPS", "32"))
|
| 26 |
TEMPERATURE = float(os.getenv("TEMPERATURE", "0.1"))
|
| 27 |
MAX_TOKENS = int(os.getenv("MAX_TOKENS", "120"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
SYSTEM_PROMPT = textwrap.dedent(
|
| 30 |
"""
|
|
|
|
| 52 |
).strip()
|
| 53 |
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
@dataclass
|
| 56 |
class _EnvResult:
|
| 57 |
observation: dict[str, Any]
|
|
|
|
| 88 |
return None
|
| 89 |
|
| 90 |
|
| 91 |
+
def _sanitize_field(value: Any) -> str:
|
| 92 |
+
return str(value).replace("\r", " ").replace("\n", " ").strip()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _format_error(error: str | None) -> str:
|
| 96 |
+
return "null" if error in (None, "") else _sanitize_field(error)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _action_to_text(action: dict[str, int]) -> str:
|
| 100 |
+
return f'{{"target_slot":{int(action["target_slot"])},"operation":{int(action["operation"])}}}'
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def log_start(task: str, env: str, model: str) -> None:
|
| 104 |
+
print(
|
| 105 |
+
f"[START] task={_sanitize_field(task)} env={_sanitize_field(env)} model={_sanitize_field(model)}",
|
| 106 |
+
flush=True,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def log_step(step: int, action: str, reward: float, done: bool, error: str | None) -> None:
|
| 111 |
+
print(
|
| 112 |
+
f"[STEP] step={step} action={_sanitize_field(action)} reward={reward:.2f} "
|
| 113 |
+
f"done={str(done).lower()} error={_format_error(error)}",
|
| 114 |
+
flush=True,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def log_end(success: bool, steps: int, score: float, rewards: list[float]) -> None:
|
| 119 |
+
rewards_text = ",".join(f"{reward:.2f}" for reward in rewards)
|
| 120 |
+
print(
|
| 121 |
+
f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_text}",
|
| 122 |
+
flush=True,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
def estimate_max_flow_score(timeline: list[int]) -> float:
|
| 127 |
slot_count = len(timeline)
|
| 128 |
if slot_count <= 0:
|
| 129 |
return 1.0
|
| 130 |
+
return max(1.0, (slot_count * 0.5) ** 2)
|
|
|
|
| 131 |
|
| 132 |
|
| 133 |
def normalize_score(total_reward: float, observation: dict[str, Any]) -> float:
|
| 134 |
+
max_score = estimate_max_flow_score(observation.get("timeline") or [])
|
| 135 |
+
return min(1.0, max(0.0, total_reward / max_score))
|
|
|
|
|
|
|
| 136 |
|
| 137 |
|
| 138 |
def first_future_slot(observation: dict[str, Any], kind: int) -> int | None:
|
|
|
|
| 144 |
return None
|
| 145 |
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
def build_user_prompt(
|
| 148 |
step: int,
|
| 149 |
observation: dict[str, Any],
|
| 150 |
rewards: list[float],
|
| 151 |
history: list[str],
|
| 152 |
) -> str:
|
|
|
|
| 153 |
metadata = observation.get("metadata") or {}
|
| 154 |
return textwrap.dedent(
|
| 155 |
f"""
|
|
|
|
| 162 |
social_debt={float(observation.get("social_debt", 0.0)):.2f}
|
| 163 |
calendar_churn={int(observation.get("calendar_churn", 0))}
|
| 164 |
recovery_state={int(observation.get("recovery_state", 0))}
|
| 165 |
+
timeline={json.dumps(observation.get("timeline", []), separators=(",", ":"))}
|
| 166 |
task_buffer={json.dumps(observation.get("task_buffer", []), separators=(",", ":"))}
|
| 167 |
last_rewards={",".join(f"{reward:.2f}" for reward in rewards[-5:]) or "none"}
|
| 168 |
+
recent_history={json.dumps(history[-5:], separators=(",", ":"))}
|
| 169 |
last_metadata={json.dumps(metadata, separators=(",", ":"))}
|
| 170 |
Choose the single next action.
|
| 171 |
"""
|
|
|
|
| 179 |
if distraction_risk >= 0.2 and not mute_comms:
|
| 180 |
return {"target_slot": current_slot, "operation": 3}
|
| 181 |
|
| 182 |
+
empty_slot = first_future_slot(observation, 0)
|
| 183 |
if empty_slot is not None and observation.get("task_buffer"):
|
| 184 |
return {"target_slot": empty_slot, "operation": 1}
|
| 185 |
|
| 186 |
meeting_slot = first_future_slot(observation, 2)
|
| 187 |
+
if meeting_slot is not None:
|
| 188 |
return {"target_slot": meeting_slot, "operation": 2}
|
| 189 |
|
| 190 |
return {"target_slot": current_slot, "operation": 0}
|
|
|
|
| 192 |
|
| 193 |
def coerce_action(raw_text: str, observation: dict[str, Any]) -> dict[str, int]:
|
| 194 |
timeline = observation.get("timeline") or []
|
|
|
|
| 195 |
fallback = choose_fallback_action(observation)
|
| 196 |
+
max_slot = max(0, len(timeline) - 1)
|
| 197 |
try:
|
| 198 |
data = json.loads(raw_text)
|
| 199 |
target_slot = int(data["target_slot"])
|
|
|
|
| 203 |
|
| 204 |
if operation not in {0, 1, 2, 3}:
|
| 205 |
return fallback
|
| 206 |
+
return {"target_slot": min(max(target_slot, 0), max_slot), "operation": operation}
|
|
|
|
| 207 |
|
| 208 |
|
| 209 |
def get_model_action(
|
| 210 |
+
client: OpenAI,
|
| 211 |
step: int,
|
| 212 |
observation: dict[str, Any],
|
| 213 |
rewards: list[float],
|
| 214 |
history: list[str],
|
| 215 |
) -> dict[str, int]:
|
|
|
|
|
|
|
|
|
|
| 216 |
user_prompt = build_user_prompt(step, observation, rewards, history)
|
| 217 |
try:
|
| 218 |
completion = client.chat.completions.create(
|
|
|
|
| 230 |
return choose_fallback_action(observation)
|
| 231 |
|
| 232 |
|
| 233 |
+
async def create_env() -> Any:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
if OPENENV_BASE_URL:
|
| 235 |
+
env = GenericEnvClient(base_url=OPENENV_BASE_URL)
|
| 236 |
+
await env.connect()
|
| 237 |
+
return env
|
| 238 |
|
| 239 |
if LOCAL_IMAGE_NAME:
|
| 240 |
+
return await GenericEnvClient.from_docker_image(LOCAL_IMAGE_NAME)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
+
env = _InProcessEnvClient()
|
| 243 |
+
await env.connect()
|
| 244 |
+
return env
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
|
| 247 |
async def main() -> None:
|
|
|
|
| 248 |
env = None
|
|
|
|
| 249 |
rewards: list[float] = []
|
| 250 |
history: list[str] = []
|
| 251 |
steps_taken = 0
|
|
|
|
| 254 |
observation: dict[str, Any] = {}
|
| 255 |
|
| 256 |
log_start(TASK_NAME, BENCHMARK, MODEL_NAME)
|
|
|
|
| 257 |
|
| 258 |
try:
|
| 259 |
+
if not HF_TOKEN:
|
| 260 |
+
raise RuntimeError("Missing required environment variable: HF_TOKEN")
|
|
|
|
|
|
|
| 261 |
|
| 262 |
+
client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
|
| 263 |
+
env = await create_env()
|
| 264 |
result = await env.reset()
|
| 265 |
observation = dict(result.observation)
|
| 266 |
|
|
|
|
| 269 |
break
|
| 270 |
|
| 271 |
action = get_model_action(client, step, observation, rewards, history)
|
| 272 |
+
action_text = _action_to_text(action)
|
| 273 |
+
step_error: str | None = None
|
| 274 |
|
| 275 |
+
try:
|
| 276 |
+
result = await env.step(action)
|
| 277 |
+
observation = dict(result.observation)
|
| 278 |
+
reward = float(result.reward or 0.0)
|
| 279 |
+
done = bool(result.done)
|
| 280 |
+
metadata = observation.get("metadata") or {}
|
| 281 |
+
step_error = metadata.get("last_action_error")
|
| 282 |
+
except Exception as exc:
|
| 283 |
+
reward = 0.0
|
| 284 |
+
done = True
|
| 285 |
+
step_error = str(exc)
|
| 286 |
|
| 287 |
rewards.append(reward)
|
| 288 |
steps_taken = step
|
| 289 |
+
log_step(step, action_text, reward, done, step_error)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
history.append(
|
| 291 |
+
f"step={step} action={action_text} reward={reward:.2f} error={_format_error(step_error)}"
|
|
|
|
|
|
|
| 292 |
)
|
| 293 |
|
| 294 |
if done:
|
| 295 |
break
|
| 296 |
|
| 297 |
+
score = round(normalize_score(math.fsum(rewards), observation), 2)
|
|
|
|
|
|
|
| 298 |
success = score > 0.0
|
| 299 |
+
except Exception:
|
| 300 |
+
success = False
|
| 301 |
+
score = 0.0
|
| 302 |
finally:
|
| 303 |
if env is not None:
|
| 304 |
try:
|
| 305 |
await env.close()
|
| 306 |
except Exception:
|
| 307 |
pass
|
|
|
|
| 308 |
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
|
| 309 |
|
| 310 |
|
| 311 |
if __name__ == "__main__":
|
| 312 |
+
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|