feat: Add fast mode with auto-fallback (INFERENCE_MODE=fast / --fast / 12s auto-switch)
Browse files5 unmodified lines67891011121314151617184 unmodified lines2324252627282930313233149 unmodified lines1831841851861871881891901911921931941954 unmodified lines20020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624751 unmodified lines29930030130230330430530630730830931031131231311 unmodified lines3253263275 unmodified linesMODEL_NAME The model identifierHF_TOKEN Your Hugging Face / API keyRun:API_BASE_URL=... MODEL_NAME=... HF_TOKEN=... python inference.py"""import osimport jsonimport reimport textwrapfrom typing import Optional4 unmodified linesfrom graders.grader import grade_episodeAPI_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "")MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/Llama-3.3-70B-Instruct")TEMPERATURE = 0.1MAX_TOKENS = 512FALLBACK_ACTION = Action(action_type=ActionType.NOOP, reason="parse_failure")SYSTEM_PROMPT = textwrap.dedent("""149 unmodified linesreturn FALLBACK_ACTIONdef run_task(client: OpenAI, task_id: str, seed: int = 42) -> dict:env = DevOpsIncidentEnv(task_id=task_id, seed=seed)obs = env.reset()print(f"[START] task={task_id} seed={seed} model={MODEL_NAME}", flush=True)print(f"\n{'β'*64}")print(f" Task: {task_id.upper()} | Seed: {seed} | Model: {MODEL_NAME}")print(f"{'β'*64}")done = False4 unmodified linesprompt = observation_to_text(obs)try:reasoning_completion = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": REASONING_PROMPT},{"role": "user", "content": prompt},],temperature=0.3,max_tokens=256,)reasoning = reasoning_completion.choices[0].message.content or ""action_prompt = f"""Based on your analysis:{reasoning}Now output your action as a JSON object:{{"action_type": "...","service": "...","query": "...","root_cause": "...","runbook": "...","version": "...","reason": "one sentence summary"}}Output ONLY the JSON object.""".strip()action_completion = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": prompt},{"role": "assistant", "content": reasoning},{"role": "user", "content": action_prompt},],temperature=0.1,max_tokens=200,)response_text = action_completion.choices[0].message.content or ""except Exception as exc:print(f" Step {step:02d}: API error β {exc}")reasoning = "(error)"response_text = ""51 unmodified linesdef main():client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)results = []for task_id in ["easy", "medium", "hard", "bonus"]:r = run_task(client, task_id, seed=42)results.append(r)print(f"\n{'β'*64}")print(" BASELINE SCORES")print(f"{'β'*64}")total = 0.0for r in results:11 unmodified linesif __name__ == "__main__":main()5 unmodified lines67891011121314151617181920212223242526274 unmodified lines32333435363738394041424344454647149 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612624 unmodified lines26726826927027127227327427527627727827928028128228328428528651 unmodified lines33833934034134234334434534634734834935035135235335435535635735811 unmodified lines3703713723735 unmodified linesMODEL_NAME The model identifierHF_TOKEN Your Hugging Face / API keyOptional:INFERENCE_MODE Set to 'fast' to skip Chain-of-Thought (1 call/step).Default is 'cot' (2 calls/step, better scores).Auto-switches to fast if any step exceeds STEP_TIMEOUT_S.STEP_TIMEOUT_S Max seconds per CoT step before auto-switching (default 12).Run:API_BASE_URL=... MODEL_NAME=... HF_TOKEN=... python inference.pyAPI_BASE_URL=... MODEL_NAME=... HF_TOKEN=... python inference.py --fast"""import osimport sysimport jsonimport reimport timeimport textwrapfrom typing import Optional4 unmodified linesfrom graders.grader import grade_episodeAPI_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "")MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/Llama-3.3-70B-Instruct")# Inference mode: 'cot' (default) or 'fast'_mode_env = os.getenv("INFERENCE_MODE", "cot").lower()FAST_MODE = _mode_env == "fast" or "--fast" in sys.argvSTEP_TIMEOUT = float(os.getenv("STEP_TIMEOUT_S", "12")) # seconds; auto-switch thresholdTEMPERATURE = 0.1MAX_TOKENS = 512FALLBACK_ACTION = Action(action_type=ActionType.NOOP, reason="parse_failure")SYSTEM_PROMPT = textwrap.dedent("""149 unmodified linesreturn FALLBACK_ACTIONdef _call_fast(client: OpenAI, prompt: str) -> tuple[str, str]:"""Single-step: one LLM call returns JSON action directly."""completion = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": prompt},],temperature=TEMPERATURE,max_tokens=MAX_TOKENS,)response_text = completion.choices[0].message.content or ""return response_text, "(fast-mode)"def _call_cot(client: OpenAI, prompt: str) -> tuple[str, str]:"""Two-step Chain-of-Thought: reason first, then emit JSON action."""reasoning_completion = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": REASONING_PROMPT},{"role": "user", "content": prompt},],temperature=0.3,max_tokens=256,)reasoning = reasoning_completion.choices[0].message.content or ""action_prompt = (f"Based on your analysis:\n{reasoning}\n\n""Now output your action as a JSON object with fields: ""action_type, service, query, root_cause, runbook, version, reason.\n""Output ONLY the JSON object.")action_completion = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": prompt},{"role": "assistant", "content": reasoning},{"role": "user", "content": action_prompt},],temperature=0.1,max_tokens=200,)response_text = action_completion.choices[0].message.content or ""return response_text, reasoningdef run_task(client: OpenAI, task_id: str, seed: int = 42) -> dict:env = DevOpsIncidentEnv(task_id=task_id, seed=seed)obs = env.reset()# Respect global mode but allow per-task auto-downgrade if API is slowuse_fast = FAST_MODEmode_label = "fast" if use_fast else "cot"print(f"[START] task={task_id} seed={seed} model={MODEL_NAME} mode={mode_label}", flush=True)print(f"\n{'β'*64}")print(f" Task: {task_id.upper()} | Seed: {seed} | Mode: {mode_label.upper()} | Model: {MODEL_NAME}")print(f"{'β'*64}")done = False4 unmodified linesprompt = observation_to_text(obs)try:t0 = time.monotonic()if use_fast:response_text, reasoning = _call_fast(client, prompt)else:response_text, reasoning = _call_cot(client, prompt)elapsed = time.monotonic() - t0# Auto-switch: if CoT step exceeds threshold, go fast for remainderif not use_fast and elapsed > STEP_TIMEOUT:use_fast = Trueprint(f" β‘ CoT took {elapsed:.1f}s > {STEP_TIMEOUT}s limit β switching to fast mode", flush=True)except Exception as exc:print(f" Step {step:02d}: API error β {exc}", flush=True)reasoning = "(error)"response_text = ""51 unmodified linesdef main():mode_label = "FAST" if FAST_MODE else "COT"client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)print(f"\n{'β'*64}", flush=True)print(f" DevOps Incident Response β OpenEnv Baseline", flush=True)print(f" Mode: {mode_label} | Timeout: {STEP_TIMEOUT}s | Model: {MODEL_NAME}", flush=True)print(f"{'β'*64}", flush=True)results = []for task_id in ["easy", "medium", "hard", "bonus"]:r = run_task(client, task_id, seed=42)results.append(r)print(f"\n{'β'*64}")print(f" BASELINE SCORES [{mode_label} mode]")print(f"{'β'*64}")total = 0.0for r in results:11 unmodified linesif __name__ == "__main__":main()
inference.py+94-48