"""Bound fn nodes for the decision-model comparison Workflow. Three independent decision models answer the SAME state + questions and each node returns (markdown_output, status_text). A node never raises: if one model fails, its panel shows the error and the other two still render. decide_d3 vllm-sr/d3 (27B) -- remote, POST /v1/systemone on the vllm-sr/d3 Studio Space decide_d3_edge vllm-sr/d3-edge (0.6B) -- local, transformers system_one decide_gliner fastino/GLiNER2.5-Decide (340M) -- local, gliner2 Classifier """ import json import os import re import threading import time import requests D3_API_URL = os.environ.get("D3_API_URL", "https://vllm-sr-d3.hf.space/v1/systemone") D3_MODEL_ID = "vllm-sr/d3" D3_EDGE_MODEL_ID = "vllm-sr/d3-edge" GLINER_MODEL_ID = "fastino/GLiNER2.5-Decide" QUESTION_TYPES = {"choice", "noul", "score"} MAX_QUESTIONS = 32 _locks = {"d3_edge": threading.Lock(), "gliner": threading.Lock()} _loaded = {"d3_edge": None, "gliner": None} # --------------------------------------------------------------------- parsing def parse_questions(raw): """Parse and validate the questions JSON string (System One schema).""" questions = json.loads(raw) if not isinstance(questions, dict) or not 1 <= len(questions) <= MAX_QUESTIONS: raise ValueError(f"questions must be a JSON object with 1-{MAX_QUESTIONS} entries") for qid, q in questions.items(): if not isinstance(qid, str) or not qid.strip(): raise ValueError("every question needs a nonempty id") if not isinstance(q, dict) or q.get("type") not in QUESTION_TYPES: raise ValueError(f"{qid}: type must be one of {sorted(QUESTION_TYPES)}") kind, criteria = q["type"], q.get("criteria") if kind == "choice": if not isinstance(criteria, dict) or not 1 <= len(criteria) <= 255: raise ValueError(f"{qid}: choice needs a criteria object of option names") elif kind == "score": if not isinstance(criteria, list) or not 2 <= len(criteria) <= 10: raise ValueError(f"{qid}: score needs a criteria list of 2-10 ordered levels") elif criteria is not None and not isinstance(criteria, dict): raise ValueError(f"{qid}: yes/no criteria must describe \"true\" and \"false\" or be omitted") return questions def bar(p): filled = int(round(max(0.0, min(1.0, float(p))) * 20)) return "\u2588" * filled + "\u2591" * (20 - filled) def error_markdown(title, message): return f"### {title}\n\n:warning: {message}" def render_answers(answers, questions, title): lines = [f"### {title}", ""] for qid, q in questions.items(): instructions = (q.get("instructions") or "").strip() heading = f"**{qid}**" + (f" \u2014 {instructions}" if instructions else "") lines.append(heading) a = answers.get(qid) if not isinstance(a, dict): lines.append(f"\u26a0\ufe0f no answer returned") continue if "error" in a: lines.append(f"\u26a0\ufe0f {a.get('message', a['error'])}") continue kind = q["type"] if kind == "noul": p_yes = float(a["noul"]) lines.append(f"- **Yes** `{bar(p_yes)}` {p_yes:.1%}") lines.append(f"- **No** `{bar(1.0 - p_yes)}` {1.0 - p_yes:.1%}") else: keys = (list(q["criteria"]) if kind == "choice" else [str(i) for i in range(len(q["criteria"]))]) probs = a.get("probabilities", {}) best_key = max(keys, key=lambda k: probs.get(k, 0.0)) for key in keys: label = key if kind == "choice" else str(q["criteria"][int(key)]) p = float(probs.get(key, 0.0)) marker = " \u2b50" if key == best_key else "" lines.append(f"- **{label}** `{bar(p)}` {p:.1%}{marker}") if kind == "choice" and "choice" in a: lines.append(f"\u2192 chose **{a['choice']}**") if kind == "score" and isinstance(a.get("score"), (int, float)): lines.append(f"\u2192 score **{a['score']:.2f}** / {len(keys) - 1}") lines.append("") return "\n".join(lines).rstrip() def safe_label(name): return re.sub(r"[^A-Za-z0-9_]", "_", name).strip("_") or "q" # ----------------------------------------------------------------- d3 (remote) def decide_d3(state, questions): """27B flagship d3, answered by the vllm-sr/d3 Studio Space's public API.""" title = "d3 \u00b7 27B \u00b7 remote API" try: qs = parse_questions(questions) except Exception as exc: return error_markdown(title, f"invalid questions JSON: {exc}"), "invalid input" body = {"model": D3_MODEL_ID, "state": state, "questions": qs} started = time.time() try: resp = requests.post(D3_API_URL, json=body, timeout=180) resp.raise_for_status() result = resp.json() except requests.RequestException as exc: detail = "" if getattr(exc, "response", None) is not None: detail = f": {exc.response.text[:300]}" return (error_markdown(title, f"the vllm-sr/d3 Space did not answer{detail}"), f"failed in {time.time() - started:.1f}s") answers = result.get("answers", {}) elapsed = time.time() - started return render_answers(answers, qs, title), f"answered in {elapsed:.1f}s via POST /v1/systemone" # ------------------------------------------------------------- d3-edge (local) def get_d3_edge(): model = _loaded["d3_edge"] if model is None: from transformers import AutoModel model = AutoModel.from_pretrained(D3_EDGE_MODEL_ID, trust_remote_code=True) model.eval() _loaded["d3_edge"] = model return model def decide_d3_edge(state, questions): """0.6B d3-edge, loaded in this Space and run on CPU via transformers.""" title = "d3-edge \u00b7 0.6B \u00b7 local (CPU)" try: qs = parse_questions(questions) except Exception as exc: return error_markdown(title, f"invalid questions JSON: {exc}"), "invalid input" started = time.time() try: with _locks["d3_edge"]: model = get_d3_edge() result = model.system_one(state=state, questions=qs) except Exception as exc: return error_markdown(title, f"d3-edge failed: {exc}"), f"failed in {time.time() - started:.1f}s" elapsed = time.time() - started return render_answers(result.get("answers", {}), qs, title), \ f"answered in {elapsed:.1f}s (includes first-run model load)" # ---------------------------------------------------------------- GLiNER local def get_gliner(): clf = _loaded["gliner"] if clf is None: from gliner2.classification import Classifier clf = Classifier.from_pretrained(GLINER_MODEL_ID, map_location="cpu") clf.eval() _loaded["gliner"] = clf return clf def build_gliner_schema(questions): from gliner2.classification import ClassificationSchema schema = ClassificationSchema() for qid, q in questions.items(): head = safe_label(qid) kind = q["type"] if kind == "choice": schema.single(head, list(q["criteria"])) elif kind == "noul": schema.single(head, ["yes", "no"]) else: schema.single(head, [str(level) for level in q["criteria"]]) return schema def decide_gliner(state, questions): """340M GLiNER2.5-Decide, loaded in this Space; yes/no and score questions are flattened to single-label heads over their option texts.""" title = "GLiNER2.5-Decide \u00b7 340M \u00b7 local (CPU)" try: qs = parse_questions(questions) except Exception as exc: return error_markdown(title, f"invalid questions JSON: {exc}"), "invalid input" started = time.time() try: from gliner2.classification import ClassificationConfig with _locks["gliner"]: clf = get_gliner() result = clf.classify(state, build_gliner_schema(qs), config=ClassificationConfig(decoder="independent")) answers = {} for qid, q in qs.items(): head = safe_label(qid) if q["type"] == "noul": probs_raw = result.probabilities(head) answers[qid] = {"type": "noul", "noul": float(probs_raw.get("yes", 0.0))} else: answers[qid] = {"type": q["type"], "probabilities": dict(result.probabilities(head))} except Exception as exc: return error_markdown(title, f"GLiNER2.5-Decide failed: {exc}"), f"failed in {time.time() - started:.1f}s" elapsed = time.time() - started return render_answers(answers, qs, title), f"answered in {elapsed:.1f}s (includes first-run model load)" def prefetch(): """Best-effort warm-up at boot so the first visitor does not pay for it.""" def warm(): for name, fn in (("d3-edge", get_d3_edge), ("gliner", get_gliner)): try: with _locks[name]: fn() print(f"prefetch {name} ok") except Exception as exc: print(f"prefetch {name} failed ({type(exc).__name__}: {exc}); will retry on first run") threading.Thread(target=warm, daemon=True).start()