Harshitjhamb/Meta_Hackathon
0
1import subprocess2import sys3 4subprocess.check_call([sys.executable, "-m", "pip", "install", "openai", "requests", "-q"])5 6 7import asyncio8import os9import textwrap10import requests11from typing import List, Optional12from openai import OpenAI13 14API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY") or "dummy"15API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"16MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"17ENV_URL = os.getenv("ENV_URL") or "https://harshitjhamb-meta-hackathon.hf.space"18TASK_NAME = os.getenv("TASK_NAME") or "easy"19BENCHMARK = "traffic-env"20MAX_STEPS = 821TEMPERATURE = 0.722MAX_TOKENS = 15023SUCCESS_SCORE_THRESHOLD = 0.124MAX_TOTAL_REWARD = MAX_STEPS * 10.025 26SYSTEM_PROMPT = textwrap.dedent("""27 You are an AI agent controlling traffic signals.28 You will receive the current lane vehicle counts and must choose which lane (0-3) to give the green signal.29 Respond with only a single integer: 0, 1, 2, or 3.30""").strip()31 32def log_start(task: str, env: str, model: str) -> None:33 print(f"[START] task={task} env={env} model={model}", flush=True)34 35def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:36 error_val = error if error else "null"37 done_val = str(done).lower()38 print(f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}", flush=True)39 40def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:41 rewards_str = ",".join(f"{r:.2f}" for r in rewards)42 print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)43 44def get_action(client: OpenAI, lanes: List[int], step: int, history: List[str]) -> int:45 history_block = "\n".join(history[-4:]) if history else "None"46 user_prompt = textwrap.dedent(f"""47 Step: {step}48 Current lane vehicle counts: {lanes}49 Previous steps:50 {history_block}51 Which lane (0-3) should get the green signal? Reply with only a single integer.52 """).strip()53 try:54 completion = client.chat.completions.create(55 model=MODEL_NAME,56 messages=[57 {"role": "system", "content": SYSTEM_PROMPT},58 {"role": "user", "content": user_prompt},59 ],60 temperature=TEMPERATURE,61 max_tokens=MAX_TOKENS,62 )63 text = (completion.choices[0].message.content or "").strip()64 return int(text[0]) % 465 except Exception as exc:66 print(f"[DEBUG] Model request failed: {exc}", flush=True)67 return 068 69def main() -> None:70 client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)71 history: List[str] = []72 rewards: List[float] = []73 steps_taken = 074 score = 0.075 success = False76 77 log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)78 79 try:80 # Reset environment81 res = requests.post(f"{ENV_URL}/reset", timeout=30)82 obs = res.json()["observation"]83 lanes = obs["lanes"]84 85 for step in range(1, MAX_STEPS + 1):86 action = get_action(client, lanes, step, history)87 88 res = requests.post(f"{ENV_URL}/step", json={"signal": action}, timeout=30)89 result = res.json()90 obs = result["observation"]91 lanes = obs["lanes"]92 reward = float(result.get("reward", 0.0))93 done = result.get("done", False)94 95 rewards.append(reward)96 steps_taken = step97 log_step(step=step, action=str(action), reward=reward, done=done, error=None)98 history.append(f"Step {step}: signal={action} lanes={lanes} reward={reward:+.2f}")99 100 if done:101 break102 103 score = sum(rewards) / MAX_TOTAL_REWARD if MAX_TOTAL_REWARD > 0 else 0.0104 score = min(max(score, 0.0), 1.0)105 success = score >= SUCCESS_SCORE_THRESHOLD106 107 except Exception as e:108 print(f"[DEBUG] Exception: {e}", flush=True)109 110 log_end(success=success, steps=steps_taken, score=score, rewards=rewards)111 112if __name__ == "__main__":113 main()