AzraelH commited on
Commit
1ed9b39
·
1 Parent(s): 926a979
Files changed (1) hide show
  1. inference.py +106 -7
inference.py CHANGED
@@ -2,7 +2,12 @@ import asyncio
2
  import json
3
  import math
4
  import os
 
 
 
5
  import textwrap
 
 
6
  from typing import Any
7
 
8
  from openai import OpenAI
@@ -19,6 +24,10 @@ BENCHMARK = os.getenv("BENCHMARK", "openenv")
19
  MAX_STEPS = int(os.getenv("MAX_STEPS", "32"))
20
  TEMPERATURE = float(os.getenv("TEMPERATURE", "0.1"))
21
  MAX_TOKENS = int(os.getenv("MAX_TOKENS", "120"))
 
 
 
 
22
 
23
  SYSTEM_PROMPT = textwrap.dedent(
24
  """
@@ -94,6 +103,13 @@ def log_error(stage: str, error: Exception) -> None:
94
  )
95
 
96
 
 
 
 
 
 
 
 
97
  def estimate_max_flow_score(timeline: list[int]) -> float:
98
  slot_count = len(timeline)
99
  if slot_count <= 0:
@@ -213,19 +229,100 @@ def get_model_action(
213
  return choose_fallback_action(observation)
214
 
215
 
216
- async def create_env() -> GenericEnvClient:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  if OPENENV_BASE_URL:
218
- env = GenericEnvClient(base_url=OPENENV_BASE_URL)
219
- await env.connect()
220
- return env
 
 
 
 
 
 
 
 
221
 
222
- image_name = _require_env("LOCAL_IMAGE_NAME", LOCAL_IMAGE_NAME)
223
- return await GenericEnvClient.from_docker_image(image_name)
 
224
 
225
 
226
  async def main() -> None:
227
  client: OpenAI | None = None
228
  env = None
 
229
  rewards: list[float] = []
230
  history: list[str] = []
231
  steps_taken = 0
@@ -241,7 +338,8 @@ async def main() -> None:
241
  else:
242
  log_error("startup", RuntimeError("Missing HF_TOKEN; using fallback policy"))
243
 
244
- env = await create_env()
 
245
  result = await env.reset()
246
  observation = dict(result.observation)
247
 
@@ -287,6 +385,7 @@ async def main() -> None:
287
  await env.close()
288
  except Exception:
289
  pass
 
290
  log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
291
 
292
 
 
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
+ from pathlib import Path
11
  from typing import Any
12
 
13
  from openai import OpenAI
 
24
  MAX_STEPS = int(os.getenv("MAX_STEPS", "32"))
25
  TEMPERATURE = float(os.getenv("TEMPERATURE", "0.1"))
26
  MAX_TOKENS = int(os.getenv("MAX_TOKENS", "120"))
27
+ LOCAL_SERVER_HOST = os.getenv("LOCAL_SERVER_HOST", "127.0.0.1")
28
+ LOCAL_SERVER_STARTUP_TIMEOUT = float(os.getenv("LOCAL_SERVER_STARTUP_TIMEOUT", "15"))
29
+
30
+ _LOCAL_SERVER_PROCESS: subprocess.Popen[str] | None = None
31
 
32
  SYSTEM_PROMPT = textwrap.dedent(
33
  """
 
103
  )
104
 
105
 
106
+ def log_info(stage: str, message: str) -> None:
107
+ print(
108
+ f"[INFO] stage={_sanitize_field(stage)} message={_sanitize_field(message)}",
109
+ flush=True,
110
+ )
111
+
112
+
113
  def estimate_max_flow_score(timeline: list[int]) -> float:
114
  slot_count = len(timeline)
115
  if slot_count <= 0:
 
229
  return choose_fallback_action(observation)
230
 
231
 
