vedkdev/FlakyTestSleuthOpenEnvRL
0
1"""2Inference Script Example3===================================4MANDATORY5- Before submitting, ensure the following variables are defined in your environment configuration:6 API_BASE_URL The API endpoint for the LLM.7 MODEL_NAME The model identifier to use for inference.8 HF_TOKEN Your Hugging Face / API key.9 LOCAL_IMAGE_NAME The name of the local image to use for the environment if you are using from_docker_image()10 method11 12- Defaults are set only for API_BASE_URL and MODEL_NAME 13 (and should reflect your active inference setup):14 API_BASE_URL = os.getenv("API_BASE_URL", "<your-active-endpoint>")15 MODEL_NAME = os.getenv("MODEL_NAME", "<your-active-model>")16 17- The inference script must be named `inference.py` and placed in the root directory of the project18- Participants must use OpenAI Client for all LLM calls using above variables19 20STDOUT FORMAT21- The script must emit exactly three line types to stdout, in this order:22 23 [START] task=<task_name> env=<benchmark> model=<model_name>24 [STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>25 [END] success=<true|false> steps=<n> score=<score> rewards=<r1,r2,...,rn>26 27 Rules:28 - One [START] line at episode begin.29 - One [STEP] line per step, immediately after env.step() returns.30 - One [END] line after env.close(), always emitted (even on exception).31 - reward and rewards are formatted to 2 decimal places.32 - done and success are lowercase booleans: true or false.33 - error is the raw last_action_error string, or null if none.34 - All fields on a single line with no newlines within a line.35 - Each tasks should return score in [0, 1]36 37 Example:38 [START] task=click-test env=miniwob model=Qwen3-VL-30B39 [STEP] step=1 action=click('123') reward=0.00 done=false error=null40 [STEP] step=2 action=fill('456','text') reward=0.00 done=false error=null41 [STEP] step=3 action=click('789') reward=1.00 done=true error=null42 [END] success=true steps=3 score=1.00 rewards=0.00,0.00,1.0043"""44 45import asyncio46import os47import textwrap48from typing import List, Optional49 50from openai import OpenAI51 52from my_env_v4 import MyEnvV4Action, MyEnvV4Env53IMAGE_NAME = os.getenv("IMAGE_NAME") # If you are using docker image 54API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")55 56API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"57MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"58TASK_NAME = os.getenv("MY_ENV_V4_TASK", "echo")59BENCHMARK = os.getenv("MY_ENV_V4_BENCHMARK", "my_env_v4")60MAX_STEPS = 861TEMPERATURE = 0.762MAX_TOKENS = 15063SUCCESS_SCORE_THRESHOLD = 0.1 # normalized score in [0, 1]64 65# Max possible reward: each token contributes 0.1, across all steps66_MAX_REWARD_PER_STEP = MAX_TOKENS * 0.167MAX_TOTAL_REWARD = MAX_STEPS * _MAX_REWARD_PER_STEP68 69SYSTEM_PROMPT = textwrap.dedent(70 """71 You are interacting with a simple echo environment.72 Each turn you must send a message. The environment will echo it back.73 Reward is proportional to message length: reward = len(message) * 0.174 Your goal is to maximize total reward by sending meaningful, substantive messages.75 Reply with exactly one message string — no quotes, no prefixes, just the message text.76 """77).strip()78 79 80def log_start(task: str, env: str, model: str) -> None:81 print(f"[START] task={task} env={env} model={model}", flush=True)82 83 84def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:85 error_val = error if error else "null"86 done_val = str(done).lower()87 print(88 f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",89 flush=True,90 )91 92 93def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:94 rewards_str = ",".join(f"{r:.2f}" for r in rewards)95 print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)96 97 98def build_user_prompt(step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:99 history_block = "\n".join(history[-4:]) if history else "None"100 return textwrap.dedent(101 f"""102 Step: {step}103 Last echoed message: {last_echoed!r}104 Last reward: {last_reward:.2f}105 Previous steps:106 {history_block}107 Send your next message.108 """109 ).strip()110 111 112def get_model_message(client: OpenAI, step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:113 user_prompt = build_user_prompt(step, last_echoed, last_reward, history)114 try:115 completion = client.chat.completions.create(116 model=MODEL_NAME,117 messages=[118 {"role": "system", "content": SYSTEM_PROMPT},119 {"role": "user", "content": user_prompt},120 ],121 temperature=TEMPERATURE,122 max_tokens=MAX_TOKENS,123 stream=False,124 )125 text = (completion.choices[0].message.content or "").strip()126 return text if text else "hello"127 except Exception as exc:128 print(f"[DEBUG] Model request failed: {exc}", flush=True)129 return "hello"130 131 132async def main() -> None:133 client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)134 135 env = await MyEnvV4Env.from_docker_image(IMAGE_NAME)136 137 history: List[str] = []138 rewards: List[float] = []139 steps_taken = 0140 score = 0.0141 success = False142 143 log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)144 145 try:146 result = await env.reset() # OpenENV.reset()147 last_echoed = result.observation.echoed_message148 last_reward = 0.0149 150 for step in range(1, MAX_STEPS + 1):151 if result.done:152 break153 154 message = get_model_message(client, step, last_echoed, last_reward, history)155 156 result = await env.step(MyEnvV4Action(message=message))157 obs = result.observation158 159 reward = result.reward or 0.0160 done = result.done161 error = None162 163 rewards.append(reward)164 steps_taken = step165 last_echoed = obs.echoed_message166 last_reward = reward167 168 log_step(step=step, action=message, reward=reward, done=done, error=error)169 170 history.append(f"Step {step}: {message!r} -> reward {reward:+.2f}")171 172 if done:173 break174 175 score = sum(rewards) / MAX_TOTAL_REWARD if MAX_TOTAL_REWARD > 0 else 0.0176 score = min(max(score, 0.001), 0.999) # clamp to (0.001, 0.999)177 success = score >= SUCCESS_SCORE_THRESHOLD178 179 finally:180 try:181 await env.close()182 except Exception as e:183 print(f"[DEBUG] env.close() error (container cleanup): {e}", flush=True)184 log_end(success=success, steps=steps_taken, score=score, rewards=rewards)185 186 187if __name__ == "__main__":188 asyncio.run(main())