import os import json import requests from openai import OpenAI API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "dummy-key") API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1") MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct") ENV_URL = os.getenv("ENV_URL", "http://localhost:7860") client = OpenAI(api_key=API_KEY, base_url=API_BASE_URL) TASKS = ["easy_classify", "medium_severity", "hard_write_fix"] def run_inference(): for task_id in TASKS: # Reset Environment try: reset_res = requests.post(f"{ENV_URL}/reset", json={"task_id": task_id}, timeout=10) if reset_res.status_code != 200: print(f"Failed to reset env: {reset_res.text}") return obs = reset_res.json() except Exception as e: print(f"Failed to connect to environment: {str(e)}") return print(f"[START] task={task_id} env=code-review-env model={MODEL_NAME}") step_num = 0 is_done = False rewards_history = [] final_score = 0.0 while not is_done: step_num += 1 action_str = "failed" error_msg = "null" reward_val = 0.00 prompt = f"""You are a Code Review Agent. Task: {task_id} Current Hunk: {json.dumps(obs.get('current_hunk', {}))} Return ONLY valid JSON matching: {{"action_type": "write_fix", "hunk_id": "h1", "issue_type": "bug", "severity": "major", "suggestion": "Fix details..."}}""" try: response = client.chat.completions.create( model=MODEL_NAME, messages=[{"role": "user", "content": prompt}], temperature=0.1 ) raw_out = response.choices[0].message.content.strip() # Strip markdown code block formatting if the LLM includes it if "```json" in raw_out: raw_out = raw_out.split("```json")[1].split("```")[0].strip() elif "```" in raw_out: raw_out = raw_out.split("```")[1].split("```")[0].strip() action_data = json.loads(raw_out) # Send the action to the environment step_res = requests.post(f"{ENV_URL}/step", json={"action": action_data}) step_data = step_res.json() obs = step_data["observation"] reward_val = step_data["reward"] is_done = step_data["done"] # Format the action string exactly as the judges expect action_str = f"{action_data.get('action_type', 'unknown')}('{action_data.get('hunk_id','')}', '{action_data.get('issue_type','')}')" rewards_history.append(f"{reward_val:.2f}") final_score += reward_val except Exception as e: # Format errors strictly to avoid breaking the judge's regex parser error_msg = f'"{str(e)}"' is_done = True rewards_history.append("0.00") print(f"[STEP] step={step_num} action={action_str} reward={reward_val:.2f} done={str(is_done).lower()} error={error_msg}") # Normalize score based on the max possible score for the task max_possible = {"easy_classify": 5, "medium_severity": 8, "hard_write_fix": 12}.get(task_id, 1) normalized = final_score / max_possible # Strict (0, 1) bounds required by validator normalized = min(0.999, max(0.001, normalized)) rewards_str = ",".join(rewards_history) if rewards_history else "0.00" success = normalized > 0.4 print(f"[END] success={str(success).lower()} steps={step_num} score={normalized:.3f} rewards={rewards_str}") if __name__ == "__main__": run_inference()