Spaces:
Sleeping
Sleeping
Commit ·
c170a1a
1
Parent(s): 5f6895d
Fix timeout: add LLM/HTTP timeouts, reduce retries, compact prompts (16s total runtime)
Browse filesFixes Phase 2 validation failure (inference.py exceeded 30min).
- LLM timeout: 30s per call
- HTTP timeout: 15s per call
- Retries: 2 with 3s flat delay (was 5 with exponential up to 80s)
- System prompt reduced from ~400 to ~120 tokens
- Max output tokens: 100 (was 256)
- Total runtime: 16.7s (was potentially 75min+ on slow endpoints)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
6 unmodified lines789101112137 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281298 unmodified lines13813914014114214314411 unmodified lines15615715815916016116212 unmodified lines1751761771781791801811821831841851861871881891901911921 unmodified line1941951961971981996 unmodified linesimport jsonimport osimport sysimport timeimport requestsfrom openai import OpenAI7 unmodified lines# Environment URL — local by default, override for remoteENV_URL = os.environ.get("ENV_URL", "http://localhost:7860")# Initialize OpenAI clientclient = OpenAI(api_key=OPENAI_API_KEY, base_url=API_BASE_URL)SYSTEM_PROMPT = """You are a senior software engineer responsible for cleaning up stale feature flags at a large tech company.For each feature flag, you will receive rich metadata including: rollout percentage, age, owner status, dependencies, incident status, usage metrics, code snippets, git history, PR context, and related incidents.You have 5 possible actions:- "remove": Delete the flag and all code references — flag is fully rolled out and safe to remove- "keep": Flag is still needed — active experiment, kill switch, partial rollout, or active development- "deprecate": Mark for future removal — notify owner, set cleanup deadline- "escalate": Requires human review — ambiguous ownership, incident-related, complex multi-service dependencies- "investigate": Spend a step to reveal hidden investigation notes before deciding (costs a small penalty)Decision guidelines:- NEVER remove a flag during an active incident- NEVER remove a kill switch- NEVER remove a flag that's part of an active experiment- Check cascade_warning — if a dependency was already removed, be extra cautious- Check previously_removed — understand what's already been cleaned up this episode- Flags at 100% rollout with no dependencies and active owners → remove- Flags at 100% rollout with dependencies or inactive owners → deprecate- Flags with many code references across multiple services and ambiguous ownership → escalate- Partially rolled out flags being actively developed → keep- When uncertain, use "investigate" to get more context (but it costs -0.05)- Look at code_snippet and pr_context for additional signalsRespond with ONLY a JSON object: {"action": "<action>", "reasoning": "<brief explanation>"}"""def call_llm(observation: dict) -> dict:"""Call the LLM to decide on a feature flag action."""flag_info = {"flag_name": observation["flag_name"],"description": observation["description"],"rollout_percentage": observation["rollout_percentage"],"age_days": observation["age_days"],"last_modified_days": observation["last_modified_days"],"owner": observation["owner"],"owner_active": observation["owner_active"],"num_code_references": observation["num_code_references"],"has_dependencies": observation["has_dependencies"],"dependent_flags": observation["dependent_flags"],"is_kill_switch": observation["is_kill_switch"],"has_active_incident": observation["has_active_incident"],"usage_last_30d": observation["usage_last_30d"],"in_active_experiment": observation["in_active_experiment"],"services": observation["services"],"flags_remaining": observation["flags_remaining"],"code_snippet": observation.get("code_snippet", ""),"last_commit_message": observation.get("last_commit_message", ""),"pr_context": observation.get("pr_context", ""),"related_incidents": observation.get("related_incidents", []),"previously_removed": observation.get("previously_removed", []),"cascade_warning": observation.get("cascade_warning", ""),}# Include investigation notes if availableif observation.get("investigation_notes"):flag_info["investigation_notes"] = observation["investigation_notes"]user_msg = f"Analyze this feature flag and decide what to do:\n\n{json.dumps(flag_info, indent=2)}"# Retry with backoff for rate limitsfor attempt in range(5):try:response = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": user_msg},],temperature=0.0,max_tokens=256,)breakexcept Exception as e:if attempt < 4:wait_time = 2 ** attempt * 5print(f" [RETRY] Rate limited, waiting {wait_time}s (attempt {attempt + 1}/5)", flush=True)time.sleep(wait_time)else:return {"action": "escalate", "reasoning": f"API error after retries: {str(e)[:100]}"}content = response.choices[0].message.content.strip()try:if content.startswith("```"):content = content.split("```")[1]if content.startswith("json"):content = content[4:]content = content.strip()result = json.loads(content)if "action" not in result:result = {"action": "escalate", "reasoning": "Failed to parse LLM response"}return resultexcept json.JSONDecodeError:return {"action": "escalate", "reasoning": f"Failed to parse: {content[:100]}"}def run_task(task_id: str) -> float:"""Run the agent on a single task and return the score."""reset_resp = requests.post(f"{ENV_URL}/reset", json={"task_id": task_id})reset_resp.raise_for_status()reset_data = reset_resp.json()8 unmodified linesaction = call_llm(observation)step_resp = requests.post(f"{ENV_URL}/step", json={"action": action})step_resp.raise_for_status()step_data = step_resp.json()11 unmodified linesflush=True,)grade_resp = requests.post(f"{ENV_URL}/grade")grade_resp.raise_for_status()grade_data = grade_resp.json()score = grade_data["score"]12 unmodified linesprint(f"Environment: {ENV_URL}")print("=" * 60)tasks = ["easy", "medium", "hard"]scores = {}for task_id in tasks:print(f"\n--- Running task: {task_id} ---")try:score = run_task(task_id)scores[task_id] = scoreexcept Exception as e:print(f"[END] task_id={task_id} score=0.0 error={str(e)}", flush=True)scores[task_id] = 0.0print("\n" + "=" * 60)print("RESULTS SUMMARY")print("=" * 60)1 unmodified lineprint(f" {task_id:10s}: {score:.4f}")avg_score = sum(scores.values()) / len(scores) if scores else 0.0print(f" {'average':10s}: {avg_score:.4f}")print("=" * 60)6 unmodified lines7891011127 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201218 unmodified lines13013113213313413513611 unmodified lines14814915015115215315412 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881 unmodified line1901911921931941951966 unmodified linesimport jsonimport osimport timeimport requestsfrom openai import OpenAI7 unmodified lines# Environment URL — local by default, override for remoteENV_URL = os.environ.get("ENV_URL", "http://localhost:7860")# TimeoutsLLM_TIMEOUT = 30 # seconds per LLM callHTTP_TIMEOUT = 15 # seconds per env HTTP callMAX_RETRIES = 2 # max retries per LLM call (down from 5)RETRY_DELAY = 3 # seconds between retries (flat, not exponential)# Initialize OpenAI client with timeoutclient = OpenAI(api_key=OPENAI_API_KEY,base_url=API_BASE_URL,timeout=LLM_TIMEOUT,max_retries=0, # We handle retries ourselves)SYSTEM_PROMPT = """You are a senior engineer cleaning up stale feature flags. For each flag, pick ONE action:- "remove": Safe to delete (100% rolled out, no deps, no incidents)- "keep": Still needed (active experiment, kill switch, partial rollout, active dev)- "deprecate": Schedule removal (100% but has deps or inactive owner)- "escalate": Needs human review (complex deps, multi-service, ambiguous)Rules: NEVER remove kill switches, active incidents, or active experiments.Respond ONLY with JSON: {"action": "<action>", "reasoning": "<brief>"}"""def call_llm(observation: dict) -> dict:"""Call the LLM to decide on a feature flag action."""# Compact flag info — only essential fields to reduce tokensflag_info = (f"Flag: {observation['flag_name']}\n"f"Desc: {observation['description']}\n"f"Rollout: {observation['rollout_percentage']*100}% | Age: {observation['age_days']}d | Modified: {observation['last_modified_days']}d ago\n"f"Owner: {observation['owner']} (active={observation['owner_active']})\n"f"Code refs: {observation['num_code_references']} | Usage 30d: {observation['usage_last_30d']}\n"f"Services: {', '.join(observation['services'])}\n"f"Kill switch: {observation['is_kill_switch']} | Active incident: {observation['has_active_incident']} | In experiment: {observation['in_active_experiment']}\n"f"Dependencies: {', '.join(observation['dependent_flags']) if observation['dependent_flags'] else 'None'}\n")# Add rich context if available (compact)if observation.get("code_snippet"):flag_info += f"Code: {observation['code_snippet'][:200]}\n"if observation.get("pr_context"):flag_info += f"PR: {observation['pr_context'][:150]}\n"if observation.get("related_incidents"):flag_info += f"Incidents: {'; '.join(observation['related_incidents'][:2])}\n"if observation.get("cascade_warning"):flag_info += f"CASCADE WARNING: {observation['cascade_warning']}\n"if observation.get("investigation_notes"):flag_info += f"Investigation: {observation['investigation_notes'][:200]}\n"for attempt in range(MAX_RETRIES + 1):try:response = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": flag_info},],temperature=0.0,max_tokens=100,)content = response.choices[0].message.content.strip()# Parse JSONif content.startswith("```"):content = content.split("```")[1]if content.startswith("json"):content = content[4:]content = content.strip()result = json.loads(content)if "action" in result and result["action"] in ("remove", "keep", "deprecate", "escalate", "investigate"):return resultreturn {"action": "escalate", "reasoning": "Invalid action in response"}except json.JSONDecodeError:# Try to extract action from plain textcontent_lower = content.lower() if 'content' in dir() else ""for act in ["remove", "keep", "deprecate", "escalate"]:if act in content_lower:return {"action": act, "reasoning": "Parsed from text"}return {"action": "escalate", "reasoning": "Unparseable response"}except Exception as e:if attempt < MAX_RETRIES:print(f" [RETRY] attempt {attempt+1}/{MAX_RETRIES}, waiting {RETRY_DELAY}s: {str(e)[:80]}", flush=True)time.sleep(RETRY_DELAY)else:return {"action": "escalate", "reasoning": f"API error: {str(e)[:80]}"}return {"action": "escalate", "reasoning": "All retries exhausted"}def run_task(task_id: str) -> float:"""Run the agent on a single task and return the score."""reset_resp = requests.post(f"{ENV_URL}/reset", json={"task_id": task_id}, timeout=HTTP_TIMEOUT)reset_resp.raise_for_status()reset_data = reset_resp.json()8 unmodified linesaction = call_llm(observation)step_resp = requests.post(f"{ENV_URL}/step", json={"action": action}, timeout=HTTP_TIMEOUT)step_resp.raise_for_status()step_data = step_resp.json()11 unmodified linesflush=True,)grade_resp = requests.post(f"{ENV_URL}/grade", timeout=HTTP_TIMEOUT)grade_resp.raise_for_status()grade_data = grade_resp.json()score = grade_data["score"]12 unmodified linesprint(f"Environment: {ENV_URL}")print("=" * 60)total_start = time.time()tasks = ["easy", "medium", "hard"]scores = {}for task_id in tasks:print(f"\n--- Running task: {task_id} ---")task_start = time.time()try:score = run_task(task_id)scores[task_id] = scoreexcept Exception as e:print(f"[END] task_id={task_id} score=0.0 error={str(e)}", flush=True)scores[task_id] = 0.0print(f" Task {task_id} took {time.time()-task_start:.1f}s", flush=True)total_time = time.time() - total_startprint("\n" + "=" * 60)print("RESULTS SUMMARY")print("=" * 60)1 unmodified lineprint(f" {task_id:10s}: {score:.4f}")avg_score = sum(scores.values()) / len(scores) if scores else 0.0print(f" {'average':10s}: {avg_score:.4f}")print(f" {'runtime':10s}: {total_time:.1f}s")print("=" * 60)
inference.py+78-81