Spaces:
Sleeping
Sleeping
fix: structured START STEP END stdout output
Browse files- inference.py +129 -42
inference.py
CHANGED
|
@@ -1,26 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
import os
|
| 6 |
import json
|
| 7 |
-
import
|
| 8 |
-
from
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
TASKS = ["easy", "medium", "hard"]
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
prompt = f"""You are a code reviewer. {task_description}
|
| 25 |
|
| 26 |
Code to review:
|
|
@@ -38,42 +71,96 @@ Respond ONLY with valid JSON, no markdown:
|
|
| 38 |
|
| 39 |
try:
|
| 40 |
response = client.chat.completions.create(
|
| 41 |
-
model=
|
| 42 |
messages=[{"role": "user", "content": prompt}],
|
| 43 |
temperature=0.0,
|
| 44 |
)
|
| 45 |
-
raw = response.choices[0].message.content.strip()
|
| 46 |
raw = raw.replace("```json", "").replace("```", "").strip()
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return score
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def main():
|
| 64 |
scores = {}
|
| 65 |
-
for
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
scores[task_id] = run_task(task_id)
|
| 67 |
-
|
| 68 |
-
average = sum(scores.values()) / len(scores)
|
| 69 |
-
scores["average"] =
|
| 70 |
-
|
| 71 |
-
print(f"\nBaseline Results: {json.dumps(scores, indent=2)}")
|
| 72 |
-
|
| 73 |
with open("baseline_scores.json", "w") as f:
|
| 74 |
json.dump(scores, f, indent=2)
|
| 75 |
-
|
| 76 |
return scores
|
| 77 |
|
|
|
|
| 78 |
if __name__ == "__main__":
|
| 79 |
main()
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Code Review Environment Baseline Evaluation.
|
| 3 |
+
|
| 4 |
+
This script is hardened for validator compatibility:
|
| 5 |
+
- Always prints [START]/[STEP]/[END] to stdout with flush=True
|
| 6 |
+
- Avoids failing before first [START] due to optional deps/credentials
|
| 7 |
+
- Never redirects stdout
|
| 8 |
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
|
|
|
| 12 |
import json
|
| 13 |
+
import os
|
| 14 |
+
from typing import Any, Dict, Optional
|
| 15 |
|
| 16 |
+
try:
|
| 17 |
+
import requests
|
| 18 |
+
except Exception:
|
| 19 |
+
requests = None # type: ignore[assignment]
|
| 20 |
|
|
|
|
| 21 |
|
| 22 |
+
# ---------------------------------------------------------------------------
|
| 23 |
+
# Configuration
|
| 24 |
+
# ---------------------------------------------------------------------------
|
| 25 |
+
|
| 26 |
+
BASE_URL = os.getenv("BASE_URL", "http://localhost:8000")
|
| 27 |
+
API_KEY = os.getenv("API_KEY") or os.getenv("HF_TOKEN")
|
| 28 |
+
MODEL = "gpt-4o-mini"
|
| 29 |
+
|
| 30 |
+
# List of task IDs to evaluate
|
| 31 |
+
TASKS = os.getenv("TASKS", "task_1,task_2,task_3").split(",")
|
| 32 |
+
|
| 33 |
+
# ---------------------------------------------------------------------------
|
| 34 |
+
# Main Task Runner
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _build_action(task_description: str, code_snippet: str) -> Dict[str, Any]:
|
| 39 |
+
"""Build an action via LLM when available; otherwise return safe fallback."""
|
| 40 |
+
fallback_action: Dict[str, Any] = {
|
| 41 |
+
"review": "Unable to run model; submitting safe fallback review.",
|
| 42 |
+
"bug_type": "none",
|
| 43 |
+
"line_number": -1,
|
| 44 |
+
"confidence": 0.0,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
if not API_KEY:
|
| 48 |
+
return fallback_action
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
from openai import OpenAI # Lazy import to avoid failing at module import time
|
| 52 |
+
|
| 53 |
+
client = OpenAI(api_key=API_KEY)
|
| 54 |
+
except Exception:
|
| 55 |
+
return fallback_action
|
| 56 |
+
|
| 57 |
prompt = f"""You are a code reviewer. {task_description}
|
| 58 |
|
| 59 |
Code to review:
|
|
|
|
| 71 |
|
| 72 |
try:
|
| 73 |
response = client.chat.completions.create(
|
| 74 |
+
model=MODEL,
|
| 75 |
messages=[{"role": "user", "content": prompt}],
|
| 76 |
temperature=0.0,
|
| 77 |
)
|
| 78 |
+
raw = (response.choices[0].message.content or "").strip()
|
| 79 |
raw = raw.replace("```json", "").replace("```", "").strip()
|
| 80 |
+
parsed = json.loads(raw)
|
| 81 |
+
if isinstance(parsed, dict):
|
| 82 |
+
return parsed
|
| 83 |
+
return fallback_action
|
| 84 |
+
except Exception:
|
| 85 |
+
return fallback_action
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _safe_post_json(url: str, payload: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 89 |
+
"""Return JSON body or None on any network/JSON failure."""
|
| 90 |
+
if requests is None:
|
| 91 |
+
return None
|
| 92 |
+
try:
|
| 93 |
+
response = requests.post(url, json=payload, timeout=30)
|
| 94 |
+
return response.json()
|
| 95 |
+
except Exception:
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _safe_get_json(url: str) -> Optional[Dict[str, Any]]:
|
| 100 |
+
"""Return JSON body or None on any network/JSON failure."""
|
| 101 |
+
if requests is None:
|
| 102 |
+
return None
|
| 103 |
+
try:
|
| 104 |
+
response = requests.get(url, timeout=30)
|
| 105 |
+
return response.json()
|
| 106 |
+
except Exception:
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def run_task(task_id: str) -> float:
|
| 111 |
+
"""Run a single code review task and return the score."""
|
| 112 |
+
print(f"[START] task={task_id}", flush=True)
|
| 113 |
+
|
| 114 |
+
score = 0.0
|
| 115 |
+
steps = 1
|
| 116 |
+
|
| 117 |
+
reset_data = _safe_post_json(f"{BASE_URL}/reset", {"task_id": task_id}) or {}
|
| 118 |
+
obs = reset_data.get("observation", {}) if isinstance(reset_data, dict) else {}
|
| 119 |
+
|
| 120 |
+
code_snippet = obs.get("code_snippet", "")
|
| 121 |
+
task_description = obs.get("task_description", "Review the provided code.")
|
| 122 |
+
action = _build_action(str(task_description), str(code_snippet))
|
| 123 |
+
|
| 124 |
+
# If stepping fails, we still emit structured output with reward=0.0
|
| 125 |
+
_safe_post_json(f"{BASE_URL}/step", {"action": action})
|
| 126 |
+
|
| 127 |
+
grader_data = _safe_get_json(f"{BASE_URL}/grader?task_id={task_id}&episode_id=baseline") or {}
|
| 128 |
+
if isinstance(grader_data, dict):
|
| 129 |
+
try:
|
| 130 |
+
score = float(grader_data.get("score", 0.0))
|
| 131 |
+
except Exception:
|
| 132 |
+
score = 0.0
|
| 133 |
+
|
| 134 |
+
print(f"[STEP] step=1 reward={score}", flush=True)
|
| 135 |
+
print(f"[END] task={task_id} score={score} steps={steps}", flush=True)
|
| 136 |
+
|
| 137 |
return score
|
| 138 |
|
| 139 |
+
|
| 140 |
+
# ---------------------------------------------------------------------------
|
| 141 |
+
# Entrypoint
|
| 142 |
+
# ---------------------------------------------------------------------------
|
| 143 |
+
|
| 144 |
+
|
| 145 |
def main():
|
| 146 |
scores = {}
|
| 147 |
+
normalized_tasks = [t.strip() for t in TASKS if t.strip()]
|
| 148 |
+
if not normalized_tasks:
|
| 149 |
+
normalized_tasks = ["task_1"]
|
| 150 |
+
|
| 151 |
+
for task_id in normalized_tasks:
|
| 152 |
scores[task_id] = run_task(task_id)
|
| 153 |
+
|
| 154 |
+
average = round(sum(scores.values()) / len(scores), 4)
|
| 155 |
+
scores["average"] = average
|
| 156 |
+
|
| 157 |
+
print(f"\nBaseline Results: {json.dumps(scores, indent=2)}", flush=True)
|
| 158 |
+
|
| 159 |
with open("baseline_scores.json", "w") as f:
|
| 160 |
json.dump(scores, f, indent=2)
|
| 161 |
+
|
| 162 |
return scores
|
| 163 |
|
| 164 |
+
|
| 165 |
if __name__ == "__main__":
|
| 166 |
main()
|