vinith17 commited on
Commit
273e960
·
1 Parent(s): a44cabe

fix(inference): align [STEP] scores with openenv.yaml task graders

Browse files

- Use tasks.*.grader grade() for stdout (same functions as manifest); LLM schema matches CodeReviewAction
- Defer API key check to run_inference(); safe to import module without env
- json_object retry without response_format for picky gateways
- Sanity-check root grader.py returns float in (0,1); keep grader import for rubric tooling

Made-with: Cursor

Files changed (1) hide show
  1. inference.py +91 -105
inference.py CHANGED
@@ -1,8 +1,10 @@
1
  """
2
- inference.py — Hackathon baseline inference (repo root).
3
 
4
- Requires an OpenAI-compatible API key: HF_TOKEN (hackathon) or OPENAI_API_KEY if HF_TOKEN is unset.
5
- Optional: API_BASE_URL, MODEL_NAME. Uses openai.OpenAI only. Stdout: [START], [STEP] … score=…, [END].
 
 
6
  """
7
 
8
  from __future__ import annotations
@@ -14,20 +16,26 @@ 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
- _LLM_KEY = (os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or "").strip()
22
 
23
- if not _LLM_KEY:
24
- print(
25
- "[ERROR] Set HF_TOKEN or OPENAI_API_KEY to your OpenAI-compatible API key.",
26
- flush=True,
27
- )
28
- sys.exit(1)
29
-
30
- client = OpenAI(api_key=_LLM_KEY, base_url=API_BASE_URL)
31
 
32
  TASKS = [
33
  {
@@ -41,14 +49,6 @@ TASKS = [
41
  " return True\n"
42
  " return False"
43
  ),
44
- "ground_truth": {
45
- "bug": {
46
- "type": "logic",
47
- "severity": 4,
48
- "description": "Strict > should likely be >= for balance transfer edge case",
49
- "line_hint": "if balance check",
50
- }
51
- },
52
  },
53
  {
54
  "task_id": "task_medium_002",
@@ -63,14 +63,6 @@ TASKS = [
63
  " max_val = numbers[i]\n"
64
  " return max_val"
65
  ),
66
- "ground_truth": {
67
- "bug": {
68
- "type": "logic",
69
- "severity": 3,
70
- "description": "Off-by-one: range(len(numbers)-1) skips last element",
71
- "line_hint": "for loop range",
72
- }
73
- },
74
  },
75
  {
76
  "task_id": "task_hard_003",
@@ -84,14 +76,6 @@ TASKS = [
84
  " return True\n"
85
  " return False"
86
  ),
87
- "ground_truth": {
88
- "bug": {
89
- "type": "security",
90
- "severity": 5,
91
- "description": "SQL injection via f-string query",
92
- "line_hint": "query construction line",
93
- }
94
- },
95
  },
96
  {
97
  "task_id": "task_extra_004",
@@ -101,14 +85,6 @@ TASKS = [
101
  "def process_data(data):\n"
102
  " return data.upper()"
103
  ),
104
- "ground_truth": {
105
- "bug": {
106
- "type": "security",
107
- "severity": 5,
108
- "description": "Hardcoded API key / secret",
109
- "line_hint": "API_KEY assignment",
110
- }
111
- },
112
  },
113
  {
114
  "task_id": "task_extra_005",
@@ -118,26 +94,17 @@ TASKS = [
118
  " # Potential bug here\n"
119
  " return a / b"
120
  ),
121
- "ground_truth": {
122
- "bug": {
123
- "type": "logic",
124
- "severity": 3,
125
- "description": "Division without zero check",
126
- "line_hint": "return division",
127
- }
128
- },
129
  },
130
  ]
131
 
132
- SYSTEM_PROMPT = """You are a code reviewer. Respond with ONLY a JSON object (no markdown) using this schema:
 
133
  {
134
- "type": "flag" or "approve",
135
- "category": "security" or "logic" or "style" or "ok",
136
- "line_hint": "<string, line or location description>",
137
- "comment": "<string explanation>",
138
- "severity": <integer 1-5>
139
- }
140
- Use type \"flag\" if you report a bug, \"approve\" if the snippet is fine."""
141
 
142
 
143
  def _parse_llm_json(raw: str | None) -> dict:
@@ -155,77 +122,96 @@ def _parse_llm_json(raw: str | None) -> dict:
155
  return {}
156
 
157
 
