Download humpback2/server.py from gregrsea/HumpBack: direct link, hf CLI and curl.
- Browser
- Download file 9.11 kB
-
https://huggingface.co/gregrsea/HumpBack/resolve/main/humpback2/server.py
- Command line
-
hf download hf://gregrsea/HumpBack/humpback2/server.py
-
curl -L -o server.py https://huggingface.co/gregrsea/HumpBack/resolve/main/humpback2/server.py
9.11 kB
| """HumpBack v2 server: local API + web UI for the belief memory. | |
| Endpoints: | |
| GET / web UI (chat + memory viewer) | |
| POST /api/ask {question} -> {answer, confidence, ...} | |
| POST /api/learn {claim, subject?, predicate?, obj?, source_type?, source_ref?} | |
| GET /api/memory -> active beliefs + stats | |
| POST /api/forget {query} -> delete matching beliefs | |
| POST /api/expire -> run expiry sweep | |
| GET /api/status -> memory + tools stats | |
| GET /api/calibration -> ECE on a held-out set | |
| """ | |
| from __future__ import annotations | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| from .config import INITIAL_CONFIDENCE, VOLATILITY | |
| from .memory import Memory | |
| from .tools import Calculator, FileLookup, SandboxRun | |
| app = FastAPI(title="HumpBack v2 — belief memory server") | |
| _m = Memory("humpback2.db") | |
| def index(): | |
| return HTMLResponse(content=UI, status_code=200) | |
| def ask(req: dict): | |
| question = (req.get("question") or "").strip() | |
| if not question: | |
| raise HTTPException(400, "question required") | |
| res = _m.ask(question, tools=_tools()) | |
| return JSONResponse({ | |
| "answer": res["answer"], | |
| "confidence": res["confidence"], | |
| "method": res["method"], | |
| "tool_calls": res["tool_calls"], | |
| "logprob": round(res["logprob"], 3), | |
| "sources": res["sources"], | |
| }) | |
| def learn(req: dict): | |
| claim = (req.get("claim") or "").strip() | |
| if not claim: | |
| raise HTTPException(400, "claim required") | |
| meta = { | |
| "subject": req.get("subject"), | |
| "predicate": req.get("predicate"), | |
| "obj": req.get("obj"), | |
| "source_type": req.get("source_type") or "user", | |
| "source_ref": req.get("source_ref"), | |
| "confidence": req.get("confidence"), | |
| "volatility": req.get("volatility"), | |
| } | |
| sid = _m.learn(claim, **{k: v for k, v in meta.items() if v is not None}) | |
| return JSONResponse({"id": sid, "memory_size": _m.size()}) | |
| def memory(): | |
| rows = _m.store.conn.execute( | |
| "SELECT id, claim, subject, predicate, object, source_type, volatility, " | |
| "confidence, support_count, contradict_count, status, last_used_at " | |
| "FROM beliefs WHERE status='active' ORDER BY last_confirmed_at DESC LIMIT 200" | |
| ).fetchall() | |
| return JSONResponse([dict(r) for r in rows] + [{"memory_size": _m.size()}]) | |
| def status(): | |
| return JSONResponse({ | |
| "memory_size": _m.size(), | |
| "active": _m.store.count_active(), | |
| "retracted": _m.store.conn.execute( | |
| "SELECT COUNT(*) c FROM beliefs WHERE status='retracted'").fetchone()["c"], | |
| "superseded": _m.store.conn.execute( | |
| "SELECT COUNT(*) c FROM beliefs WHERE status='superseded'").fetchone()["c"], | |
| "volatility": dict(VOLATILITY), | |
| "priors": INITIAL_CONFIDENCE, | |
| "tools": [t.name for t in _tools()], | |
| }) | |
| def forget(req: dict): | |
| query = (req.get("query") or "").strip() | |
| if not query: | |
| raise HTTPException(400, "query required") | |
| n = _m.forget(query) | |
| return JSONResponse({"removed": n, "memory_size": _m.size()}) | |
| def expire(): | |
| n = _m.expiry_sweep() | |
| return JSONResponse({"retracted": n, "memory_size": _m.size()}) | |
| def calibration(): | |
| from .evaluate import calibration_report | |
| rep = calibration_report(_m) | |
| return JSONResponse(rep) | |
| def _tools(): | |
| return [Calculator(), FileLookup(), SandboxRun()] | |
| # --- single-file web UI ------------------------------------------------- | |
| UI = r"""<!doctype html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>HumpBack v2 — Belief Memory</title> | |
| <style> | |
| :root { color-scheme: dark; } | |
| * { box-sizing: border-box; } | |
| body { margin: 0; font-family: system-ui, sans-serif; background: #0b1020; | |
| color: #e6e9f2; height: 100vh; display: flex; flex-direction: column; } | |
| header { padding: 12px 16px; border-bottom: 1px solid #1a2544; display: flex; | |
| justify-content: space-between; align-items: center; } | |
| header h1 { font-size: 16px; margin: 0; } | |
| header .sub { font-size: 12px; color: #8899bb; } | |
| .pill { font-size: 11px; padding: 2px 8px; border-radius: 10px; | |
| background: #1a2544; color: #8899bb; margin-left: 8px; } | |
| .main { flex: 1; display: flex; gap: 12px; overflow: hidden; } | |
| .panel { display: flex; flex-direction: column; min-width: 0; } | |
| .side { width: 320px; border-left: 1px solid #1a2544; display: flex; | |
| flex-direction: column; min-height: 0; } | |
| .side > div { padding: 10px; border-bottom: 1px solid #1a2544; flex: 1; overflow: auto; } | |
| .chat { flex: 1; display: flex; flex-direction: column; } | |
| .chat .log { flex: 1; overflow: auto; padding: 12px; font-size: 14px; } | |
| .chat .msg { padding: 10px 12px; border-radius: 10px; margin-bottom: 8px; | |
| max-width: 86%; line-height: 1.45; } | |
| .msg.out { background: #1a2a44; align-self: flex-end; } | |
| .msg.in { background: #101830; align-self: flex-start; } | |
| .msg .h { font-weight: 600; color: #4f6cff; font-size: 12px; margin-bottom: 4px; } | |
| .chat .compose { display: flex; gap: 8px; padding: 10px; border-top: 1px solid #1a2544; } | |
| .chat input { flex: 1; padding: 10px 12px; border-radius: 8px; border: 1px solid #2a3a5a; | |
| background: #0b1020; color: #e6e9f2; font-size: 14px; font-family: inherit; } | |
| .chat input:focus { outline: 1px solid #4f6cff; } | |
| .toolbar { display: flex; gap: 8px; padding: 8px 12px; border-top: 1px solid #1a2544; } | |
| .toolbar button { background: #1a2544; color: #e6e9f2; border: 1px solid #2a3a5a; | |
| padding: 6px 10px; border-radius: 8px; cursor: pointer; font-size: 12px; } | |
| .toolbar button:hover { background: #243552; } | |
| .memory p { margin: 4px 0; font-size: 12px; } | |
| .memory b { color: #ffd166; } | |
| .stat { font-size: 11px; color: #8899bb; } | |
| .grid2 { display: grid; grid-template-columns: 1fr 1fr; } | |
| @media (max-width: 700px) { .side { width: 240px; } .grid2 { grid-template-columns: 1fr; } } | |
| </style> | |
| </head> | |
| <body> | |
| <header> | |
| <h1>HumpBack v2 — Belief Memory</h1> | |
| <span class="sub" id="status"></span> | |
| </header> | |
| <div class="main"> | |
| <div class="panel chat"> | |
| <div class="log" id="log"></div> | |
| <div class="compose"> | |
| <input id="q" type="text" placeholder="Ask anything about its knowledge base..." autofocus> | |
| <button id="send">Ask</button> | |
| <button id="learn">Learn</button> | |
| </div> | |
| <div class="toolbar"> | |
| <button id="learnBtn">Learn fact</button> | |
| <button id="forgetBtn">Forget</button> | |
| <button id="expireBtn">Expiry sweep</button> | |
| </div> | |
| </div> | |
| <div class="panel side"> | |
| <div> | |
| <div class="stat">Memory size: <b id="n">0</b></div> | |
| <div class="stat">Status: <b id="st">active</b></div> | |
| <div class="stat">Tools: <b id="tname">none</b></div> | |
| </div> | |
| <div id="facts"></div> | |
| </div> | |
| </div> | |
| <script> | |
| const $ = s => document.querySelector(s); | |
| const log = el => { const d = document.createElement('div'); d.className='msg out'; d.textContent = el; $('log').appendChild(d); $('log').scrollTop = $('log').scrollHeight; }; | |
| const ask = async q => { | |
| const r = await fetch('/api/ask', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({question: q})}); | |
| const j = await r.json(); | |
| const m = document.createElement('div'); m.className='msg out'; | |
| m.innerHTML = `<div class='h'>A:</div>${j.answer} <span class='stat'>(${j.confidence})</span>`; | |
| $('log').appendChild(m); | |
| log(`sources: ${j.sources.join(' | ')}`); | |
| }; | |
| $('send').onclick = e => { const q = $('q').value.trim(); if(!q) return; ask(q); $('q').value=''; }; | |
| $('learnBtn').onclick = () => { | |
| const c = prompt('Claim:'); const s = prompt('Subject:'); const o = prompt('Object/value:'); | |
| if(!c) return; | |
| fetch('/api/learn', {method:'POST', headers:{'Content-Type':'application/json'}, | |
| body: JSON.stringify({claim: c, subject: s, obj: o, source_type:'user', confidence:0.8, volatility:'static'})}) | |
| .then(r=>r.json()).then(j=>{ log(`learned #${j.id}`); $('n').textContent=j.memory_size; }); | |
| }; | |
| $('forgetBtn').onclick = () => { const q = prompt('Claim(s) to forget:'); if(!q) return; | |
| fetch('/api/forget', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({query:q})}) | |
| .then(r=>r.json()).then(j=>{ log(`removed ${j.removed}`); $('n').textContent=j.memory_size; }); | |
| }; | |
| $('expireBtn').onclick = () => { fetch('/api/expire').then(r=>r.json()).then(j=>{ log(`expired ${j.retracted}`); $('n').textContent=j.memory_size; }); }; | |
| (async () => { | |
| const st = await fetch('/api/status').then(r=>r.json()); | |
| $('status').textContent = `${st.memory_size} beliefs · ${st.tools.join(', ')}`; | |
| $('n').textContent = st.memory_size; $('tname').textContent = st.tools.join(', '); | |
| })(); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |