Spaces:
Sleeping
Sleeping
Update inference.py
Browse files1234567 unmodified lines1415161718199 unmodified lines2930313233343519 unmodified lines5556575859606123 unmodified lines8586878889909192939495969798991001012 unmodified lines10410510610710810911011111211311 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147import osimport jsonimport textwrapfrom typing import Listfrom openai import OpenAI7 unmodified linesTEMPERATURE = 0.2MAX_TOKENS = 200FALLBACK_ACTION = "skip"SYSTEM_PROMPT = textwrap.dedent("""9 unmodified lines""").strip()def build_user_prompt(step: int, obs: Observation, history: List[str]) -> str:newline = "\n"comments_str = newline.join(obs.comments) if obs.comments else "No existing comments"19 unmodified lines).strip()return promptdef parse_model_action(response_text: str) -> Action:if not response_text:return Action(action_type=FALLBACK_ACTION)23 unmodified linesreturn Action(action_type="propose_fix", fix_code=fix)return Action(action_type="write_comment", comment_text=raw)def main() -> None:if not API_BASE_URL or not API_KEY or not MODEL_NAME:# This error message is printed to stderr? It must not appear on stdout.# Use sys.stderr to avoid polluting structured output.import sysprint("Error: API_BASE_URL, HF_TOKEN/API_KEY, and MODEL_NAME must be set.", file=sys.stderr)returnclient = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)env = CodeReviewEnv()tasks = ["easy", "medium", "hard", "harder", "hardest"]for task in tasks:2 unmodified lineshistory: List[str] = []done = Falsestep = 0final_reward = 0.0# START markerprint(f"[START] task={task}", flush=True)while not done and step < MAX_STEPS:step += 111 unmodified lines)response_text = completion.choices[0].message.content or ""except Exception as exc:# Print error to stderr onlyimport sysprint(f"Request failed: {exc}. Using fallback.", file=sys.stderr)response_text = FALLBACK_ACTIONaction = parse_model_action(response_text)obs, reward, done, info = env.step(action)final_reward = reward.value# STEP marker with required key=value formatprint(f"[STEP] step={step} reward={final_reward:.3f}", flush=True)history.append(f"Step {step}: {action.action_type}")# END markerprint(f"[END] task={task} score={final_reward:.3f} steps={step}", flush=True)if __name__ == "__main__":main()123456787 unmodified lines1617181920212223249 unmodified lines34353637383919 unmodified lines59606162636423 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131142 unmodified lines11711811912012112212312412512611 unmodified lines138139140141142143144145146147148149150151152153154155156157158159160161162163164165import osimport sysimport jsonimport textwrapimport asynciofrom typing import Listfrom openai import OpenAI7 unmodified linesTEMPERATURE = 0.2MAX_TOKENS = 200FALLBACK_ACTION = "skip"TASK_NAME = "code_review" # or "easy", "medium", etc. – but we'll vary per taskENV_NAME = "code_review_env"SUCCESS_THRESHOLD = 0.5 # if final score >= 0.5, consider successSYSTEM_PROMPT = textwrap.dedent("""9 unmodified lines""").strip()def build_user_prompt(step: int, obs: Observation, history: List[str]) -> str:newline = "\n"comments_str = newline.join(obs.comments) if obs.comments else "No existing comments"19 unmodified lines).strip()return promptdef parse_model_action(response_text: str) -> Action:if not response_text:return Action(action_type=FALLBACK_ACTION)23 unmodified linesreturn Action(action_type="propose_fix", fix_code=fix)return Action(action_type="write_comment", comment_text=raw)def log_start(task: str, env: str, model: str):print(f"[START] task={task} env={env} model={model}", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: str = None):error_str = f" error={error}" if error else ""print(f"[STEP] step={step} action={action} reward={reward:.3f} done={done}{error_str}", flush=True)def log_end(success: bool, steps: int, score: float, rewards: List[float]):# rewards as JSON array to match sample (though sample shows `rewards=rewards` which might be a list)rewards_str = json.dumps(rewards, separators=(',', ':'))print(f"[END] success={success} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)async def main() -> None:if not API_BASE_URL or not API_KEY or not MODEL_NAME:print("Error: API_BASE_URL, HF_TOKEN/API_KEY, and MODEL_NAME must be set.", file=sys.stderr)returnclient = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)env = CodeReviewEnv() # synchronous environment – we'll wrap calls in async? The sample uses async, but we can run sync and just not await.# Since our env is sync, we'll call methods directly. The logging is the key part.tasks = ["easy", "medium", "hard", "harder", "hardest"]for task in tasks:2 unmodified lineshistory: List[str] = []done = Falsestep = 0rewards = []final_score = 0.0log_start(task=task, env=ENV_NAME, model=MODEL_NAME)while not done and step < MAX_STEPS:step += 111 unmodified lines)response_text = completion.choices[0].message.content or ""except Exception as exc:print(f"Request failed: {exc}. Using fallback.", file=sys.stderr)response_text = FALLBACK_ACTIONaction = parse_model_action(response_text)obs, reward, done, info = env.step(action)reward_val = reward.valuerewards.append(reward_val)log_step(step=step, action=action.action_type, reward=reward_val, done=done)history.append(f"Step {step}: {action.action_type}")# Compute overall score (e.g., average reward or final reward? Sample uses sum(rewards)/MAX_TOTAL_REWARD.# We'll use average reward per step as score, clamped to [0,1].if rewards:avg_reward = sum(rewards) / len(rewards)score = max(0.0, min(1.0, avg_reward))else:score = 0.0success = score >= SUCCESS_THRESHOLDlog_end(success=success, steps=step, score=score, rewards=rewards)if __name__ == "__main__":asyncio.run(main())
inference.py+36-18