Spaces:
Sleeping
Sleeping
Commit ·
ff84a08
1
Parent(s): b2e4f79
optimised the code
Browse files- Dockerfile +3 -2
- README.md +48 -10
- __pycache__/inference.cpython-313.pyc +0 -0
- app/__pycache__/main.cpython-313.pyc +0 -0
- app/inference.py +1 -102
- app/main.py +2 -1
- inference.py +204 -0
- openenv.yaml +1 -1
- requirements.txt +2 -2
- validate_submission.py +129 -0
Dockerfile
CHANGED
|
@@ -2,6 +2,7 @@ FROM python:3.11-slim
|
|
| 2 |
|
| 3 |
ENV PYTHONDONTWRITEBYTECODE=1
|
| 4 |
ENV PYTHONUNBUFFERED=1
|
|
|
|
| 5 |
|
| 6 |
WORKDIR /app
|
| 7 |
|
|
@@ -10,6 +11,6 @@ RUN pip install --no-cache-dir -r requirements.txt
|
|
| 10 |
|
| 11 |
COPY . .
|
| 12 |
|
| 13 |
-
EXPOSE
|
| 14 |
|
| 15 |
-
CMD ["
|
|
|
|
| 2 |
|
| 3 |
ENV PYTHONDONTWRITEBYTECODE=1
|
| 4 |
ENV PYTHONUNBUFFERED=1
|
| 5 |
+
ENV PORT=7860
|
| 6 |
|
| 7 |
WORKDIR /app
|
| 8 |
|
|
|
|
| 11 |
|
| 12 |
COPY . .
|
| 13 |
|
| 14 |
+
EXPOSE 7860
|
| 15 |
|
| 16 |
+
CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-7860}"]
|
README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Synapse Code Auditor (OpenEnv Environment)
|
| 2 |
|
| 3 |
Synapse Code Auditor is a production-ready OpenEnv environment for evaluating AI code-review behavior across deterministic tasks.
|
|
@@ -10,6 +16,8 @@ Software teams use code review to catch bugs, improve quality, and enforce maint
|
|
| 10 |
|
| 11 |
```text
|
| 12 |
.
|
|
|
|
|
|
|
| 13 |
├── app/
|
| 14 |
│ ├── __init__.py
|
| 15 |
│ ├── env.py
|
|
@@ -107,7 +115,7 @@ pip install -r requirements.txt
|
|
| 107 |
### 2. Run FastAPI server
|
| 108 |
|
| 109 |
```bash
|
| 110 |
-
uvicorn app.main:app --host 0.0.0.0 --port
|
| 111 |
```
|
| 112 |
|
| 113 |
### 3. Validate OpenEnv manifest
|
|
@@ -120,36 +128,66 @@ openenv validate
|
|
| 120 |
|
| 121 |
```bash
|
| 122 |
docker build -t synapse-code-auditor .
|
| 123 |
-
docker run --rm -p
|
| 124 |
```
|
| 125 |
|
| 126 |
Then test:
|
| 127 |
|
| 128 |
```bash
|
| 129 |
-
curl http://localhost:
|
| 130 |
-
curl -X POST http://localhost:
|
| 131 |
```
|
| 132 |
|
| 133 |
## Baseline Inference Script
|
| 134 |
|
| 135 |
-
The baseline runner uses
|
| 136 |
|
| 137 |
Required environment variables:
|
| 138 |
|
| 139 |
-
-
|
| 140 |
-
-
|
| 141 |
-
-
|
| 142 |
|
| 143 |
Optional:
|
| 144 |
|
| 145 |
-
- ENV_BASE_URL: environment API base URL (default http://localhost:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
Run:
|
| 148 |
|
| 149 |
```bash
|
| 150 |
-
python
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
```
|
| 152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
## Example Baseline Output
|
| 154 |
|
| 155 |
```text
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Synapse Code Auditor
|
| 3 |
+
sdk: docker
|
| 4 |
+
app_port: 7860
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
# Synapse Code Auditor (OpenEnv Environment)
|
| 8 |
|
| 9 |
Synapse Code Auditor is a production-ready OpenEnv environment for evaluating AI code-review behavior across deterministic tasks.
|
|
|
|
| 16 |
|
| 17 |
```text
|
| 18 |
.
|
| 19 |
+
├── inference.py
|
| 20 |
+
├── validate_submission.py
|
| 21 |
├── app/
|
| 22 |
│ ├── __init__.py
|
| 23 |
│ ├── env.py
|
|
|
|
| 115 |
### 2. Run FastAPI server
|
| 116 |
|
| 117 |
```bash
|
| 118 |
+
uvicorn app.main:app --host 0.0.0.0 --port 7860
|
| 119 |
```
|
| 120 |
|
| 121 |
### 3. Validate OpenEnv manifest
|
|
|
|
| 128 |
|
| 129 |
```bash
|
| 130 |
docker build -t synapse-code-auditor .
|
| 131 |
+
docker run --rm -p 7860:7860 synapse-code-auditor
|
| 132 |
```
|
| 133 |
|
| 134 |
Then test:
|
| 135 |
|
| 136 |
```bash
|
| 137 |
+
curl http://localhost:7860/health
|
| 138 |
+
curl -X POST http://localhost:7860/reset -H "Content-Type: application/json" -d "{\"task_id\":\"easy\",\"seed\":42}"
|
| 139 |
```
|
| 140 |
|
| 141 |
## Baseline Inference Script
|
| 142 |
|
| 143 |
+
The baseline runner is `inference.py` at the project root. It uses the OpenAI client and executes all 3 tasks.
|
| 144 |
|
| 145 |
Required environment variables:
|
| 146 |
|
| 147 |
+
- API_BASE_URL: OpenAI-compatible API URL
|
| 148 |
+
- MODEL_NAME: model identifier
|
| 149 |
+
- HF_TOKEN: API key used by OpenAI client
|
| 150 |
|
| 151 |
Optional:
|
| 152 |
|
| 153 |
+
- ENV_BASE_URL: environment API base URL (default http://localhost:7860)
|
| 154 |
+
- DRY_RUN: set to `1` to skip external LLM calls and use deterministic local responses
|
| 155 |
+
|
| 156 |
+
Structured logs:
|
| 157 |
+
|
| 158 |
+
- `[START]` one event at run start
|
| 159 |
+
- `[STEP]` one event per task
|
| 160 |
+
- `[END]` one event at run finish
|
| 161 |
|
| 162 |
Run:
|
| 163 |
|
| 164 |
```bash
|
| 165 |
+
python inference.py
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
### Required env var example
|
| 169 |
+
|
| 170 |
+
```bash
|
| 171 |
+
export API_BASE_URL="https://api.openai.com/v1"
|
| 172 |
+
export MODEL_NAME="gpt-4o-mini"
|
| 173 |
+
export HF_TOKEN="your_token_here"
|
| 174 |
+
export ENV_BASE_URL="http://localhost:7860"
|
| 175 |
+
python inference.py
|
| 176 |
```
|
| 177 |
|
| 178 |
+
### Pre-submission validator
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
python validate_submission.py
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
Validator checks:
|
| 185 |
+
|
| 186 |
+
- OpenEnv manifest keys
|
| 187 |
+
- `/health`, `/reset`, `/step`, `/state` endpoint behavior
|
| 188 |
+
- 3+ tasks and grader output range in `[0.0, 1.0]`
|
| 189 |
+
- root `inference.py` requirements and structured logs
|
| 190 |
+
|
| 191 |
## Example Baseline Output
|
| 192 |
|
| 193 |
```text
|
__pycache__/inference.cpython-313.pyc
ADDED
|
Binary file (9.07 kB). View file
|
|
|
app/__pycache__/main.cpython-313.pyc
CHANGED
|
Binary files a/app/__pycache__/main.cpython-313.pyc and b/app/__pycache__/main.cpython-313.pyc differ
|
|
|
app/inference.py
CHANGED
|
@@ -1,105 +1,4 @@
|
|
| 1 |
-
import
|
| 2 |
-
from dataclasses import dataclass
|
| 3 |
-
|
| 4 |
-
import requests
|
| 5 |
-
from openai import OpenAI
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
@dataclass
|
| 9 |
-
class BaselineResult:
|
| 10 |
-
task_id: str
|
| 11 |
-
score: float
|
| 12 |
-
rationale: str
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def _build_prompt(task_id: str, instructions: str, code: str) -> str:
|
| 16 |
-
return (
|
| 17 |
-
"You are a code reviewer. Complete exactly the requested review task.\n"
|
| 18 |
-
f"Task ID: {task_id}\n"
|
| 19 |
-
f"Instructions: {instructions}\n"
|
| 20 |
-
"Code:\n"
|
| 21 |
-
f"{code}\n\n"
|
| 22 |
-
"Return concise, actionable review feedback."
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def _run_task(
|
| 27 |
-
env_base_url: str,
|
| 28 |
-
client: OpenAI,
|
| 29 |
-
model_name: str,
|
| 30 |
-
task_id: str,
|
| 31 |
-
) -> BaselineResult:
|
| 32 |
-
reset_response = requests.post(
|
| 33 |
-
f"{env_base_url}/reset",
|
| 34 |
-
json={"task_id": task_id, "seed": 42},
|
| 35 |
-
timeout=30,
|
| 36 |
-
)
|
| 37 |
-
reset_response.raise_for_status()
|
| 38 |
-
reset_payload = reset_response.json()
|
| 39 |
-
|
| 40 |
-
observation = reset_payload["observation"]
|
| 41 |
-
prompt = _build_prompt(
|
| 42 |
-
task_id=observation["task_id"],
|
| 43 |
-
instructions=observation["instructions"],
|
| 44 |
-
code=observation["code"],
|
| 45 |
-
)
|
| 46 |
-
|
| 47 |
-
completion = client.chat.completions.create(
|
| 48 |
-
model=model_name,
|
| 49 |
-
temperature=0,
|
| 50 |
-
seed=42,
|
| 51 |
-
messages=[
|
| 52 |
-
{
|
| 53 |
-
"role": "system",
|
| 54 |
-
"content": "You are an expert software engineer specializing in code review.",
|
| 55 |
-
},
|
| 56 |
-
{"role": "user", "content": prompt},
|
| 57 |
-
],
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
-
review = completion.choices[0].message.content or ""
|
| 61 |
-
|
| 62 |
-
step_response = requests.post(
|
| 63 |
-
f"{env_base_url}/step",
|
| 64 |
-
json={"action": {"review": review}},
|
| 65 |
-
timeout=30,
|
| 66 |
-
)
|
| 67 |
-
step_response.raise_for_status()
|
| 68 |
-
step_payload = step_response.json()
|
| 69 |
-
|
| 70 |
-
return BaselineResult(
|
| 71 |
-
task_id=task_id,
|
| 72 |
-
score=float(step_payload["reward"]["score"]),
|
| 73 |
-
rationale=step_payload["reward"]["rationale"],
|
| 74 |
-
)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def main() -> None:
|
| 78 |
-
env_base_url = os.getenv("ENV_BASE_URL", "http://localhost:8000")
|
| 79 |
-
api_base_url = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
|
| 80 |
-
model_name = os.getenv("MODEL_NAME", "gpt-4o-mini")
|
| 81 |
-
api_key = os.getenv("OPENAI_API_KEY")
|
| 82 |
-
|
| 83 |
-
if not api_key:
|
| 84 |
-
raise RuntimeError("OPENAI_API_KEY must be set to run inference.py")
|
| 85 |
-
|
| 86 |
-
client = OpenAI(base_url=api_base_url, api_key=api_key)
|
| 87 |
-
|
| 88 |
-
task_ids = ["easy", "medium", "hard"]
|
| 89 |
-
results = [_run_task(env_base_url, client, model_name, task_id) for task_id in task_ids]
|
| 90 |
-
|
| 91 |
-
print("Synapse Code Auditor baseline run")
|
| 92 |
-
print(f"Environment URL: {env_base_url}")
|
| 93 |
-
print(f"Model endpoint: {api_base_url}")
|
| 94 |
-
print(f"Model: {model_name}")
|
| 95 |
-
|
| 96 |
-
total = 0.0
|
| 97 |
-
for result in results:
|
| 98 |
-
total += result.score
|
| 99 |
-
print(f"- {result.task_id}: score={result.score:.4f} | {result.rationale}")
|
| 100 |
-
|
| 101 |
-
avg_score = total / len(results)
|
| 102 |
-
print(f"Average score: {avg_score:.4f}")
|
| 103 |
|
| 104 |
|
| 105 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
from inference import main
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
|
| 4 |
if __name__ == "__main__":
|
app/main.py
CHANGED
|
@@ -18,7 +18,8 @@ def health() -> dict[str, str]:
|
|
| 18 |
|
| 19 |
|
| 20 |
@app.post("/reset", response_model=ResetResponse)
|
| 21 |
-
def reset(request: ResetRequest) -> ResetResponse:
|
|
|
|
| 22 |
try:
|
| 23 |
observation = env.reset(task_id=request.task_id, seed=request.seed)
|
| 24 |
except KeyError as exc:
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
@app.post("/reset", response_model=ResetResponse)
|
| 21 |
+
def reset(request: ResetRequest | None = None) -> ResetResponse:
|
| 22 |
+
request = request or ResetRequest()
|
| 23 |
try:
|
| 24 |
observation = env.reset(task_id=request.task_id, seed=request.seed)
|
| 25 |
except KeyError as exc:
|
inference.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
from openai import OpenAI
|
| 9 |
+
|
| 10 |
+
from app.main import app
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from fastapi.testclient import TestClient
|
| 14 |
+
except Exception: # pragma: no cover
|
| 15 |
+
TestClient = None
|
| 16 |
+
|
| 17 |
+
TASK_IDS: list[str] = ["easy", "medium", "hard"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class TaskRun:
|
| 22 |
+
task_id: str
|
| 23 |
+
score: float
|
| 24 |
+
rationale: str
|
| 25 |
+
latency_s: float
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _TestResponse:
|
| 29 |
+
def __init__(self, status_code: int, payload: dict[str, Any]) -> None:
|
| 30 |
+
self.status_code = status_code
|
| 31 |
+
self._payload = payload
|
| 32 |
+
|
| 33 |
+
def raise_for_status(self) -> None:
|
| 34 |
+
if self.status_code >= 400:
|
| 35 |
+
raise RuntimeError(f"Request failed with status {self.status_code}: {self._payload}")
|
| 36 |
+
|
| 37 |
+
def json(self) -> dict[str, Any]:
|
| 38 |
+
return self._payload
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class _InProcessSession:
|
| 42 |
+
def __init__(self) -> None:
|
| 43 |
+
if TestClient is None:
|
| 44 |
+
raise RuntimeError("fastapi test client is unavailable in this environment")
|
| 45 |
+
self._client = TestClient(app)
|
| 46 |
+
|
| 47 |
+
def post(self, path: str, json_payload: dict[str, Any]) -> _TestResponse:
|
| 48 |
+
response = self._client.post(path, json=json_payload)
|
| 49 |
+
return _TestResponse(response.status_code, response.json())
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _emit(tag: str, payload: dict[str, Any]) -> None:
|
| 53 |
+
# Strict tag-prefixed structured logs for evaluator parsing.
|
| 54 |
+
print(f"[{tag}] {json.dumps(payload, separators=(',', ':'), ensure_ascii=True)}", flush=True)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _required_env(name: str) -> str:
|
| 58 |
+
value = os.getenv(name)
|
| 59 |
+
if not value:
|
| 60 |
+
raise RuntimeError(f"Missing required environment variable: {name}")
|
| 61 |
+
return value
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _build_prompt(task_id: str, instructions: str, code: str) -> str:
|
| 65 |
+
return (
|
| 66 |
+
"You are a code reviewer. Complete exactly the requested review task.\n"
|
| 67 |
+
f"Task ID: {task_id}\n"
|
| 68 |
+
f"Instructions: {instructions}\n"
|
| 69 |
+
"Code:\n"
|
| 70 |
+
f"{code}\n\n"
|
| 71 |
+
"Return concise, actionable review feedback."
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _dry_run_review(task_id: str) -> str:
|
| 76 |
+
if task_id == "easy":
|
| 77 |
+
return (
|
| 78 |
+
"There is a syntax error: missing colon in the function definition. "
|
| 79 |
+
"Fix with def add_numbers(a, b):"
|
| 80 |
+
)
|
| 81 |
+
if task_id == "medium":
|
| 82 |
+
return (
|
| 83 |
+
"Use a list comprehension to preserve behavior and improve readability: "
|
| 84 |
+
"return [n * n for n in numbers if n % 2 == 0]."
|
| 85 |
+
)
|
| 86 |
+
return (
|
| 87 |
+
"Code review: handle empty list to prevent division by zero, avoid broad except Exception, "
|
| 88 |
+
"iterate directly over values, add type hints and tests. Overall score: 0.86/1.0."
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _run_task(env_base_url: str, client: OpenAI, model_name: str, task_id: str, dry_run: bool) -> TaskRun:
|
| 93 |
+
t0 = time.perf_counter()
|
| 94 |
+
|
| 95 |
+
if env_base_url == "inprocess":
|
| 96 |
+
session = _InProcessSession()
|
| 97 |
+
reset_response = session.post("/reset", {"task_id": task_id, "seed": 42})
|
| 98 |
+
else:
|
| 99 |
+
reset_response = requests.post(
|
| 100 |
+
f"{env_base_url}/reset",
|
| 101 |
+
json={"task_id": task_id, "seed": 42},
|
| 102 |
+
timeout=30,
|
| 103 |
+
)
|
| 104 |
+
reset_response.raise_for_status()
|
| 105 |
+
observation = reset_response.json()["observation"]
|
| 106 |
+
|
| 107 |
+
if dry_run:
|
| 108 |
+
review = _dry_run_review(task_id)
|
| 109 |
+
else:
|
| 110 |
+
prompt = _build_prompt(
|
| 111 |
+
task_id=observation["task_id"],
|
| 112 |
+
instructions=observation["instructions"],
|
| 113 |
+
code=observation["code"],
|
| 114 |
+
)
|
| 115 |
+
completion = client.chat.completions.create(
|
| 116 |
+
model=model_name,
|
| 117 |
+
temperature=0,
|
| 118 |
+
seed=42,
|
| 119 |
+
messages=[
|
| 120 |
+
{
|
| 121 |
+
"role": "system",
|
| 122 |
+
"content": "You are an expert software engineer specializing in code review.",
|
| 123 |
+
},
|
| 124 |
+
{"role": "user", "content": prompt},
|
| 125 |
+
],
|
| 126 |
+
)
|
| 127 |
+
review = completion.choices[0].message.content or ""
|
| 128 |
+
|
| 129 |
+
if env_base_url == "inprocess":
|
| 130 |
+
step_response = session.post("/step", {"action": {"review": review}})
|
| 131 |
+
else:
|
| 132 |
+
step_response = requests.post(
|
| 133 |
+
f"{env_base_url}/step",
|
| 134 |
+
json={"action": {"review": review}},
|
| 135 |
+
timeout=30,
|
| 136 |
+
)
|
| 137 |
+
step_response.raise_for_status()
|
| 138 |
+
reward = step_response.json()["reward"]
|
| 139 |
+
|
| 140 |
+
return TaskRun(
|
| 141 |
+
task_id=task_id,
|
| 142 |
+
score=float(reward["score"]),
|
| 143 |
+
rationale=str(reward["rationale"]),
|
| 144 |
+
latency_s=round(time.perf_counter() - t0, 3),
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def main() -> None:
|
| 149 |
+
start_ts = int(time.time())
|
| 150 |
+
env_base_url = os.getenv("ENV_BASE_URL", "http://localhost:7860")
|
| 151 |
+
api_base_url = _required_env("API_BASE_URL")
|
| 152 |
+
model_name = _required_env("MODEL_NAME")
|
| 153 |
+
hf_token = _required_env("HF_TOKEN")
|
| 154 |
+
dry_run = os.getenv("DRY_RUN", "0") == "1"
|
| 155 |
+
|
| 156 |
+
_emit(
|
| 157 |
+
"START",
|
| 158 |
+
{
|
| 159 |
+
"event": "run_started",
|
| 160 |
+
"timestamp": start_ts,
|
| 161 |
+
"env_base_url": env_base_url,
|
| 162 |
+
"api_base_url": api_base_url,
|
| 163 |
+
"model_name": model_name,
|
| 164 |
+
"task_count": len(TASK_IDS),
|
| 165 |
+
"dry_run": dry_run,
|
| 166 |
+
},
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
client = OpenAI(base_url=api_base_url, api_key=hf_token)
|
| 170 |
+
|
| 171 |
+
results: list[TaskRun] = []
|
| 172 |
+
for index, task_id in enumerate(TASK_IDS, start=1):
|
| 173 |
+
result = _run_task(env_base_url, client, model_name, task_id, dry_run)
|
| 174 |
+
results.append(result)
|
| 175 |
+
_emit(
|
| 176 |
+
"STEP",
|
| 177 |
+
{
|
| 178 |
+
"event": "task_completed",
|
| 179 |
+
"index": index,
|
| 180 |
+
"task_id": result.task_id,
|
| 181 |
+
"score": result.score,
|
| 182 |
+
"rationale": result.rationale,
|
| 183 |
+
"latency_s": result.latency_s,
|
| 184 |
+
},
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
avg_score = round(sum(item.score for item in results) / len(results), 4)
|
| 188 |
+
total_latency = round(sum(item.latency_s for item in results), 3)
|
| 189 |
+
|
| 190 |
+
_emit(
|
| 191 |
+
"END",
|
| 192 |
+
{
|
| 193 |
+
"event": "run_finished",
|
| 194 |
+
"timestamp": int(time.time()),
|
| 195 |
+
"average_score": avg_score,
|
| 196 |
+
"total_latency_s": total_latency,
|
| 197 |
+
"tasks": [{"task_id": r.task_id, "score": r.score} for r in results],
|
| 198 |
+
"status": "ok",
|
| 199 |
+
},
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
main()
|
openenv.yaml
CHANGED
|
@@ -3,4 +3,4 @@ name: synapse_code_auditor
|
|
| 3 |
type: space
|
| 4 |
runtime: fastapi
|
| 5 |
app: app.main:app
|
| 6 |
-
port:
|
|
|
|
| 3 |
type: space
|
| 4 |
runtime: fastapi
|
| 5 |
app: app.main:app
|
| 6 |
+
port: 7860
|
requirements.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
fastapi==0.115.12
|
| 2 |
uvicorn[standard]==0.34.0
|
| 3 |
-
pydantic==2.11.
|
| 4 |
-
openai==
|
| 5 |
requests==2.32.3
|
| 6 |
openenv-core==0.2.3
|
|
|
|
| 1 |
fastapi==0.115.12
|
| 2 |
uvicorn[standard]==0.34.0
|
| 3 |
+
pydantic==2.11.7
|
| 4 |
+
openai==2.7.2
|
| 5 |
requests==2.32.3
|
| 6 |
openenv-core==0.2.3
|
validate_submission.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from fastapi.testclient import TestClient
|
| 10 |
+
|
| 11 |
+
from app.grader import grade_review
|
| 12 |
+
from app.main import app
|
| 13 |
+
from app.tasks import TASKS
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _check_openenv_yaml(path: Path) -> None:
|
| 17 |
+
content = path.read_text(encoding="utf-8")
|
| 18 |
+
required = ["spec_version:", "name:", "type:", "runtime:", "app:", "port:"]
|
| 19 |
+
missing = [key for key in required if key not in content]
|
| 20 |
+
if missing:
|
| 21 |
+
raise AssertionError(f"openenv.yaml missing keys: {missing}")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _check_api_contracts() -> None:
|
| 25 |
+
client = TestClient(app)
|
| 26 |
+
|
| 27 |
+
health = client.get("/health")
|
| 28 |
+
assert health.status_code == 200, f"/health returned {health.status_code}"
|
| 29 |
+
|
| 30 |
+
reset = client.post("/reset", json={})
|
| 31 |
+
assert reset.status_code == 200, f"/reset returned {reset.status_code}"
|
| 32 |
+
|
| 33 |
+
obs = reset.json()["observation"]
|
| 34 |
+
assert "task_id" in obs and "instructions" in obs and "code" in obs
|
| 35 |
+
|
| 36 |
+
step = client.post(
|
| 37 |
+
"/step",
|
| 38 |
+
json={
|
| 39 |
+
"action": {
|
| 40 |
+
"review": (
|
| 41 |
+
"There is a syntax error with a missing colon. "
|
| 42 |
+
"Fix to def add_numbers(a, b):"
|
| 43 |
+
)
|
| 44 |
+
}
|
| 45 |
+
},
|
| 46 |
+
)
|
| 47 |
+
assert step.status_code == 200, f"/step returned {step.status_code}"
|
| 48 |
+
|
| 49 |
+
state = client.get("/state")
|
| 50 |
+
assert state.status_code == 200, f"/state returned {state.status_code}"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _check_tasks_and_graders() -> None:
|
| 54 |
+
assert len(TASKS) >= 3, "At least 3 tasks are required"
|
| 55 |
+
|
| 56 |
+
sample_reviews = {
|
| 57 |
+
"easy": "Syntax error due to missing colon after function definition. Use def add_numbers(a, b):",
|
| 58 |
+
"medium": "Use a list comprehension while preserving behavior for readability and concise code.",
|
| 59 |
+
"hard": (
|
| 60 |
+
"Handle empty list to avoid division by zero, avoid broad except Exception, "
|
| 61 |
+
"iterate directly, add type hints/tests, overall score: 0.85/1.0."
|
| 62 |
+
),
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
for task_id, task in TASKS.items():
|
| 66 |
+
review = sample_reviews.get(task_id, "Provide relevant code review feedback with score.")
|
| 67 |
+
result = grade_review(task, review)
|
| 68 |
+
assert 0.0 <= result.score <= 1.0, f"Score out of range for {task_id}: {result.score}"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _check_inference_script(path: Path) -> None:
|
| 72 |
+
assert path.exists(), "Root inference.py is required"
|
| 73 |
+
content = path.read_text(encoding="utf-8")
|
| 74 |
+
|
| 75 |
+
required_tokens = [
|
| 76 |
+
"API_BASE_URL",
|
| 77 |
+
"MODEL_NAME",
|
| 78 |
+
"HF_TOKEN",
|
| 79 |
+
"OpenAI(",
|
| 80 |
+
'"START"',
|
| 81 |
+
'"STEP"',
|
| 82 |
+
'"END"',
|
| 83 |
+
]
|
| 84 |
+
missing = [token for token in required_tokens if token not in content]
|
| 85 |
+
if missing:
|
| 86 |
+
raise AssertionError(f"inference.py missing required tokens: {missing}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _run_inference_dry_run(root: Path) -> None:
|
| 90 |
+
env = os.environ.copy()
|
| 91 |
+
env.setdefault("API_BASE_URL", "https://api.openai.com/v1")
|
| 92 |
+
env.setdefault("MODEL_NAME", "gpt-4o-mini")
|
| 93 |
+
env.setdefault("HF_TOKEN", "dummy-token-for-dry-run")
|
| 94 |
+
env.setdefault("ENV_BASE_URL", "inprocess")
|
| 95 |
+
env["DRY_RUN"] = "1"
|
| 96 |
+
|
| 97 |
+
proc = subprocess.run(
|
| 98 |
+
[sys.executable, "inference.py"],
|
| 99 |
+
cwd=str(root),
|
| 100 |
+
env=env,
|
| 101 |
+
capture_output=True,
|
| 102 |
+
text=True,
|
| 103 |
+
timeout=120,
|
| 104 |
+
check=False,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
if proc.returncode != 0:
|
| 108 |
+
raise AssertionError(f"inference.py dry run failed: {proc.stderr or proc.stdout}")
|
| 109 |
+
|
| 110 |
+
lines = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
|
| 111 |
+
assert any(line.startswith("[START]") for line in lines), "Missing [START] log"
|
| 112 |
+
assert sum(1 for line in lines if line.startswith("[STEP]")) >= 3, "Expected >=3 [STEP] logs"
|
| 113 |
+
assert any(line.startswith("[END]") for line in lines), "Missing [END] log"
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def main() -> None:
|
| 117 |
+
root = Path(__file__).resolve().parent
|
| 118 |
+
|
| 119 |
+
_check_openenv_yaml(root / "openenv.yaml")
|
| 120 |
+
_check_api_contracts()
|
| 121 |
+
_check_tasks_and_graders()
|
| 122 |
+
_check_inference_script(root / "inference.py")
|
| 123 |
+
_run_inference_dry_run(root)
|
| 124 |
+
|
| 125 |
+
print(json.dumps({"status": "ok", "message": "Pre-submission validation passed."}))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
main()
|