CoolFace
Apppublic

nik-55/medchain-openenv-hackathon

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
sample_inference.py187 linesDownload Raw Back to root
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> 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 36  Example:37    [START] task=click-test env=miniwob model=Qwen3-VL-30B38    [STEP] step=1 action=click('123') reward=0.00 done=false error=null39    [STEP] step=2 action=fill('456','text') reward=0.00 done=false error=null40    [STEP] step=3 action=click('789') reward=1.00 done=true error=null41    [END] success=true steps=3 rewards=0.00,0.00,1.0042"""43 44import asyncio45import os46import textwrap47from typing import List, Optional48 49from openai import OpenAI50 51from my_env_v4 import MyEnvV4Action, MyEnvV4Env52IMAGE_NAME = os.getenv("IMAGE_NAME") # If you are using docker image 53API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")54 55API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"56MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"57TASK_NAME = os.getenv("MY_ENV_V4_TASK", "echo")58BENCHMARK = os.getenv("MY_ENV_V4_BENCHMARK", "my_env_v4")59MAX_STEPS = 860TEMPERATURE = 0.761MAX_TOKENS = 15062SUCCESS_SCORE_THRESHOLD = 0.1  # normalized score in [0, 1]63 64# Max possible reward: each token contributes 0.1, across all steps65_MAX_REWARD_PER_STEP = MAX_TOKENS * 0.166MAX_TOTAL_REWARD = MAX_STEPS * _MAX_REWARD_PER_STEP67 68SYSTEM_PROMPT = textwrap.dedent(69    """70    You are interacting with a simple echo environment.71    Each turn you must send a message. The environment will echo it back.72    Reward is proportional to message length: reward = len(message) * 0.173    Your goal is to maximize total reward by sending meaningful, substantive messages.74    Reply with exactly one message string — no quotes, no prefixes, just the message text.75    """76).strip()77 78 79def log_start(task: str, env: str, model: str) -> None:80    print(f"[START] task={task} env={env} model={model}", flush=True)81 82 83def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:84    error_val = error if error else "null"85    done_val = str(done).lower()86    print(87        f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",88        flush=True,89    )90 91 92def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:93    rewards_str = ",".join(f"{r:.2f}" for r in rewards)94    print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)95 96 97def build_user_prompt(step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:98    history_block = "\n".join(history[-4:]) if history else "None"99    return textwrap.dedent(100        f"""101        Step: {step}102        Last echoed message: {last_echoed!r}103        Last reward: {last_reward:.2f}104        Previous steps:105        {history_block}106        Send your next message.107        """108    ).strip()109 110 111def get_model_message(client: OpenAI, step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:112    user_prompt = build_user_prompt(step, last_echoed, last_reward, history)113    try:114        completion = client.chat.completions.create(115            model=MODEL_NAME,116            messages=[117                {"role": "system", "content": SYSTEM_PROMPT},118                {"role": "user", "content": user_prompt},119            ],120            temperature=TEMPERATURE,121            max_tokens=MAX_TOKENS,122            stream=False,123        )124        text = (completion.choices[0].message.content or "").strip()125        return text if text else "hello"126    except Exception as exc:127        print(f"[DEBUG] Model request failed: {exc}", flush=True)128        return "hello"129 130 131async def main() -> None:132    client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)133 134    env = await MyEnvV4Env.from_docker_image(IMAGE_NAME)135 136    history: List[str] = []137    rewards: List[float] = []138    steps_taken = 0139    score = 0.0140    success = False141 142    log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)143 144    try:145        result = await env.reset() # OpenENV.reset()146        last_echoed = result.observation.echoed_message147        last_reward = 0.0148 149        for step in range(1, MAX_STEPS + 1):150            if result.done:151                break152 153            message = get_model_message(client, step, last_echoed, last_reward, history)154 155            result = await env.step(MyEnvV4Action(message=message))156            obs = result.observation157 158            reward = result.reward or 0.0159            done = result.done160            error = None161 162            rewards.append(reward)163            steps_taken = step164            last_echoed = obs.echoed_message165            last_reward = reward166 167            log_step(step=step, action=message, reward=reward, done=done, error=error)168 169            history.append(f"Step {step}: {message!r} -> reward {reward:+.2f}")170 171            if done:172                break173 174        score = sum(rewards) / MAX_TOTAL_REWARD if MAX_TOTAL_REWARD > 0 else 0.0175        score = min(max(score, 0.0), 1.0)  # clamp to [0, 1]176        success = score >= SUCCESS_SCORE_THRESHOLD177 178    finally:179        try:180            await env.close()181        except Exception as e:182            print(f"[DEBUG] env.close() error (container cleanup): {e}", flush=True)183        log_end(success=success, steps=steps_taken, score=score, rewards=rewards)184 185 186if __name__ == "__main__":187    asyncio.run(main())