Spaces:
Sleeping
Sleeping
File size: 9,803 Bytes
c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c 6cbd2ef c47c81c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | """
CodeSensei — OpenEnv-Compatible Client.
Provides both sync and async clients that connect to the CodeDebug
environment server. Supports the standard OpenEnv patterns:
- CodeSenseiEnv.from_docker_image(image_name)
- await env.reset() -> StepResult
- await env.step(action) -> StepResult
- await env.close()
"""
from __future__ import annotations
import json
import asyncio
import subprocess
import time
import uuid
from dataclasses import dataclass
from typing import Optional, List
try:
import websockets
import websockets.sync.client as ws_sync
except ImportError:
websockets = None # type: ignore
ws_sync = None # type: ignore
try:
import aiohttp
except ImportError:
aiohttp = None # type: ignore
from env.models import CodeDebugAction, CodeDebugObservation, TestResult
# ---------------------------------------------------------------------------
# Result wrapper — matches OpenEnv pattern: result.observation, result.reward, result.done
# ---------------------------------------------------------------------------
@dataclass
class StepResult:
"""Wrapper returned by reset() and step() to match the OpenEnv pattern."""
observation: CodeDebugObservation
reward: float = 0.0
done: bool = False
# ---------------------------------------------------------------------------
# Async client — matches the sample inference script pattern
# ---------------------------------------------------------------------------
class CodeSenseiEnv:
"""Async OpenEnv-compatible client for the CodeDebug environment.
Usage (matches sample inference script):
env = await CodeSenseiEnv.from_docker_image(IMAGE_NAME)
result = await env.reset()
result = await env.step(CodeSenseiAction(proposed_fix="..."))
await env.close()
"""
def __init__(self, base_url: str):
self.base_url = base_url.rstrip("/")
self._session_id: str = ""
self._container_id: Optional[str] = None
@classmethod
async def from_docker_image(cls, image_name: Optional[str] = None) -> "CodeSenseiEnv":
"""Start the environment from a Docker image (OpenEnv standard).
If image_name is provided, starts a Docker container and connects.
If image_name is None, connects to localhost:7860 (for local dev).
"""
if image_name:
# Start Docker container
port = 7860
container_id = subprocess.check_output(
[
"docker", "run", "-d", "--rm",
"-p", f"{port}:{port}",
image_name,
],
text=True,
).strip()
# Wait for container to be ready
base_url = f"http://localhost:{port}"
env = cls(base_url)
env._container_id = container_id
# Poll health endpoint
for _ in range(60):
try:
if aiohttp:
async with aiohttp.ClientSession() as session:
async with session.get(f"{base_url}/health", timeout=aiohttp.ClientTimeout(total=2)) as resp:
if resp.status == 200:
return env
else:
import urllib.request
urllib.request.urlopen(f"{base_url}/health", timeout=2)
return env
except Exception:
await asyncio.sleep(1)
raise RuntimeError(f"Docker container {image_name} did not become healthy in 60s")
else:
# No image — connect to local server
return cls("http://localhost:7860")
async def reset(self) -> StepResult:
"""Start a new debugging episode."""
self._session_id = str(uuid.uuid4())
data = await self._post("/reset", {"session_id": self._session_id})
self._session_id = data.get("session_id", self._session_id)
obs = self._parse_observation(data)
return StepResult(observation=obs, reward=0.0, done=False)
async def step(self, action: CodeDebugAction) -> StepResult:
"""Submit a proposed code fix."""
data = await self._post("/step", {
"proposed_fix": action.proposed_fix,
"session_id": self._session_id,
})
obs = self._parse_observation(data)
return StepResult(observation=obs, reward=obs.reward, done=obs.done)
async def state(self) -> dict:
"""Get current episode state."""
return await self._get(f"/state?session_id={self._session_id}")
async def close(self) -> None:
"""Clean up: stop Docker container if we started one."""
if self._container_id:
try:
subprocess.run(
["docker", "stop", self._container_id],
capture_output=True, timeout=30,
)
except Exception:
pass
self._container_id = None
# --- HTTP helpers ---
async def _post(self, path: str, payload: dict) -> dict:
url = f"{self.base_url}{path}"
if aiohttp:
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, timeout=aiohttp.ClientTimeout(total=30)) as resp:
return await resp.json()
else:
import urllib.request
req = urllib.request.Request(
url,
data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
async def _get(self, path: str) -> dict:
url = f"{self.base_url}{path}"
if aiohttp:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=30)) as resp:
return await resp.json()
else:
import urllib.request
with urllib.request.urlopen(url, timeout=30) as resp:
return json.loads(resp.read().decode())
# --- Parse ---
@staticmethod
def _parse_observation(data: dict) -> CodeDebugObservation:
test_results = [
TestResult(
test_name=tr.get("test_name", ""),
passed=tr.get("passed", False),
error_message=tr.get("error_message", ""),
)
for tr in data.get("test_results", [])
]
return CodeDebugObservation(
buggy_code=data.get("buggy_code", ""),
current_code=data.get("current_code", ""),
error_output=data.get("error_output", ""),
test_results=test_results,
tests_passed=data.get("tests_passed", 0),
tests_total=data.get("tests_total", 0),
reward=data.get("reward", 0.0),
done=data.get("done", False),
attempt=data.get("attempt", 0),
max_attempts=data.get("max_attempts", 6),
feedback=data.get("feedback", ""),
)
# ---------------------------------------------------------------------------
# Sync client (kept for backward compat / training)
# ---------------------------------------------------------------------------
class CodeDebugEnv:
"""Synchronous WebSocket client for the CodeDebug OpenEnv.
Usage:
env = CodeDebugEnv(base_url="wss://your-space.hf.space")
obs = env.reset()
obs = env.step("def add(a, b):\\n return a + b")
"""
def __init__(self, base_url: str):
self.base_url = self._to_ws_url(base_url)
self._ws = None
self._session_id: str = ""
def connect(self):
if ws_sync is None:
raise ImportError("websockets is required. pip install websockets")
ws_url = f"{self.base_url}/ws"
self._ws = ws_sync.connect(ws_url)
return self
def close(self):
if self._ws:
self._ws.close()
self._ws = None
def reset(self, session_id: str = "") -> CodeDebugObservation:
if self._ws is None:
self.connect()
msg = {"type": "reset"}
if session_id:
msg["session_id"] = session_id
self._ws.send(json.dumps(msg))
raw = self._ws.recv()
data = json.loads(raw)
self._session_id = data.get("session_id", session_id)
return CodeSenseiEnv._parse_observation(data)
def step(self, proposed_fix: str) -> CodeDebugObservation:
if self._ws is None:
raise RuntimeError("Not connected. Call connect() or reset() first.")
msg = {"type": "step", "proposed_fix": proposed_fix}
self._ws.send(json.dumps(msg))
raw = self._ws.recv()
data = json.loads(raw)
return CodeSenseiEnv._parse_observation(data)
def state(self) -> dict:
if self._ws is None:
raise RuntimeError("Not connected.")
self._ws.send(json.dumps({"type": "state"}))
raw = self._ws.recv()
return json.loads(raw)
@property
def session_id(self) -> str:
return self._session_id
def __enter__(self):
self.connect()
return self
def __exit__(self, *args):
self.close()
@staticmethod
def _to_ws_url(url: str) -> str:
url = url.rstrip("/")
if url.startswith("https://"):
return "wss://" + url[8:]
elif url.startswith("http://"):
return "ws://" + url[7:]
elif url.startswith("wss://") or url.startswith("ws://"):
return url
else:
return "ws://" + url
|