AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
"""Tier-1 (history vote) on the SAME rows the tier-2 run scores, through the
node's own decide endpoints — the #1064 comparison table's other arm.
- SMS: the 4,000-row seed-7 train history indexed as `sms4000`, the 1,574
held-out rows scored via /_decide (index named per request, k=10,
positive_label=spam) — the same endpoint/shape the tier-2 SMS run used.
- Banking77: the 10,003 train rows indexed as the node's configured
[decisions] index, the full 3,080-row test split scored as a 77-way
choice via /v1/systemone.
Requires one node booted with [decisions] index = "b77" for the Banking77
half (the wire surface reads the configured index); the SMS half names its
index per request and works on any node.
"""
import argparse, csv, http.client, json, os, time
def ece(conf_correct, bins=10):
n = len(conf_correct); tot = 0.0
for b in range(bins):
xs = [(c, k) for c, k in conf_correct
if b/bins < c <= (b+1)/bins or (b == 0 and c == 0)]
if xs:
tot += len(xs)/n*abs(sum(k for _, k in xs)/len(xs) - sum(c for c, _ in xs)/len(xs))
return tot
class C:
def __init__(self, base):
h, p = base.split("//")[1].split(":")
self.c = http.client.HTTPConnection(h, int(p), timeout=900)
def req(self, method, path, body=None, ct="application/json"):
data = None if body is None else (
body if isinstance(body, bytes) else json.dumps(body).encode())
for _ in range(3):
try:
self.c.request(method, path, data, {"content-type": ct})
r = self.c.getresponse()
return r.status, json.loads(r.read() or b"{}")
except Exception:
self.c.close()
self.c = http.client.HTTPConnection(self.c.host, self.c.port, timeout=900)
raise SystemExit("request kept failing: " + path)
def load_index(es, index, rows):
es.req("DELETE", f"/{index}")
st, _ = es.req("PUT", f"/{index}", {"mappings": {"properties": {
"text": {"type": "text"}, "label": {"type": "keyword"}}}})
lines = []
for i, (t, l) in enumerate(rows):
lines.append(json.dumps({"index": {"_index": index, "_id": str(i)}}))
lines.append(json.dumps({"text": t, "label": l}))
if len(lines) >= 5000:
st, r = es.req("POST", "/_bulk", ("\n".join(lines)+"\n").encode(), "application/x-ndjson")
assert not r.get("errors"), r
lines = []
if lines:
st, r = es.req("POST", "/_bulk", ("\n".join(lines)+"\n").encode(), "application/x-ndjson")
assert not r.get("errors"), r
es.req("POST", f"/{index}/_refresh", {})
st, r = es.req("GET", f"/{index}/_count")
print(f" indexed {index}: {r.get('count')} docs", flush=True)
def summarise(name, cc, ms, extra=None):
hi = [k for c, k in cc if c >= 0.8]
out = {"set": name, "n": len(cc),
"accuracy": round(sum(k for _, k in cc)/len(cc), 4),
"ECE": round(ece(cc), 4),
"conf>=0.8 share": round(len(hi)/len(cc), 4),
"acc@>=0.8": round(sum(hi)/max(len(hi), 1), 4),
"ms/item": round(ms, 1)}
if extra:
out.update(extra)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--es", default="http://localhost:9604")
ap.add_argument("--native", default="http://localhost:9605")
ap.add_argument("--data", default="/tmp/xerj-rc80gates-work/data")
ap.add_argument("--out", default=".")
ap.add_argument("--sets", default="sms,b77")
args = ap.parse_args()
es, nat = C(args.es), C(args.native)
rows_out = open(os.path.join(args.out, "rows_history.jsonl"), "a")
summary = []
import random
if "sms" in args_sets(args, "sms"):
s = [l.rstrip("\n").split("\t", 1) for l in open(f"{args.data}/sms.tsv")]
s = [(t, l) for l, t in s]
random.Random(7).shuffle(s)
load_index(es, "sms4000", s[:4000])
test = s[4000:]
cc, praw = [], []
tp = fp = fn = 0
t0 = time.time()
for i, (text, gold) in enumerate(test):
st, r = es.req("POST", "/_decide", {"index": "sms4000", "question": text,
"positive_label": "spam", "k": 10})
assert st == 200, r
pred_spam = r["label"] == "spam"
correct = int(pred_spam == (gold == "spam"))
cc.append((r["confidence"], correct))
praw.append((r["p_raw"], int(gold == "spam")))
tp += pred_spam and gold == "spam"
fp += pred_spam and gold != "spam"
fn += (not pred_spam) and gold == "spam"
rows_out.write(json.dumps({"set": "sms_history", "i": i, "gold": gold,
"label": r["label"], "confidence": r["confidence"],
"p_raw": r["p_raw"]}) + "\n")
ms = (time.time()-t0)/len(test)*1000
p = tp/max(tp+fp, 1); rc = tp/max(tp+fn, 1)
summary.append(summarise("SMS held-out — tier-1 history vote (/_decide, k=10, 4000 docs)", cc, ms, {
"ECE_noul_p_raw": round(ece(praw), 4),
"spam_P": round(p, 3), "spam_R": round(rc, 3),
"spam_F1": round(2*p*rc/max(p+rc, 1e-9), 3)}))
if "b77" in args_sets(args, "b77"):
train = [(r["text"], r["category"]) for r in csv.DictReader(open(f"{args.data}/b77_train.csv"))]
load_index(es, "b77", train)
labels = json.load(open(f"{args.data}/b77_labels.json"))
criteria = {l: f"example of {l}" for l in labels}
test = json.load(open(f"{args.data}/b77_test.json"))
cc = []
t0 = time.time()
for i, (text, gold) in enumerate(test):
st, r = nat.req("POST", "/v1/systemone", {
"model": "xerj-history-vote-1", "state": {"message": text},
"questions": {"intent": {"type": "choice",
"instructions": "Which intent matches `message`?",
"criteria": criteria}}})
assert st == 200, r
pred = r["answers"]["intent"]["choice"]
cc.append((r["answers"]["intent"]["confidence"], int(pred == gold)))
rows_out.write(json.dumps({"set": "b77_history", "i": i, "gold": gold,
"label": pred,
"confidence": r["answers"]["intent"]["confidence"]}) + "\n")
if (i+1) % 500 == 0:
print(f" b77 {i+1}/{len(test)}", flush=True)
ms = (time.time()-t0)/len(test)*1000
summary.append(summarise("Banking77 test — tier-1 history vote (/v1/systemone, k=10, 10003 docs)", cc, ms))
rows_out.close()
for s_ in summary:
print(json.dumps(s_), flush=True)
with open(os.path.join(args.out, "summary_history.json"), "a") as f:
f.write(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "summary": summary},
indent=1) + "\n")
def args_sets(args, _):
return args.sets.split(",")
if __name__ == "__main__":
main()