Spaces:
Sleeping
Sleeping
bbjjj9u
#1
by vinith17 - opened
- .github/workflows/sync-huggingface-space.yml +0 -35
- .gitignore +1 -1
- .vibecheck/last-score.json +1 -1
- .vibecheck/provenance/attestations.db +0 -0
- .vibecheck/provenance/edits.jsonl +0 -5
- .vibecheck/sync-queue.json +1 -1
- agent.py +114 -156
- api/index.py +9 -0
- config.py +4 -1
- environment.py +14 -45
- grader.py +7 -45
- inference.py +104 -162
- main.py +3 -4
- openenv.yaml +4 -35
- pyproject.toml +1 -1
- requirements.txt +0 -1
- server/__init__.py +1 -1
- server/app.py +6 -20
- tasks/__init__.py +0 -1
- tasks/easy/__init__.py +0 -1
- tasks/easy/grader.py +0 -49
- tasks/extra1/__init__.py +0 -1
- tasks/extra1/grader.py +0 -37
- tasks/extra2/__init__.py +0 -1
- tasks/extra2/grader.py +0 -37
- tasks/hard/__init__.py +0 -1
- tasks/hard/grader.py +0 -37
- tasks/medium/__init__.py +0 -1
- tasks/medium/grader.py +0 -37
- tasks/scoring.py +0 -19
- test_api_directly.py +15 -15
- test_api_settings.py +0 -13
- test_graders.py +0 -53
- test_no_api.py +0 -27
- vercel.json +15 -0
.github/workflows/sync-huggingface-space.yml
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 1 |
-
# Mirrors this GitHub repo to your Hugging Face Space on every push to main.
|
| 2 |
-
#
|
| 3 |
-
# Setup (one-time):
|
| 4 |
-
# 1. GitHub → Settings → Secrets and variables → Actions → New secret: HF_TOKEN
|
| 5 |
-
# (Hugging Face token with write access to the Space — create at huggingface.co/settings/tokens)
|
| 6 |
-
# 2. If your Space is not "vinith17/CodeBug", edit huggingface_repo_id in this file.
|
| 7 |
-
#
|
| 8 |
-
# If the Space is also "Connected to GitHub" in HF Settings, pick ONE sync method to avoid conflicts
|
| 9 |
-
# (either disconnect native GitHub on HF and rely on this Action, or fix the native integration and
|
| 10 |
-
# delete this workflow).
|
| 11 |
-
#
|
| 12 |
-
# Docs: https://huggingface.co/docs/hub/main/spaces-github-actions
|
| 13 |
-
|
| 14 |
-
name: Sync to Hugging Face Space
|
| 15 |
-
|
| 16 |
-
on:
|
| 17 |
-
push:
|
| 18 |
-
branches: [main]
|
| 19 |
-
workflow_dispatch:
|
| 20 |
-
|
| 21 |
-
jobs:
|
| 22 |
-
sync:
|
| 23 |
-
runs-on: ubuntu-latest
|
| 24 |
-
steps:
|
| 25 |
-
- uses: actions/checkout@v4
|
| 26 |
-
|
| 27 |
-
- name: Sync GitHub → Hugging Face Space
|
| 28 |
-
uses: huggingface/hub-sync@v0.1.0
|
| 29 |
-
with:
|
| 30 |
-
github_repo_id: ${{ github.repository }}
|
| 31 |
-
# Must match your Space: https://huggingface.co/spaces/<user>/<name>
|
| 32 |
-
huggingface_repo_id: vinith17/CodeBug
|
| 33 |
-
hf_token: ${{ secrets.HF_TOKEN }}
|
| 34 |
-
repo_type: space
|
| 35 |
-
space_sdk: docker
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
CHANGED
|
@@ -34,7 +34,7 @@ history.json
|
|
| 34 |
.islstudio/
|
| 35 |
.vibecheck/
|
| 36 |
|
| 37 |
-
# Vercel
|
| 38 |
.vercel
|
| 39 |
|
| 40 |
# Backups
|
|
|
|
| 34 |
.islstudio/
|
| 35 |
.vibecheck/
|
| 36 |
|
| 37 |
+
# Vercel
|
| 38 |
.vercel
|
| 39 |
|
| 40 |
# Backups
|
.vibecheck/last-score.json
CHANGED
|
@@ -6,5 +6,5 @@
|
|
| 6 |
"runtimeProof": 0,
|
| 7 |
"contracts": 0,
|
| 8 |
"mockData": 0,
|
| 9 |
-
"lastUpdated": "2026-04-
|
| 10 |
}
|
|
|
|
| 6 |
"runtimeProof": 0,
|
| 7 |
"contracts": 0,
|
| 8 |
"mockData": 0,
|
| 9 |
+
"lastUpdated": "2026-04-08T11:13:30.294Z"
|
| 10 |
}
|
.vibecheck/provenance/attestations.db
CHANGED
|
Binary files a/.vibecheck/provenance/attestations.db and b/.vibecheck/provenance/attestations.db differ
|
|
|
.vibecheck/provenance/edits.jsonl
CHANGED
|
@@ -29,8 +29,3 @@
|
|
| 29 |
{"id":"prov-1775597065328-d59yla-1","file":"main.py","startLine":8,"endLine":9,"timestamp":"2026-04-08T11:14:38.761Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":32,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"0f547befe2909c85","preview":" env_cls=CodeBugEnvironment,\\n"}
|
| 30 |
{"id":"prov-1775597065328-d59yla-2","file":"main.py","startLine":8,"endLine":12,"timestamp":"2026-04-08T11:16:01.548Z","editSource":"ai-completion","linesAdded":4,"linesRemoved":4,"charsInserted":93,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"6be0fb36841e90c0","preview":" CodeBugEnvironment,\\n CodeReviewAction,\\n CodeReviewObservation,\\n CodeReviewState\\n"}
|
| 31 |
{"id":"prov-1775597065328-d59yla-3","file":"frontend\\codebug (1).html","startLine":547,"endLine":862,"timestamp":"2026-04-08T14:21:06.864Z","editSource":"ai-completion","linesAdded":315,"linesRemoved":302,"charsInserted":14256,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"b681b8ee26679d7f","preview":" <div id=\"bugNav\" style=\"display:none; margin-bottom:16px;\"></div>\\n <div id=\"bugList\"></div>\\n </div>\\n </div>\\n </div>\\n </div>\\n </div>\\n</section>\\n\\n<!-- ── "}
|
| 32 |
-
{"id":"prov-1775597065328-d59yla-4","file":"main.py","startLine":5,"endLine":6,"timestamp":"2026-04-08T16:57:15.506Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":53,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"d9cfe9bdbb9f1467","preview":"from fastapi import FastAPI, Request, HTTPException\r\\n"}
|
| 33 |
-
{"id":"prov-1775597065328-d59yla-5","file":"main.py","startLine":582,"endLine":583,"timestamp":"2026-04-08T17:19:29.839Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":17,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"47d050b814b477b9","preview":" return bugs\r\\n"}
|
| 34 |
-
{"id":"prov-1775998400628-0g4k00-1","file":"environment.py","startLine":65,"endLine":66,"timestamp":"2026-04-12T13:01:47.747Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":25,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"b86323de97bd6fd0","preview":" reward=None,\\n"}
|
| 35 |
-
{"id":"prov-1775998400628-0g4k00-2","file":"environment.py","startLine":88,"endLine":89,"timestamp":"2026-04-12T13:12:10.182Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":61,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"c00d563b4e8024ae","preview":" reward=0.01, # Start with a baseline safe score\\n"}
|
| 36 |
-
{"id":"prov-1775998400628-0g4k00-3","file":"server\\__init__.py","startLine":1,"endLine":2,"timestamp":"2026-04-12T14:48:52.806Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":60,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"497cd81d76c9fcb5","preview":"# Server package for OpenEnv-style layouts (server/app.py).\\n"}
|
|
|
|
| 29 |
{"id":"prov-1775597065328-d59yla-1","file":"main.py","startLine":8,"endLine":9,"timestamp":"2026-04-08T11:14:38.761Z","editSource":"human-typing","linesAdded":1,"linesRemoved":1,"charsInserted":32,"editVelocity":0,"aiTool":"none","aiModel":"human","confidence":85,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"0f547befe2909c85","preview":" env_cls=CodeBugEnvironment,\\n"}
|
| 30 |
{"id":"prov-1775597065328-d59yla-2","file":"main.py","startLine":8,"endLine":12,"timestamp":"2026-04-08T11:16:01.548Z","editSource":"ai-completion","linesAdded":4,"linesRemoved":4,"charsInserted":93,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"6be0fb36841e90c0","preview":" CodeBugEnvironment,\\n CodeReviewAction,\\n CodeReviewObservation,\\n CodeReviewState\\n"}
|
| 31 |
{"id":"prov-1775597065328-d59yla-3","file":"frontend\\codebug (1).html","startLine":547,"endLine":862,"timestamp":"2026-04-08T14:21:06.864Z","editSource":"ai-completion","linesAdded":315,"linesRemoved":302,"charsInserted":14256,"editVelocity":0,"aiTool":"none","aiModel":"unknown","confidence":50,"ide":"vscode","gitAuthor":"vinith17-k","gitEmail":"vinitharidas6@gmail.com","contentHash":"b681b8ee26679d7f","preview":" <div id=\"bugNav\" style=\"display:none; margin-bottom:16px;\"></div>\\n <div id=\"bugList\"></div>\\n </div>\\n </div>\\n </div>\\n </div>\\n </div>\\n</section>\\n\\n<!-- ── "}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.vibecheck/sync-queue.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
{
|
| 2 |
"version": 1,
|
| 3 |
"entries": [],
|
| 4 |
-
"updatedAt": "2026-04-
|
| 5 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"version": 1,
|
| 3 |
"entries": [],
|
| 4 |
+
"updatedAt": "2026-04-05T17:51:55.096Z"
|
| 5 |
}
|
agent.py
CHANGED
|
@@ -1,40 +1,44 @@
|
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
import logging
|
| 6 |
|
| 7 |
-
from openai import OpenAI
|
| 8 |
-
|
| 9 |
logger = logging.getLogger(__name__)
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
MAX_TOKENS = 1024
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
_LLM_KEY = (
|
| 17 |
-
os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or ""
|
| 18 |
-
).strip()
|
| 19 |
-
has_openai_client = bool(_LLM_KEY)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
if not
|
| 24 |
print(
|
| 25 |
"\n"
|
| 26 |
"╔══════════════════════════════════════════════════════════╗\n"
|
| 27 |
"║ WARNING: No LLM API key found. ║\n"
|
| 28 |
"║ ║\n"
|
| 29 |
-
"║ Set
|
| 30 |
-
"║
|
|
|
|
| 31 |
"║ ║\n"
|
| 32 |
-
"║ The server will start, but reviews
|
|
|
|
| 33 |
"╚══════════════════════════════════════════════════════════╝\n",
|
| 34 |
file=sys.stderr,
|
| 35 |
)
|
| 36 |
return
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
_check_api_keys()
|
|
@@ -93,37 +97,56 @@ def build_user_message(code: str, retry: bool = False) -> str:
|
|
| 93 |
# LLM call
|
| 94 |
# ---------------------------------------------------------------------------
|
| 95 |
|
| 96 |
-
|
| 97 |
def call_llm(prompt: str, *, system: str | None = None) -> str | None:
|
| 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 |
# JSON parsing helper
|
| 124 |
# ---------------------------------------------------------------------------
|
| 125 |
|
| 126 |
-
|
| 127 |
def _parse_json(raw: str) -> dict | None:
|
| 128 |
"""Try direct parse, then regex-extracted substring."""
|
| 129 |
if not raw:
|
|
@@ -155,129 +178,75 @@ def mock_review(code: str) -> list:
|
|
| 155 |
|
| 156 |
# SQL injection
|
| 157 |
if 'f"select' in code_lower or "f'select" in code_lower:
|
| 158 |
-
bugs.append(
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
}
|
| 168 |
-
)
|
| 169 |
|
| 170 |
# Hardcoded password
|
| 171 |
if "hashed = password" in code_lower or (
|
| 172 |
-
"password" in code_lower
|
| 173 |
-
and "hash" not in code_lower
|
| 174 |
-
and "bcrypt" not in code_lower
|
| 175 |
):
|
| 176 |
-
bugs.append(
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
}
|
| 186 |
-
)
|
| 187 |
|
| 188 |
# Off-by-one
|
| 189 |
if "range(len(" in code_lower and "- 1" in code_lower:
|
| 190 |
-
bugs.append(
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
}
|
| 200 |
-
)
|
| 201 |
|
| 202 |
# Division by zero
|
| 203 |
if "/ 0" in code_lower:
|
| 204 |
-
bugs.append(
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
}
|
| 214 |
-
)
|
| 215 |
|
| 216 |
# Strict comparison
|
| 217 |
-
if (
|
| 218 |
-
(
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
"comment": "Strict > / < in balance check; may miss the equality edge case.",
|
| 228 |
-
"fix": "Use >= or <= to include equality edge case.",
|
| 229 |
-
"confidence": 0.8,
|
| 230 |
-
"line_hint": "comparison check",
|
| 231 |
-
}
|
| 232 |
-
)
|
| 233 |
|
| 234 |
return bugs
|
| 235 |
|
| 236 |
|
| 237 |
-
def mock_review_action(code: str) -> dict:
|
| 238 |
-
"""
|
| 239 |
-
Rule-based fallback that returns a single action dict (not a list).
|
| 240 |
-
Used when LLM is unavailable - provides heuristic-based scoring.
|
| 241 |
-
Returns format compatible with inference.py graders:
|
| 242 |
-
{
|
| 243 |
-
"category": "logic" | "security" | "style" | "approve",
|
| 244 |
-
"severity": int 1-5,
|
| 245 |
-
"line_hint": int | None,
|
| 246 |
-
"comment": str
|
| 247 |
-
}
|
| 248 |
-
"""
|
| 249 |
-
bugs = mock_review(code)
|
| 250 |
-
if not bugs:
|
| 251 |
-
return {
|
| 252 |
-
"category": "approve",
|
| 253 |
-
"severity": 1,
|
| 254 |
-
"line_hint": None,
|
| 255 |
-
"comment": "no_issues_found",
|
| 256 |
-
}
|
| 257 |
-
bug = bugs[0]
|
| 258 |
-
cat = str(bug.get("category", "logic"))
|
| 259 |
-
if cat not in ("logic", "security", "style", "approve"):
|
| 260 |
-
cat = "logic"
|
| 261 |
-
return {
|
| 262 |
-
"category": cat,
|
| 263 |
-
"severity": int(bug.get("severity", 3)),
|
| 264 |
-
"line_hint": None,
|
| 265 |
-
"comment": bug.get("comment", "")[:100],
|
| 266 |
-
}
|
| 267 |
-
|
| 268 |
-
|
| 269 |
# ---------------------------------------------------------------------------
|
| 270 |
# Main entry point
|
| 271 |
# ---------------------------------------------------------------------------
|
| 272 |
|
| 273 |
_REQUIRED_KEYS = {"type", "category", "line_hint", "comment", "severity"}
|
| 274 |
-
_DEFAULTS = {
|
| 275 |
-
"type": "approve",
|
| 276 |
-
"category": "ok",
|
| 277 |
-
"line_hint": "",
|
| 278 |
-
"comment": "",
|
| 279 |
-
"severity": 0,
|
| 280 |
-
}
|
| 281 |
|
| 282 |
|
| 283 |
def review(code: str) -> list:
|
|
@@ -297,9 +266,7 @@ def review(code: str) -> list:
|
|
| 297 |
|
| 298 |
if result is None or not isinstance(result, list):
|
| 299 |
# One retry: tell the model its output was invalid
|
| 300 |
-
logger.warning(
|
| 301 |
-
"LLM returned malformed JSON or not a list — retrying with correction hint."
|
| 302 |
-
)
|
| 303 |
user_msg_retry = build_user_message(code, retry=True)
|
| 304 |
raw_retry = call_llm(user_msg_retry, system=_SYSTEM_PROMPT)
|
| 305 |
result = _parse_json(raw_retry)
|
|
@@ -322,19 +289,10 @@ def review(code: str) -> list:
|
|
| 322 |
|
| 323 |
if __name__ == "__main__":
|
| 324 |
_TESTS = [
|
| 325 |
-
(
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
),
|
| 329 |
-
(
|
| 330 |
-
"Off-by-one",
|
| 331 |
-
"def find_max(nums):\n mx = nums[0]\n for i in range(len(nums) - 1):\n if nums[i] > mx: mx = nums[i]\n return mx",
|
| 332 |
-
),
|
| 333 |
-
(
|
| 334 |
-
"Plain password",
|
| 335 |
-
"def save(u, pw, db):\n db.insert('users', {'username': u, 'password': pw})",
|
| 336 |
-
),
|
| 337 |
-
("Clean code", "def add(a: int, b: int) -> int:\n return a + b"),
|
| 338 |
]
|
| 339 |
|
| 340 |
print("=== Agent Tests ===\n")
|
|
|
|
| 1 |
+
|
| 2 |
import os
|
| 3 |
import sys
|
| 4 |
import json
|
| 5 |
import re
|
| 6 |
import logging
|
| 7 |
|
|
|
|
|
|
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
|
| 10 |
+
# Configuration
|
| 11 |
+
ANTHROPIC_MODEL = "claude-3-5-haiku-20241022"
|
| 12 |
+
OPENAI_MODEL = "gpt-4o-mini"
|
| 13 |
MAX_TOKENS = 1024
|
| 14 |
|
| 15 |
+
# Check for available API keys
|
| 16 |
+
has_anthropic = bool(os.environ.get("ANTHROPIC_API_KEY", "").strip())
|
| 17 |
+
has_openai = bool(os.environ.get("OPENAI_API_KEY", "").strip())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
def _check_api_keys():
|
| 20 |
+
"""Warn if no LLM APIs are configured"""
|
| 21 |
+
if not (has_anthropic or has_openai):
|
| 22 |
print(
|
| 23 |
"\n"
|
| 24 |
"╔══════════════════════════════════════════════════════════╗\n"
|
| 25 |
"║ WARNING: No LLM API key found. ║\n"
|
| 26 |
"║ ║\n"
|
| 27 |
+
"║ Set at least one of: ║\n"
|
| 28 |
+
"║ ANTHROPIC_API_KEY (preferred — uses Claude Haiku) ║\n"
|
| 29 |
+
"║ OPENAI_API_KEY (fallback — uses GPT-4o-mini) ║\n"
|
| 30 |
"║ ║\n"
|
| 31 |
+
"║ The server will start, but ALL reviews will fall back ║\n"
|
| 32 |
+
"║ to the local mock reviewer. ║\n"
|
| 33 |
"╚══════════════════════════════════════════════════════════╝\n",
|
| 34 |
file=sys.stderr,
|
| 35 |
)
|
| 36 |
return
|
| 37 |
+
|
| 38 |
+
if has_anthropic:
|
| 39 |
+
logger.info("API key found: Anthropic (primary)")
|
| 40 |
+
if has_openai:
|
| 41 |
+
logger.info("API key found: OpenAI (fallback)")
|
| 42 |
|
| 43 |
|
| 44 |
_check_api_keys()
|
|
|
|
| 97 |
# LLM call
|
| 98 |
# ---------------------------------------------------------------------------
|
| 99 |
|
|
|
|
| 100 |
def call_llm(prompt: str, *, system: str | None = None) -> str | None:
|
| 101 |
"""
|
| 102 |
+
Try Anthropic first, then OpenAI. Returns the raw text response or None.
|
| 103 |
+
Exceptions are always logged — never silently swallowed.
|
| 104 |
"""
|
| 105 |
+
# --- Anthropic ---
|
| 106 |
+
anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "").strip()
|
| 107 |
+
if anthropic_key:
|
| 108 |
+
try:
|
| 109 |
+
import anthropic
|
| 110 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
| 111 |
+
kwargs: dict = {
|
| 112 |
+
"model": ANTHROPIC_MODEL,
|
| 113 |
+
"max_tokens": MAX_TOKENS,
|
| 114 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 115 |
+
}
|
| 116 |
+
if system:
|
| 117 |
+
kwargs["system"] = system
|
| 118 |
+
message = client.messages.create(**kwargs)
|
| 119 |
+
return message.content[0].text
|
| 120 |
+
except Exception as exc:
|
| 121 |
+
logger.error("Anthropic call failed: %s: %s", type(exc).__name__, exc)
|
| 122 |
+
|
| 123 |
+
# --- OpenAI fallback ---
|
| 124 |
+
openai_key = os.environ.get("OPENAI_API_KEY", "").strip()
|
| 125 |
+
if openai_key:
|
| 126 |
+
try:
|
| 127 |
+
import openai
|
| 128 |
+
client = openai.OpenAI(api_key=openai_key)
|
| 129 |
+
messages = []
|
| 130 |
+
if system:
|
| 131 |
+
messages.append({"role": "system", "content": system})
|
| 132 |
+
messages.append({"role": "user", "content": prompt})
|
| 133 |
+
response = client.chat.completions.create(
|
| 134 |
+
model=OPENAI_MODEL,
|
| 135 |
+
max_tokens=MAX_TOKENS,
|
| 136 |
+
messages=messages,
|
| 137 |
+
)
|
| 138 |
+
return response.choices[0].message.content
|
| 139 |
+
except Exception as exc:
|
| 140 |
+
logger.error("OpenAI call failed: %s: %s", type(exc).__name__, exc)
|
| 141 |
+
|
| 142 |
+
logger.warning("All LLM providers failed — falling back to mock reviewer.")
|
| 143 |
+
return None
|
| 144 |
|
| 145 |
|
| 146 |
# ---------------------------------------------------------------------------
|
| 147 |
# JSON parsing helper
|
| 148 |
# ---------------------------------------------------------------------------
|
| 149 |
|
|
|
|
| 150 |
def _parse_json(raw: str) -> dict | None:
|
| 151 |
"""Try direct parse, then regex-extracted substring."""
|
| 152 |
if not raw:
|
|
|
|
| 178 |
|
| 179 |
# SQL injection
|
| 180 |
if 'f"select' in code_lower or "f'select" in code_lower:
|
| 181 |
+
bugs.append({
|
| 182 |
+
"type": "bug",
|
| 183 |
+
"category": "security",
|
| 184 |
+
"severity": 5,
|
| 185 |
+
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 186 |
+
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 187 |
+
"confidence": 0.95,
|
| 188 |
+
"line_hint": "database query line"
|
| 189 |
+
})
|
|
|
|
|
|
|
| 190 |
|
| 191 |
# Hardcoded password
|
| 192 |
if "hashed = password" in code_lower or (
|
| 193 |
+
"password" in code_lower and "hash" not in code_lower and "bcrypt" not in code_lower
|
|
|
|
|
|
|
| 194 |
):
|
| 195 |
+
bugs.append({
|
| 196 |
+
"type": "bug",
|
| 197 |
+
"category": "security",
|
| 198 |
+
"severity": 5,
|
| 199 |
+
"comment": "Hardcoded password/credential detected.",
|
| 200 |
+
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 201 |
+
"confidence": 0.98,
|
| 202 |
+
"line_hint": "password assignment line"
|
| 203 |
+
})
|
|
|
|
|
|
|
| 204 |
|
| 205 |
# Off-by-one
|
| 206 |
if "range(len(" in code_lower and "- 1" in code_lower:
|
| 207 |
+
bugs.append({
|
| 208 |
+
"type": "bug",
|
| 209 |
+
"category": "logic",
|
| 210 |
+
"severity": 3,
|
| 211 |
+
"comment": "Off-by-one error: range(len(x)-1) skips the last element.",
|
| 212 |
+
"fix": "Use range(len(arr)) or check bounds: if i+1 < len(arr)",
|
| 213 |
+
"confidence": 0.85,
|
| 214 |
+
"line_hint": "loop range call"
|
| 215 |
+
})
|
|
|
|
|
|
|
| 216 |
|
| 217 |
# Division by zero
|
| 218 |
if "/ 0" in code_lower:
|
| 219 |
+
bugs.append({
|
| 220 |
+
"type": "bug",
|
| 221 |
+
"category": "logic",
|
| 222 |
+
"severity": 3,
|
| 223 |
+
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 224 |
+
"fix": "Add check: if denominator != 0: result = numerator / denominator",
|
| 225 |
+
"confidence": 0.99,
|
| 226 |
+
"line_hint": "division line"
|
| 227 |
+
})
|
|
|
|
|
|
|
| 228 |
|
| 229 |
# Strict comparison
|
| 230 |
+
if ("> amount" in code_lower or "< amount" in code_lower) and ">=" not in code_lower and "<=" not in code_lower:
|
| 231 |
+
bugs.append({
|
| 232 |
+
"type": "bug",
|
| 233 |
+
"category": "logic",
|
| 234 |
+
"severity": 4,
|
| 235 |
+
"comment": "Strict > / < in balance check; may miss the equality edge case.",
|
| 236 |
+
"fix": "Use >= or <= to include equality edge case.",
|
| 237 |
+
"confidence": 0.8,
|
| 238 |
+
"line_hint": "comparison check"
|
| 239 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
return bugs
|
| 242 |
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
# ---------------------------------------------------------------------------
|
| 245 |
# Main entry point
|
| 246 |
# ---------------------------------------------------------------------------
|
| 247 |
|
| 248 |
_REQUIRED_KEYS = {"type", "category", "line_hint", "comment", "severity"}
|
| 249 |
+
_DEFAULTS = {"type": "approve", "category": "ok", "line_hint": "", "comment": "", "severity": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
|
| 252 |
def review(code: str) -> list:
|
|
|
|
| 266 |
|
| 267 |
if result is None or not isinstance(result, list):
|
| 268 |
# One retry: tell the model its output was invalid
|
| 269 |
+
logger.warning("LLM returned malformed JSON or not a list — retrying with correction hint.")
|
|
|
|
|
|
|
| 270 |
user_msg_retry = build_user_message(code, retry=True)
|
| 271 |
raw_retry = call_llm(user_msg_retry, system=_SYSTEM_PROMPT)
|
| 272 |
result = _parse_json(raw_retry)
|
|
|
|
| 289 |
|
| 290 |
if __name__ == "__main__":
|
| 291 |
_TESTS = [
|
| 292 |
+
("SQL injection", "def login(u, p, db):\n q = f\"SELECT * FROM users WHERE username='{u}'\"\n return db.execute(q)"),
|
| 293 |
+
("Off-by-one", "def find_max(nums):\n mx = nums[0]\n for i in range(len(nums) - 1):\n if nums[i] > mx: mx = nums[i]\n return mx"),
|
| 294 |
+
("Plain password", "def save(u, pw, db):\n db.insert('users', {'username': u, 'password': pw})"),
|
| 295 |
+
("Clean code", "def add(a: int, b: int) -> int:\n return a + b"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
]
|
| 297 |
|
| 298 |
print("=== Agent Tests ===\n")
|
api/index.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
# Add root directory to path so imports work identically to running locally
|
| 5 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 6 |
+
|
| 7 |
+
from app import app
|
| 8 |
+
|
| 9 |
+
# Vercel needs the flask app to be exposed exactly like this in api/index.py
|
config.py
CHANGED
|
@@ -49,7 +49,10 @@ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
| 49 |
EPISODES_FILE = os.path.join(BASE_DIR, "episodes.json")
|
| 50 |
ANSWERS_FILE = os.path.join(BASE_DIR, "answers.json")
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
CHECKPOINT_FILE = os.path.join(RUNS_DIR, "checkpoint.json")
|
| 54 |
|
| 55 |
# ---------------------------------------------------------------------------
|
|
|
|
| 49 |
EPISODES_FILE = os.path.join(BASE_DIR, "episodes.json")
|
| 50 |
ANSWERS_FILE = os.path.join(BASE_DIR, "answers.json")
|
| 51 |
|
| 52 |
+
if os.environ.get("VERCEL"):
|
| 53 |
+
RUNS_DIR = "/tmp/runs"
|
| 54 |
+
else:
|
| 55 |
+
RUNS_DIR = os.path.join(BASE_DIR, "runs")
|
| 56 |
CHECKPOINT_FILE = os.path.join(RUNS_DIR, "checkpoint.json")
|
| 57 |
|
| 58 |
# ---------------------------------------------------------------------------
|
environment.py
CHANGED
|
@@ -1,12 +1,6 @@
|
|
| 1 |
import uuid
|
| 2 |
from openenv.core.env_server import Environment
|
| 3 |
from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
|
| 4 |
-
from tasks.easy.grader import grade as grade_task_easy_001
|
| 5 |
-
from tasks.medium.grader import grade as grade_task_medium_002
|
| 6 |
-
from tasks.hard.grader import grade as grade_task_hard_003
|
| 7 |
-
from tasks.extra1.grader import grade as grade_task_extra_004
|
| 8 |
-
from tasks.extra2.grader import grade as grade_task_extra_005
|
| 9 |
-
from tasks.scoring import finalize_task_reward
|
| 10 |
|
| 11 |
|
| 12 |
class CodeBugEnvironment(Environment):
|
|
@@ -14,7 +8,6 @@ class CodeBugEnvironment(Environment):
|
|
| 14 |
|
| 15 |
TASKS = [
|
| 16 |
{
|
| 17 |
-
"id": "task_easy_001",
|
| 18 |
"difficulty": "easy",
|
| 19 |
"snippet": (
|
| 20 |
"def transfer(from_account, to_account, amount):\n"
|
|
@@ -27,7 +20,6 @@ class CodeBugEnvironment(Environment):
|
|
| 27 |
"truth": {"category": "logic", "severity": 4, "line_hint": 2},
|
| 28 |
},
|
| 29 |
{
|
| 30 |
-
"id": "task_medium_002",
|
| 31 |
"difficulty": "medium",
|
| 32 |
"snippet": (
|
| 33 |
"def find_max(numbers):\n"
|
|
@@ -42,7 +34,6 @@ class CodeBugEnvironment(Environment):
|
|
| 42 |
"truth": {"category": "logic", "severity": 3, "line_hint": 5},
|
| 43 |
},
|
| 44 |
{
|
| 45 |
-
"id": "task_hard_003",
|
| 46 |
"difficulty": "hard",
|
| 47 |
"snippet": (
|
| 48 |
"def login(username, password):\n"
|
|
@@ -55,36 +46,8 @@ class CodeBugEnvironment(Environment):
|
|
| 55 |
),
|
| 56 |
"truth": {"category": "security", "severity": 5, "line_hint": 2},
|
| 57 |
},
|
| 58 |
-
{
|
| 59 |
-
"id": "task_extra_004",
|
| 60 |
-
"difficulty": "hard",
|
| 61 |
-
"snippet": (
|
| 62 |
-
"API_KEY = \"sk-1234567890abcdef\"\n"
|
| 63 |
-
"def process_data(data):\n"
|
| 64 |
-
" return data.upper()"
|
| 65 |
-
),
|
| 66 |
-
"truth": {"category": "security", "severity": 5, "line_hint": 1},
|
| 67 |
-
},
|
| 68 |
-
{
|
| 69 |
-
"id": "task_extra_005",
|
| 70 |
-
"difficulty": "medium",
|
| 71 |
-
"snippet": (
|
| 72 |
-
"def divide(a, b):\n"
|
| 73 |
-
" # Potential bug here\n"
|
| 74 |
-
" return a / b"
|
| 75 |
-
),
|
| 76 |
-
"truth": {"category": "logic", "severity": 3, "line_hint": 3},
|
| 77 |
-
},
|
| 78 |
]
|
| 79 |
|
| 80 |
-
_TASK_GRADERS = {
|
| 81 |
-
"task_easy_001": grade_task_easy_001,
|
| 82 |
-
"task_medium_002": grade_task_medium_002,
|
| 83 |
-
"task_hard_003": grade_task_hard_003,
|
| 84 |
-
"task_extra_004": grade_task_extra_004,
|
| 85 |
-
"task_extra_005": grade_task_extra_005,
|
| 86 |
-
}
|
| 87 |
-
|
| 88 |
def __init__(self):
|
| 89 |
self._state = CodeReviewState()
|
| 90 |
|
|
@@ -99,7 +62,7 @@ class CodeBugEnvironment(Environment):
|
|
| 99 |
task = self.TASKS[0]
|
| 100 |
return CodeReviewObservation(
|
| 101 |
done=False,
|
| 102 |
-
reward=0.
|
| 103 |
code_snippet=task["snippet"],
|
| 104 |
difficulty=task["difficulty"],
|
| 105 |
feedback=(
|
|
@@ -114,14 +77,20 @@ class CodeBugEnvironment(Environment):
|
|
| 114 |
|
| 115 |
idx = self._state.current_task_idx
|
| 116 |
task = self.TASKS[idx]
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
grader = self._TASK_GRADERS.get(task_id)
|
| 120 |
-
if grader is None:
|
| 121 |
-
reward = 0.5
|
| 122 |
-
else:
|
| 123 |
-
reward = float(grader(action))
|
| 124 |
-
reward = finalize_task_reward(reward)
|
| 125 |
self._state.total_score += reward
|
| 126 |
self._state.current_task_idx += 1
|
| 127 |
|
|
|
|
| 1 |
import uuid
|
| 2 |
from openenv.core.env_server import Environment
|
| 3 |
from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
class CodeBugEnvironment(Environment):
|
|
|
|
| 8 |
|
| 9 |
TASKS = [
|
| 10 |
{
|
|
|
|
| 11 |
"difficulty": "easy",
|
| 12 |
"snippet": (
|
| 13 |
"def transfer(from_account, to_account, amount):\n"
|
|
|
|
| 20 |
"truth": {"category": "logic", "severity": 4, "line_hint": 2},
|
| 21 |
},
|
| 22 |
{
|
|
|
|
| 23 |
"difficulty": "medium",
|
| 24 |
"snippet": (
|
| 25 |
"def find_max(numbers):\n"
|
|
|
|
| 34 |
"truth": {"category": "logic", "severity": 3, "line_hint": 5},
|
| 35 |
},
|
| 36 |
{
|
|
|
|
| 37 |
"difficulty": "hard",
|
| 38 |
"snippet": (
|
| 39 |
"def login(username, password):\n"
|
|
|
|
| 46 |
),
|
| 47 |
"truth": {"category": "security", "severity": 5, "line_hint": 2},
|
| 48 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
]
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def __init__(self):
|
| 52 |
self._state = CodeReviewState()
|
| 53 |
|
|
|
|
| 62 |
task = self.TASKS[0]
|
| 63 |
return CodeReviewObservation(
|
| 64 |
done=False,
|
| 65 |
+
reward=0.0,
|
| 66 |
code_snippet=task["snippet"],
|
| 67 |
difficulty=task["difficulty"],
|
| 68 |
feedback=(
|
|
|
|
| 77 |
|
| 78 |
idx = self._state.current_task_idx
|
| 79 |
task = self.TASKS[idx]
|
| 80 |
+
truth = task["truth"]
|
| 81 |
+
|
| 82 |
+
# Reward: 0.0 → 1.0
|
| 83 |
+
reward = 0.0
|
| 84 |
+
if action.category.strip().lower() == truth["category"]:
|
| 85 |
+
reward += 0.5
|
| 86 |
+
sev_diff = abs(action.severity - truth["severity"])
|
| 87 |
+
if sev_diff == 0:
|
| 88 |
+
reward += 0.3
|
| 89 |
+
elif sev_diff == 1:
|
| 90 |
+
reward += 0.15
|
| 91 |
+
if action.line_hint is not None and action.line_hint == truth["line_hint"]:
|
| 92 |
+
reward += 0.2
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
self._state.total_score += reward
|
| 95 |
self._state.current_task_idx += 1
|
| 96 |
|
grader.py
CHANGED
|
@@ -30,40 +30,6 @@ from config import (
|
|
| 30 |
)
|
| 31 |
|
| 32 |
|
| 33 |
-
def _raw_reward_bounds() -> tuple[int, int]:
|
| 34 |
-
"""Worst and best achievable integer scores in grade() (single step)."""
|
| 35 |
-
penalties = (
|
| 36 |
-
PENALTY_WRONG_CATEGORY,
|
| 37 |
-
PENALTY_MISS_CRITICAL,
|
| 38 |
-
PENALTY_MISS_HIGH,
|
| 39 |
-
PENALTY_MISS_MEDIUM,
|
| 40 |
-
PENALTY_MISS_LOW,
|
| 41 |
-
PENALTY_UNKNOWN_ACTION,
|
| 42 |
-
)
|
| 43 |
-
min_r = min(penalties)
|
| 44 |
-
bundles = (
|
| 45 |
-
REWARD_SECURITY_CATCH + REWARD_SEVERITY_EXACT + REWARD_COMMENT_LONG + REWARD_LINE_HINT,
|
| 46 |
-
REWARD_LOGIC_CATCH + REWARD_SEVERITY_EXACT + REWARD_COMMENT_LONG + REWARD_LINE_HINT,
|
| 47 |
-
REWARD_OTHER_CATCH + REWARD_SEVERITY_EXACT + REWARD_COMMENT_LONG + REWARD_LINE_HINT,
|
| 48 |
-
REWARD_PARTIAL_CREDIT,
|
| 49 |
-
REWARD_CLEAN_APPROVE,
|
| 50 |
-
)
|
| 51 |
-
max_r = max(bundles)
|
| 52 |
-
return min_r, max_r
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
_RAW_MIN, _RAW_MAX = _raw_reward_bounds()
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def _normalize_reward(raw: int) -> float:
|
| 59 |
-
"""Map integer rubric score to (0, 1) exclusive for hackathon / OpenEnv validators."""
|
| 60 |
-
clamped = max(_RAW_MIN, min(_RAW_MAX, raw))
|
| 61 |
-
if _RAW_MAX == _RAW_MIN:
|
| 62 |
-
return 0.5
|
| 63 |
-
scaled = (clamped - _RAW_MIN) / (_RAW_MAX - _RAW_MIN)
|
| 64 |
-
return round(0.01 + scaled * 0.98, 4)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
# ---------------------------------------------------------------------------
|
| 68 |
# GradeResult
|
| 69 |
# ---------------------------------------------------------------------------
|
|
@@ -72,7 +38,7 @@ def _normalize_reward(raw: int) -> float:
|
|
| 72 |
class GradeResult:
|
| 73 |
def __init__(
|
| 74 |
self,
|
| 75 |
-
reward:
|
| 76 |
breakdown: list[str],
|
| 77 |
correct: bool,
|
| 78 |
bug_type: str = "unknown",
|
|
@@ -88,7 +54,7 @@ class GradeResult:
|
|
| 88 |
lines = [
|
| 89 |
"GRADE SUMMARY",
|
| 90 |
"-" * 25,
|
| 91 |
-
f"Reward: {self.reward:+
|
| 92 |
f"Correct: {'Yes' if self.correct else 'No'}",
|
| 93 |
f"Bug was: {self.bug_type} (severity {self.bug_severity})",
|
| 94 |
"",
|
|
@@ -97,7 +63,7 @@ class GradeResult:
|
|
| 97 |
for entry in self.breakdown:
|
| 98 |
lines.append(f" {entry}")
|
| 99 |
lines.append("-" * 25)
|
| 100 |
-
lines.append(f"Total: {self.reward:+
|
| 101 |
return "\n".join(lines)
|
| 102 |
|
| 103 |
def to_dict(self) -> dict:
|
|
@@ -123,11 +89,7 @@ def grade(ai_action: dict, ground_truth: dict | None) -> GradeResult:
|
|
| 123 |
ground_truth keys: bug → {type, severity, description, line_hint}
|
| 124 |
"""
|
| 125 |
if ground_truth is None or "bug" not in ground_truth:
|
| 126 |
-
return GradeResult(
|
| 127 |
-
reward=_normalize_reward(0),
|
| 128 |
-
breakdown=["No ground truth available"],
|
| 129 |
-
correct=False,
|
| 130 |
-
)
|
| 131 |
|
| 132 |
bug = ground_truth["bug"]
|
| 133 |
bug_type = bug.get("type", "none")
|
|
@@ -241,7 +203,7 @@ def grade(ai_action: dict, ground_truth: dict | None) -> GradeResult:
|
|
| 241 |
breakdown.append(f"{PENALTY_UNKNOWN_ACTION}: unknown action type '{ai_type}'")
|
| 242 |
|
| 243 |
return GradeResult(
|
| 244 |
-
reward=
|
| 245 |
breakdown=breakdown,
|
| 246 |
correct=correct,
|
| 247 |
bug_type=bug_type,
|
|
@@ -257,7 +219,7 @@ def grade(ai_action: dict, ground_truth: dict | None) -> GradeResult:
|
|
| 257 |
def batch_grade(episodes: list[dict]) -> dict:
|
| 258 |
"""Summarise grading across multiple episodes."""
|
| 259 |
results_list: list[dict] = []
|
| 260 |
-
total_reward = 0
|
| 261 |
correct_count = 0
|
| 262 |
best_score = -float("inf")
|
| 263 |
worst_score = float("inf")
|
|
@@ -272,7 +234,7 @@ def batch_grade(episodes: list[dict]) -> dict:
|
|
| 272 |
d = res.to_dict()
|
| 273 |
results_list.append(d)
|
| 274 |
|
| 275 |
-
total_reward +=
|
| 276 |
if d["correct"]:
|
| 277 |
correct_count += 1
|
| 278 |
if d["bug_type"] == "security":
|
|
|
|
| 30 |
)
|
| 31 |
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# ---------------------------------------------------------------------------
|
| 34 |
# GradeResult
|
| 35 |
# ---------------------------------------------------------------------------
|
|
|
|
| 38 |
class GradeResult:
|
| 39 |
def __init__(
|
| 40 |
self,
|
| 41 |
+
reward: int,
|
| 42 |
breakdown: list[str],
|
| 43 |
correct: bool,
|
| 44 |
bug_type: str = "unknown",
|
|
|
|
| 54 |
lines = [
|
| 55 |
"GRADE SUMMARY",
|
| 56 |
"-" * 25,
|
| 57 |
+
f"Reward: {self.reward:+d}",
|
| 58 |
f"Correct: {'Yes' if self.correct else 'No'}",
|
| 59 |
f"Bug was: {self.bug_type} (severity {self.bug_severity})",
|
| 60 |
"",
|
|
|
|
| 63 |
for entry in self.breakdown:
|
| 64 |
lines.append(f" {entry}")
|
| 65 |
lines.append("-" * 25)
|
| 66 |
+
lines.append(f"Total: {self.reward:+d}")
|
| 67 |
return "\n".join(lines)
|
| 68 |
|
| 69 |
def to_dict(self) -> dict:
|
|
|
|
| 89 |
ground_truth keys: bug → {type, severity, description, line_hint}
|
| 90 |
"""
|
| 91 |
if ground_truth is None or "bug" not in ground_truth:
|
| 92 |
+
return GradeResult(reward=0, breakdown=["No ground truth available"], correct=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
bug = ground_truth["bug"]
|
| 95 |
bug_type = bug.get("type", "none")
|
|
|
|
| 203 |
breakdown.append(f"{PENALTY_UNKNOWN_ACTION}: unknown action type '{ai_type}'")
|
| 204 |
|
| 205 |
return GradeResult(
|
| 206 |
+
reward=reward,
|
| 207 |
breakdown=breakdown,
|
| 208 |
correct=correct,
|
| 209 |
bug_type=bug_type,
|
|
|
|
| 219 |
def batch_grade(episodes: list[dict]) -> dict:
|
| 220 |
"""Summarise grading across multiple episodes."""
|
| 221 |
results_list: list[dict] = []
|
| 222 |
+
total_reward = 0
|
| 223 |
correct_count = 0
|
| 224 |
best_score = -float("inf")
|
| 225 |
worst_score = float("inf")
|
|
|
|
| 234 |
d = res.to_dict()
|
| 235 |
results_list.append(d)
|
| 236 |
|
| 237 |
+
total_reward += d["reward"]
|
| 238 |
if d["correct"]:
|
| 239 |
correct_count += 1
|
| 240 |
if d["bug_type"] == "security":
|
inference.py
CHANGED
|
@@ -1,46 +1,45 @@
|
|
| 1 |
"""
|
| 2 |
-
inference.py —
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
| 8 |
"""
|
| 9 |
|
| 10 |
-
from __future__ import annotations
|
| 11 |
-
|
| 12 |
-
import json
|
| 13 |
import os
|
| 14 |
-
import
|
| 15 |
import sys
|
| 16 |
|
| 17 |
from openai import OpenAI
|
| 18 |
-
from agent import mock_review_action
|
| 19 |
-
|
| 20 |
-
# Manifest graders (must match openenv.yaml `grader:` entries exactly)
|
| 21 |
-
from tasks.easy.grader import grade as grade_task_easy_001
|
| 22 |
-
from tasks.extra1.grader import grade as grade_task_extra_004
|
| 23 |
-
from tasks.extra2.grader import grade as grade_task_extra_005
|
| 24 |
-
from tasks.hard.grader import grade as grade_task_hard_003
|
| 25 |
-
from tasks.medium.grader import grade as grade_task_medium_002
|
| 26 |
-
|
| 27 |
-
# Root rubric (integer → normalized); imported so static checks / RL tooling see grader.py
|
| 28 |
-
from grader import grade as root_rubric_grade
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
|
| 31 |
-
MODEL_NAME
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
"
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
TASKS = [
|
| 42 |
{
|
| 43 |
-
"
|
| 44 |
"difficulty": "easy",
|
| 45 |
"code": (
|
| 46 |
"def transfer(from_account, to_account, amount):\n"
|
|
@@ -50,9 +49,10 @@ TASKS = [
|
|
| 50 |
" return True\n"
|
| 51 |
" return False"
|
| 52 |
),
|
|
|
|
| 53 |
},
|
| 54 |
{
|
| 55 |
-
"
|
| 56 |
"difficulty": "medium",
|
| 57 |
"code": (
|
| 58 |
"def find_max(numbers):\n"
|
|
@@ -64,9 +64,10 @@ TASKS = [
|
|
| 64 |
" max_val = numbers[i]\n"
|
| 65 |
" return max_val"
|
| 66 |
),
|
|
|
|
| 67 |
},
|
| 68 |
{
|
| 69 |
-
"
|
| 70 |
"difficulty": "hard",
|
| 71 |
"code": (
|
| 72 |
"def login(username, password):\n"
|
|
@@ -77,158 +78,99 @@ TASKS = [
|
|
| 77 |
" return True\n"
|
| 78 |
" return False"
|
| 79 |
),
|
| 80 |
-
|
| 81 |
-
{
|
| 82 |
-
"task_id": "task_extra_004",
|
| 83 |
-
"difficulty": "hard",
|
| 84 |
-
"code": (
|
| 85 |
-
'API_KEY = "sk-1234567890abcdef"\n'
|
| 86 |
-
"def process_data(data):\n"
|
| 87 |
-
" return data.upper()"
|
| 88 |
-
),
|
| 89 |
-
},
|
| 90 |
-
{
|
| 91 |
-
"task_id": "task_extra_005",
|
| 92 |
-
"difficulty": "medium",
|
| 93 |
-
"code": ("def divide(a, b):\n # Potential bug here\n return a / b"),
|
| 94 |
},
|
| 95 |
]
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
|
|
|
| 99 |
{
|
| 100 |
"category": "logic" | "security" | "style" | "approve",
|
| 101 |
"severity": <integer 1-5>,
|
| 102 |
-
"line_hint": <integer line number or null
|
| 103 |
-
"comment": "<short
|
| 104 |
-
}
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
return json.loads(m.group(0))
|
| 117 |
-
except json.JSONDecodeError:
|
| 118 |
-
pass
|
| 119 |
-
return {}
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
def _coerce_code_review_action(data: dict) -> dict:
|
| 123 |
-
cat = str(data.get("category", "approve")).strip().lower()
|
| 124 |
-
if cat not in ("logic", "security", "style", "approve"):
|
| 125 |
-
cat = "approve"
|
| 126 |
-
try:
|
| 127 |
-
sev = int(data.get("severity", 1))
|
| 128 |
-
except (TypeError, ValueError):
|
| 129 |
-
sev = 1
|
| 130 |
-
sev = max(1, min(5, sev))
|
| 131 |
-
lh = data.get("line_hint")
|
| 132 |
-
if lh is not None and lh != "":
|
| 133 |
-
try:
|
| 134 |
-
lh = int(lh)
|
| 135 |
-
except (TypeError, ValueError):
|
| 136 |
-
lh = None
|
| 137 |
-
else:
|
| 138 |
-
lh = None
|
| 139 |
-
return {
|
| 140 |
-
"category": cat,
|
| 141 |
-
"severity": sev,
|
| 142 |
-
"line_hint": lh,
|
| 143 |
-
"comment": str(data.get("comment", "")).strip(),
|
| 144 |
-
}
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
def _chat_json(client: OpenAI, user_text: str) -> dict:
|
| 148 |
-
"""Prefer json_object mode; retry without it if the deployment rejects it."""
|
| 149 |
-
kwargs = dict(
|
| 150 |
model=MODEL_NAME,
|
| 151 |
-
max_tokens=400,
|
| 152 |
-
temperature=0.2,
|
| 153 |
messages=[
|
| 154 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 155 |
-
{"role": "user",
|
| 156 |
],
|
|
|
|
|
|
|
| 157 |
)
|
| 158 |
-
|
| 159 |
-
response = client.chat.completions.create(
|
| 160 |
-
**kwargs, response_format={"type": "json_object"}
|
| 161 |
-
)
|
| 162 |
-
except Exception:
|
| 163 |
-
response = client.chat.completions.create(**kwargs)
|
| 164 |
raw = response.choices[0].message.content
|
| 165 |
-
|
| 166 |
-
return _coerce_code_review_action(parsed) if parsed else {}
|
| 167 |
|
| 168 |
|
| 169 |
-
def
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
"severity": 1,
|
| 176 |
-
"line_hint": None,
|
| 177 |
-
"comment": "parse_error",
|
| 178 |
-
}
|
| 179 |
-
return data
|
| 180 |
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
| 186 |
|
| 187 |
-
|
|
|
|
|
|
|
| 188 |
|
| 189 |
-
|
| 190 |
-
print(
|
| 191 |
-
"[WARNING] HF_TOKEN or OPENAI_API_KEY not set — using rule-based fallback for scoring.",
|
| 192 |
-
flush=True,
|
| 193 |
-
)
|
| 194 |
|
| 195 |
-
client = None
|
| 196 |
-
if has_api_key:
|
| 197 |
-
client = OpenAI(api_key=llm_key, base_url=API_BASE_URL)
|
| 198 |
-
|
| 199 |
-
_san = root_rubric_grade(
|
| 200 |
-
{
|
| 201 |
-
"type": "approve",
|
| 202 |
-
"category": "ok",
|
| 203 |
-
"line_hint": "",
|
| 204 |
-
"comment": "",
|
| 205 |
-
"severity": 0,
|
| 206 |
-
},
|
| 207 |
-
{"bug": {"type": "none", "severity": 0, "description": "", "line_hint": ""}},
|
| 208 |
-
)
|
| 209 |
-
if not (isinstance(_san.reward, float) and 0.0 < _san.reward < 1.0):
|
| 210 |
-
print(f"[ERROR] grader.py reward out of (0,1): {_san.reward!r}", flush=True)
|
| 211 |
-
sys.exit(1)
|
| 212 |
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
for task in TASKS:
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
try:
|
| 217 |
-
|
| 218 |
-
action = run_task(client, task)
|
| 219 |
-
else:
|
| 220 |
-
action = mock_review_action(task["code"])
|
| 221 |
except Exception as exc:
|
| 222 |
-
action = {
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
|
| 234 |
if __name__ == "__main__":
|
|
|
|
| 1 |
"""
|
| 2 |
+
inference.py — CodeBug baseline inference script.
|
| 3 |
|
| 4 |
+
Strictly follows the Meta PyTorch Hackathon pre-submission checklist:
|
| 5 |
+
- Environment variables: API_BASE_URL, MODEL_NAME, HF_TOKEN
|
| 6 |
+
- Defaults ONLY for API_BASE_URL and MODEL_NAME (not HF_TOKEN)
|
| 7 |
+
- All LLM calls use `from openai import OpenAI` configured via these variables
|
| 8 |
+
- Stdout logs follow the required [START] / [STEP] / [END] format exactly
|
| 9 |
"""
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
import os
|
| 12 |
+
import json
|
| 13 |
import sys
|
| 14 |
|
| 15 |
from openai import OpenAI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# ─────────────────────────────────────────────────────────────
|
| 18 |
+
# Environment variables (checklist requirement)
|
| 19 |
+
# Defaults ONLY for API_BASE_URL and MODEL_NAME — NOT HF_TOKEN
|
| 20 |
+
# ─────────────────────────────────────────────────────────────
|
| 21 |
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
|
| 22 |
+
MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
|
| 23 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # No default — must be set by user
|
| 24 |
+
|
| 25 |
+
if not HF_TOKEN:
|
| 26 |
+
print("[ERROR] HF_TOKEN environment variable is required but not set.", flush=True)
|
| 27 |
+
sys.exit(1)
|
| 28 |
+
|
| 29 |
+
# ─────────────────────────────────────────────────────────────
|
| 30 |
+
# OpenAI client — configured strictly via the env variables
|
| 31 |
+
# ─────────────────────────────────────────────────────────────
|
| 32 |
+
client = OpenAI(
|
| 33 |
+
api_key=HF_TOKEN,
|
| 34 |
+
base_url=API_BASE_URL,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# ─────────────────────────────────────────────────────────────
|
| 38 |
+
# Code review tasks (3 difficulty levels: easy → medium → hard)
|
| 39 |
+
# ─────────────────────────────────────────────────────────────
|
| 40 |
TASKS = [
|
| 41 |
{
|
| 42 |
+
"id": "task_easy_001",
|
| 43 |
"difficulty": "easy",
|
| 44 |
"code": (
|
| 45 |
"def transfer(from_account, to_account, amount):\n"
|
|
|
|
| 49 |
" return True\n"
|
| 50 |
" return False"
|
| 51 |
),
|
| 52 |
+
"truth": {"category": "logic", "severity": 4},
|
| 53 |
},
|
| 54 |
{
|
| 55 |
+
"id": "task_medium_002",
|
| 56 |
"difficulty": "medium",
|
| 57 |
"code": (
|
| 58 |
"def find_max(numbers):\n"
|
|
|
|
| 64 |
" max_val = numbers[i]\n"
|
| 65 |
" return max_val"
|
| 66 |
),
|
| 67 |
+
"truth": {"category": "logic", "severity": 3},
|
| 68 |
},
|
| 69 |
{
|
| 70 |
+
"id": "task_hard_003",
|
| 71 |
"difficulty": "hard",
|
| 72 |
"code": (
|
| 73 |
"def login(username, password):\n"
|
|
|
|
| 78 |
" return True\n"
|
| 79 |
" return False"
|
| 80 |
),
|
| 81 |
+
"truth": {"category": "security", "severity": 5},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
},
|
| 83 |
]
|
| 84 |
|
| 85 |
+
SYSTEM_PROMPT = """\
|
| 86 |
+
You are a code review agent. Your task is to identify bugs in code snippets.
|
| 87 |
+
Return ONLY a valid JSON object with this exact schema (no markdown, no prose):
|
| 88 |
{
|
| 89 |
"category": "logic" | "security" | "style" | "approve",
|
| 90 |
"severity": <integer 1-5>,
|
| 91 |
+
"line_hint": <integer line number or null>,
|
| 92 |
+
"comment": "<short description of the bug>"
|
| 93 |
+
}
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def call_llm(code: str, difficulty: str) -> dict:
|
| 98 |
+
"""Call LLM via OpenAI client and parse the structured JSON response."""
|
| 99 |
+
user_prompt = (
|
| 100 |
+
f"Difficulty level: {difficulty}\n\n"
|
| 101 |
+
f"Review the following code and identify any bugs:\n\n{code}"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
response = client.chat.completions.create(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
model=MODEL_NAME,
|
|
|
|
|
|
|
| 106 |
messages=[
|
| 107 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 108 |
+
{"role": "user", "content": user_prompt},
|
| 109 |
],
|
| 110 |
+
response_format={"type": "json_object"},
|
| 111 |
+
temperature=0.2,
|
| 112 |
)
|
| 113 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
raw = response.choices[0].message.content
|
| 115 |
+
return json.loads(raw)
|
|
|
|
| 116 |
|
| 117 |
|
| 118 |
+
def score_action(action: dict, truth: dict) -> float:
|
| 119 |
+
"""
|
| 120 |
+
Score the agent's action against ground truth.
|
| 121 |
+
Returns a float in [0.0, 1.0].
|
| 122 |
+
"""
|
| 123 |
+
reward = 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
# Category match → 0.5
|
| 126 |
+
if action.get("category", "").lower() == truth["category"]:
|
| 127 |
+
reward += 0.5
|
| 128 |
|
| 129 |
+
# Severity accuracy → up to 0.3
|
| 130 |
+
sev_diff = abs(int(action.get("severity", 0)) - truth["severity"])
|
| 131 |
+
if sev_diff == 0:
|
| 132 |
+
reward += 0.3
|
| 133 |
+
elif sev_diff == 1:
|
| 134 |
+
reward += 0.15
|
| 135 |
|
| 136 |
+
# Any non-None line hint when a bug exists → 0.2
|
| 137 |
+
if action.get("line_hint") is not None and truth["category"] != "approve":
|
| 138 |
+
reward += 0.2
|
| 139 |
|
| 140 |
+
return round(min(reward, 1.0), 4)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
+
def run_inference():
|
| 144 |
+
total_reward = 0.0
|
| 145 |
+
|
| 146 |
+
# ── [START] ───────────────────────────────────────────────
|
| 147 |
+
print(f"[START] api_base={API_BASE_URL} model={MODEL_NAME} tasks={len(TASKS)}", flush=True)
|
| 148 |
+
|
| 149 |
for task in TASKS:
|
| 150 |
+
task_id = task["id"]
|
| 151 |
+
code = task["code"]
|
| 152 |
+
difficulty = task["difficulty"]
|
| 153 |
+
truth = task["truth"]
|
| 154 |
+
|
| 155 |
+
# ── [STEP] send action ─────────────────────────────────
|
| 156 |
try:
|
| 157 |
+
action = call_llm(code, difficulty)
|
|
|
|
|
|
|
|
|
|
| 158 |
except Exception as exc:
|
| 159 |
+
action = {"category": "approve", "severity": 1, "line_hint": None, "comment": str(exc)}
|
| 160 |
+
|
| 161 |
+
reward = score_action(action, truth)
|
| 162 |
+
total_reward += reward
|
| 163 |
+
|
| 164 |
+
print(
|
| 165 |
+
f"[STEP] task_id={task_id} difficulty={difficulty} "
|
| 166 |
+
f"category={action.get('category')} severity={action.get('severity')} "
|
| 167 |
+
f"reward={reward:.4f}",
|
| 168 |
+
flush=True,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# ── [END] ─────────────────────────────────────────────────
|
| 172 |
+
avg_reward = total_reward / len(TASKS)
|
| 173 |
+
print(f"[END] total_reward={total_reward:.4f} avg_reward={avg_reward:.4f}", flush=True)
|
| 174 |
|
| 175 |
|
| 176 |
if __name__ == "__main__":
|
main.py
CHANGED
|
@@ -19,10 +19,9 @@ try:
|
|
| 19 |
except ImportError:
|
| 20 |
_AGENT_IMPORTED = False
|
| 21 |
|
| 22 |
-
|
| 23 |
-
(os.environ.get("
|
| 24 |
-
)
|
| 25 |
-
HAS_LLM = _AGENT_IMPORTED and _HAS_HF_OR_OPENAI
|
| 26 |
|
| 27 |
logger = logging.getLogger(__name__)
|
| 28 |
|
|
|
|
| 19 |
except ImportError:
|
| 20 |
_AGENT_IMPORTED = False
|
| 21 |
|
| 22 |
+
_HAS_ANTHROPIC = bool(os.environ.get("ANTHROPIC_API_KEY", "").strip())
|
| 23 |
+
_HAS_OPENAI = bool(os.environ.get("OPENAI_API_KEY", "").strip())
|
| 24 |
+
HAS_LLM = _AGENT_IMPORTED and (_HAS_ANTHROPIC or _HAS_OPENAI)
|
|
|
|
| 25 |
|
| 26 |
logger = logging.getLogger(__name__)
|
| 27 |
|
openenv.yaml
CHANGED
|
@@ -1,40 +1,9 @@
|
|
| 1 |
name: "CodeBug Review Environment"
|
| 2 |
-
version: "1.
|
| 3 |
-
description: "RL environment where an AI agent reviews code snippets to identify bugs.
|
| 4 |
entry_point: "main:app"
|
|
|
|
|
|
|
| 5 |
environment_class: "environment.CodeBugEnvironment"
|
| 6 |
action_class: "models.CodeReviewAction"
|
| 7 |
observation_class: "models.CodeReviewObservation"
|
| 8 |
-
author: "vinith17"
|
| 9 |
-
tags: ["rl", "code-review", "security", "agent", "pytorch-hackathon"]
|
| 10 |
-
|
| 11 |
-
tasks:
|
| 12 |
-
- id: "task_easy_001"
|
| 13 |
-
name: "Balance Transfer Boundary Bug"
|
| 14 |
-
description: "Detect strict > instead of >= in balance check."
|
| 15 |
-
difficulty: "easy"
|
| 16 |
-
grader: "tasks.easy.grader:grade"
|
| 17 |
-
|
| 18 |
-
- id: "task_medium_002"
|
| 19 |
-
name: "Find Max Off-by-One"
|
| 20 |
-
description: "Detect range(len(x)-1) skipping the last element."
|
| 21 |
-
difficulty: "medium"
|
| 22 |
-
grader: "tasks.medium.grader:grade"
|
| 23 |
-
|
| 24 |
-
- id: "task_hard_003"
|
| 25 |
-
name: "SQL Injection Detection"
|
| 26 |
-
description: "Detect f-string SQL injection."
|
| 27 |
-
difficulty: "hard"
|
| 28 |
-
grader: "tasks.hard.grader:grade"
|
| 29 |
-
|
| 30 |
-
- id: "task_extra_004"
|
| 31 |
-
name: "Hardcoded API Key"
|
| 32 |
-
description: "Detect hardcoded secrets."
|
| 33 |
-
difficulty: "hard"
|
| 34 |
-
grader: "tasks.extra1.grader:grade"
|
| 35 |
-
|
| 36 |
-
- id: "task_extra_005"
|
| 37 |
-
name: "Division by Zero"
|
| 38 |
-
description: "Detect division without zero-check."
|
| 39 |
-
difficulty: "medium"
|
| 40 |
-
grader: "tasks.extra2.grader:grade"
|
|
|
|
| 1 |
name: "CodeBug Review Environment"
|
| 2 |
+
version: "1.0.0"
|
| 3 |
+
description: "RL environment where an AI agent reviews code snippets to identify bugs. Three tasks: easy (logic/boundary), medium (off-by-one), hard (SQL injection). Reward 0-1 per step."
|
| 4 |
entry_point: "main:app"
|
| 5 |
+
author: "vinith17"
|
| 6 |
+
tags: ["rl", "code-review", "security", "agent", "pytorch-hackathon"]
|
| 7 |
environment_class: "environment.CodeBugEnvironment"
|
| 8 |
action_class: "models.CodeReviewAction"
|
| 9 |
observation_class: "models.CodeReviewObservation"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pyproject.toml
CHANGED
|
@@ -23,4 +23,4 @@ requires = ["setuptools>=68.0"]
|
|
| 23 |
build-backend = "setuptools.backends._legacy:_Backend"
|
| 24 |
|
| 25 |
[tool.setuptools.packages.find]
|
| 26 |
-
include = ["*.py", "server"
|
|
|
|
| 23 |
build-backend = "setuptools.backends._legacy:_Backend"
|
| 24 |
|
| 25 |
[tool.setuptools.packages.find]
|
| 26 |
+
include = ["*.py", "server"]
|
requirements.txt
CHANGED
|
@@ -31,4 +31,3 @@ typing-inspection==0.4.2
|
|
| 31 |
typing_extensions==4.15.0
|
| 32 |
Werkzeug==3.1.8
|
| 33 |
wrapt==2.1.2
|
| 34 |
-
openenv-core>=0.2.2
|
|
|
|
| 31 |
typing_extensions==4.15.0
|
| 32 |
Werkzeug==3.1.8
|
| 33 |
wrapt==2.1.2
|
|
|
server/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
#
|
|
|
|
| 1 |
+
# server package
|
server/app.py
CHANGED
|
@@ -1,25 +1,11 @@
|
|
| 1 |
-
"""
|
| 2 |
-
|
|
|
|
| 3 |
|
| 4 |
-
The real FastAPI app lives at repo root (main.py). CMD uses: uvicorn main:app
|
| 5 |
-
"""
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
import sys
|
| 11 |
-
|
| 12 |
-
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 13 |
-
if _ROOT not in sys.path:
|
| 14 |
-
sys.path.insert(0, _ROOT)
|
| 15 |
-
|
| 16 |
-
from main import app as app # noqa: E402
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def main(host: str = "0.0.0.0", port: int = 7860) -> None:
|
| 20 |
-
import uvicorn
|
| 21 |
-
|
| 22 |
-
uvicorn.run("server.app:app", host=host, port=port, factory=False)
|
| 23 |
|
| 24 |
|
| 25 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
"""server/app.py — OpenEnv multi-mode entry point."""
|
| 2 |
+
import uvicorn
|
| 3 |
+
from main import app
|
| 4 |
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
def main():
|
| 7 |
+
"""Start the CodeBug server."""
|
| 8 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
if __name__ == "__main__":
|
tasks/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# tasks package — one grader per task for OpenEnv submission validation
|
|
|
|
|
|
tasks/easy/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# easy task package
|
|
|
|
|
|
tasks/easy/grader.py
DELETED
|
@@ -1,49 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Grader for task_easy_001 — Balance Transfer boundary bug.
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
TRUTH = {"category": "logic", "severity": 4, "line_hint": 2}
|
| 6 |
-
|
| 7 |
-
def _clamp(x: float) -> float:
|
| 8 |
-
"""Strictly between 0 and 1 exclusive."""
|
| 9 |
-
try:
|
| 10 |
-
val = float(x)
|
| 11 |
-
except (ValueError, TypeError):
|
| 12 |
-
val = 0.5
|
| 13 |
-
return max(0.01, min(0.99, val))
|
| 14 |
-
|
| 15 |
-
def grade(action: object, **kwargs) -> float:
|
| 16 |
-
reward = 0.0
|
| 17 |
-
|
| 18 |
-
def get_attr(obj, attr, default=None):
|
| 19 |
-
if isinstance(obj, dict):
|
| 20 |
-
return obj.get(attr, default)
|
| 21 |
-
return getattr(obj, attr, default)
|
| 22 |
-
|
| 23 |
-
# Category match → 0.5
|
| 24 |
-
cat = str(get_attr(action, "category", "")).strip().lower()
|
| 25 |
-
if cat == TRUTH["category"]:
|
| 26 |
-
reward += 0.5
|
| 27 |
-
|
| 28 |
-
# Severity accuracy → up to 0.3
|
| 29 |
-
try:
|
| 30 |
-
sev = int(get_attr(action, "severity", 0))
|
| 31 |
-
sev_diff = abs(sev - TRUTH["severity"])
|
| 32 |
-
except (ValueError, TypeError):
|
| 33 |
-
sev_diff = 99
|
| 34 |
-
|
| 35 |
-
if sev_diff == 0:
|
| 36 |
-
reward += 0.3
|
| 37 |
-
elif sev_diff == 1:
|
| 38 |
-
reward += 0.15
|
| 39 |
-
|
| 40 |
-
# Line hint → 0.2
|
| 41 |
-
lh = get_attr(action, "line_hint")
|
| 42 |
-
if lh is not None:
|
| 43 |
-
try:
|
| 44 |
-
if int(lh) == TRUTH["line_hint"]:
|
| 45 |
-
reward += 0.2
|
| 46 |
-
except (ValueError, TypeError):
|
| 47 |
-
pass
|
| 48 |
-
|
| 49 |
-
return _clamp(reward)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tasks/extra1/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# Subpackage for task_extra_004 grader (explicit package for all import paths).
|
|
|
|
|
|
tasks/extra1/grader.py
DELETED
|
@@ -1,37 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Grader for task_extra_004 — Hardcoded API key.
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
TRUTH = {"category": "security", "severity": 5, "line_hint": 1}
|
| 6 |
-
|
| 7 |
-
def _clamp(x: float) -> float:
|
| 8 |
-
try:
|
| 9 |
-
val = float(x)
|
| 10 |
-
except:
|
| 11 |
-
val = 0.5
|
| 12 |
-
return max(0.01, min(0.99, val))
|
| 13 |
-
|
| 14 |
-
def grade(action: object, **kwargs) -> float:
|
| 15 |
-
reward = 0.0
|
| 16 |
-
def get_attr(obj, attr, default=None):
|
| 17 |
-
if isinstance(obj, dict): return obj.get(attr, default)
|
| 18 |
-
return getattr(obj, attr, default)
|
| 19 |
-
|
| 20 |
-
cat = str(get_attr(action, "category", "")).strip().lower()
|
| 21 |
-
if cat == TRUTH["category"]: reward += 0.5
|
| 22 |
-
|
| 23 |
-
try:
|
| 24 |
-
sev = int(get_attr(action, "severity", 0))
|
| 25 |
-
sev_diff = abs(sev - TRUTH["severity"])
|
| 26 |
-
except: sev_diff = 99
|
| 27 |
-
|
| 28 |
-
if sev_diff == 0: reward += 0.3
|
| 29 |
-
elif sev_diff == 1: reward += 0.15
|
| 30 |
-
|
| 31 |
-
lh = get_attr(action, "line_hint")
|
| 32 |
-
if lh is not None:
|
| 33 |
-
try:
|
| 34 |
-
if int(lh) == TRUTH["line_hint"]: reward += 0.2
|
| 35 |
-
except: pass
|
| 36 |
-
|
| 37 |
-
return _clamp(reward)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tasks/extra2/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# Subpackage for task_extra_005 grader (explicit package for all import paths).
|
|
|
|
|
|
tasks/extra2/grader.py
DELETED
|
@@ -1,37 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Grader for task_extra_005 — Division by zero.
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
TRUTH = {"category": "logic", "severity": 3, "line_hint": 3}
|
| 6 |
-
|
| 7 |
-
def _clamp(x: float) -> float:
|
| 8 |
-
try:
|
| 9 |
-
val = float(x)
|
| 10 |
-
except:
|
| 11 |
-
val = 0.5
|
| 12 |
-
return max(0.01, min(0.99, val))
|
| 13 |
-
|
| 14 |
-
def grade(action: object, **kwargs) -> float:
|
| 15 |
-
reward = 0.0
|
| 16 |
-
def get_attr(obj, attr, default=None):
|
| 17 |
-
if isinstance(obj, dict): return obj.get(attr, default)
|
| 18 |
-
return getattr(obj, attr, default)
|
| 19 |
-
|
| 20 |
-
cat = str(get_attr(action, "category", "")).strip().lower()
|
| 21 |
-
if cat == TRUTH["category"]: reward += 0.5
|
| 22 |
-
|
| 23 |
-
try:
|
| 24 |
-
sev = int(get_attr(action, "severity", 0))
|
| 25 |
-
sev_diff = abs(sev - TRUTH["severity"])
|
| 26 |
-
except: sev_diff = 99
|
| 27 |
-
|
| 28 |
-
if sev_diff == 0: reward += 0.3
|
| 29 |
-
elif sev_diff == 1: reward += 0.15
|
| 30 |
-
|
| 31 |
-
lh = get_attr(action, "line_hint")
|
| 32 |
-
if lh is not None:
|
| 33 |
-
try:
|
| 34 |
-
if int(lh) == TRUTH["line_hint"]: reward += 0.2
|
| 35 |
-
except: pass
|
| 36 |
-
|
| 37 |
-
return _clamp(reward)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tasks/hard/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# hard task package
|
|
|
|
|
|
tasks/hard/grader.py
DELETED
|
@@ -1,37 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Grader for task_hard_003 — SQL injection detection.
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
TRUTH = {"category": "security", "severity": 5, "line_hint": 2}
|
| 6 |
-
|
| 7 |
-
def _clamp(x: float) -> float:
|
| 8 |
-
try:
|
| 9 |
-
val = float(x)
|
| 10 |
-
except:
|
| 11 |
-
val = 0.5
|
| 12 |
-
return max(0.01, min(0.99, val))
|
| 13 |
-
|
| 14 |
-
def grade(action: object, **kwargs) -> float:
|
| 15 |
-
reward = 0.0
|
| 16 |
-
def get_attr(obj, attr, default=None):
|
| 17 |
-
if isinstance(obj, dict): return obj.get(attr, default)
|
| 18 |
-
return getattr(obj, attr, default)
|
| 19 |
-
|
| 20 |
-
cat = str(get_attr(action, "category", "")).strip().lower()
|
| 21 |
-
if cat == TRUTH["category"]: reward += 0.5
|
| 22 |
-
|
| 23 |
-
try:
|
| 24 |
-
sev = int(get_attr(action, "severity", 0))
|
| 25 |
-
sev_diff = abs(sev - TRUTH["severity"])
|
| 26 |
-
except: sev_diff = 99
|
| 27 |
-
|
| 28 |
-
if sev_diff == 0: reward += 0.3
|
| 29 |
-
elif sev_diff == 1: reward += 0.15
|
| 30 |
-
|
| 31 |
-
lh = get_attr(action, "line_hint")
|
| 32 |
-
if lh is not None:
|
| 33 |
-
try:
|
| 34 |
-
if int(lh) == TRUTH["line_hint"]: reward += 0.2
|
| 35 |
-
except: pass
|
| 36 |
-
|
| 37 |
-
return _clamp(reward)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tasks/medium/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
# medium task package
|
|
|
|
|
|
tasks/medium/grader.py
DELETED
|
@@ -1,37 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Grader for task_medium_002 — find_max off-by-one bug.
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
TRUTH = {"category": "logic", "severity": 3, "line_hint": 5}
|
| 6 |
-
|
| 7 |
-
def _clamp(x: float) -> float:
|
| 8 |
-
try:
|
| 9 |
-
val = float(x)
|
| 10 |
-
except:
|
| 11 |
-
val = 0.5
|
| 12 |
-
return max(0.01, min(0.99, val))
|
| 13 |
-
|
| 14 |
-
def grade(action: object, **kwargs) -> float:
|
| 15 |
-
reward = 0.0
|
| 16 |
-
def get_attr(obj, attr, default=None):
|
| 17 |
-
if isinstance(obj, dict): return obj.get(attr, default)
|
| 18 |
-
return getattr(obj, attr, default)
|
| 19 |
-
|
| 20 |
-
cat = str(get_attr(action, "category", "")).strip().lower()
|
| 21 |
-
if cat == TRUTH["category"]: reward += 0.5
|
| 22 |
-
|
| 23 |
-
try:
|
| 24 |
-
sev = int(get_attr(action, "severity", 0))
|
| 25 |
-
sev_diff = abs(sev - TRUTH["severity"])
|
| 26 |
-
except: sev_diff = 99
|
| 27 |
-
|
| 28 |
-
if sev_diff == 0: reward += 0.3
|
| 29 |
-
elif sev_diff == 1: reward += 0.15
|
| 30 |
-
|
| 31 |
-
lh = get_attr(action, "line_hint")
|
| 32 |
-
if lh is not None:
|
| 33 |
-
try:
|
| 34 |
-
if int(lh) == TRUTH["line_hint"]: reward += 0.2
|
| 35 |
-
except: pass
|
| 36 |
-
|
| 37 |
-
return _clamp(reward)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tasks/scoring.py
DELETED
|
@@ -1,19 +0,0 @@
|
|
| 1 |
-
"""Shared task reward shaping for OpenEnv validation (scores must lie strictly in (0, 1))."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
import math
|
| 6 |
-
from numbers import Real
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def finalize_task_reward(raw: float) -> float:
|
| 10 |
-
"""
|
| 11 |
-
Return a finite float strictly between 0 and 1.
|
| 12 |
-
OpenEnv task validators reject 0.0, 1.0, NaN, and inf.
|
| 13 |
-
"""
|
| 14 |
-
if not isinstance(raw, Real):
|
| 15 |
-
return 0.5
|
| 16 |
-
x = float(raw)
|
| 17 |
-
if not math.isfinite(x):
|
| 18 |
-
return 0.5
|
| 19 |
-
return min(0.99, max(0.01, x))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_api_directly.py
CHANGED
|
@@ -10,20 +10,20 @@ except:
|
|
| 10 |
print(x)"""
|
| 11 |
|
| 12 |
print("Test 1: Simple code with bare except")
|
| 13 |
-
print("
|
| 14 |
print(code1)
|
| 15 |
-
print("
|
| 16 |
|
| 17 |
try:
|
| 18 |
response = requests.post(
|
| 19 |
"http://127.0.0.1:7860/api/review",
|
| 20 |
json={"code": code1, "language": "python"},
|
| 21 |
-
timeout=3
|
| 22 |
)
|
| 23 |
-
|
| 24 |
data = response.json()
|
| 25 |
print(f"Bugs found: {data['bugs_found']}")
|
| 26 |
-
for i, bug in enumerate(data[
|
| 27 |
print(f"{i}. {bug['comment'][:60]} (confidence: {bug['confidence']})")
|
| 28 |
except Exception as e:
|
| 29 |
print(f"Error: {e}")
|
|
@@ -36,20 +36,20 @@ b = 10
|
|
| 36 |
result = a + b"""
|
| 37 |
|
| 38 |
print("Test 2: Type error")
|
| 39 |
-
print("
|
| 40 |
print(code2)
|
| 41 |
-
print("
|
| 42 |
|
| 43 |
try:
|
| 44 |
response = requests.post(
|
| 45 |
"http://127.0.0.1:7860/api/review",
|
| 46 |
json={"code": code2, "language": "python"},
|
| 47 |
-
timeout=3
|
| 48 |
)
|
| 49 |
-
|
| 50 |
data = response.json()
|
| 51 |
print(f"Bugs found: {data['bugs_found']}")
|
| 52 |
-
for i, bug in enumerate(data[
|
| 53 |
print(f"{i}. {bug['comment'][:60]} (confidence: {bug['confidence']})")
|
| 54 |
except Exception as e:
|
| 55 |
print(f"Error: {e}")
|
|
@@ -60,20 +60,20 @@ print("\n")
|
|
| 60 |
code3 = """query = f'SELECT * FROM users WHERE id={user_id}'"""
|
| 61 |
|
| 62 |
print("Test 3: SQL Injection")
|
| 63 |
-
print("
|
| 64 |
print(code3)
|
| 65 |
-
print("
|
| 66 |
|
| 67 |
try:
|
| 68 |
response = requests.post(
|
| 69 |
"http://127.0.0.1:7860/api/review",
|
| 70 |
json={"code": code3, "language": "python"},
|
| 71 |
-
timeout=3
|
| 72 |
)
|
| 73 |
-
|
| 74 |
data = response.json()
|
| 75 |
print(f"Bugs found: {data['bugs_found']}")
|
| 76 |
-
for i, bug in enumerate(data[
|
| 77 |
print(f"{i}. {bug['comment'][:60]} (confidence: {bug['confidence']})")
|
| 78 |
except Exception as e:
|
| 79 |
print(f"Error: {e}")
|
|
|
|
| 10 |
print(x)"""
|
| 11 |
|
| 12 |
print("Test 1: Simple code with bare except")
|
| 13 |
+
print("─" * 60)
|
| 14 |
print(code1)
|
| 15 |
+
print("─" * 60)
|
| 16 |
|
| 17 |
try:
|
| 18 |
response = requests.post(
|
| 19 |
"http://127.0.0.1:7860/api/review",
|
| 20 |
json={"code": code1, "language": "python"},
|
| 21 |
+
timeout=3
|
| 22 |
)
|
| 23 |
+
|
| 24 |
data = response.json()
|
| 25 |
print(f"Bugs found: {data['bugs_found']}")
|
| 26 |
+
for i, bug in enumerate(data['bugs'], 1):
|
| 27 |
print(f"{i}. {bug['comment'][:60]} (confidence: {bug['confidence']})")
|
| 28 |
except Exception as e:
|
| 29 |
print(f"Error: {e}")
|
|
|
|
| 36 |
result = a + b"""
|
| 37 |
|
| 38 |
print("Test 2: Type error")
|
| 39 |
+
print("─" * 60)
|
| 40 |
print(code2)
|
| 41 |
+
print("─" * 60)
|
| 42 |
|
| 43 |
try:
|
| 44 |
response = requests.post(
|
| 45 |
"http://127.0.0.1:7860/api/review",
|
| 46 |
json={"code": code2, "language": "python"},
|
| 47 |
+
timeout=3
|
| 48 |
)
|
| 49 |
+
|
| 50 |
data = response.json()
|
| 51 |
print(f"Bugs found: {data['bugs_found']}")
|
| 52 |
+
for i, bug in enumerate(data['bugs'], 1):
|
| 53 |
print(f"{i}. {bug['comment'][:60]} (confidence: {bug['confidence']})")
|
| 54 |
except Exception as e:
|
| 55 |
print(f"Error: {e}")
|
|
|
|
| 60 |
code3 = """query = f'SELECT * FROM users WHERE id={user_id}'"""
|
| 61 |
|
| 62 |
print("Test 3: SQL Injection")
|
| 63 |
+
print("─" * 60)
|
| 64 |
print(code3)
|
| 65 |
+
print("─" * 60)
|
| 66 |
|
| 67 |
try:
|
| 68 |
response = requests.post(
|
| 69 |
"http://127.0.0.1:7860/api/review",
|
| 70 |
json={"code": code3, "language": "python"},
|
| 71 |
+
timeout=3
|
| 72 |
)
|
| 73 |
+
|
| 74 |
data = response.json()
|
| 75 |
print(f"Bugs found: {data['bugs_found']}")
|
| 76 |
+
for i, bug in enumerate(data['bugs'], 1):
|
| 77 |
print(f"{i}. {bug['comment'][:60]} (confidence: {bug['confidence']})")
|
| 78 |
except Exception as e:
|
| 79 |
print(f"Error: {e}")
|
test_api_settings.py
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
import os
|
| 3 |
-
|
| 4 |
-
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
|
| 5 |
-
MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o")
|
| 6 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 7 |
-
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 8 |
-
|
| 9 |
-
print("API Settings:")
|
| 10 |
-
print(f" API_BASE_URL: {API_BASE_URL}")
|
| 11 |
-
print(f" MODEL_NAME: {MODEL_NAME}")
|
| 12 |
-
print(f" HF_TOKEN set: {HF_TOKEN is not None}")
|
| 13 |
-
print(f" OPENAI_API_KEY set: {OPENAI_API_KEY is not None}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_graders.py
DELETED
|
@@ -1,53 +0,0 @@
|
|
| 1 |
-
import sys
|
| 2 |
-
|
| 3 |
-
sys.path.insert(0, "C:/Users/vinit/Projects/CodeBug")
|
| 4 |
-
|
| 5 |
-
from tasks.easy.grader import grade as grade_easy
|
| 6 |
-
from tasks.medium.grader import grade as grade_medium
|
| 7 |
-
from tasks.hard.grader import grade as grade_hard
|
| 8 |
-
from tasks.extra1.grader import grade as grade_extra1
|
| 9 |
-
from tasks.extra2.grader import grade as grade_extra2
|
| 10 |
-
|
| 11 |
-
# Test with correct actions
|
| 12 |
-
correct_easy = {"category": "logic", "severity": 4, "line_hint": 2}
|
| 13 |
-
correct_medium = {"category": "logic", "severity": 3, "line_hint": 5}
|
| 14 |
-
correct_hard = {"category": "security", "severity": 5, "line_hint": 2}
|
| 15 |
-
correct_extra1 = {"category": "security", "severity": 5, "line_hint": 1}
|
| 16 |
-
correct_extra2 = {"category": "logic", "severity": 3, "line_hint": 2}
|
| 17 |
-
|
| 18 |
-
# Test with wrong actions
|
| 19 |
-
wrong_action = {"category": "approve", "severity": 1, "line_hint": None}
|
| 20 |
-
|
| 21 |
-
print("Testing graders:")
|
| 22 |
-
scores = {
|
| 23 |
-
"easy": grade_easy(correct_easy),
|
| 24 |
-
"medium": grade_medium(correct_medium),
|
| 25 |
-
"hard": grade_hard(correct_hard),
|
| 26 |
-
"extra1": grade_extra1(correct_extra1),
|
| 27 |
-
"extra2": grade_extra2(correct_extra2),
|
| 28 |
-
}
|
| 29 |
-
|
| 30 |
-
for name, score in scores.items():
|
| 31 |
-
print(f" {name}: {score}")
|
| 32 |
-
|
| 33 |
-
print("\nWith wrong action:")
|
| 34 |
-
wrong_scores = {
|
| 35 |
-
"easy": grade_easy(wrong_action),
|
| 36 |
-
"medium": grade_medium(wrong_action),
|
| 37 |
-
"hard": grade_hard(wrong_action),
|
| 38 |
-
"extra1": grade_extra1(wrong_action),
|
| 39 |
-
"extra2": grade_extra2(wrong_action),
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
for name, score in wrong_scores.items():
|
| 43 |
-
print(f" {name}: {score}")
|
| 44 |
-
|
| 45 |
-
# Check for issues
|
| 46 |
-
print("\nIssues:")
|
| 47 |
-
for name, score in scores.items():
|
| 48 |
-
if score <= 0 or score >= 1:
|
| 49 |
-
print(f" {name}: OUT OF RANGE ({score})")
|
| 50 |
-
|
| 51 |
-
for name, score in wrong_scores.items():
|
| 52 |
-
if score <= 0 or score >= 1:
|
| 53 |
-
print(f" {name}: OUT OF RANGE ({score})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_no_api.py
DELETED
|
@@ -1,27 +0,0 @@
|
|
| 1 |
-
import sys
|
| 2 |
-
|
| 3 |
-
sys.path.insert(0, "C:/Users/vinit/Projects/CodeBug")
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
print("=== API Configuration ===")
|
| 7 |
-
print(f"HF_TOKEN set: {bool(os.environ.get('HF_TOKEN'))}")
|
| 8 |
-
print(f"OPENAI_API_KEY set: {bool(os.environ.get('OPENAI_API_KEY'))}")
|
| 9 |
-
|
| 10 |
-
from main import HAS_LLM, analyze_code_comprehensively
|
| 11 |
-
|
| 12 |
-
print(f"\nHAS_LLM: {HAS_LLM}")
|
| 13 |
-
|
| 14 |
-
test_cases = [
|
| 15 |
-
("python", "query = f'SELECT * FROM users WHERE id={user_id}'"),
|
| 16 |
-
("python", "import requests\nresponse = requests.get(url)"),
|
| 17 |
-
("python", "api_key = 'sk-1234567890abcdef'"),
|
| 18 |
-
("python", "@app.get('/users')\ndef get_users():\n return []"),
|
| 19 |
-
("javascript", "fetch(url)"),
|
| 20 |
-
]
|
| 21 |
-
|
| 22 |
-
for lang, code in test_cases:
|
| 23 |
-
result = analyze_code_comprehensively(code, lang)
|
| 24 |
-
print(f"\n=== {lang}: {code[:40]}... ===")
|
| 25 |
-
print(f"Bugs found: {len(result)}")
|
| 26 |
-
for bug in result:
|
| 27 |
-
print(f" - {bug['category']} ({bug['rule_id']}): {bug['comment'][:50]}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
vercel.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": 2,
|
| 3 |
+
"builds": [
|
| 4 |
+
{
|
| 5 |
+
"src": "api/index.py",
|
| 6 |
+
"use": "@vercel/python"
|
| 7 |
+
}
|
| 8 |
+
],
|
| 9 |
+
"routes": [
|
| 10 |
+
{
|
| 11 |
+
"src": "/(.*)",
|
| 12 |
+
"dest": "api/index.py"
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|