Update src/afhtp.py
Browse filesupdate logic to fix error "NameError: free variable 'parsed' referenced before assignment in enclosing scope" in function def llm_refine_eligibility()
- src/afhtp.py +90 -29
src/afhtp.py
CHANGED
|
@@ -156,9 +156,7 @@ def llm_refine_eligibility(app: Dict, base_eligible: list) -> Dict[str, Any]:
|
|
| 156 |
"""
|
| 157 |
Refines rule-based eligibility by asking the LLM to keep/add/remove plans.
|
| 158 |
Returns dict with keys: keep, add, remove, explanation, final.
|
| 159 |
-
Also embeds raw output in explanation if parsing fails, so callers can log it.
|
| 160 |
"""
|
| 161 |
-
|
| 162 |
def build_prompt(previous_output: Optional[str] = None) -> str:
|
| 163 |
few_shot = """
|
| 164 |
Example:
|
|
@@ -192,15 +190,14 @@ All available plans with description and risk:
|
|
| 192 |
{json.dumps({k: {'description': v['description'], 'risk_score': v['risk_score']} for k, v in hardship_plans.items()}, indent=2)}
|
| 193 |
|
| 194 |
REFINEMENT INSTRUCTIONS:
|
| 195 |
-
-
|
| 196 |
-
-
|
| 197 |
-
- "keep", "add", "remove",
|
| 198 |
-
-
|
| 199 |
-
- Do
|
| 200 |
|
| 201 |
-
Example for format guidance only
|
| 202 |
"""
|
| 203 |
-
|
| 204 |
if previous_output:
|
| 205 |
base += (
|
| 206 |
f"Previous output was invalid or unparseable: {previous_output}\n"
|
|
@@ -208,28 +205,92 @@ Example for format guidance only (do not copy the values verbatim): {few_shot}
|
|
| 208 |
)
|
| 209 |
else:
|
| 210 |
base += "Output only the single JSON object as specified, nothing else.\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
-
#
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
return {
|
| 226 |
-
"keep":
|
| 227 |
-
"add":
|
| 228 |
-
"remove":
|
| 229 |
-
"explanation":
|
| 230 |
-
"final":
|
| 231 |
-
}
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
|
| 235 |
def call_and_parse(prompt_text: str):
|
|
|
|
| 156 |
"""
|
| 157 |
Refines rule-based eligibility by asking the LLM to keep/add/remove plans.
|
| 158 |
Returns dict with keys: keep, add, remove, explanation, final.
|
|
|
|
| 159 |
"""
|
|
|
|
| 160 |
def build_prompt(previous_output: Optional[str] = None) -> str:
|
| 161 |
few_shot = """
|
| 162 |
Example:
|
|
|
|
| 190 |
{json.dumps({k: {'description': v['description'], 'risk_score': v['risk_score']} for k, v in hardship_plans.items()}, indent=2)}
|
| 191 |
|
| 192 |
REFINEMENT INSTRUCTIONS:
|
| 193 |
+
- Output **exactly one JSON object** and **only** that object (no surrounding explanation, no bare lists).
|
| 194 |
+
- Required lowercase keys: "keep", "add", "remove", "explanation", "final".
|
| 195 |
+
- "keep", "add", "remove", "final" are lists of plan names; "explanation" is a concise rationale.
|
| 196 |
+
- final = (keep ∪ add) − remove.
|
| 197 |
+
- Do not output anything malformed (no trailing commas, no extraneous text).
|
| 198 |
|
| 199 |
+
Example for format guidance only: {few_shot}
|
| 200 |
"""
|
|
|
|
| 201 |
if previous_output:
|
| 202 |
base += (
|
| 203 |
f"Previous output was invalid or unparseable: {previous_output}\n"
|
|
|
|
| 205 |
)
|
| 206 |
else:
|
| 207 |
base += "Output only the single JSON object as specified, nothing else.\n"
|
| 208 |
+
return base
|
| 209 |
+
|
| 210 |
+
def call_and_parse(prompt_text: str):
|
| 211 |
+
try:
|
| 212 |
+
with torch.no_grad():
|
| 213 |
+
input_ids = llm_tokenizer(prompt_text, return_tensors="pt", truncation=True, max_length=512).input_ids
|
| 214 |
+
outputs = llm_model.generate(input_ids=input_ids, max_new_tokens=300, do_sample=False)
|
| 215 |
+
raw = llm_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 216 |
+
except Exception as e:
|
| 217 |
+
return None, f"LLM invocation failed: {e}"
|
| 218 |
+
|
| 219 |
+
# Try to extract a JSON object
|
| 220 |
+
parsed = None
|
| 221 |
+
# 1. Full JSON parse
|
| 222 |
+
try:
|
| 223 |
+
candidate = json.loads(raw)
|
| 224 |
+
if isinstance(candidate, dict):
|
| 225 |
+
parsed = candidate
|
| 226 |
+
except Exception:
|
| 227 |
+
pass
|
| 228 |
|
| 229 |
+
# 2. Try to find first {...} block and parse
|
| 230 |
+
if parsed is None:
|
| 231 |
+
obj_match = re.search(r"\{[\s\S]*\}", raw)
|
| 232 |
+
if obj_match:
|
| 233 |
+
try:
|
| 234 |
+
candidate = json.loads(obj_match.group(0))
|
| 235 |
+
if isinstance(candidate, dict):
|
| 236 |
+
parsed = candidate
|
| 237 |
+
except Exception:
|
| 238 |
+
parsed = None
|
| 239 |
+
|
| 240 |
+
return parsed, raw
|
| 241 |
+
|
| 242 |
+
# First attempt
|
| 243 |
+
parsed, raw_output = call_and_parse(build_prompt())
|
| 244 |
+
if parsed is None:
|
| 245 |
+
# Retry once with corrective context
|
| 246 |
+
parsed, raw_output = call_and_parse(build_prompt(previous_output=raw_output))
|
| 247 |
+
|
| 248 |
+
# Fallback if still not a dict: check if raw output is a bare list of strings
|
| 249 |
+
if not isinstance(parsed, dict):
|
| 250 |
+
try:
|
| 251 |
+
maybe_list = json.loads(raw_output)
|
| 252 |
+
if isinstance(maybe_list, list) and all(isinstance(x, str) for x in maybe_list):
|
| 253 |
+
final = [p for p in maybe_list if p in hardship_plans]
|
| 254 |
+
if not final:
|
| 255 |
+
final = base_eligible.copy()
|
| 256 |
+
return {
|
| 257 |
+
"keep": final,
|
| 258 |
+
"add": [],
|
| 259 |
+
"remove": [],
|
| 260 |
+
"explanation": "LLM returned a list of plans; using it as final eligibility.",
|
| 261 |
+
"final": final
|
| 262 |
+
}
|
| 263 |
+
except Exception:
|
| 264 |
+
pass
|
| 265 |
+
# Ultimate fallback: use base eligible
|
| 266 |
return {
|
| 267 |
+
"keep": base_eligible,
|
| 268 |
+
"add": [],
|
| 269 |
+
"remove": [],
|
| 270 |
+
"explanation": f"LLM output not parseable as JSON; raw: {raw_output.strip()[:300]}",
|
| 271 |
+
"final": base_eligible.copy()
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
# At this point parsed is a dict: sanitize its contents
|
| 275 |
+
keep = [p for p in parsed.get("keep", base_eligible) if p in hardship_plans]
|
| 276 |
+
add = [p for p in parsed.get("add", []) if p in hardship_plans]
|
| 277 |
+
remove = [p for p in parsed.get("remove", []) if p in hardship_plans]
|
| 278 |
+
explanation = parsed.get("explanation", "").strip() or "No explanation provided."
|
| 279 |
+
|
| 280 |
+
final_set = set(keep) | set(add)
|
| 281 |
+
final_set -= set(remove)
|
| 282 |
+
final = list(final_set)
|
| 283 |
+
if not final:
|
| 284 |
+
final = base_eligible.copy()
|
| 285 |
+
|
| 286 |
+
return {
|
| 287 |
+
"keep": keep or base_eligible,
|
| 288 |
+
"add": add,
|
| 289 |
+
"remove": remove,
|
| 290 |
+
"explanation": explanation,
|
| 291 |
+
"final": final
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
|
| 295 |
|
| 296 |
def call_and_parse(prompt_text: str):
|