deploy: sync from qagent 2b322e9
Browse filesFiles changed (11)
- .gitignoreAdded+5
- DockerfileAdded+34
- README.md+50-4
- app.pyAdded+480
- assets/hero_qaoa.svgAdded
- assets/quantum_labor_logo.svgAdded
- assets/styles.cssAdded+121
- precomputed/benchmark_results.jsonAdded
- precomputed/dataset.jsonAdded
- requirements.txtAdded+7
- safety.pyAdded+162
12345.venv/__pycache__/*.pyc.pytest_cache/.cache/12345678910111213141516171819202122232425262728293031323334FROM python:3.11-slim
WORKDIR /app
# git is needed for the qagent install from GitHub below.RUN apt-get update \ && apt-get install -y --no-install-recommends git \ && rm -rf /var/lib/apt/lists/*
# Light deps only (Gradio + numpy + matplotlib). The Space does not run live# QAOA, so torch / pennylane are intentionally absent.COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Install qagent WITHOUT its declared deps (torch / pennylane / scipy): the# Space only uses qagent.oracle (brute-force, greedy) and qagent.qaoa.encoding,# all pure Python, plus the precomputed QAOA results JSON.RUN pip install --no-cache-dir --no-deps \ "qagent @ git+https://github.com/Quantum-Labor/qagent.git@main"
COPY app.py .COPY safety.py .COPY assets/ ./assets/COPY precomputed/ ./precomputed/
# HuggingFace Spaces expect the app on 0.0.0.0:7860. No SYSTEM=spaces: this Space# has no OAuth (it is fully open), so Gradio never takes the OAuth code path and# the hot-reload watcher warning that SYSTEM=spaces triggers is avoided.ENV GRADIO_SERVER_NAME=0.0.0.0 \ GRADIO_SERVER_PORT=7860 \ PYTHONUNBUFFERED=1EXPOSE 7860
CMD ["python", "-u", "app.py"]12345678910---title: Qagentemoji: 📊colorFrom: purplecolorTo: purplesdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556---title: QAgentcolorFrom: purplecolorTo: indigosdk: dockerapp_port: 7860pinned: falselicense: apache-2.0hardware: cpu-basictags:- quantum-computing- qaoa- pennylane- llm-agents- tool-selection- auto-deploy---# QAgent - quantum tool selection for LLM agentsThis Space demonstrates [QAgent](https://github.com/Quantum-Labor/qagent): pickingthe best subset of `k` tools from `N` candidates for an agent task, solved with theQuantum Approximate Optimization Algorithm (QAOA). It is project 2 of 3 in theQuantum Co-Processor program (after QVerify, alongside QRoute).## What you can do here- **Explore the qagent-mini-50 tasks.** Pick any of the 50 benchmark tasks; the4x4 (or 4x2) tool grid highlights which tools the brute-force optimum, QAOA, andgreedy each select, with score cards and approximation ratios.- **See the score landscape.** A chart plots the scores of every size-`k` subsetwith markers showing exactly where QAOA, greedy, and the optimum fall - so youcan see how close QAOA gets and how far greedy misses.- **Build an exploration history.** As you browse tasks, the session tracks theQAOA vs greedy approximation ratio.- **Verify live.** A button runs the pure-Python brute-force and greedy solverslive (no precomputed lookup) and confirms they match the served numbers.- **Read the leaderboard.** The qagent-mini-50 summary: exact-match and meanapproximation ratio for brute-force, greedy, and QAOA.## Design notes- **Precomputed QAOA.** QAOA on 16 qubits is slow on CPU, so the QAOA results areprecomputed with the documented v0.2 config (p=4, 160 steps, 1024 shots, seed 0,x mixer) and served from JSON for an instant experience. The classical solversrun live (they are pure Python and finish in milliseconds), which keeps theserved numbers honest and the Docker image small (no torch / pennylane).- **Fully open.** There is no IBM hardware path and no quota to protect, so theSpace has no OAuth gating - anyone can use every feature.- **Honest scope.** Simulator only; no quantum advantage is claimed. QAOA matchesthe optimum on every N=8 task and reaches a 0.915 mean approximation ratio atN=16, but exact-match at N=16 remains hard (the next step is Dicke-initialisedXY-QAOA). Full benchmarks and source: the GitHub repo.Auto-deployed from the `qagent` repository `main` branch via a GitHub Action(`HfApi.upload_folder`); see `docs/deploy.md` in the repo.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480"""QAgent HuggingFace Space - QAOA tool selection, runs on CPU Basic.
The Space serves *precomputed* QAOA results (p=4, 160 steps, seed 0 - thedocumented v0.2 config) for the 50 qagent-mini tasks, so the experience isinstant and needs no torch / pennylane in the image. The pure-Python classicalsolvers (brute-force exact, greedy top-k) run *live* on demand so visitors canconfirm the served numbers are real. There is no IBM hardware path and no OAuth:the Space is fully open.
Design (see README.md): a hero with the QAOA ansatz, a task explorer with a 4x4tool grid that highlights which tools each solver picks, score cards withapproximation ratios, a score-landscape chart showing where QAOA / greedy /optimal fall among all size-k subsets, an exploration history, and theqagent-mini-50 leaderboard."""
from __future__ import annotations
import jsonimport osfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any
import gradio as grimport matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltfrom safety import RateLimiter, default_persist_path
from qagent.oracle.bruteforce import brute_force_bestfrom qagent.oracle.greedy import greedy_top_kfrom qagent.qaoa.encoding import ToolScoring
HERE = Path(__file__).resolve().parentRESULTS_PATH = HERE / "precomputed" / "benchmark_results.json"ASSETS = HERE / "assets"REPO_URL = "https://github.com/Quantum-Labor/qagent"
_RATE_LIMITER = RateLimiter(window_seconds=3, daily_cap=5000, persist_path=default_persist_path())
def _load_results() -> dict[str, Any]: try: return json.loads(RESULTS_PATH.read_text(encoding="utf-8")) # type: ignore[no-any-return] except (FileNotFoundError, json.JSONDecodeError): return {"config": {}, "summary": {}, "tasks": []}
RESULTS = _load_results()TASKS: list[dict[str, Any]] = RESULTS.get("tasks", [])TASK_BY_ID: dict[str, dict[str, Any]] = {t["id"]: t for t in TASKS}
# The source dataset (weights + full synergy matrix) is bundled so the live# brute-force / greedy check reconstructs the exact scoring behind each task._DATASET_PATH = HERE / "precomputed" / "dataset.json"
def _load_dataset() -> dict[str, dict[str, Any]]: try: rows = json.loads(_DATASET_PATH.read_text(encoding="utf-8")) return {r["id"]: r for r in rows} except (FileNotFoundError, json.JSONDecodeError): return {}
DATASET_BY_ID = _load_dataset()
def _read_asset(name: str) -> str: try: return (ASSETS / name).read_text(encoding="utf-8") except FileNotFoundError: return ""
def _client_ip(request: gr.Request | None) -> str: if request is None: return "unknown" fwd = request.headers.get("x-forwarded-for") if request.headers else None if fwd: return fwd.split(",")[0].strip() return getattr(request.client, "host", "unknown") or "unknown"
# --- rendering helpers (pure, unit-testable) --------------------------------
def task_label(task: dict[str, Any]) -> str: return f"{task['id']} · {task['tier']} · N={task['n_tools']} k={task['k']}"
def task_choices() -> list[str]: return [task_label(t) for t in TASKS]
def _label_to_id(label: str) -> str: return label.split(" ", 1)[0]
def render_tool_grid(task: dict[str, Any]) -> str: optimal = set(task["optimal"]["subset"]) qaoa = set(task["qaoa"]["subset"]) greedy = set(task["greedy"]["subset"]) cards: list[str] = [] for tool in task["tools"]: i = tool["index"] w = tool["weight"] classes = "qa-tool-card" if i in optimal: classes += " sel-optimal" if i in qaoa: classes += " sel-qaoa" tags = [] if i in optimal: tags.append('<span class="qa-tag optimal">optimal</span>') if i in qaoa: tags.append('<span class="qa-tag qaoa">qaoa</span>') if i in greedy: tags.append('<span class="qa-tag greedy">greedy</span>') tags_html = f'<div class="qa-tags">{"".join(tags)}</div>' if tags else "" bar = f'<div class="qa-tool-bar"><span style="width:{min(w, 1.0) * 100:.0f}%"></span></div>' cards.append( f'<div class="{classes}"><div class="qa-tool-name">{tool["name"]}</div>' f'<div class="qa-tool-weight">w = {w:.3f}</div>{bar}{tags_html}</div>' ) legend = ( '<div class="qa-legend">' '<span><span class="dot" style="background:#34D399"></span>optimal (brute-force)</span>' '<span><span class="dot" style="background:#67E8F9"></span>QAOA</span>' '<span><span class="dot" style="background:#F59E0B"></span>greedy</span>' "</div>" ) return f'<div class="qa-tool-grid">{"".join(cards)}</div>{legend}'
def render_scores(task: dict[str, Any]) -> str: opt = task["optimal"] qa = task["qaoa"] gd = task["greedy"] exact = "exact match" if qa["exact_match"] else "approximate"
def card(kind: str, title: str, score: float, sub: str) -> str: return ( f'<div class="qa-score-card {kind}"><h4>{title}</h4>' f'<div class="qa-score-val">{score:.3f}</div>' f'<div class="qa-score-sub">{sub}</div></div>' )
return ( '<div class="qa-scores">' + card( "optimal", "Optimal (brute-force)", opt["score"], f"{task['k']} of {task['n_tools']} tools", ) + card("qaoa", "QAOA", qa["score"], f"ratio {qa['approx_ratio']:.3f} · {exact}") + card("greedy", "Greedy top-k", gd["score"], f"ratio {gd['approx_ratio']:.3f}") + "</div>" )
def landscape_figure(task: dict[str, Any]) -> Any: hist = task["score_hist"] edges = hist["bin_edges"] counts = hist["counts"] centers = [(edges[i] + edges[i + 1]) / 2 for i in range(len(counts))] width = (edges[1] - edges[0]) * 0.9 if len(edges) > 1 else 0.1
plt.style.use("dark_background") fig, ax = plt.subplots(figsize=(7.6, 3.3), dpi=110) fig.patch.set_facecolor("#0B0B16") ax.set_facecolor("#0B0B16") ax.bar( centers, counts, width=width, color="#3A3460", edgecolor="none", label="all size-k subsets" ) for score, color, label in [ (task["greedy"]["score"], "#F59E0B", "greedy"), (task["qaoa"]["score"], "#22D3EE", "QAOA"), (task["optimal"]["score"], "#34D399", "optimal"), ]: ax.axvline(score, color=color, linewidth=2.2, label=label) ax.set_xlabel("subset score", color="#9CA3AF", fontsize=10) ax.set_ylabel(f"# subsets ({hist['n_subsets']})", color="#9CA3AF", fontsize=10) ax.set_title("Score landscape: where each solver lands", color="#E5E7EB", fontsize=12, pad=10) ax.tick_params(colors="#6B6788", labelsize=8) for spine in ax.spines.values(): spine.set_color("#2A2440") ax.legend( facecolor="#15152A", edgecolor="#2A2440", labelcolor="#E5E7EB", fontsize=9, loc="upper left" ) fig.tight_layout() return fig
def history_figure(history: list[dict[str, Any]]) -> Any: plt.style.use("dark_background") fig, ax = plt.subplots(figsize=(7.6, 2.8), dpi=110) fig.patch.set_facecolor("#0B0B16") ax.set_facecolor("#0B0B16") if history: xs = list(range(len(history))) ax.plot(xs, [h["qaoa"] for h in history], "-o", color="#22D3EE", label="QAOA", linewidth=2) ax.plot( xs, [h["greedy"] for h in history], "-o", color="#F59E0B", label="greedy", linewidth=2 ) ax.axhline(1.0, color="#34D399", linewidth=1.2, linestyle="--", label="optimal") ax.set_xticks(xs) ax.set_xticklabels([h["id"] for h in history], rotation=45, ha="right", fontsize=7) ax.set_ylim(0.5, 1.05) ax.legend( facecolor="#15152A", edgecolor="#2A2440", labelcolor="#E5E7EB", fontsize=9, loc="lower left", ) else: ax.text( 0.5, 0.5, "Explore tasks to build a history", ha="center", va="center", color="#6B6788", fontsize=11, transform=ax.transAxes, ) ax.set_ylabel("approx ratio", color="#9CA3AF", fontsize=10) ax.set_title("Approximation-ratio history (this session)", color="#E5E7EB", fontsize=12, pad=8) ax.tick_params(colors="#6B6788", labelsize=8) for spine in ax.spines.values(): spine.set_color("#2A2440") fig.tight_layout() return fig
def _task_description(task: dict[str, Any]) -> str: return ( f"**{task['id']}** · {task['tier']} pool · select **{task['k']}** of " f"**{task['n_tools']}** tools. {task['description']}" )
def select_task( label: str, history: list[dict[str, Any]]) -> tuple[str, str, str, Any, Any, list[dict[str, Any]]]: task = TASK_BY_ID[_label_to_id(label)] history = [h for h in history if h["id"] != task["id"]] history.append( { "id": task["id"], "qaoa": task["qaoa"]["approx_ratio"], "greedy": task["greedy"]["approx_ratio"], } ) history = history[-12:] return ( _task_description(task), render_tool_grid(task), render_scores(task), landscape_figure(task), history_figure(history), history, )
def verify_live(label: str, request: gr.Request | None = None) -> str: """Run brute-force + greedy live to prove the served numbers are real.""" verdict = _RATE_LIMITER.check_and_register(ip=_client_ip(request), now=datetime.now(UTC)) if not verdict.allowed: return f"_{verdict.detail}_" task = TASK_BY_ID[_label_to_id(label)] entry = DATASET_BY_ID.get(task["id"]) if entry is None: return "_Source scoring unavailable for live verification._" sc = ToolScoring( weights=tuple(entry["weights"]), synergy=tuple(tuple(row) for row in entry["synergy"]), ) k = task["k"] bf_sub, bf_score = brute_force_best(sc, k) gd_sub, gd_score = greedy_top_k(sc, k) opt = task["optimal"]["score"] bf_ok = abs(bf_score - opt) < 1e-6 return ( f"Live solve of **{task['id']}** (pure-Python, no precomputed lookup):\n\n" f"- brute-force optimum: `{sorted(bf_sub)}` score **{bf_score:.4f}** " f"{'matches' if bf_ok else 'DIFFERS FROM'} the served optimal `{opt:.4f}`\n" f"- greedy top-k: `{sorted(gd_sub)}` score **{gd_score:.4f}**\n\n" f"The served QAOA result (score {task['qaoa']['score']:.4f}, ratio " f"{task['qaoa']['approx_ratio']:.3f}) was precomputed with p={RESULTS['config'].get('p')} " f"on the PennyLane simulator." )
def leaderboard_markdown() -> str: s = RESULTS.get("summary", {}) if not s: return "_Leaderboard unavailable._"
def cell(exact: int, ratio: float, n: int) -> str: return f"{100 * exact // n}% ({exact}/{n}) · {ratio:.3f}"
def row(group: str, g: dict[str, Any]) -> str: n = g["n"] gd = cell(g["greedy_exact"], g["greedy_ratio"], n) qa = cell(g["qaoa_exact"], g["qaoa_ratio"], n) return f"| {group} | 100% ({n}/{n}) | {gd} | {qa} |"
lines = [ "| Group | Brute-force | Greedy | QAOA |", "| --- | --- | --- | --- |", ] for key, name in [("small", "small (N=8, k=3)"), ("full", "full (N=16, k=5)"), ("all", "all")]: if key in s: lines.append(row(name, s[key])) cfg = RESULTS.get("config", {}) note = ( "\n\nMetric: exact-match (and mean approximation ratio). QAOA config: " f"p={cfg.get('p')}, {cfg.get('steps')} steps, {cfg.get('shots')} shots, " f"seed {cfg.get('seed')}, x mixer. Brute-force is the oracle (100% by construction)." ) return "\n".join(lines) + note
# --- UI ---------------------------------------------------------------------
_THEME = gr.themes.Base( primary_hue="purple", neutral_hue="slate", font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"], font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],).set( body_background_fill="#0B0B16", body_text_color="#E5E7EB", background_fill_primary="#15152A", background_fill_secondary="#0B0B16", border_color_primary="#2A2440", button_primary_background_fill="#7C3AED", button_primary_background_fill_hover="#8B5CF6", button_primary_text_color="#FFFFFF", block_background_fill="#15152A", block_border_color="#2A2440", input_background_fill="#15152A",)
def _hero_html() -> str: hero_svg = _read_asset("hero_qaoa.svg") art = ( f'<div class="qa-hero-art">{hero_svg}</div>' if hero_svg else '<div class="qa-hero-art"></div>' ) return f"""<div class="qa-hero"><div class="qa-hero-inner"> {art} <div class="qa-hero-copy"> <h1 class="qa-title">QAgent</h1> <p class="qa-tagline">Quantum-optimized tool selection for LLM agents. Pick the best subset of <b>k</b> tools from <b>N</b> with QAOA.</p> <p class="qa-sub">Tools interact - some synergise, some are redundant - so the optimal set is a combinatorial optimization, not a ranking. QAgent encodes "select k of N" on one qubit per tool and solves it with the Quantum Approximate Optimization Algorithm.</p> <div class="qa-badges"> <span class="qa-badge">v0.2.0</span> <a class="qa-badge" href="{REPO_URL}">GitHub</a> <span class="qa-badge cyan">Project 2 of 3</span> <span class="qa-badge green">simulator</span> <span class="qa-badge amber">Apache-2.0</span> </div> </div></div></div>"""
_WHAT = """### What is this?
An LLM agent with many tools should only be handed a few per task - to fit acontext budget, cut cost, and reduce confusion. Picking the *k* individually mostrelevant tools is greedy and often wrong, because tools have **pairwiseinteractions**: a retriever plus a summariser synergise; two overlapping searchtools are redundant. The value of a tool set is
```score(S) = sum of tool relevances + sum of pairwise interactions```
and the task is to maximise it subject to choosing exactly *k* tools - a quadraticbinary optimization, exactly the structure QAOA targets."""
_HOW = """### How it works (in 30 seconds)
- **Encode** the task as per-tool relevances and a pairwise interaction matrix.- **Map** "select k of N" to N qubits (one-hot: qubit i = tool i in/out), folding the cardinality constraint into the cost Hamiltonian as a penalty.- **Optimize** a QAOA ansatz (cost layer + mixer) with PyTorch on the PennyLane simulator; measure and keep the best valid subset.- **Compare** against an exact brute-force oracle and a greedy top-k baseline.
This Space serves results precomputed with that pipeline; the classical solversrun live so you can check the numbers."""
_ABOUT = f"""### About
QAgent is project 2 of 3 in the Quantum Co-Processor program, after[QVerify](https://github.com/Quantum-Labor/qverify) (quantum-assisted reasoningverification) and alongside[QRoute](https://github.com/Quantum-Labor/qroute) (a VQC mixture-of-expertsrouter). Source and full benchmarks: [{REPO_URL}]({REPO_URL}).
**Honest scope.** Simulator only; no quantum advantage is claimed. Onqagent-mini-50, QAOA matches the optimum on every N=8 task and reaches a 0.915mean approximation ratio at N=16, but exact-match at N=16 remains hard (thedocumented next step is Dicke-initialised XY-QAOA). The point is the architectureand an honest baseline."""
def build_demo() -> gr.Blocks: # In Gradio 6.x, theme and css are passed to launch(), not the Blocks # constructor (where they are silently ignored) -- mirrors the QVerify Space. with gr.Blocks(title="QAgent - quantum tool selection") as demo: gr.HTML(_hero_html()) with gr.Row(): with gr.Column(scale=1): gr.Markdown(_WHAT) with gr.Column(scale=1): gr.Markdown(_HOW)
gr.HTML('<div class="qa-section-title">Try it now</div>') history = gr.State([]) default_label = task_choices()[0] if TASKS else None task_dd = gr.Dropdown( choices=task_choices(), value=default_label, label="qagent-mini-50 task", info="Pick a task to see which tools each solver selects.", ) task_desc = gr.Markdown() grid = gr.HTML() scores = gr.HTML() with gr.Row(): verify_btn = gr.Button("Verify live (brute-force + greedy)", variant="primary") verify_out = gr.Markdown() with gr.Row(): landscape = gr.Plot(label="Score landscape") history_plot = gr.Plot(label="History")
gr.HTML('<div class="qa-section-title">qagent-mini-50 leaderboard</div>') gr.Markdown(leaderboard_markdown())
gr.Markdown(_ABOUT)
outputs = [task_desc, grid, scores, landscape, history_plot, history] task_dd.change(select_task, inputs=[task_dd, history], outputs=outputs) verify_btn.click(verify_live, inputs=[task_dd], outputs=[verify_out]) if default_label is not None: demo.load(select_task, inputs=[task_dd, history], outputs=outputs) return demo
demo = build_demo()
if __name__ == "__main__": demo.launch( theme=_THEME, css=_read_asset("styles.css"), server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"), server_port=int(os.environ.get("GRADIO_SERVER_PORT", "7860")), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121/* QAgent Space — luxury dark theme. Loaded by app.py into gr.Blocks(css=...). */
/* Hide Gradio's built-in footer (it localises to the viewer's browser language, which surfaced as a stray non-English footer on the QVerify Space). */footer { display: none !important; }
:root { --qa-bg: #0B0B16; --qa-surface: #15152A; --qa-border: #2A2440; --qa-violet: #7C3AED; --qa-violet-soft: #A78BFA; --qa-cyan: #22D3EE; --qa-amber: #F59E0B; --qa-green: #34D399; --qa-text: #E5E7EB; --qa-muted: #9CA3AF;}
.qa-hero { position: relative; border-radius: 18px; overflow: hidden; border: 1px solid var(--qa-border); background: radial-gradient(1200px 300px at 20% -10%, rgba(124, 58, 237, 0.25), transparent), radial-gradient(900px 300px at 90% 120%, rgba(34, 211, 238, 0.18), transparent), #0B0B16; margin-bottom: 8px;}.qa-hero-inner { display: flex; align-items: center; gap: 28px; padding: 30px 34px; flex-wrap: wrap;}.qa-hero-art { flex: 1 1 520px; min-width: 320px; }.qa-hero-art img { width: 100%; height: auto; display: block; border-radius: 12px; }.qa-hero-copy { flex: 1 1 320px; min-width: 280px; }.qa-title { font-family: "Inter", system-ui, sans-serif; font-weight: 800; font-size: 44px; letter-spacing: -0.02em; margin: 0 0 6px; background: linear-gradient(90deg, #FFFFFF, #A78BFA 60%, #22D3EE); -webkit-background-clip: text; background-clip: text; color: transparent;}.qa-tagline { color: var(--qa-text); font-size: 17px; line-height: 1.5; margin: 0 0 14px; }.qa-sub { color: var(--qa-muted); font-size: 13.5px; margin: 0 0 16px; }
.qa-badges { display: flex; flex-wrap: wrap; gap: 8px; }.qa-badge { display: inline-flex; align-items: center; gap: 6px; font-family: "JetBrains Mono", ui-monospace, monospace; font-size: 11.5px; font-weight: 600; padding: 4px 10px; border-radius: 999px; border: 1px solid var(--qa-border); background: #11101F; color: var(--qa-violet-soft); text-decoration: none;}.qa-badge.cyan { color: #67E8F9; }.qa-badge.green { color: var(--qa-green); }.qa-badge.amber { color: var(--qa-amber); }
/* Tool grid */.qa-tool-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin: 6px 0 4px;}.qa-tool-card { border: 1px solid var(--qa-border); border-radius: 12px; background: var(--qa-surface); padding: 10px 12px; transition: transform 0.12s ease, border-color 0.12s ease, box-shadow 0.12s ease;}.qa-tool-card:hover { transform: translateY(-2px); border-color: #3A3460; }.qa-tool-card.sel-optimal { border-color: var(--qa-green); box-shadow: 0 0 0 1px var(--qa-green) inset; }.qa-tool-card.sel-qaoa { box-shadow: 0 0 14px rgba(34, 211, 238, 0.35); }.qa-tool-name { font-family: "JetBrains Mono", ui-monospace, monospace; font-size: 12.5px; color: var(--qa-text); font-weight: 700;}.qa-tool-weight { display: inline-block; margin-top: 6px; font-family: "JetBrains Mono", monospace; font-size: 11px; color: var(--qa-muted);}.qa-tool-bar { height: 5px; border-radius: 4px; background: #20203A; margin-top: 6px; overflow: hidden; }.qa-tool-bar > span { display: block; height: 100%; background: linear-gradient(90deg, #7C3AED, #22D3EE); }.qa-tags { display: flex; gap: 5px; margin-top: 8px; flex-wrap: wrap; }.qa-tag { font-family: "JetBrains Mono", monospace; font-size: 9.5px; font-weight: 700; padding: 2px 7px; border-radius: 999px; letter-spacing: 0.03em;}.qa-tag.optimal { background: rgba(52, 211, 153, 0.16); color: var(--qa-green); }.qa-tag.qaoa { background: rgba(34, 211, 238, 0.16); color: #67E8F9; }.qa-tag.greedy { background: rgba(245, 158, 11, 0.16); color: var(--qa-amber); }
.qa-legend { display: flex; gap: 16px; flex-wrap: wrap; margin: 4px 0 2px; color: var(--qa-muted); font-size: 12px; }.qa-legend .dot { display: inline-block; width: 9px; height: 9px; border-radius: 50%; margin-right: 6px; }
/* Score cards */.qa-scores { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 6px; }.qa-score-card { border: 1px solid var(--qa-border); border-radius: 12px; background: var(--qa-surface); padding: 12px 14px; }.qa-score-card h4 { margin: 0 0 6px; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--qa-muted); }.qa-score-val { font-family: "JetBrains Mono", monospace; font-size: 22px; font-weight: 800; color: var(--qa-text); }.qa-score-sub { font-family: "JetBrains Mono", monospace; font-size: 11.5px; color: var(--qa-muted); margin-top: 2px; }.qa-score-card.optimal .qa-score-val { color: var(--qa-green); }.qa-score-card.qaoa .qa-score-val { color: #67E8F9; }.qa-score-card.greedy .qa-score-val { color: var(--qa-amber); }
.qa-section-title { font-family: "Inter", sans-serif; font-weight: 800; font-size: 22px; margin: 8px 0 2px; color: #FFFFFF; letter-spacing: -0.01em;}1234567# Verifier-only deps: the Space serves precomputed QAOA results and runs the# pure-Python classical solvers (brute-force, greedy) live. qagent itself is# installed --no-deps in the Dockerfile, so torch / pennylane / scipy are NOT# pulled in -- the served paths do not need them, keeping the image small.gradio>=5.0numpy<2.1matplotlib>=3.8123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Lightweight rate limiting for the Space's live-solve path.
The Space serves precomputed QAOA results instantly, but it also runs thepure-Python classical solvers (brute-force, greedy) live so visitors can confirmthe served numbers are real. Those solves are cheap (milliseconds), but a publicendpoint still warrants a guard against rapid-fire hammering. Two layers:
1. **Per-IP rate limit** - at most one live solve per ``window_seconds`` per visitor IP (read from ``x-forwarded-for``, set by HF's reverse proxy).2. **Global daily cap** - a generous ceiling on live solves per UTC day across all visitors, persisted to JSON when a writable dir is available.
There is no IBM-quota guard here (this Space has no hardware path). Verdicts arereturned as a dataclass so the Gradio layer stays thin and the logic is triviallyunit-testable."""
from __future__ import annotations
import jsonimport threadingfrom dataclasses import dataclassfrom datetime import UTC, date, datetimefrom pathlib import Pathfrom typing import Literal
SafetyReason = Literal["rate_limited", "daily_cap"]
@dataclass(frozen=True)class SafetyVerdict: """Outcome of a :meth:`RateLimiter.check_and_register` call."""
allowed: bool reason: SafetyReason | None detail: str daily_remaining: int daily_cap: int
class RateLimiter: """Per-IP + daily gate for the live-solve path. Thread-safe via one lock."""
def __init__( self, *, window_seconds: int = 3, daily_cap: int = 5000, persist_path: Path | None = None, ) -> None: if window_seconds < 0: raise ValueError("window_seconds must be >= 0") if daily_cap < 0: raise ValueError("daily_cap must be >= 0") self._window = window_seconds self._cap = daily_cap self._persist_path = persist_path self._lock = threading.Lock() self._last_ip: dict[str, float] = {} self._day: date | None = None self._count: int = 0 self._load_persisted()
def check_and_register(self, *, ip: str, now: datetime) -> SafetyVerdict: """Decide whether ``ip`` may run a live solve at ``now`` (commit-on-allow).""" with self._lock: self._roll_day_if_needed(now) self._evict_stale_ips(now.timestamp())
if self._count >= self._cap: return SafetyVerdict( allowed=False, reason="daily_cap", detail=f"Daily limit of {self._cap} live solves reached. Resets midnight UTC.", daily_remaining=0, daily_cap=self._cap, )
last = self._last_ip.get(ip) if last is not None and (now.timestamp() - last) < self._window: wait = self._window - int(now.timestamp() - last) return SafetyVerdict( allowed=False, reason="rate_limited", detail=f"Please wait {max(wait, 1)}s between live solves.", daily_remaining=max(0, self._cap - self._count), daily_cap=self._cap, )
self._last_ip[ip] = now.timestamp() self._count += 1 self._persist() return SafetyVerdict( allowed=True, reason=None, detail="ok", daily_remaining=max(0, self._cap - self._count), daily_cap=self._cap, )
def daily_remaining(self, now: datetime) -> int: with self._lock: self._roll_day_if_needed(now) return max(0, self._cap - self._count)
def daily_cap(self) -> int: return self._cap
def _roll_day_if_needed(self, now: datetime) -> None: today = now.astimezone(UTC).date() if self._day != today: self._day = today self._count = 0
def _evict_stale_ips(self, now_ts: float) -> None: if self._window <= 0: self._last_ip.clear() return cutoff = now_ts - self._window self._last_ip = {ip: ts for ip, ts in self._last_ip.items() if ts > cutoff}
def _load_persisted(self) -> None: if self._persist_path is None: return try: raw = json.loads(self._persist_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): return if not isinstance(raw, dict): return try: self._day = date.fromisoformat(str(raw.get("date"))) self._count = int(raw.get("count", 0)) except (TypeError, ValueError): self._day = None self._count = 0
def _persist(self) -> None: if self._persist_path is None or self._day is None: return try: self._persist_path.parent.mkdir(parents=True, exist_ok=True) self._persist_path.write_text( json.dumps({"date": self._day.isoformat(), "count": self._count}), encoding="utf-8", ) except OSError: self._persist_path = None
def default_persist_path() -> Path | None: """Return ``/data/qagent_quota.json`` when HF Persistent Storage is mounted.""" candidate = Path("/data") if candidate.is_dir(): try: test = candidate / ".qa_write_test" test.write_text("x") test.unlink() except OSError: return None return candidate / "qagent_quota.json" return None.gitignoreAdded+5
DockerfileAdded+34
README.md+50-4
app.pyAdded+480
assets/hero_qaoa.svgAdded
assets/quantum_labor_logo.svgAdded
assets/styles.cssAdded+121
precomputed/benchmark_results.jsonAdded
precomputed/dataset.jsonAdded
requirements.txtAdded+7
safety.pyAdded+162