import os
import sys
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # noqa: E402 (must precede torch)
import torch # noqa: E402
import html # noqa: E402
import json # noqa: E402
import time # noqa: E402
import gradio as gr # noqa: E402
from huggingface_hub import snapshot_download # noqa: E402
from safetensors.torch import load_file # noqa: E402
# Vendored inference code from https://github.com/PostHog/jeeves (MIT).
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "jeeves_src"))
import inference.engine as engine_mod # noqa: E402
from drafter.view import DrafterView # noqa: E402
from export import load_export # noqa: E402
from inference.api import parse_request, response # noqa: E402
from inference.types import Options # noqa: E402
MODEL_ID = "PostHog/jeeves"
BLOCK = 4 # serving default drafter (block-4)
MAX_ROWS = 8 # questions decoded in parallel
MAX_LEN = 4096 # prompt + reasoning tokens per question
WEIGHTS = snapshot_download(
MODEL_ID,
allow_patterns=["model-*.safetensors", "*.json", "head.pt", "tokenizer*", "vocab.json", "merges.txt",
"chat_template.jinja", f"drafter_k{BLOCK}.safetensors"],
)
# Build everything on CPU (bf16), then move to "cuda" eagerly so ZeroGPU can pack the weights.
base, head, encoder = load_export(WEIGHTS, device="cpu")
view = DrafterView(base, block=BLOCK)
loaded = view.load_state_dict(load_file(os.path.join(WEIGHTS, f"drafter_k{BLOCK}.safetensors")), strict=False)
_missing = [k for k in loaded.missing_keys if not k.startswith("base.")]
if loaded.unexpected_keys or _missing:
raise ValueError(f"drafter keys do not match: unexpected {loaded.unexpected_keys[:3]}, missing {_missing[:3]}")
view.requires_grad_(False)
for _proj in view.projections():
_proj.to(torch.bfloat16)
view.to("cuda")
head.to("cuda")
print(f"Loaded {MODEL_ID}: temperature={head.temperature:.3f}, torch={torch.__version__}", flush=True)
_ENGINE = None
def get_engine():
"""Build the Jeeves serving engine once per GPU worker (caches, CUDA graphs), reusing the preloaded weights."""
global _ENGINE
if _ENGINE is None:
engine_mod.load_export = lambda *a, **k: (base, head, encoder)
engine_mod.DrafterView = lambda b, block: view
engine_mod.load_file = lambda *a, **k: {n: t for n, t in view.state_dict().items() if not n.startswith("base.")}
_ENGINE = engine_mod.Engine(WEIGHTS, "preloaded", block=BLOCK, precision="bf16",
max_rows=MAX_ROWS, max_len=MAX_LEN, device="cuda")
return _ENGINE
def _parse_state(state: str):
s = (state or "").strip()
if s[:1] in "{[":
try:
return json.loads(s)
except json.JSONDecodeError:
pass
return state
def _bar(label: str, p: float, best: bool) -> str:
pct = max(0.0, min(1.0, p)) * 100
color = "var(--color-accent)" if best else "var(--neutral-400)"
weight = "700" if best else "400"
return (
f"
"
f"
{html.escape(label)}
"
f"
"
f"
{p:.2f}
"
)
def render(out: dict, questions: dict) -> str:
parts = []
reasoning = out.get("reasoning", {})
for qid, a in out["answers"].items():
q = questions.get(qid, {})
instr = q.get("instructions") or ""
if not isinstance(instr, str):
instr = json.dumps(instr)
body = []
if a["type"] == "noul":
p = a["noul"]
body.append(_bar("yes", p, p >= 0.5))
body.append(_bar("no", round(1 - p, 2), p < 0.5))
headline = f"{'Yes' if p >= 0.5 else 'No'} · P(yes) = {p:.2f}"
elif a["type"] == "choice":
for k, p in a["probabilities"].items():
body.append(_bar(k, p, k == a["choice"]))
headline = f"{html.escape(a['choice'])} · confidence {a['confidence']:.2f}"
else:
mode = max(a["probabilities"], key=a["probabilities"].get)
for k, p in a["probabilities"].items():
body.append(_bar(f"{k}: {a['legend'].get(k, '')}", p, k == mode))
headline = f"expected score {a['score']:.2f} · confidence {a['confidence']:.2f}"
r = reasoning.get(qid)
if r and r.get("thought"):
note = "" if r.get("closed") else " (truncated at max_think)"
body.append(
f"Reasoning · {r['tokens']} tokens{note}
"
f"{html.escape(r['text'])}
"
)
elif r is not None:
body.append("Answered without thinking.
")
parts.append(
f""
f"
{html.escape(qid)} · {a['type']}
"
f"
{html.escape(instr)}
"
f"
{headline}
{''.join(body)}
"
)
u = out["usage"]
parts.append(
f"{out['latency_ms'] / 1000:.1f}s · "
f"{u['input_tokens']} input / {u['reasoning_tokens']} reasoning tokens
"
)
return "" + "".join(parts) + "
"
def _duration(state, questions_json, think=True, max_think=1024, nothink_threshold=0.0, *args, **kwargs) -> int:
# Measured on the Space: ~60 s one-off engine setup on a cold worker (Triton JIT + CUDA graphs), ~10 s fixed,
# ~0.011 s per reasoning token per batch of up to 8 questions. +15% margin.
try:
n = max(1, len(json.loads(questions_json)))
except Exception:
n = 1
tokens = int(max_think) if think else 0
groups = -(-n // MAX_ROWS)
return int(min(240, (70 + 0.011 * tokens * groups) * 1.15))
@spaces.GPU(duration=_duration)
def decide(state: str, questions_json: str, think: bool = True, max_think: int = 1024,
nothink_threshold: float = 0.0) -> tuple[str, dict]:
"""Answer yes/no, multiple-choice and rating questions about a state with Jeeves-9B.
Args:
state: The state to decide on: free text, or a JSON object/list.
questions_json: JSON object of questions in Jev's /v1/systemone format, e.g.
{"billing": {"type": "noul", "instructions": "Is this about billing?"},
"tone": {"type": "choice", "instructions": "Tone?", "criteria": {"calm": null, "angry": null}},
"urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["low", "medium", "high"]}}
think: Whether the model writes a reasoning chain before deciding.
max_think: Maximum reasoning tokens per question (chains are truncated, then answered).
nothink_threshold: If > 0, skip thinking for questions whose no-think confidence is at least this value.
Returns:
An HTML rendering of the answers and the raw Jev-format JSON response (with reasoning).
"""
try:
questions = json.loads(questions_json)
except json.JSONDecodeError as e:
raise gr.Error(f"Questions must be valid JSON: {e}")
body = {
"state": _parse_state(state),
"questions": questions,
"options": {
"think": bool(think),
"max_think": int(max_think),
"nothink_threshold": float(nothink_threshold) if nothink_threshold and nothink_threshold > 0 else None,
"return_reasoning": True,
},
}
try:
record, model, opts = parse_request(body, Options())
except (ValueError, KeyError) as e:
raise gr.Error(str(e))
eng = get_engine()
torch.cuda.synchronize()
t0 = time.time()
try:
results = eng.answer(record, opts)
except ValueError as e:
raise gr.Error(str(e))
torch.cuda.synchronize()
ms = (time.time() - t0) * 1000
out = response(record, model, opts, results, eng.encoder.tok, ms)
return render(out, questions), out
def _q(d: dict) -> str:
return json.dumps(d, indent=2)
EXAMPLES = [
[
"Shoes arrived two weeks late and in the wrong size. Also I see two charges on my card.",
_q({
"department": {"type": "choice", "instructions": "Which team should handle this?",
"criteria": {"returns": "Exchanges, refunds, wrong or damaged items",
"shipping": "Delivery status, delays, lost packages",
"billing": "Charges, invoices, payment problems"}},
"escalate": {"type": "noul", "instructions": "Does this need urgent human attention?"},
"frustration": {"type": "score", "instructions": "How frustrated is the customer?",
"criteria": ["Calm", "Frustrated", "Very angry"]},
}),
],
[
"I was charged twice for one order.",
_q({
"billing": {"type": "noul", "instructions": "Is this about billing?"},
"tone": {"type": "choice", "instructions": "What is the customer's tone?",
"criteria": {"calm": None, "frustrated": None, "angry": None}},
}),
],
[
"I was charged twice. Please help.",
_q({
"billing": {"type": "noul", "instructions": "Is this about billing?"},
"tone": {"type": "choice", "instructions": "What is the tone?", "criteria": {"calm": None, "angry": None}},
"urgency": {"type": "score", "instructions": "How urgent is this?",
"criteria": ["can wait", "this week", "today"]},
}),
],
]
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
with gr.Blocks(title="Jeeves-9B") as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# Jeeves-9B\n"
"A Jev-like decision model that **reasons before it decides**. Give it a state (text or JSON) and "
"yes/no (`noul`), multiple-choice (`choice`) or rating (`score`) questions; it writes a reasoning chain "
"per question and returns a calibrated probability for every option.\n\n"
"[Model](https://huggingface.co/PostHog/jeeves) · [Code](https://github.com/PostHog/jeeves)"
)
with gr.Row():
with gr.Column(scale=1):
state = gr.Textbox(label="State (text or JSON)", lines=4, value=EXAMPLES[0][0],
placeholder="e.g. a customer message, a ticket, a JSON record…")
questions = gr.Code(label="Questions (Jev /v1/systemone format)", language="json",
value=EXAMPLES[0][1], lines=14)
run = gr.Button("Decide", variant="primary")
with gr.Accordion("Advanced options", open=False):
think = gr.Checkbox(label="Think before deciding", value=True)
max_think = gr.Slider(label="max_think (reasoning tokens per question)", minimum=0,
maximum=2560, step=64, value=1024)
nothink_threshold = gr.Slider(
label="nothink_threshold (0 = off; skip thinking when the no-think answer is this confident)",
minimum=0.0, maximum=1.0, step=0.05, value=0.0)
with gr.Column(scale=1):
answers = gr.HTML(label="Answers")
with gr.Accordion("Raw JSON response", open=False):
raw = gr.JSON(label="Response")
gr.Examples(
examples=EXAMPLES,
inputs=[state, questions],
outputs=[answers, raw],
fn=decide,
cache_examples=True,
cache_mode="lazy",
)
run.click(decide, inputs=[state, questions, think, max_think, nothink_threshold], outputs=[answers, raw],
api_name="decide")
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)