vinith17 commited on
Commit
8e2e914
·
1 Parent(s): 5d1f2a8

fix(hackathon): root inference + normalized grader + OpenAI-only agent

Browse files

- grader.py: map integer rubric scores to (0,1) exclusive via config-derived bounds
- inference.py: OpenAI client (HF_TOKEN, API_BASE_URL, MODEL_NAME); grader.grade(); 5 tasks; [START]/[STEP] task_id score/[END] only on stdout
- agent.py: remove Anthropic; use openai.OpenAI with HF_TOKEN or OPENAI_API_KEY
- main.py: enable LLM when HF_TOKEN or OPENAI_API_KEY is set

Made-with: Cursor

Files changed (4) hide show
  1. agent.py +34 -61
  2. grader.py +45 -7
  3. inference.py +143 -105
  4. main.py +4 -3
agent.py CHANGED
@@ -1,44 +1,38 @@
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()
@@ -99,48 +93,27 @@ def build_user_message(code: str, retry: bool = False) -> str:
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
  # ---------------------------------------------------------------------------
 
 
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
+ API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
14
+ MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
15
+ # Hackathon / Spaces: HF_TOKEN; local dev may use OPENAI_API_KEY
16
+ _LLM_KEY = (os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or "").strip()
17
+ has_openai_client = bool(_LLM_KEY)
18
+
19
 
20
+ def _check_api_keys() -> None:
21
+ if not has_openai_client:
 
22
  print(
23
  "\n"
24
  "╔══════════════════════════════════════════════════════════╗\n"
25
  "║ WARNING: No LLM API key found. ║\n"
26
  "║ ║\n"
27
+ "║ Set HF_TOKEN (OpenAI-compatible key) or OPENAI_API_KEY ║\n"
28
+ "║ Optional: API_BASE_URL, MODEL_NAME ║\n"
 
29
  "║ ║\n"
30
+ "║ The server will start, but reviews use the mock engine. ║\n"
 
31
  "╚══════════════════════════════════════════════════════════╝\n",
32
  file=sys.stderr,
33
  )
34
  return
35
+ logger.info("OpenAI client configured (HF_TOKEN or OPENAI_API_KEY)")
 
 
 
 
36
 
37
 
38
  _check_api_keys()
 
93
 
94
  def call_llm(prompt: str, *, system: str | None = None) -> str | None:
95
  """
96
+ Call the OpenAI-compatible Chat Completions API (HF_TOKEN or OPENAI_API_KEY).
97
+ Returns raw assistant text or None on failure.
98
  """
99
+ if not _LLM_KEY:
100
+ logger.warning("No HF_TOKEN / OPENAI_API_KEY — mock reviewer.")
101
+ return None
102
+ try:
103
+ client = OpenAI(api_key=_LLM_KEY, base_url=API_BASE_URL)
104
+ messages: list[dict] = []
105
+ if system:
106
+ messages.append({"role": "system", "content": system})
107
+ messages.append({"role": "user", "content": prompt})
108
+ response = client.chat.completions.create(
109
+ model=MODEL_NAME,
110
+ max_tokens=MAX_TOKENS,
111
+ messages=messages,
112
+ )
113
+ return response.choices[0].message.content
114
+ except Exception as exc:
115
+ logger.error("OpenAI client call failed: %s: %s", type(exc).__name__, exc)
116
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
 
119
  # ---------------------------------------------------------------------------
grader.py CHANGED
@@ -30,6 +30,40 @@ from config import (
30
  )
31
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  # ---------------------------------------------------------------------------
34
  # GradeResult
35
  # ---------------------------------------------------------------------------