232
+ def _reserve_local_port(host: str) -> int:
233
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
234
+ sock.bind((host, 0))
235
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
236
+ return int(sock.getsockname()[1])
237
+
238
+
239
+ def _server_script_path() -> Path:
240
+ return Path(__file__).resolve().parent / "server" / "app.py"
241
+
242
+
243
+ async def _connect_env(base_url: str) -> GenericEnvClient:
244
+ env = GenericEnvClient(base_url=base_url)
245
+ await env.connect()
246
+ return env
247
+
248
+
249
+ def _start_local_server() -> str:
250
+ global _LOCAL_SERVER_PROCESS
251
+
252
+ if _LOCAL_SERVER_PROCESS is not None:
253
+ raise RuntimeError("Local server process is already running")
254
+
255
+ host = LOCAL_SERVER_HOST
256
+ port = _reserve_local_port(host)
257
+ script_path = _server_script_path()
258
+ process = subprocess.Popen(
259
+ [sys.executable, str(script_path), "--host", host, "--port", str(port)],
260
+ cwd=str(Path(__file__).resolve().parent),
261
+ stdout=subprocess.DEVNULL,
262
+ stderr=subprocess.DEVNULL,
263
+ text=True,
264
+ )
265
+ _LOCAL_SERVER_PROCESS = process
266
+
267
+ deadline = time.monotonic() + LOCAL_SERVER_STARTUP_TIMEOUT
268
+ health_url = f"http://{host}:{port}/health"
269
+ base_url = f"http://{host}:{port}"
270
+
271
+ while time.monotonic() < deadline:
272
+ if process.poll() is not None:
273
+ raise RuntimeError("Local server process exited before becoming healthy")
274
+ try:
275
+ import urllib.request
276
+
277
+ with urllib.request.urlopen(health_url, timeout=1.0) as response:
278
+ if response.status == 200:
279
+ return base_url
280
+ except Exception:
281
+ time.sleep(0.25)
282
+
283
+ raise RuntimeError("Timed out waiting for the local server to become healthy")
284
+
285
+
286
+ def stop_local_server() -> None:
287
+ global _LOCAL_SERVER_PROCESS
288
+
289
+ process = _LOCAL_SERVER_PROCESS
290
+ _LOCAL_SERVER_PROCESS = None
291
+ if process is None:
292
+ return
293
+
294
+ if process.poll() is None:
295
+ process.terminate()
296
+ try:
297
+ process.wait(timeout=5)
298
+ except subprocess.TimeoutExpired:
299
+ process.kill()
300
+ process.wait(timeout=5)
301
+
302
+
303
+ async def create_env() -> tuple[GenericEnvClient, str]:
304
  if OPENENV_BASE_URL:
305
+ return await _connect_env(OPENENV_BASE_URL), "remote"
306
+
307
+ if LOCAL_IMAGE_NAME:
308
+ try:
309
+ return await GenericEnvClient.from_docker_image(LOCAL_IMAGE_NAME), "docker"
310
+ except Exception as error:
311
+ log_error("docker", error)
312
+ log_info("docker", "Falling back to bundled local server")
313
+
314
+ else:
315
+ log_info("startup", "LOCAL_IMAGE_NAME not set; using bundled local server")
316
 
317
+ local_base_url = _start_local_server()
318
+ log_info("local-server", f"Started bundled env server at {local_base_url}")
319
+ return await _connect_env(local_base_url), "local-server"
320
 
321
 
322
  async def main() -> None:
323
  client: OpenAI | None = None
324
  env = None
325
+ env_mode = "unknown"
326
  rewards: list[float] = []
327
  history: list[str] = []
328
  steps_taken = 0
 
338
  else:
339
  log_error("startup", RuntimeError("Missing HF_TOKEN; using fallback policy"))
340
 
341
+ env, env_mode = await create_env()
342
+ log_info("env", f"Connected via {env_mode}")
343
  result = await env.reset()
344
  observation = dict(result.observation)
345
 
 
385
  await env.close()
386
  except Exception:
387
  pass
388
+ stop_local_server()
389
  log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
390
 
391