File size: 9,114 Bytes
fbb4123 17c8456 fbb4123 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | """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")
@app.get("/", response_class=HTMLResponse)
def index():
return HTMLResponse(content=UI, status_code=200)
@app.post("/api/ask")
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"],
})
@app.post("/api/learn")
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()})
@app.get("/api/memory")
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()}])
@app.get("/api/status")
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()],
})
@app.post("/api/forget")
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()})
@app.post("/api/expire")
def expire():
n = _m.expiry_sweep()
return JSONResponse({"retracted": n, "memory_size": _m.size()})
@app.get("/api/calibration")
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>
"""
|