@@ -38,7 +72,7 @@ from config import (
38
  class GradeResult:
39
  def __init__(
40
  self,
41
- reward: int,
42
  breakdown: list[str],
43
  correct: bool,
44
  bug_type: str = "unknown",
@@ -54,7 +88,7 @@ class GradeResult:
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,7 +97,7 @@ class GradeResult:
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,7 +123,11 @@ def grade(ai_action: dict, ground_truth: dict | None) -> GradeResult:
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,7 +241,7 @@ def grade(ai_action: dict, ground_truth: dict | None) -> GradeResult:
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,7 +257,7 @@ def grade(ai_action: dict, ground_truth: dict | None) -> GradeResult:
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,7 +272,7 @@ def batch_grade(episodes: list[dict]) -> dict:
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":
 
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
  class GradeResult:
73
  def __init__(
74
  self,
75
+ reward: float,
76
  breakdown: list[str],
77
  correct: bool,
78
  bug_type: str = "unknown",
 
88
  lines = [
89
  "GRADE SUMMARY",
90
  "-" * 25,
91
+ f"Reward: {self.reward:+.4f} (normalized 0–1)",
92
  f"Correct: {'Yes' if self.correct else 'No'}",
93
  f"Bug was: {self.bug_type} (severity {self.bug_severity})",
94
  "",
 
97
  for entry in self.breakdown:
98
  lines.append(f" {entry}")
99
  lines.append("-" * 25)
100
+ lines.append(f"Total: {self.reward:+.4f}")
101
  return "\n".join(lines)
102
 
103
  def to_dict(self) -> dict:
 
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
  breakdown.append(f"{PENALTY_UNKNOWN_ACTION}: unknown action type '{ai_type}'")
242
 
243
  return GradeResult(
244
+ reward=_normalize_reward(reward),
245
  breakdown=breakdown,
246
  correct=correct,
247
  bug_type=bug_type,
 
257
  def batch_grade(episodes: list[dict]) -> dict:
258
  """Summarise grading across multiple episodes."""
259
  results_list: list[dict] = []
260
+ total_reward = 0.0
261
  correct_count = 0
262
  best_score = -float("inf")
263
  worst_score = float("inf")
 
272
  d = res.to_dict()
273
  results_list.append(d)
274
 
275
+ total_reward += float(d["reward"])
276
  if d["correct"]:
277
  correct_count += 1
278
  if d["bug_type"] == "security":
inference.py CHANGED
@@ -1,50 +1,34 @@
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
- from tasks.easy.grader import grade as grade_task_easy_001
17
- from tasks.medium.grader import grade as grade_task_medium_002
18
- from tasks.hard.grader import grade as grade_task_hard_003
19
- from tasks.extra1.grader import grade as grade_task_extra_004
20
- from tasks.extra2.grader import grade as grade_task_extra_005
21
-
22
- # ─────────────────────────────────────────────────────────────
23
- # Environment variables (checklist requirement)
24
- # Defaults ONLY for API_BASE_URL and MODEL_NAME — NOT HF_TOKEN
25
- # ─────────────────────────────────────────────────────────────
26
  API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
27
- MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
28
- HF_TOKEN = os.environ.get("HF_TOKEN") # No default — must be set by user
29
 
30
  if not HF_TOKEN:
31
  print("[ERROR] HF_TOKEN environment variable is required but not set.", flush=True)
32
  sys.exit(1)
33
 
34
- # ─────────────────────────────────────────────────────────────
35
- # OpenAI client — configured strictly via the env variables
36
- # ─────────────────────────────────────────────────────────────
37
- client = OpenAI(
38
- api_key=HF_TOKEN,
39
- base_url=API_BASE_URL,
40
- )
41
-
42
- # ─────────────────────────────────────────────────────────────
43
- # Code review tasks (5 tasks)
44
- # ─────────────────────────────────────────────────────────────
45
  TASKS = [
46
  {
47
- "id": "task_easy_001",
48
  "difficulty": "easy",
49
  "code": (
50
  "def transfer(from_account, to_account, amount):\n"
@@ -54,10 +38,17 @@ TASKS = [
54
  " return True\n"
55
  " return False"
56
  ),
57
- "truth": {"category": "logic", "severity": 4, "line_hint": 2},
 
 
 
 
 
 
 
58
  },
59
  {
60
- "id": "task_medium_002",
61
  "difficulty": "medium",
62
  "code": (
63
  "def find_max(numbers):\n"
@@ -69,10 +60,17 @@ TASKS = [
69
  " max_val = numbers[i]\n"
70
  " return max_val"
71
  ),
72
- "truth": {"category": "logic", "severity": 3, "line_hint": 5},
 
 
 
 
 
 
 
73
  },
74
  {
75
- "id": "task_hard_003",
76
  "difficulty": "hard",
77
  "code": (
78
  "def login(username, password):\n"
@@ -83,109 +81,149 @@ TASKS = [
83
  " return True\n"
84
  " return False"
85
  ),
86
- "truth": {"category": "security", "severity": 5, "line_hint": 2},
 
 
 
 
 
 
 
87
  },
88
  {
89
- "id": "task_extra_004",
90
  "difficulty": "hard",
91
  "code": (
92
  "API_KEY = \"sk-1234567890abcdef\"\n"
93
  "def process_data(data):\n"
94
  " return data.upper()"
95
  ),
96
- "truth": {"category": "security", "severity": 5, "line_hint": 1},
 
 
 
 
 
 
 
97
  },
98
  {
99
- "id": "task_extra_005",
100
  "difficulty": "medium",
101
  "code": (
102
  "def divide(a, b):\n"
103
  " # Potential bug here\n"
104
  " return a / b"
105
  ),
106
- "truth": {"category": "logic", "severity": 3, "line_hint": 3},
 
 
 
 
 
 
 
107
  },
108
  ]
109
 
110
- SYSTEM_PROMPT = """\
111
- You are a code review agent. Your task is to identify bugs in code snippets.
112
- Return ONLY a valid JSON object with this exact schema (no markdown, no prose):
113
  {
114
- "category": "logic" | "security" | "style" | "approve",
115
- "severity": <integer 1-5>,
116
- "line_hint": <integer line number or null>,
117
- "comment": "<short description of the bug>"
 
118
  }
119
- """
120
-
121
-
122
- def call_llm(code: str, difficulty: str) -> dict:
123
- """Call LLM via OpenAI client and parse the structured JSON response."""
124
- user_prompt = (
125
- f"Difficulty level: {difficulty}\n\n"
126
- f"Review the following code and identify any bugs:\n\n{code}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  )
128
-
129
  response = client.chat.completions.create(
130
  model=MODEL_NAME,
 
 
131
  messages=[
132
  {"role": "system", "content": SYSTEM_PROMPT},
133
- {"role": "user", "content": user_prompt},
134
  ],
135
  response_format={"type": "json_object"},
136
- temperature=0.2,
137
  )
138
-
139
  raw = response.choices[0].message.content
140
- return json.loads(raw)
141
-
142
-
143
- # Same callables as openenv.yaml `grader:` entries — validators compare [STEP] rewards to these.
144
- _TASK_GRADERS = {
145
- "task_easy_001": grade_task_easy_001,
146
- "task_medium_002": grade_task_medium_002,
147
- "task_hard_003": grade_task_hard_003,
148
- "task_extra_004": grade_task_extra_004,
149
- "task_extra_005": grade_task_extra_005,
150
- }
151
-
152
-
153
- def grade_action_for_task(task_id: str, action: dict) -> float:
154
- """Delegate to the YAML-configured grader so stdout matches manifest grading exactly."""
155
- grader = _TASK_GRADERS[task_id]
156
- return round(float(grader(action)), 6)
157
-
158
-
159
- def run_inference():
160
- total_reward = 0.0
161
-
162
- # ── [START] ───────────────────────────────────────────────
163
- print(f"[START] api_base={API_BASE_URL} model={MODEL_NAME} tasks={len(TASKS)}", flush=True)
164
-
165
  for task in TASKS:
166
- task_id = task["id"]
167
- code = task["code"]
168
- difficulty = task["difficulty"]
169
-
170
- # ── [STEP] send action ─────────────────────────────────
171
  try:
172
- action = call_llm(code, difficulty)
173
  except Exception as exc:
174
- action = {"category": "approve", "severity": 1, "line_hint": None, "comment": str(exc)}
175
-
176
- reward = grade_action_for_task(task_id, action)
177
- total_reward += reward
178
-
179
- print(
180
- f"[STEP] task_id={task_id} difficulty={difficulty} "
181
- f"category={action.get('category')} severity={action.get('severity')} "
182
- f"reward={reward:.4f}",
183
- flush=True,
184
- )
185
-
186
- # ── [END] ─────────────────────────────────────────────────
187
- avg_reward = total_reward / len(TASKS)
188
- print(f"[END] total_reward={total_reward:.4f} avg_reward={avg_reward:.4f}", flush=True)
189
 
190
 
191
  if __name__ == "__main__":
 
1
  """
2
+ inference.py — Hackathon baseline inference (repo root).
3
 
4
+ Requires env: HF_TOKEN (no default). Optional: API_BASE_URL, MODEL_NAME (OpenAI-compatible defaults).
5
+ Uses openai.OpenAI only. Emits exact stdout lines for the evaluator: [START], [STEP] … score=…, [END].
 
 
 
6
  """
7
 
8
+ from __future__ import annotations
9
+
10
  import json
11
+ import os
12
+ import re
13
  import sys
14
 
15
  from openai import OpenAI
16
+
17
+ from grader import grade
18
+
 
 
 
 
 
 
 
19
  API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
20
+ MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
21
+ HF_TOKEN = os.environ.get("HF_TOKEN")
22
 
23
  if not HF_TOKEN:
24
  print("[ERROR] HF_TOKEN environment variable is required but not set.", flush=True)
25
  sys.exit(1)
26
 
27
+ client = OpenAI(api_key=HF_TOKEN, base_url=API_BASE_URL)
28
+
 
 
 
 
 
 
 
 
 
29
  TASKS = [
30
  {
31
+ "task_id": "task_easy_001",
32
  "difficulty": "easy",
33
  "code": (
34
  "def transfer(from_account, to_account, amount):\n"
 
38
  " return True\n"
39
  " return False"
40
  ),
41
+ "ground_truth": {
42
+ "bug": {
43
+ "type": "logic",
44
+ "severity": 4,
45
+ "description": "Strict > should likely be >= for balance transfer edge case",
46
+ "line_hint": "if balance check",
47
+ }
48
+ },
49
  },
50
  {
51
+ "task_id": "task_medium_002",
52
  "difficulty": "medium",
53
  "code": (
54
  "def find_max(numbers):\n"
 
60
  " max_val = numbers[i]\n"
61
  " return max_val"
62
  ),
63
+ "ground_truth": {
64
+ "bug": {
65
+ "type": "logic",
66
+ "severity": 3,
67
+ "description": "Off-by-one: range(len(numbers)-1) skips last element",
68
+ "line_hint": "for loop range",
69
+ }
70
+ },
71
  },
72
  {
73
+ "task_id": "task_hard_003",
74
  "difficulty": "hard",
75
  "code": (
76
  "def login(username, password):\n"
 
81
  " return True\n"
82
  " return False"
83
  ),
84
+ "ground_truth": {
85
+ "bug": {
86
+ "type": "security",
87
+ "severity": 5,
88
+ "description": "SQL injection via f-string query",
89
+ "line_hint": "query construction line",
90
+ }
91
+ },
92
  },
93
  {
94
+ "task_id": "task_extra_004",
95
  "difficulty": "hard",
96
  "code": (
97
  "API_KEY = \"sk-1234567890abcdef\"\n"
98
  "def process_data(data):\n"
99
  " return data.upper()"
100
  ),
101
+ "ground_truth": {
102
+ "bug": {
103
+ "type": "security",
104
+ "severity": 5,
105
+ "description": "Hardcoded API key / secret",
106
+ "line_hint": "API_KEY assignment",
107
+ }
108
+ },
109
  },
110
  {
111
+ "task_id": "task_extra_005",
112
  "difficulty": "medium",
113
  "code": (
114
  "def divide(a, b):\n"
115
  " # Potential bug here\n"
116
  " return a / b"
117
  ),
118
+ "ground_truth": {
119
+ "bug": {
120
+ "type": "logic",
121
+ "severity": 3,
122
+ "description": "Division without zero check",
123
+ "line_hint": "return division",
124
+ }
125
+ },
126
  },
127
  ]
128
 
129
+ SYSTEM_PROMPT = """You are a code reviewer. Respond with ONLY a JSON object (no markdown) using this schema:
 
 
130
  {
131
+ "type": "flag" or "approve",
132
+ "category": "security" or "logic" or "style" or "ok",
133
+ "line_hint": "<string, line or location description>",
134
+ "comment": "<string explanation>",
135
+ "severity": <integer 1-5>
136
  }
137
+ Use type \"flag\" if you report a bug, \"approve\" if the snippet is fine."""
138
+
139
+
140
+ def _parse_llm_json(raw: str | None) -> dict:
141
+ if not raw:
142
+ return {}
143
+ try:
144
+ return json.loads(raw)
145
+ except json.JSONDecodeError:
146
+ m = re.search(r"\{[\s\S]*\}", raw)
147
+ if m:
148
+ try:
149
+ return json.loads(m.group(0))
150
+ except json.JSONDecodeError:
151
+ pass
152
+ return {}
153
+
154
+
155
+ def _coerce_action(data: dict) -> dict:
156
+ """Shape model output for grader.grade(ai_action, ground_truth)."""
157
+ typ = str(data.get("type", "approve")).strip().lower()
158
+ if typ not in ("flag", "approve"):
159
+ typ = "approve"
160
+ cat = str(data.get("category", "ok")).strip().lower()
161
+ if cat not in ("security", "logic", "style", "ok"):
162
+ cat = "ok"
163
+ lh = data.get("line_hint", "")
164
+ if lh is None:
165
+ lh = ""
166
+ lh = str(lh).strip()
167
+ comment = str(data.get("comment", "")).strip()
168
+ try:
169
+ sev = int(data.get("severity", 0))
170
+ except (TypeError, ValueError):
171
+ sev = 0
172
+ return {
173
+ "type": typ,
174
+ "category": cat,
175
+ "line_hint": lh,
176
+ "comment": comment,
177
+ "severity": sev,
178
+ }
179
+
180
+
181
+ def run_task(task: dict) -> dict:
182
+ user = (
183
+ f"Difficulty: {task['difficulty']}\n\n"
184
+ f"Review this code:\n\n{task['code']}"
185
  )
 
186
  response = client.chat.completions.create(
187
  model=MODEL_NAME,
188
+ max_tokens=300,
189
+ temperature=0.2,
190
  messages=[
191
  {"role": "system", "content": SYSTEM_PROMPT},
192
+ {"role": "user", "content": user},
193
  ],
194
  response_format={"type": "json_object"},
 
195
  )
 
196
  raw = response.choices[0].message.content
197
+ parsed = _parse_llm_json(raw)
198
+ if not parsed:
199
+ return {
200
+ "type": "approve",
201
+ "category": "ok",
202
+ "line_hint": "",
203
+ "comment": "parse_error",
204
+ "severity": 0,
205
+ }
206
+ return _coerce_action(parsed)
207
+
208
+
209
+ def run_inference() -> None:
210
+ print("[START]", flush=True)
 
 
 
 
 
 
 
 
 
 
 
211
  for task in TASKS:
212
+ tid = task["task_id"]
 
 
 
 
213
  try:
214
+ action = run_task(task)
215
  except Exception as exc:
216
+ action = {
217
+ "type": "approve",
218
+ "category": "ok",
219
+ "line_hint": "",
220
+ "comment": str(exc),
221
+ "severity": 0,
222
+ }
223
+ result = grade(action, task["ground_truth"])
224
+ score = result.reward
225
+ print(f"[STEP] task_id={tid} score={score}", flush=True)
226
+ print("[END]", flush=True)
 
 
 
 
227
 
228
 
229
  if __name__ == "__main__":
main.py CHANGED
@@ -19,9 +19,10 @@ try:
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
 
 
19
  except ImportError:
20
  _AGENT_IMPORTED = False
21
 
22
+ _HAS_HF_OR_OPENAI = bool(
23
+ (os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or "").strip()
24
+ )
25
+ HAS_LLM = _AGENT_IMPORTED and _HAS_HF_OR_OPENAI
26
 
27
  logger = logging.getLogger(__name__)
28