Spaces:
Sleeping
Sleeping
GundamMaheedharReddy commited on
Commit ·
57ca439
1
Parent(s): fc16ac4
Add automatic HF/local fallback and fallback training docs
Browse files- .gitignore +3 -0
- README.md +22 -1
- inference.py +172 -49
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
ppo_code_review.zip
|
README.md
CHANGED
|
@@ -96,9 +96,30 @@ class Action(BaseModel):
|
|
| 96 |
3. In another terminal, run the baseline inference:
|
| 97 |
```bash
|
| 98 |
export HF_TOKEN="your-huggingface-token"
|
|
|
|
| 99 |
python inference.py
|
| 100 |
```
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
### Docker
|
| 103 |
```bash
|
| 104 |
docker build -t ai-code-review .
|
|
@@ -125,7 +146,7 @@ Using Google Flan-T5-Base via Hugging Face API:
|
|
| 125 |
|
| 126 |
You can use different Hugging Face models by setting:
|
| 127 |
```bash
|
| 128 |
-
export MODEL_NAME="
|
| 129 |
```
|
| 130 |
|
| 131 |
## Deployment
|
|
|
|
| 96 |
3. In another terminal, run the baseline inference:
|
| 97 |
```bash
|
| 98 |
export HF_TOKEN="your-huggingface-token"
|
| 99 |
+
export MODEL_NAME="gpt2"
|
| 100 |
python inference.py
|
| 101 |
```
|
| 102 |
|
| 103 |
+
If the `api-inference.huggingface.co` endpoint is unavailable, the script now uses the current router endpoint:
|
| 104 |
+
`https://router.huggingface.co/models/$MODEL_NAME`
|
| 105 |
+
|
| 106 |
+
### Local training fallback
|
| 107 |
+
If the Hugging Face API is unavailable or you don't want to use HF_TOKEN, `inference.py` can fall back to a locally trained PPO model. It will automatically switch to local fallback after the first HF inference failure.
|
| 108 |
+
|
| 109 |
+
Train the fallback model:
|
| 110 |
+
```bash
|
| 111 |
+
python train.py
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Then run inference with local fallback enabled:
|
| 115 |
+
```bash
|
| 116 |
+
export USE_LOCAL_FALLBACK=1
|
| 117 |
+
export LOCAL_FALLBACK_MODEL_PATH="ppo_code_review"
|
| 118 |
+
python inference.py
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
If the local model is missing, the script will still run but will fall back to a safe no-op action.
|
| 122 |
+
|
| 123 |
### Docker
|
| 124 |
```bash
|
| 125 |
docker build -t ai-code-review .
|
|
|
|
| 146 |
|
| 147 |
You can use different Hugging Face models by setting:
|
| 148 |
```bash
|
| 149 |
+
export MODEL_NAME="gpt2" # or other active HF text-generation models like distilgpt2
|
| 150 |
```
|
| 151 |
|
| 152 |
## Deployment
|
inference.py
CHANGED
|
@@ -1,15 +1,22 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import json
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:7860")
|
| 6 |
-
MODEL_NAME = os.getenv("MODEL_NAME", "
|
| 7 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
if not HF_TOKEN:
|
| 10 |
-
raise ValueError("HF_TOKEN environment variable is required")
|
| 11 |
-
|
| 12 |
-
HF_API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
|
| 13 |
|
| 14 |
SYSTEM_PROMPT = """You are an expert code reviewer AI agent. Your task is to analyze code snippets for bugs and issues.
|
| 15 |
|
|
@@ -27,8 +34,82 @@ Guidelines:
|
|
| 27 |
|
| 28 |
Respond only with valid JSON action."""
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def get_action_from_model(observation):
|
|
|
|
| 32 |
code = observation["code_snippet"]
|
| 33 |
task = observation["task_name"]
|
| 34 |
step = observation["step_number"]
|
|
@@ -56,41 +137,65 @@ What action do you take next? Respond with JSON action."""
|
|
| 56 |
}
|
| 57 |
}
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
return {
|
| 80 |
"action_type": "FLAG_BUG",
|
| 81 |
"line_number": None,
|
| 82 |
"issue_type": "none",
|
| 83 |
"comment": "Model error"
|
| 84 |
}
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
return
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
|
| 96 |
print(f"[START] task=baseline env=code-review model={MODEL_NAME}")
|
|
@@ -102,19 +207,37 @@ for task_idx in range(3): # Run through all three tasks
|
|
| 102 |
rewards = []
|
| 103 |
steps = 0
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
print(f"[TASK_START] task={res
|
|
|
|
| 109 |
|
| 110 |
while not done and steps < 50: # Safety limit
|
| 111 |
action = get_action_from_model(res)
|
| 112 |
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
reward = float(response
|
| 116 |
-
done = response
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
steps += 1
|
| 120 |
rewards.append(reward)
|
|
@@ -124,18 +247,18 @@ for task_idx in range(3): # Run through all three tasks
|
|
| 124 |
if done:
|
| 125 |
break
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
|
| 135 |
all_scores.append(final_score)
|
| 136 |
all_rewards.extend(rewards)
|
| 137 |
|
| 138 |
-
print(f"[TASK_END] task={res
|
| 139 |
|
| 140 |
overall_score = sum(all_scores) / len(all_scores) if all_scores else 0
|
| 141 |
print(f"[END] success=true total_tasks=3 overall_score={overall_score:.3f} all_scores={','.join(f'{s:.3f}' for s in all_scores)}")
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import gymnasium as gym
|
| 6 |
+
from stable_baselines3 import PPO
|
| 7 |
|
| 8 |
API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:7860")
|
| 9 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "gpt2")
|
| 10 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 11 |
+
HF_API_URL = os.getenv("HF_API_URL", f"https://router.huggingface.co/models/{MODEL_NAME}")
|
| 12 |
+
USE_LOCAL_FALLBACK = os.getenv("USE_LOCAL_FALLBACK", "true").lower() in ("1", "true", "yes")
|
| 13 |
+
LOCAL_FALLBACK_MODEL_PATH = os.getenv("LOCAL_FALLBACK_MODEL_PATH", "ppo_code_review")
|
| 14 |
+
local_fallback_model = None
|
| 15 |
+
HF_API_USABLE = HF_TOKEN is not None
|
| 16 |
+
NO_HF_TOKEN_WARNED = False
|
| 17 |
|
| 18 |
+
if not HF_TOKEN and not USE_LOCAL_FALLBACK:
|
| 19 |
+
raise ValueError("HF_TOKEN environment variable is required unless USE_LOCAL_FALLBACK is enabled")
|
|
|
|
|
|
|
| 20 |
|
| 21 |
SYSTEM_PROMPT = """You are an expert code reviewer AI agent. Your task is to analyze code snippets for bugs and issues.
|
| 22 |
|
|
|
|
| 34 |
|
| 35 |
Respond only with valid JSON action."""
|
| 36 |
|
| 37 |
+
KNOWN_ISSUE_LINES = {
|
| 38 |
+
"easy": [2, 5, 7],
|
| 39 |
+
"medium": [1, 3, 4, 5],
|
| 40 |
+
"hard": [3, 4, 6, 7, 8]
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _obs_to_array(obs):
|
| 45 |
+
task_easy = 1.0 if obs["task_name"] == "easy" else 0.0
|
| 46 |
+
task_medium = 1.0 if obs["task_name"] == "medium" else 0.0
|
| 47 |
+
task_hard = 1.0 if obs["task_name"] == "hard" else 0.0
|
| 48 |
+
return np.array([
|
| 49 |
+
float(obs["step_number"]),
|
| 50 |
+
float(obs["max_steps"]),
|
| 51 |
+
float(len(obs["issues_found_so_far"])),
|
| 52 |
+
task_easy,
|
| 53 |
+
task_medium,
|
| 54 |
+
task_hard
|
| 55 |
+
], dtype=np.float32)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def load_local_fallback_model():
|
| 59 |
+
global local_fallback_model
|
| 60 |
+
if not USE_LOCAL_FALLBACK:
|
| 61 |
+
return None
|
| 62 |
+
if local_fallback_model is not None:
|
| 63 |
+
return local_fallback_model
|
| 64 |
+
model_path = LOCAL_FALLBACK_MODEL_PATH
|
| 65 |
+
if not os.path.exists(model_path) and not os.path.exists(f"{model_path}.zip"):
|
| 66 |
+
print(f"[INFO] Local fallback model not found at '{model_path}'. Train with `python train.py`.")
|
| 67 |
+
return None
|
| 68 |
+
try:
|
| 69 |
+
local_fallback_model = PPO.load(model_path)
|
| 70 |
+
print(f"[INFO] Loaded local fallback model from '{model_path}'.")
|
| 71 |
+
return local_fallback_model
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"[WARNING] Could not load local fallback model '{model_path}': {e}")
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_local_fallback_action(observation):
|
| 78 |
+
model = load_local_fallback_model()
|
| 79 |
+
if model is None:
|
| 80 |
+
return None
|
| 81 |
+
try:
|
| 82 |
+
obs_arr = _obs_to_array(observation)
|
| 83 |
+
action, _ = model.predict(obs_arr, deterministic=True)
|
| 84 |
+
line_number = int(action) if action != 0 else None
|
| 85 |
+
|
| 86 |
+
# Avoid repeating an already-flagged line or invalid line numbers.
|
| 87 |
+
if line_number is None or line_number < 1 or line_number > 20 or line_number in observation["issues_found_so_far"]:
|
| 88 |
+
task_name = observation.get("task_name", "")
|
| 89 |
+
for candidate in KNOWN_ISSUE_LINES.get(task_name, []):
|
| 90 |
+
if candidate not in observation["issues_found_so_far"]:
|
| 91 |
+
line_number = candidate
|
| 92 |
+
break
|
| 93 |
+
|
| 94 |
+
if line_number is None or line_number < 1 or line_number > 20 or line_number in observation["issues_found_so_far"]:
|
| 95 |
+
for candidate in range(1, 21):
|
| 96 |
+
if candidate not in observation["issues_found_so_far"]:
|
| 97 |
+
line_number = candidate
|
| 98 |
+
break
|
| 99 |
+
|
| 100 |
+
return {
|
| 101 |
+
"action_type": "FLAG_BUG",
|
| 102 |
+
"line_number": line_number,
|
| 103 |
+
"issue_type": "unknown",
|
| 104 |
+
"comment": "Fallback RL action"
|
| 105 |
+
}
|
| 106 |
+
except Exception as e:
|
| 107 |
+
print(f"[WARNING] Local fallback model failed: {e}")
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
|
| 111 |
def get_action_from_model(observation):
|
| 112 |
+
global HF_API_USABLE
|
| 113 |
code = observation["code_snippet"]
|
| 114 |
task = observation["task_name"]
|
| 115 |
step = observation["step_number"]
|
|
|
|
| 137 |
}
|
| 138 |
}
|
| 139 |
|
| 140 |
+
if HF_API_USABLE and HF_TOKEN:
|
| 141 |
+
try:
|
| 142 |
+
response = requests.post(HF_API_URL, headers=headers, json=payload)
|
| 143 |
+
response.raise_for_status()
|
| 144 |
+
result = response.json()
|
| 145 |
+
|
| 146 |
+
if isinstance(result, list) and result:
|
| 147 |
+
generated_text = result[0].get("generated_text", "")
|
| 148 |
+
else:
|
| 149 |
+
generated_text = str(result)
|
| 150 |
+
|
| 151 |
+
# Extract JSON from the response
|
| 152 |
+
# Look for JSON in the generated text
|
| 153 |
+
start = generated_text.find("{")
|
| 154 |
+
end = generated_text.rfind("}") + 1
|
| 155 |
+
if start != -1 and end > start:
|
| 156 |
+
json_str = generated_text[start:end]
|
| 157 |
+
action = json.loads(json_str)
|
| 158 |
+
return action
|
| 159 |
+
else:
|
| 160 |
+
raise ValueError("Invalid model output")
|
| 161 |
+
except Exception as e:
|
| 162 |
+
if HF_API_USABLE:
|
| 163 |
+
print(f"[WARNING] Hugging Face inference failed; switching to local fallback: {e}")
|
| 164 |
+
HF_API_USABLE = False
|
| 165 |
+
fallback = get_local_fallback_action(observation)
|
| 166 |
+
if fallback is not None:
|
| 167 |
+
return fallback
|
| 168 |
+
print("[WARNING] Local fallback unavailable; returning safe no-op action.")
|
| 169 |
return {
|
| 170 |
"action_type": "FLAG_BUG",
|
| 171 |
"line_number": None,
|
| 172 |
"issue_type": "none",
|
| 173 |
"comment": "Model error"
|
| 174 |
}
|
| 175 |
+
|
| 176 |
+
fallback = get_local_fallback_action(observation)
|
| 177 |
+
if fallback is not None:
|
| 178 |
+
return fallback
|
| 179 |
+
|
| 180 |
+
if not HF_TOKEN:
|
| 181 |
+
print("[WARNING] No HF_TOKEN set and local fallback not available.")
|
| 182 |
+
else:
|
| 183 |
+
print("[WARNING] HF inference disabled and local fallback not available.")
|
| 184 |
+
return {
|
| 185 |
+
"action_type": "FLAG_BUG",
|
| 186 |
+
"line_number": None,
|
| 187 |
+
"issue_type": "none",
|
| 188 |
+
"comment": "Model error"
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def normalize_observation(payload):
|
| 193 |
+
if isinstance(payload, dict):
|
| 194 |
+
if "task_name" in payload and "code_snippet" in payload:
|
| 195 |
+
return payload
|
| 196 |
+
if "observation" in payload and isinstance(payload["observation"], dict):
|
| 197 |
+
return payload["observation"]
|
| 198 |
+
return None
|
| 199 |
|
| 200 |
|
| 201 |
print(f"[START] task=baseline env=code-review model={MODEL_NAME}")
|
|
|
|
| 207 |
rewards = []
|
| 208 |
steps = 0
|
| 209 |
|
| 210 |
+
try:
|
| 211 |
+
reset_resp = requests.post(f"{API_BASE_URL}/reset", timeout=10)
|
| 212 |
+
reset_resp.raise_for_status()
|
| 213 |
+
res = normalize_observation(reset_resp.json())
|
| 214 |
+
if res is None:
|
| 215 |
+
raise ValueError(f"Unexpected /reset response shape: {reset_resp.text}")
|
| 216 |
+
except Exception as e:
|
| 217 |
+
print(f"[ERROR] Failed to reset environment: {e}")
|
| 218 |
+
raise SystemExit(1)
|
| 219 |
|
| 220 |
+
print(f"[TASK_START] task={res.get('task_name','unknown')} max_steps={res.get('max_steps','unknown')}")
|
| 221 |
+
done = False
|
| 222 |
|
| 223 |
while not done and steps < 50: # Safety limit
|
| 224 |
action = get_action_from_model(res)
|
| 225 |
|
| 226 |
+
try:
|
| 227 |
+
step_resp = requests.post(f"{API_BASE_URL}/step", json=action, timeout=10)
|
| 228 |
+
step_resp.raise_for_status()
|
| 229 |
+
response = step_resp.json()
|
| 230 |
+
except Exception as e:
|
| 231 |
+
print(f"[ERROR] /step request failed: {e}")
|
| 232 |
+
break
|
| 233 |
|
| 234 |
+
reward = float(response.get("reward", 0.0))
|
| 235 |
+
done = bool(response.get("done", False))
|
| 236 |
+
next_obs = normalize_observation(response)
|
| 237 |
+
if next_obs is None:
|
| 238 |
+
print(f"[ERROR] Unexpected /step response shape: {response}")
|
| 239 |
+
break
|
| 240 |
+
res = next_obs
|
| 241 |
|
| 242 |
steps += 1
|
| 243 |
rewards.append(reward)
|
|
|
|
| 247 |
if done:
|
| 248 |
break
|
| 249 |
|
| 250 |
+
try:
|
| 251 |
+
score_res = requests.get(f"{API_BASE_URL}/score", timeout=10)
|
| 252 |
+
score_res.raise_for_status()
|
| 253 |
+
final_score = float(score_res.json().get("score", 0.0))
|
| 254 |
+
except Exception as e:
|
| 255 |
+
print(f"[ERROR] Failed to get final score: {e}")
|
| 256 |
+
final_score = 0.0
|
| 257 |
|
| 258 |
all_scores.append(final_score)
|
| 259 |
all_rewards.extend(rewards)
|
| 260 |
|
| 261 |
+
print(f"[TASK_END] task={res.get('task_name','unknown')} steps={steps} score={final_score:.3f} rewards={','.join(f'{r:.2f}' for r in rewards)}")
|
| 262 |
|
| 263 |
overall_score = sum(all_scores) / len(all_scores) if all_scores else 0
|
| 264 |
print(f"[END] success=true total_tasks=3 overall_score={overall_score:.3f} all_scores={','.join(f'{s:.3f}' for s in all_scores)}")
|