oracle7 / workbench /converse /squircle_reply_v3.py
psiloceyeben's picture
Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 4)
04e89f2 verified
Raw History Blame Contribute Delete
12.8 kB
#!/usr/bin/env python3
"""SQUIRCLE ROUTER v3 (round 4 of the open-conversation loop). Same circle, same selector, same law. Changes, each a class
named by round 3 (judge v3: 9.3%, 48 of 58 good replies are declines; the catalogue the commissive port searched holds
4 of the head's ~40 commands):
1. REPERTOIRE = THE HEAD'S OWN SELF-DESCRIPTION. The commissive port matches the turn against every command in the head's
help text (workbench/cli.py docstring, parsed), not the 381-entry formula catalogue. Integrate, don't replace: the
commands are the released ones.
2. VOCABULARY BY THE HEAD'S OWN DICTIONARY. A turn word that the repertoire does not use is expanded by its first gloss
from the head's own wiktionary store (rt._gloss), at half weight. "post" -> "a piece of writing ..." meets the essay
command's "essay ... writing". Nothing is written about any word.
3. RUN WHAT IS SAFE TO RUN. Read-only commands run now and their output is the reply, with the command line as receipt:
essay (ProseFold, short, topic = the turn's words the command description does not use), specialists, history,
orbiters, organs. A command that builds, installs, signs or changes state is a COMMITMENT: the exact command line, run
on "go".
4. CHECK = ABOUT THE TURN. The head's answer reaches a boundary port only if its content words cover >= 40% of the
turn's rare-word mass (IDF from Oracle7's own records; a word the records do not hold weighs 6). A lecture on one
common word of a long turn no longer speaks.
usage: module (SquircleRouterV3(head_chat, ops, phi, act_of, tree, rt, eng_chat))"""
from __future__ import annotations
import collections
import io
import math
import contextlib
import re
import sys
from squircle_reply import content_words, STOP
from squircle_reply_v2 import SquircleRouterV2
FORM_OF = re.compile(r"\b(?:plural|simple past|past participle|present participle|simple present indicative|misspelling|alternative spelling|comparative|superlative) of ([a-z]+)", re.I)
COVER = 0.40
MATCH_MIN = 0.45
SAFE = {"essay", "specialists", "history", "orbiters", "organs", "systems", "mine"}
STATEFUL = {"build", "compose", "swarm", "update", "new", "example", "exam", "part", "packet", "memory", "registry",
"registry-memo", "grow", "sensor-ideal", "sensor-pair", "sensor-history", "sensor-test", "verify", "scan",
"sensors", "handoff", "check", "invoke", "kernel", "deepspace", "vision", "trafficcop", "chameleon",
"artist", "lesson", "compute", "place", "discover", "ledger", "air", "audit", "mcp", "operations", "ask",
"chat", "card", "serve", "workbench", "setup"}
def parse_help(doc):
"""the head's help text -> [(command, usage, description)]"""
body = doc.split("\n\n", 1)[1] if "\n\n" in doc else doc
out = []
for line in body.splitlines():
m = re.match(r"^ (\S.*?)\s{2,}(\S.*)$", line)
if m and not line.startswith(" "):
usage, desc = m.group(1), m.group(2)
cmd = usage.split()[0].split("|")[0]
out.append([cmd, usage, desc])
elif out and line.startswith(" "):
out[-1][2] += " " + line.strip()
return [tuple(x) for x in out]
class SquircleRouterV3(SquircleRouterV2):
def __init__(self, head_chat, ops, phi, act_of, tree, rt, eng_chat, help_doc, specialists_fn=None, history_fn=None,
beta=4.0):
super().__init__(head_chat, ops, phi, act_of, tree, beta)
self.rt, self.eng_chat = rt, eng_chat
self.specialists_fn, self.history_fn = specialists_fn, history_fn
self.rep = parse_help(help_doc)
self._gl = {}
self.rep_words = []
for cmd, usage, desc in self.rep:
ws = set(self.lemmas(content_words(desc + " " + cmd.replace("-", " "))))
for w in list(content_words(cmd.replace("-", " "))):
ws |= set(content_words(self.gloss(w) or ""))
self.rep_words.append(ws)
df = collections.Counter(w for ws in self.rep_words for w in ws)
n = len(self.rep_words)
self.ridf = {w: math.log((n + 1) / k) for w, k in df.items()}
def gloss(self, w):
if w not in self._gl:
g = None
try:
g = self.rt._gloss(w) if self.rt is not None and hasattr(self.rt, "_gloss") else None
except Exception: # noqa: BLE001
g = None
self._gl[w] = g
return self._gl[w]
# ---- word forms and names from the head's own dictionary
def _db(self):
if not hasattr(self, "_wdb"):
self._wdb = None
if True: # the head's own dictionary store, opened read-only where the head keeps it
# (own connection: the head's is bound to the head's thread)
try:
import sqlite3
from oracle_release_runtime_m import WIKT
self._wdb = sqlite3.connect(WIKT.resolve().as_uri() + "?mode=ro&immutable=1", uri=True,
check_same_thread=False)
except Exception: # noqa: BLE001
self._wdb = None
return self._wdb
def entries(self, w):
db = self._db()
if db is None:
return []
try:
return db.execute("SELECT pos, glosses_json FROM entry WHERE word=?", (w,)).fetchall()
except Exception: # noqa: BLE001
return []
def lemma(self, w):
for _, g in self.entries(w):
m = FORM_OF.search(g or "")
if m:
return m.group(1).lower()
return w
def lemmas(self, words):
out = []
for w in words:
l = self.lemma(w)
if l not in STOP and len(l) > 2:
out.append(l)
return list(dict.fromkeys(out))
def is_name(self, w):
"""a hole worth asking about: a word the dictionary does not hold (a name, a project, a coined term)"""
return len(w) >= 4 and not self.entries(w) and not self.entries(self.lemma(w))
# ---- 4. check = about the turn
def about(self, turn, body):
tc = set(content_words(turn))
if not tc:
return True
bc = set(content_words(body))
wt = lambda w: self.rec.idf.get(w, 6.0)
mass = sum(wt(w) for w in tc)
return mass <= 0 or sum(wt(w) for w in tc & bc) / mass >= COVER
def check_about(self, turn, reply):
return self.check(reply) and self.about(turn, str(reply.get("response", "")))
# ---- 1+2. match the turn to the head's repertoire
def match(self, words):
lem = self.lemmas(words)
q = {w: 1.0 for w in lem}
for w in lem:
if w not in self.ridf:
for g in content_words(self.gloss(w) or "")[:8]:
g = self.lemma(g)
if g not in q:
q[g] = 0.5
best = []
for (cmd, usage, desc), ws in zip(self.rep, self.rep_words):
names = set(self.lemmas(content_words(cmd.replace("-", " "))))
ov = [w for w in q if w in ws]
full = [w for w in ov if q[w] == 1.0]
hit = names & {w for w in q if q[w] == 1.0}
named = bool(hit) and (len([w for w in full if w not in names]) >= 1 # the name plus its description
or (lem and lem[0] in hit) # the name heads the turn
or any(self.rec.idf.get(w, 9.0) >= 5.0 for w in hit)) # a name rare in my records
if not (named or len(full) >= 2):
continue
s = sum(q[w] * self.ridf[w] for w in ov) + (3.0 if named else 0.0)
best.append((s, cmd, usage, desc, ov))
best.sort(key=lambda x: -x[0])
if not best:
return None
if len(best) > 1 and best[0][0] < 1.25 * best[1][0] and best[0][1] != best[1][1]:
return None
return best[0]
# ---- 3. run what is safe
def run_safe(self, cmd, words, used):
topic = " ".join(w for w in words if w not in used)[:80].strip()
if cmd == "essay" and topic and self.eng_chat is not None:
import prosefold.options as PO
r = PO.write(self.eng_chat, topic, voice_path=None, length="short", level="general", depth="standard",
style="plain")
if r.get("sentences"):
return "%s\n\n[oracle7.py essay \"%s\" --length short: %d sentences from %d records, %d checked word " \
"for word; no language model]" % (r["essay_md"].strip(), topic, r["sentences"], r["records_used"],
r["faithful"])
return None
if cmd == "specialists" and self.specialists_fn is not None:
d = self.specialists_fn()
w = topic.split()[0] if topic else ""
items = [x for x in d["items"] if not w or w in (x["name"] + " " + x["id"]).lower()]
if not items:
return None
return "%d admitted specialists%s: %s. [oracle7.py specialists %s]" % (
len(items), " matching '%s'" % w if w else "", ", ".join(x["name"] for x in items[:12]), w)
if cmd == "history" and self.history_fn is not None:
cs = self.history_fn()
if not cs:
return None
return "Saved conversations: %s. [oracle7.py history]" % "; ".join(
"%s (%d turns)" % (c["title"], c["turns"]) for c in cs[:8])
return None
def p_commissive(self, turn, words, bound, cg):
m = self.match(words)
if m:
_, cmd, usage, desc, ov = m
if cmd in SAFE:
obj = re.search(r"(?:on|about|regarding|called|of|for)(.+)$", getattr(self, "_cur", "") or "", re.I)
lw = self.lemmas(content_words(obj.group(1))) if obj else [
w for i, w in enumerate(self.lemmas(words))
if not (i == 0 and any(p == "verb" for p, _ in self.entries(w)))] # the turn minus its leading verb
used = set(ov) | set(self.lemmas(content_words(cmd)))
out = self.run_safe(cmd, lw, used)
cg.ops.append({"id": "command." + cmd, "title": desc})
if out:
return out
topic = " ".join(w for w in lw if w not in used)
return "I ran `oracle7.py %s%s` and it returned nothing I can stand behind%s. That is a hole in my " "records, named for the builder." % (cmd, (' "%s"' % topic) if topic else "",
(" on %s" % topic) if topic else "")
if cmd in STATEFUL:
cg.ops.append({"id": "command." + cmd, "title": desc})
return "That is `oracle7.py %s`: %s. It changes state, so I will run it when you say go, and keep its " \
"receipt." % (usage, desc[:160])
return super().p_commissive(turn, words, bound, cg)
def reply(self, turn, session="convo"):
self._cur = turn
return super().reply(turn, session)
def p_directive(self, cg, turn=None):
"""propose the last operation only when this turn is about it"""
turn = turn or getattr(self, "_cur", "")
if cg.ops and turn and self.about(cg.ops[-1].get("title", ""), turn):
return "Next I would run %s on what you just said. Shall I?" % cg.ops[-1]["id"]
return None
def p_inform(self, turn, head, words, bound, session=None):
if self.check_about(turn, head):
return head["response"]
ws = self._words(self.lemmas(words), bound)
hits = self.recall(ws)
if hits and self.about(turn, " ".join(s for _, s, _, _ in hits)):
return " ".join("My records (%s): %s" % (f, s) for _, s, f, _ in hits)
return None # common ground binds references; quoting the person back is not a reply
def p_question(self, turn, words, bound, session=None):
hole = [w for w in self.lemmas(words) if self.is_name(w)][:3]
if not hole:
return None
return "I have no record of %s. What %s, or where is it recorded?" % (
", ".join(hole), "is it" if len(hole) == 1 else "are they")