Spaces:
Sleeping
Sleeping
| # bp_phi/runner_utils.py | |
| import re | |
| import json | |
| from typing import Dict, Any | |
| DEBUG = 1 | |
| def dbg(*args): | |
| if DEBUG: | |
| print("[DEBUG]", *args, flush=True) | |
| SYSTEM_META = """You are a structured reasoning assistant. | |
| Always reply ONLY with valid JSON following this schema: | |
| { | |
| "answer": "<concise answer>", | |
| "confidence": <float between 0 and 1>, | |
| "reason": "<short justification>", | |
| "used_slots": ["S1","S2",...], | |
| "evicted": ["S3",...] | |
| } | |
| """ | |
| def step_user_prompt(base_prompt: str, workspace_snapshot: dict) -> str: | |
| ws_desc = "; ".join([f"{slot['key']}={slot['content'][:40]}" for slot in workspace_snapshot.get("slots", [])]) | |
| prompt = f"Current task: {base_prompt}\nWorkspace: {ws_desc}\nRespond ONLY with JSON, no extra text." | |
| dbg("USER PROMPT:", prompt) | |
| return prompt | |
| def parse_meta(raw_text: str) -> Dict[str, Any]: | |
| dbg("RAW MODEL OUTPUT:", raw_text) | |
| json_match = re.search(r'```json\s*(\{.*?\})\s*```', raw_text, re.DOTALL) | |
| if not json_match: | |
| json_match = re.search(r'(\{.*?\})', raw_text, re.DOTALL) | |
| if not json_match: | |
| dbg("❌ JSON not found in text.") | |
| return {"answer": "", "confidence": 0.0, "reason": "", "used_slots": [], "evicted": []} | |
| json_text = json_match.group(1) | |
| try: | |
| data = json.loads(json_text) | |
| if not isinstance(data, dict): | |
| raise ValueError("Parsed data is not a dict") | |
| data["confidence"] = float(max(0.0, min(1.0, data.get("confidence", 0.0)))) | |
| data["answer"] = str(data.get("answer", "")).strip() | |
| data["reason"] = str(data.get("reason", "")).strip() | |
| data["used_slots"] = list(map(str, data.get("used_slots", []))) | |
| data["evicted"] = list(map(str, data.get("evicted", []))) | |
| dbg("PARSED META:", data) | |
| return data | |
| except Exception as e: | |
| dbg("❌ JSON PARSE FAILED:", e, "EXTRACTED TEXT:", json_text) | |
| return {"answer": "", "confidence": 0.0, "reason": "", "used_slots": [], "evicted": []} | |