158
- def _coerce_action(data: dict) -> dict:
159
- """Shape model output for grader.grade(ai_action, ground_truth)."""
160
- typ = str(data.get("type", "approve")).strip().lower()
161
- if typ not in ("flag", "approve"):
162
- typ = "approve"
163
- cat = str(data.get("category", "ok")).strip().lower()
164
- if cat not in ("security", "logic", "style", "ok"):
165
- cat = "ok"
166
- lh = data.get("line_hint", "")
167
- if lh is None:
168
- lh = ""
169
- lh = str(lh).strip()
170
- comment = str(data.get("comment", "")).strip()
171
  try:
172
- sev = int(data.get("severity", 0))
173
  except (TypeError, ValueError):
174
- sev = 0
 
 
 
 
 
 
 
 
 
175
  return {
176
- "type": typ,
177
  "category": cat,
178
- "line_hint": lh,
179
- "comment": comment,
180
  "severity": sev,
 
 
181
  }
182
 
183
 
184
- def run_task(task: dict) -> dict:
185
- user = (
186
- f"Difficulty: {task['difficulty']}\n\n"
187
- f"Review this code:\n\n{task['code']}"
188
- )
189
- response = client.chat.completions.create(
190
  model=MODEL_NAME,
191
- max_tokens=300,
192
  temperature=0.2,
193
  messages=[
194
  {"role": "system", "content": SYSTEM_PROMPT},
195
- {"role": "user", "content": user},
196
  ],
197
- response_format={"type": "json_object"},
198
  )
 
 
 
 
 
 
199
  raw = response.choices[0].message.content
200
  parsed = _parse_llm_json(raw)
201
- if not parsed:
202
- return {
203
- "type": "approve",
204
- "category": "ok",
205
- "line_hint": "",
206
- "comment": "parse_error",
207
- "severity": 0,
208
- }
209
- return _coerce_action(parsed)
210
 
211
 
212
  def run_inference() -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  print("[START]", flush=True)
214
  for task in TASKS:
215
  tid = task["task_id"]
216
  try:
217
- action = run_task(task)
218
  except Exception as exc:
219
  action = {
220
- "type": "approve",
221
- "category": "ok",
222
- "line_hint": "",
223
  "comment": str(exc),
224
- "severity": 0,
225
  }
226
- result = grade(action, task["ground_truth"])
227
- score = result.reward
228
- print(f"[STEP] task_id={tid} score={score}", flush=True)
229
  print("[END]", flush=True)
230
 
231
 
 
1
  """
2
+ inference.py — Repo-root inference for hackathon + OpenEnv Task Validation.
3
 
4
+ Task Validation loads graders from openenv.yaml (tasks.*.grader). Stdout scores MUST come from
5
+ those same grade() functions so parsed [STEP] lines match the manifest.
6
+
7
+ Env: HF_TOKEN or OPENAI_API_KEY (OpenAI-compatible key). Optional: API_BASE_URL, MODEL_NAME.
8
  """
9
 
10
  from __future__ import annotations
 
16
 
17
  from openai import OpenAI
18
 
19
+ # Manifest graders (must match openenv.yaml `grader:` entries exactly)
20
+ from tasks.easy.grader import grade as grade_task_easy_001
21
+ from tasks.extra1.grader import grade as grade_task_extra_004
22
+ from tasks.extra2.grader import grade as grade_task_extra_005
23
+ from tasks.hard.grader import grade as grade_task_hard_003
24
+ from tasks.medium.grader import grade as grade_task_medium_002
25
+
26
+ # Root rubric (integer → normalized); imported so static checks / RL tooling see grader.py
27
+ from grader import grade as root_rubric_grade
28
 
29
  API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
30
  MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
 
31
 
32
+ _TASK_GRADERS = {
33
+ "task_easy_001": grade_task_easy_001,
34
+ "task_medium_002": grade_task_medium_002,
35
+ "task_hard_003": grade_task_hard_003,
36
+ "task_extra_004": grade_task_extra_004,
37
+ "task_extra_005": grade_task_extra_005,
38
+ }
 
39
 
40
  TASKS = [
41
  {
 
49
  " return True\n"
50
  " return False"
51
  ),
 
 
 
 
 
 
 
 
52
  },
53
  {
54
  "task_id": "task_medium_002",
 
63
  " max_val = numbers[i]\n"
64
  " return max_val"
65
  ),
 
 
 
 
 
 
 
 
66
  },
67
  {
68
  "task_id": "task_hard_003",
 
76
  " return True\n"
77
  " return False"
78
  ),
 
 
 
 
 
 
 
 
79
  },
80
  {
81
  "task_id": "task_extra_004",
 
85
  "def process_data(data):\n"
86
  " return data.upper()"
87
  ),
 
 
 
 
 
 
 
 
88
  },
