openenv_hackathon / inference.py
sharancreates's picture
bugs fixed
b7c56ea
Raw History Blame Contribute Delete
4.35 kB
import os
import json
import sys
from openai import OpenAI
from env import CodeReviewEnv
from models import Action
# Dummy Token Failsafe Armor
HF_TOKEN = os.getenv("HF_TOKEN")
safe_token = HF_TOKEN if HF_TOKEN else "dummy_key_for_server_boot"
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
if not HF_TOKEN:
print("WARNING: HF_TOKEN not found. Booting with dummy key for Docker resilience.", flush=True)
client = OpenAI(base_url=API_BASE_URL, api_key=safe_token)
def log_start(task: str, model: str):
print(f"[START] task={task} env=aion-code-reviewer model={model}", flush=True)
sys.stdout.flush()
def log_step(step: int, action_type: str, reward: float, done: bool, error: str = "null"):
done_str = str(done).lower()
print(f"[STEP] step={step} action={action_type} reward={reward:.2f} done={done_str} error={error}", flush=True)
sys.stdout.flush()
def log_end(success: bool, steps: int, score: float, rewards: list):
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
# PDF Compliant: Mathematically forced exactly 2 decimal places and score= keyword
print(f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_str}", flush=True)
sys.stdout.flush()
def run_inference():
env = CodeReviewEnv()
# Phase 2 Standard Tasks
for task_id in ["style-cleanup", "efficiency-boost", "security-audit"]:
try:
obs, _ = env.reset(options={"task_id": task_id})
log_start(task_id, MODEL_NAME)
step_idx, total_rewards, is_success = 1, [], False
# Optimized to 3 steps for faster evaluation
while step_idx <= 3:
prompt = f"""
You are an expert Code Reviewer.
CURRENT TASK: {obs.current_task}
LINTER ERRORS: {obs.linter_report}
CODE TO REVIEW:
\"\"\"
{obs.code_content}
\"\"\"
INSTRUCTIONS:
1. Use "apply_fix" and provide the FULL corrected code.
2. Use "submit" ONLY if the code is optimal.
3. Response MUST be a single JSON object.
REQUIRED JSON FORMAT:
{{
"action_type": "apply_fix" or "submit",
"content": "the entire code string here",
"line_number": 0
}}
"""
try:
response = client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "system", "content": "Respond ONLY with valid JSON."}, {"role": "user", "content": prompt}],
response_format={"type": "json_object"},
timeout=30.0
)
content = response.choices[0].message.content
if not content: raise ValueError("Empty response")
agent_action = Action(**json.loads(content))
obs, reward, done, _ = env.step(agent_action)
# Auto-Submit Optimization: If agent hit the target, end early
if reward >= 0.95:
done = True
total_rewards.append(reward)
log_step(step_idx, agent_action.action_type, reward, done)
if done:
is_success = reward >= 0.8
break
step_idx += 1
except Exception as e:
log_step(step_idx, "error", 0.01, True, error=str(e))
total_rewards.append(0.01)
break
final_score = max(total_rewards) if total_rewards else 0.01
log_end(is_success, min(step_idx, 3), final_score, total_rewards)
except Exception as e:
print(f"ERROR: Task crashed: {e}", flush=True)
log_end(False, 0, 0.01, [0.01])
if __name__ == "__main__":
run_inference()