File size: 6,844 Bytes
e5443c9
 
 
 
 
 
 
 
 
 
5235bfa
 
e5443c9
 
5235bfa
 
e5443c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5235bfa
e5443c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5235bfa
e5443c9
 
 
 
 
 
 
 
 
 
 
5235bfa
e5443c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5235bfa
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
inference.py β€” CodeBug baseline inference script.

Strictly follows the Meta PyTorch Hackathon pre-submission checklist:
  - Environment variables: API_BASE_URL, MODEL_NAME, HF_TOKEN
  - Defaults ONLY for API_BASE_URL and MODEL_NAME (not HF_TOKEN)
  - All LLM calls use `from openai import OpenAI` configured via these variables
  - Stdout logs follow the required [START] / [STEP] / [END] format exactly
"""

import os
import json
import sys

from openai import OpenAI

# ─────────────────────────────────────────────────────────────
# Environment variables (checklist requirement)
# Defaults ONLY for API_BASE_URL and MODEL_NAME β€” NOT HF_TOKEN
# ─────────────────────────────────────────────────────────────
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
MODEL_NAME   = os.environ.get("MODEL_NAME",   "gpt-4o-mini")
HF_TOKEN     = os.environ.get("HF_TOKEN")     # No default β€” must be set by user

if not HF_TOKEN:
    print("[ERROR] HF_TOKEN environment variable is required but not set.", flush=True)
    sys.exit(1)

# ─────────────────────────────────────────────────────────────
# OpenAI client β€” configured strictly via the env variables
# ─────────────────────────────────────────────────────────────
client = OpenAI(
    api_key=HF_TOKEN,
    base_url=API_BASE_URL,
)

# ─────────────────────────────────────────────────────────────
# Code review tasks (3 difficulty levels: easy β†’ medium β†’ hard)
# ─────────────────────────────────────────────────────────────
TASKS = [
    {
        "id": "task_easy_001",
        "difficulty": "easy",
        "code": (
            "def transfer(from_account, to_account, amount):\n"
            "    if from_account.balance > amount:\n"
            "        from_account.balance -= amount\n"
            "        to_account.balance += amount\n"
            "        return True\n"
            "    return False"
        ),
        "truth": {"category": "logic", "severity": 4},
    },
    {
        "id": "task_medium_002",
        "difficulty": "medium",
        "code": (
            "def find_max(numbers):\n"
            "    if not numbers:\n"
            "        return None\n"
            "    max_val = numbers[0]\n"
            "    for i in range(len(numbers) - 1):\n"
            "        if numbers[i] > max_val:\n"
            "            max_val = numbers[i]\n"
            "    return max_val"
        ),
        "truth": {"category": "logic", "severity": 3},
    },
    {
        "id": "task_hard_003",
        "difficulty": "hard",
        "code": (
            "def login(username, password):\n"
            "    query = f\"SELECT * FROM users WHERE username = '{username}'"
            " AND password = '{password}'\"\n"
            "    user = db.execute(query)\n"
            "    if user:\n"
            "        return True\n"
            "    return False"
        ),
        "truth": {"category": "security", "severity": 5},
    },
]

SYSTEM_PROMPT = """\
You are a code review agent. Your task is to identify bugs in code snippets.
Return ONLY a valid JSON object with this exact schema (no markdown, no prose):
{
  "category": "logic" | "security" | "style" | "approve",
  "severity": <integer 1-5>,
  "line_hint": <integer line number or null>,
  "comment": "<short description of the bug>"
}
"""


def call_llm(code: str, difficulty: str) -> dict:
    """Call LLM via OpenAI client and parse the structured JSON response."""
    user_prompt = (
        f"Difficulty level: {difficulty}\n\n"
        f"Review the following code and identify any bugs:\n\n{code}"
    )

    response = client.chat.completions.create(
        model=MODEL_NAME,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user",   "content": user_prompt},
        ],
        response_format={"type": "json_object"},
        temperature=0.2,
    )

    raw = response.choices[0].message.content
    return json.loads(raw)


def score_action(action: dict, truth: dict) -> float:
    """
    Score the agent's action against ground truth.
    Returns a float in [0.0, 1.0].
    """
    reward = 0.0

    # Category match β†’ 0.5
    if action.get("category", "").lower() == truth["category"]:
        reward += 0.5

    # Severity accuracy β†’ up to 0.3
    sev_diff = abs(int(action.get("severity", 0)) - truth["severity"])
    if sev_diff == 0:
        reward += 0.3
    elif sev_diff == 1:
        reward += 0.15

    # Any non-None line hint when a bug exists β†’ 0.2
    if action.get("line_hint") is not None and truth["category"] != "approve":
        reward += 0.2

    return round(min(reward, 1.0), 4)


def run_inference():
    total_reward = 0.0

    # ── [START] ───────────────────────────────────────────────
    print(f"[START] api_base={API_BASE_URL} model={MODEL_NAME} tasks={len(TASKS)}", flush=True)

    for task in TASKS:
        task_id   = task["id"]
        code      = task["code"]
        difficulty = task["difficulty"]
        truth     = task["truth"]

        # ── [STEP] send action ─────────────────────────────────
        try:
            action = call_llm(code, difficulty)
        except Exception as exc:
            action = {"category": "approve", "severity": 1, "line_hint": None, "comment": str(exc)}

        reward = score_action(action, truth)
        total_reward += reward

        print(
            f"[STEP] task_id={task_id} difficulty={difficulty} "
            f"category={action.get('category')} severity={action.get('severity')} "
            f"reward={reward:.4f}",
            flush=True,
        )

    # ── [END] ─────────────────────────────────────────────────
    avg_reward = total_reward / len(TASKS)
    print(f"[END] total_reward={total_reward:.4f} avg_reward={avg_reward:.4f}", flush=True)


if __name__ == "__main__":
    run_inference()