89
  {
90
  "task_id": "task_extra_005",
 
94
  " # Potential bug here\n"
95
  " return a / b"
96
  ),
 
 
 
 
 
 
 
 
97
  },
98
  ]
99
 
100
+ # Matches models.CodeReviewAction — same shape YAML task graders expect
101
+ SYSTEM_PROMPT = """You are a code reviewer. Reply with ONLY a JSON object (no markdown):
102
  {
103
+ "category": "logic" | "security" | "style" | "approve",
104
+ "severity": <integer 1-5>,
105
+ "line_hint": <integer line number or null if unknown>,
106
+ "comment": "<short string>"
107
+ }"""
 
 
108
 
109
 
110
  def _parse_llm_json(raw: str | None) -> dict:
 
122
  return {}
123
 
124
 
125
+ def _coerce_code_review_action(data: dict) -> dict:
126
+ cat = str(data.get("category", "approve")).strip().lower()
127
+ if cat not in ("logic", "security", "style", "approve"):
128
+ cat = "approve"
 
 
 
 
 
 
 
 
 
129
  try:
130
+ sev = int(data.get("severity", 1))
131
  except (TypeError, ValueError):
132
+ sev = 1
133
+ sev = max(1, min(5, sev))
134
+ lh = data.get("line_hint")
135
+ if lh is not None and lh != "":
136
+ try:
137
+ lh = int(lh)
138
+ except (TypeError, ValueError):
139
+ lh = None
140
+ else:
141
+ lh = None
142
  return {
 
143
  "category": cat,
 
 
144
  "severity": sev,
145
+ "line_hint": lh,
146
+ "comment": str(data.get("comment", "")).strip(),
147
  }
148
 
149
 
150
+ def _chat_json(client: OpenAI, user_text: str) -> dict:
151
+ """Prefer json_object mode; retry without it if the deployment rejects it."""
152
+ kwargs = dict(
 
 
 
153
  model=MODEL_NAME,
154
+ max_tokens=400,
155
  temperature=0.2,
156
  messages=[
157
  {"role": "system", "content": SYSTEM_PROMPT},
158
+ {"role": "user", "content": user_text},
159
  ],
 
160
  )
161
+ try:
162
+ response = client.chat.completions.create(
163
+ **kwargs, response_format={"type": "json_object"}
164
+ )
165
+ except Exception:
166
+ response = client.chat.completions.create(**kwargs)
167
  raw = response.choices[0].message.content
168
  parsed = _parse_llm_json(raw)
169
+ return _coerce_code_review_action(parsed) if parsed else {}
170
+
171
+
172
+ def run_task(client: OpenAI, task: dict) -> dict:
173
+ user = f"Difficulty: {task['difficulty']}\n\nReview this code:\n\n{task['code']}"
174
+ data = _chat_json(client, user)
175
+ if not data:
176
+ return {"category": "approve", "severity": 1, "line_hint": None, "comment": "parse_error"}
177
+ return data
178
 
179
 
180
  def run_inference() -> None:
181
+ llm_key = (os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or "").strip()
182
+ if not llm_key:
183
+ print(
184
+ "[ERROR] Set HF_TOKEN or OPENAI_API_KEY to your OpenAI-compatible API key.",
185
+ flush=True,
186
+ )
187
+ sys.exit(1)
188
+
189
+ client = OpenAI(api_key=llm_key, base_url=API_BASE_URL)
190
+
191
+ # Ensure grader.py rubric returns (0,1); does not change [STEP] scores (those use manifest graders).
192
+ _san = root_rubric_grade(
193
+ {"type": "approve", "category": "ok", "line_hint": "", "comment": "", "severity": 0},
194
+ {"bug": {"type": "none", "severity": 0, "description": "", "line_hint": ""}},
195
+ )
196
+ if not (isinstance(_san.reward, float) and 0.0 < _san.reward < 1.0):
197
+ print(f"[ERROR] grader.py reward out of (0,1): {_san.reward!r}", flush=True)
198
+ sys.exit(1)
199
+
200
  print("[START]", flush=True)
201
  for task in TASKS:
202
  tid = task["task_id"]
203
  try:
204
+ action = run_task(client, task)
205
  except Exception as exc:
206
  action = {
207
+ "category": "approve",
208
+ "severity": 1,
209
+ "line_hint": None,
210
  "comment": str(exc),
 
211
  }
212
+ grader = _TASK_GRADERS[tid]
213
+ score = float(grader(action))
214
+ print(f"[STEP] task_id={tid} score={score:.4f}", flush=True)
215
  print("[END]", flush=True)
216
 
217