Spaces:
Sleeping
Sleeping
Commit ·
a3d500f
1
Parent(s): aa04f19
feat: fully LLM-powered baseline agent, no hardcoded answers
Browse files- baseline/run_baseline.py +151 -160
baseline/run_baseline.py
CHANGED
|
@@ -1,190 +1,181 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
BASE_URL = os.environ.get("DATAENGENV_URL", "http://localhost:8000")
|
| 4 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
|
| 5 |
|
| 6 |
-
SYSTEM_PROMPT = """
|
| 7 |
-
You
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
def run_episode():
|
|
|
|
| 36 |
from groq import Groq
|
| 37 |
client = Groq(api_key=GROQ_API_KEY)
|
| 38 |
-
|
| 39 |
-
# Reset
|
| 40 |
-
|
| 41 |
-
|
|
|
|
| 42 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 43 |
-
messages.append({"role": "user", "content":
|
| 44 |
-
|
| 45 |
-
f"Script:\n{obs.get('script_content', '')[:800]}\n\n"
|
| 46 |
-
f"Error: {obs.get('last_run_error', 'none')}\n"
|
| 47 |
-
f"Log: {obs.get('last_run_output', '')[:300]}"
|
| 48 |
-
})
|
| 49 |
-
|
| 50 |
total_steps = 0
|
| 51 |
final_score = 0.0
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
| 54 |
for step in range(60):
|
| 55 |
-
#
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
"new": "df = df.dropna()\ndf['salary'] = df['salary'].clip(upper=df['salary'].quantile(0.99))\nX = df[['age', 'salary', 'credit_score', 'loan_amount', 'employment_years']].copy()"
|
| 70 |
-
}}
|
| 71 |
-
elif current_stage == 1 and stage_step == 3:
|
| 72 |
-
action = {"action_type": "run_script", "payload": {}}
|
| 73 |
-
elif current_stage == 1 and stage_step == 4:
|
| 74 |
-
action = {"action_type": "submit", "payload": {}}
|
| 75 |
-
|
| 76 |
-
# Stage 2 hardcoded
|
| 77 |
-
elif current_stage == 2 and stage_step == 0:
|
| 78 |
-
action = {"action_type": "inspect_data", "payload": {}}
|
| 79 |
-
elif current_stage == 2 and stage_step == 1:
|
| 80 |
-
action = {"action_type": "edit_script", "payload": {
|
| 81 |
-
"old": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)",
|
| 82 |
-
"new": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)"
|
| 83 |
-
}}
|
| 84 |
-
elif current_stage == 2 and stage_step == 2:
|
| 85 |
-
action = {"action_type": "run_script", "payload": {}}
|
| 86 |
-
elif current_stage == 2 and stage_step == 3:
|
| 87 |
-
action = {"action_type": "submit", "payload": {}}
|
| 88 |
-
|
| 89 |
-
# Stage 3 hardcoded
|
| 90 |
-
elif current_stage == 3 and stage_step == 0:
|
| 91 |
-
action = {"action_type": "run_script", "payload": {}}
|
| 92 |
-
elif current_stage == 3 and stage_step == 1:
|
| 93 |
-
action = {"action_type": "edit_script", "payload": {
|
| 94 |
-
"old": "scaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\nX_train, X_test, y_train, y_test = train_test_split(\n X_scaled, y, test_size=0.2, random_state=42, stratify=y\n)",
|
| 95 |
-
"new": "X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=42, stratify=y\n)\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)"
|
| 96 |
-
}}
|
| 97 |
-
elif current_stage == 3 and stage_step == 2:
|
| 98 |
-
action = {"action_type": "run_script", "payload": {}}
|
| 99 |
-
elif current_stage == 3 and stage_step == 3:
|
| 100 |
-
action = {"action_type": "submit", "payload": {}}
|
| 101 |
-
|
| 102 |
-
# Stage 4 hardcoded
|
| 103 |
-
elif current_stage == 4 and stage_step == 0:
|
| 104 |
action = {"action_type": "inspect_data", "payload": {}}
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
elif current_stage == 4 and stage_step == 2:
|
| 108 |
-
action = {"action_type": "edit_script", "payload": {
|
| 109 |
-
"old": "clf = LogisticRegression(max_iter=1000, random_state=42)",
|
| 110 |
-
"new": "clf = LogisticRegression(max_iter=1000, random_state=42, class_weight='balanced')"
|
| 111 |
-
}}
|
| 112 |
-
elif current_stage == 4 and stage_step == 3:
|
| 113 |
-
action = {"action_type": "run_script", "payload": {}}
|
| 114 |
-
elif current_stage == 4 and stage_step == 4:
|
| 115 |
-
action = {"action_type": "submit", "payload": {}}
|
| 116 |
-
|
| 117 |
-
else:
|
| 118 |
-
# LLM fallback for any unexpected state
|
| 119 |
-
try:
|
| 120 |
-
trimmed = [messages[0]] + messages[-4:]
|
| 121 |
-
response = client.chat.completions.create(
|
| 122 |
-
model="llama-3.1-8b-instant",
|
| 123 |
-
messages=trimmed,
|
| 124 |
-
max_tokens=200,
|
| 125 |
-
temperature=0.1
|
| 126 |
-
)
|
| 127 |
-
raw = response.choices[0].message.content.strip()
|
| 128 |
-
import re
|
| 129 |
-
match = re.search(r'\{.*\}', raw, re.DOTALL)
|
| 130 |
-
action = json.loads(match.group()) if match else \
|
| 131 |
-
{"action_type": "inspect_data", "payload": {}}
|
| 132 |
-
except:
|
| 133 |
-
action = {"action_type": "submit", "payload": {}}
|
| 134 |
-
|
| 135 |
-
# Take the step
|
| 136 |
try:
|
| 137 |
result = requests.post(f"{BASE_URL}/step", json=action).json()
|
| 138 |
obs = result.get("observation", {})
|
| 139 |
reward = result.get("reward", {})
|
| 140 |
-
|
| 141 |
total_steps += 1
|
| 142 |
-
|
| 143 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
messages.append({"role": "assistant", "content": json.dumps(action)})
|
| 145 |
-
messages.append({"role": "user", "content":
|
| 146 |
-
|
| 147 |
-
f"Score: {reward.get('score', 0)}\n"
|
| 148 |
-
f"Message: {reward.get('message', '')}\n"
|
| 149 |
-
f"Error: {str(obs.get('last_run_error', ''))[:200]}\n"
|
| 150 |
-
f"Output: {str(obs.get('last_run_output', ''))[:200]}\n"
|
| 151 |
-
f"Actor: {obs.get('actor_feedback', '')[:200]}"
|
| 152 |
-
})
|
| 153 |
-
|
| 154 |
-
stages_completed = obs.get("stages_completed", [])
|
| 155 |
-
|
| 156 |
if obs.get("done", False):
|
| 157 |
final_score = reward.get("score", 0.0)
|
| 158 |
break
|
| 159 |
-
|
| 160 |
-
time.sleep(0.
|
| 161 |
-
|
| 162 |
except Exception as e:
|
| 163 |
-
print(f"Step error: {e}")
|
| 164 |
continue
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
return {
|
| 167 |
-
"final_score":
|
| 168 |
"total_steps": total_steps,
|
| 169 |
-
"stages_completed":
|
| 170 |
-
"episode_score":
|
| 171 |
-
f"{BASE_URL}/pipeline_status").json().get("episode_score", 0)
|
| 172 |
}
|
| 173 |
|
| 174 |
-
# Main
|
| 175 |
-
print("Running PipelineOps Arena baseline...")
|
| 176 |
-
print("=" * 50)
|
| 177 |
-
|
| 178 |
-
results = run_episode()
|
| 179 |
-
|
| 180 |
-
print(f"Stages Completed: {results['stages_completed']}")
|
| 181 |
-
print(f"Total Steps: {results['total_steps']}")
|
| 182 |
-
print(f"Final Score: {results['final_score']:.2f}")
|
| 183 |
-
print(f"Episode Score: {results['episode_score']:.2f}")
|
| 184 |
-
print("=" * 50)
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
|
| 190 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PipelineOps Arena — LLM-Powered Agent (No Hardcoded Answers)
|
| 3 |
+
|
| 4 |
+
The agent uses Groq's Llama 3.1 API to read error logs, inspect data,
|
| 5 |
+
reason about the bug, and generate fix actions entirely on its own.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os, time, json, re, requests
|
| 9 |
|
| 10 |
BASE_URL = os.environ.get("DATAENGENV_URL", "http://localhost:8000")
|
| 11 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
|
| 12 |
|
| 13 |
+
SYSTEM_PROMPT = """You are a senior Data Engineer debugging a broken ML pipeline.
|
| 14 |
+
The pipeline has 4 stages. You must fix each stage by submitting a correct fix.
|
| 15 |
+
|
| 16 |
+
You will receive observations containing:
|
| 17 |
+
- script_content: the current Python script
|
| 18 |
+
- last_run_error: any error from the last run
|
| 19 |
+
- last_run_output: stdout from the last run
|
| 20 |
+
- data_preview: dataset info (columns, nulls, stats)
|
| 21 |
+
- actor_feedback: feedback from the MLOps reviewer bot
|
| 22 |
+
|
| 23 |
+
Available actions (respond with ONLY valid JSON, nothing else):
|
| 24 |
+
|
| 25 |
+
1. Inspect data first:
|
| 26 |
+
{"action_type": "inspect_data", "payload": {}}
|
| 27 |
+
|
| 28 |
+
2. Check column schema:
|
| 29 |
+
{"action_type": "check_schema", "payload": {}}
|
| 30 |
+
|
| 31 |
+
3. Run the script to see errors/output:
|
| 32 |
+
{"action_type": "run_script", "payload": {}}
|
| 33 |
+
|
| 34 |
+
4. Edit the script (find and replace):
|
| 35 |
+
{"action_type": "edit_script", "payload": {"old": "exact text to find", "new": "replacement text"}}
|
| 36 |
+
|
| 37 |
+
5. Ask the MLOps reviewer for feedback:
|
| 38 |
+
{"action_type": "query_actor", "payload": {}}
|
| 39 |
+
|
| 40 |
+
6. Submit when you believe the fix is correct:
|
| 41 |
+
{"action_type": "submit", "payload": {}}
|
| 42 |
+
|
| 43 |
+
STRATEGY:
|
| 44 |
+
- Start by inspecting data OR running the script to see the error
|
| 45 |
+
- Read the error carefully and diagnose the root cause
|
| 46 |
+
- Use edit_script to fix the bug (the "old" text must EXACTLY match the script)
|
| 47 |
+
- Run the script again to verify your fix works
|
| 48 |
+
- Submit once the script runs without errors
|
| 49 |
+
|
| 50 |
+
IMPORTANT: Respond with ONLY a JSON object. No explanation, no markdown, no extra text."""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def parse_action(raw_text: str) -> dict:
|
| 54 |
+
"""Extract a JSON action from the LLM's response."""
|
| 55 |
+
# Try to find JSON in the response
|
| 56 |
+
match = re.search(r'\{[^{}]*\}', raw_text, re.DOTALL)
|
| 57 |
+
if match:
|
| 58 |
+
try:
|
| 59 |
+
action = json.loads(match.group())
|
| 60 |
+
if "action_type" in action:
|
| 61 |
+
return action
|
| 62 |
+
except json.JSONDecodeError:
|
| 63 |
+
pass
|
| 64 |
+
# Fallback
|
| 65 |
+
return {"action_type": "inspect_data", "payload": {}}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def format_observation(obs: dict, reward: dict = None) -> str:
|
| 69 |
+
"""Format the environment observation into a readable prompt for the LLM."""
|
| 70 |
+
parts = []
|
| 71 |
+
parts.append(f"Current Stage: {obs.get('current_stage', '?')}")
|
| 72 |
+
parts.append(f"Step: {obs.get('stage_step_number', '?')}")
|
| 73 |
+
|
| 74 |
+
if obs.get("last_run_error"):
|
| 75 |
+
parts.append(f"\nERROR:\n{str(obs['last_run_error'])[:500]}")
|
| 76 |
+
|
| 77 |
+
if obs.get("last_run_output"):
|
| 78 |
+
parts.append(f"\nOUTPUT:\n{str(obs['last_run_output'])[:500]}")
|
| 79 |
+
|
| 80 |
+
if obs.get("data_preview"):
|
| 81 |
+
parts.append(f"\nDATA PREVIEW:\n{str(obs['data_preview'])[:600]}")
|
| 82 |
+
|
| 83 |
+
if obs.get("actor_feedback"):
|
| 84 |
+
parts.append(f"\nREVIEWER FEEDBACK:\n{obs['actor_feedback'][:400]}")
|
| 85 |
+
|
| 86 |
+
if obs.get("script_content"):
|
| 87 |
+
parts.append(f"\nCURRENT SCRIPT:\n{obs['script_content'][:1000]}")
|
| 88 |
+
|
| 89 |
+
if reward:
|
| 90 |
+
parts.append(f"\nREWARD: {reward.get('score', 0)} — {reward.get('message', '')}")
|
| 91 |
+
|
| 92 |
+
return "\n".join(parts)
|
| 93 |
+
|
| 94 |
|
| 95 |
def run_episode():
|
| 96 |
+
"""Run a full episode where the LLM agent solves the pipeline."""
|
| 97 |
from groq import Groq
|
| 98 |
client = Groq(api_key=GROQ_API_KEY)
|
| 99 |
+
|
| 100 |
+
# Reset environment
|
| 101 |
+
reset_resp = requests.post(f"{BASE_URL}/reset", json={}).json()
|
| 102 |
+
obs = reset_resp if "current_stage" in reset_resp else reset_resp.get("observation", reset_resp)
|
| 103 |
+
|
| 104 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 105 |
+
messages.append({"role": "user", "content": format_observation(obs)})
|
| 106 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
total_steps = 0
|
| 108 |
final_score = 0.0
|
| 109 |
+
|
| 110 |
+
print(f"\n{'='*60}")
|
| 111 |
+
print(f" PIPELINEOPS ARENA — LLM AGENT (Llama 3.1 8B)")
|
| 112 |
+
print(f"{'='*60}\n")
|
| 113 |
+
|
| 114 |
for step in range(60):
|
| 115 |
+
# Ask the LLM what to do
|
| 116 |
+
try:
|
| 117 |
+
# Keep context manageable — system + last 6 messages
|
| 118 |
+
trimmed = [messages[0]] + messages[-6:]
|
| 119 |
+
response = client.chat.completions.create(
|
| 120 |
+
model="llama-3.1-8b-instant",
|
| 121 |
+
messages=trimmed,
|
| 122 |
+
max_tokens=300,
|
| 123 |
+
temperature=0.1,
|
| 124 |
+
)
|
| 125 |
+
raw = response.choices[0].message.content.strip()
|
| 126 |
+
action = parse_action(raw)
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f" LLM error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
action = {"action_type": "inspect_data", "payload": {}}
|
| 130 |
+
|
| 131 |
+
# Take the action
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
try:
|
| 133 |
result = requests.post(f"{BASE_URL}/step", json=action).json()
|
| 134 |
obs = result.get("observation", {})
|
| 135 |
reward = result.get("reward", {})
|
|
|
|
| 136 |
total_steps += 1
|
| 137 |
+
|
| 138 |
+
# Print what happened
|
| 139 |
+
stage = obs.get("current_stage", "?")
|
| 140 |
+
score = reward.get("score", 0)
|
| 141 |
+
msg = reward.get("message", "")
|
| 142 |
+
print(f" Step {total_steps:02d} | Stage {stage} | {action['action_type']:<15} | reward={score:.2f} | {msg[:50]}")
|
| 143 |
+
|
| 144 |
+
# Add to conversation
|
| 145 |
messages.append({"role": "assistant", "content": json.dumps(action)})
|
| 146 |
+
messages.append({"role": "user", "content": format_observation(obs, reward)})
|
| 147 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
if obs.get("done", False):
|
| 149 |
final_score = reward.get("score", 0.0)
|
| 150 |
break
|
| 151 |
+
|
| 152 |
+
time.sleep(0.3)
|
| 153 |
+
|
| 154 |
except Exception as e:
|
| 155 |
+
print(f" Step error: {e}")
|
| 156 |
continue
|
| 157 |
+
|
| 158 |
+
# Get final status
|
| 159 |
+
status = requests.get(f"{BASE_URL}/pipeline_status").json()
|
| 160 |
+
episode_score = status.get("episode_score", final_score)
|
| 161 |
+
stages = status.get("stages_completed", [])
|
| 162 |
+
|
| 163 |
+
print(f"\n{'='*60}")
|
| 164 |
+
print(f" RESULT: Score={episode_score:.2f} | Stages={stages} | Steps={total_steps}")
|
| 165 |
+
print(f"{'='*60}\n")
|
| 166 |
+
|
| 167 |
return {
|
| 168 |
+
"final_score": float(episode_score),
|
| 169 |
"total_steps": total_steps,
|
| 170 |
+
"stages_completed": stages,
|
| 171 |
+
"episode_score": float(episode_score),
|
|
|
|
| 172 |
}
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
print("Running PipelineOps Arena — LLM Agent (no hardcoded answers)...")
|
| 177 |
+
results = run_episode()
|
| 178 |
|
| 179 |
+
with open("baseline/results.json", "w") as f:
|
| 180 |
+
json.dump(results, f, indent=2)
|
| 181 |
+
print(f"Results saved to baseline/results.json")
|