vinith17 commited on
Commit
e5443c9
Β·
1 Parent(s): af2db79

fix: fully compliant inference.py per hackathon pre-submission checklist

Browse files
Files changed (1) hide show
  1. inference.py +167 -68
inference.py CHANGED
@@ -1,78 +1,177 @@
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import json
 
 
3
  from openai import OpenAI
4
- from environment import CodeBugEnvironment
5
- from models import CodeReviewAction
6
 
7
- def run_inference():
8
- # Read required environment variables
9
- api_base = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
10
- model_name = os.environ.get("MODEL_NAME", "gpt-3.5-turbo")
11
- hf_token = os.environ.get("HF_TOKEN")
12
-
13
- # Initialize OpenEnv environment locally for baseline test
14
- env = CodeBugEnvironment()
15
- obs = env.reset()
16
-
17
- print(f"[START] Episode {env.state.episode_id}")
18
-
19
- client = OpenAI(
20
- api_key=hf_token, # HF_TOKEN acts as the API key per instructions
21
- base_url=api_base
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  )
23
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  total_reward = 0.0
25
- step_count = 0
26
-
27
- while not obs.done:
28
- step_count += 1
29
-
30
- prompt = f"""
31
- You are a code review agent. Difficulty: {obs.difficulty}.
32
- Given this code snippet:
33
- {obs.code_snippet}
34
-
35
- Output a valid JSON matching this schema exactly:
36
- {{
37
- "category": "logic | security | style | approve",
38
- "severity": 1-5 (int),
39
- "line_hint": line number where bug exists (int),
40
- "comment": "short description"
41
- }}
42
- """
43
-
44
  try:
45
- response = client.chat.completions.create(
46
- model=model_name,
47
- messages=[{"role": "user", "content": prompt}],
48
- response_format={ "type": "json_object" }
49
- )
50
- raw_action = json.loads(response.choices[0].message.content)
51
-
52
- action = CodeReviewAction(
53
- category=raw_action.get("category", "style"),
54
- severity=int(raw_action.get("severity", 1)),
55
- line_hint=int(raw_action.get("line_hint", 0)) if raw_action.get("line_hint") else None,
56
- comment=raw_action.get("comment", "")
57
- )
58
- except Exception as e:
59
- # Fallback action on parsing failure
60
- action = CodeReviewAction(
61
- category="approve",
62
- severity=1,
63
- line_hint=None,
64
- comment="Failed to parse LLM output."
65
- )
66
-
67
- print(f"[STEP] Sending Action -> Category: {action.category}, Severity: {action.severity}")
68
-
69
- # Step environment
70
- obs = env.step(action)
71
- total_reward += obs.reward or 0.0
72
-
73
- print(f"[STEP] Result -> Reward: {obs.reward:.2f} | Info: {obs.feedback}")
74
-
75
- print(f"[END] Total Reward: {total_reward:.2f}")
76
 
77
  if __name__ == "__main__":
78
  run_inference()
 
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"
46
+ " if from_account.balance > amount:\n"
47
+ " from_account.balance -= amount\n"
48
+ " to_account.balance += 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"
59
+ " if not numbers:\n"
60
+ " return None\n"
61
+ " max_val = numbers[0]\n"
62
+ " for i in range(len(numbers) - 1):\n"
63
+ " if numbers[i] > max_val:\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"
74
+ " query = f\"SELECT * FROM users WHERE username = '{username}'"
75
+ " AND password = '{password}'\"\n"
76
+ " user = db.execute(query)\n"
77
+ " if user:\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__":
177
  run_inference()