Download rlm_core.py from Haster1137/AI_Forum: direct link, hf CLI and curl.
- Browser
- Download file 43.7 kB
-
https://huggingface.co/datasets/Haster1137/AI_Forum/resolve/main/rlm_core.py
- Command line
-
hf download hf://datasets/Haster1137/AI_Forum/rlm_core.py
-
curl -L -o rlm_core.py https://huggingface.co/datasets/Haster1137/AI_Forum/resolve/main/rlm_core.py
43.7 kB
| """ | |
| rlm_core.py - Recursive Language Model engine for local_agent.py. | |
| The model does not read a huge input; it is handed a Python REPL in which the | |
| input lives as the variable `context`, and writes code to explore, filter, | |
| decompose, recurse (llm_query / rlm_query), aggregate, verify and finally | |
| FINAL(answer). | |
| Self-improvement loop (all state under <base>/): | |
| journal.jsonl every episode (task, approach, recipe, score, errors), | |
| feedback and lessons | |
| skills/*.py reusable Python helpers the model wrote and tested; they | |
| are loaded into every REPL and tracked (uses / errors), | |
| and pruned when they keep failing | |
| memory.json key/value scratch that survives restarts (store/recall) | |
| Before each run, similar past episodes, lessons and the skill index are put | |
| in front of the model; after each run the outcome is journaled; improve() | |
| asks the model to turn recent failures into a new tested skill + a lesson. | |
| The engine knows nothing about local_agent: it only needs llm_fn(messages, | |
| max_tokens) -> str. `python rlm_core.py` runs its own self-test. | |
| """ | |
| import ast | |
| import collections | |
| import ctypes | |
| import itertools | |
| import json | |
| import math | |
| import os | |
| import random | |
| import re | |
| import statistics | |
| import sys | |
| import threading | |
| import time | |
| import traceback | |
| import uuid | |
| try: | |
| import rlm_vec as V | |
| except ImportError: # pragma: no cover | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import rlm_vec as V | |
| DEFAULT_CFG = { | |
| "max_depth": 3, # rlm_query nesting; at the limit it degrades to llm_query | |
| "max_iters": 8, # REPL turns per solve | |
| "max_calls": 80, # model calls per top-level run (all depths) | |
| "max_seconds": 1800, # wall clock per top-level run | |
| "sub_chars": 12000, # text allowed into one sub-call | |
| "sub_tokens": 1536, # reply cap for llm_query | |
| "step_tokens": 1800, # reply cap for a REPL turn | |
| "out_chars": 2500, # REPL output shown back to the model per turn | |
| "exec_timeout": 60, # seconds per code block | |
| "verify": True, # one verifier pass on the final answer (depth 0) | |
| "lessons_k": 3, | |
| "dim": 256, | |
| "prune_min_uses": 5, | |
| "prune_error_rate": 0.6, | |
| "max_load_bytes": 64 * 1024 * 1024, | |
| } | |
| SKILL_NAME = re.compile(r"^[a-z_][a-z0-9_]{2,40}$") | |
| FINAL_TEXT = re.compile(r"^\s*FINAL\s*:\s*(.+)\Z", re.S | re.M) | |
| THINK_RE = re.compile(r"<think>.*?</think>", re.S) | |
| FENCE = re.compile(r"```([A-Za-z0-9_+-]*)[ \t]*\r?\n(.*?)```", re.S) | |
| SUB_SYSTEM = ("You are a precise reading assistant. Use only the text you are " | |
| "given. Answer concisely and say 'not found' if it is not there.") | |
| RLM_SYSTEM = """\ | |
| You are a Recursive Language Model (RLM) working inside a persistent Python REPL. | |
| The input is NOT in this chat. It is the Python string variable `context`. | |
| Never print it whole and never try to read it linearly; inspect it with code. | |
| Reply with ```python blocks. You then see their printed output and continue. | |
| Variables persist between blocks. Pipeline: | |
| 1 EXPLORE ctx.stats() ctx.outline() ctx.peek(i,n) ctx.grep(regex) ctx.top_terms() | |
| 2 FILTER ctx.lexical(q) ctx.rank(q) re.* ; drop noise early | |
| 3 DECOMPOSE ctx.chunk(size) / split by headings; each piece must fit < __SUB__ chars | |
| 4 RECURSE llm_query(prompt, text) = one-shot read of a piece | |
| rlm_query(task, text) = full sub-REPL for a hard sub-problem | |
| llm_map(prompt, items) = llm_query over a list | |
| 5 AGGREGATE in code: dicts, lists, tables; keep partial results in variables | |
| 6 VERIFY re-check key facts with grep or a second query | |
| 7 FINISH FINAL(answer) or FINAL_VAR('variable_name') | |
| Vector math (pure python, already imported): embed(text) cosine(a,b) dot norm | |
| normalize add sub scale mean matmul transpose softmax kmeans(vecs,k) pca(vecs,k) | |
| topk(q,vecs,k) bm25_rank(q,docs,k) solve(A,b) linreg(X,y) power_iter(M) | |
| VectorIndex() . Also: re json math statistics collections itertools random. | |
| Memory: store(key,value) / recall(key) persist across runs. | |
| Skills: skill_save(name, code, description, tests) stores a helper function you | |
| wrote for reuse; saved skills are listed below and callable by name. | |
| Rules: keep each output under ~2000 chars. Prefer code over guessing. Never call | |
| FINAL before you have evidence. If no context is needed, call FINAL('...'). | |
| """ | |
| IMPROVE_PROMPT = """\ | |
| You improve a Recursive Language Model's toolkit. Below are recent tasks it ran | |
| (score 0..1, errors, approach). Existing skills: __SKILLS__ | |
| Focus: __FOCUS__ | |
| __EPISODES__ | |
| Write ONE new reusable Python helper that would have made these tasks faster or | |
| more reliable (parsing, chunking, extraction, vector math, aggregation, ...). | |
| It may use the REPL globals (re, json, math, statistics, embed, cosine, kmeans, | |
| bm25_rank, ctx helpers, llm_query). Reply in exactly this form: | |
| DESC: one line describing the helper | |
| LESSON: one line rule of thumb for future runs | |
| ```python | |
| def helper_name(...): | |
| \"\"\"docstring\"\"\" | |
| ... | |
| ``` | |
| ```test | |
| assert helper_name(...) == ... | |
| ``` | |
| The function name must be lowercase snake_case, 3+ chars. The test block must | |
| use assert and must pass. | |
| """ | |
| RESERVED = set(V.VEC_API) | { | |
| "context", "ctx", "contexts", "llm_query", "llm_map", "rlm_query", "store", | |
| "recall", "FINAL", "FINAL_VAR", "show_vars", "skill_save", "skills", "print", | |
| "re", "json", "math", "statistics", "collections", "itertools", "random", | |
| "mem", "len", "str", "int", "list", "dict", "set", "open", "eval", "exec"} | |
| class RLMError(Exception): | |
| pass | |
| class RLMBudget(RLMError): | |
| pass | |
| class _Final(BaseException): | |
| """Raised by FINAL() to stop the running block (not catchable by `except Exception`).""" | |
| def _clip(text, limit): | |
| text = text if isinstance(text, str) else str(text) | |
| if len(text) <= limit: | |
| return text | |
| return text[:limit] + "\n...[%d more chars]" % (len(text) - limit) | |
| def _to_str(value): | |
| if isinstance(value, str): | |
| return value | |
| try: | |
| return json.dumps(value, ensure_ascii=False, indent=2, default=str) | |
| except (TypeError, ValueError): | |
| return repr(value) | |
| def _short_tb(limit=6): | |
| lines = traceback.format_exc().strip().splitlines() | |
| return "\n".join(lines[-limit:]) | |
| # --------------------------------------------------------------------------- | |
| # REPL | |
| # --------------------------------------------------------------------------- | |
| class Repl: | |
| """A persistent namespace that runs code blocks with a hard-ish timeout.""" | |
| def __init__(self, ns): | |
| self.ns = ns | |
| self.final = {"done": False, "value": None} | |
| def run(self, code, timeout=60): | |
| buf = [] | |
| def _print(*args, sep=" ", end="\n", **_kw): | |
| buf.append(sep.join(str(a) for a in args) + end) | |
| self.ns["print"] = _print | |
| box = {"error": None} | |
| def target(): | |
| try: | |
| tree = ast.parse(code) | |
| last = None | |
| if tree.body and isinstance(tree.body[-1], ast.Expr): | |
| last = ast.Expression(tree.body.pop().value) | |
| ast.fix_missing_locations(last) | |
| exec(compile(tree, "<rlm>", "exec"), self.ns) | |
| if last is not None: | |
| val = eval(compile(last, "<rlm>", "eval"), self.ns) | |
| if val is not None: | |
| buf.append(repr(val)[:4000] + "\n") | |
| except _Final: | |
| pass | |
| except SyntaxError as exc: | |
| box["error"] = "SyntaxError: %s (line %s)" % (exc.msg, exc.lineno) | |
| except TimeoutError: | |
| box["error"] = "TimeoutError: block exceeded %ss" % timeout | |
| except BaseException as exc: # noqa: BLE001 | |
| box["error"] = "%s: %s\n%s" % (type(exc).__name__, exc, _short_tb(5)) | |
| th = threading.Thread(target=target, daemon=True) | |
| th.start() | |
| th.join(timeout) | |
| if th.is_alive(): | |
| try: | |
| ctypes.pythonapi.PyThreadState_SetAsyncExc( | |
| ctypes.c_ulong(th.ident), ctypes.py_object(TimeoutError)) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| th.join(3) | |
| if box["error"] is None: | |
| box["error"] = "TimeoutError: block exceeded %ss" % timeout | |
| return {"output": "".join(buf), "error": box["error"], | |
| "final": self.final["done"]} | |
| # --------------------------------------------------------------------------- | |
| # Engine | |
| # --------------------------------------------------------------------------- | |
| class Engine: | |
| def __init__(self, base_dir, llm_fn=None, cfg=None): | |
| self.base = os.path.abspath(base_dir) | |
| self.skill_dir = os.path.join(self.base, "skills") | |
| self.hist_dir = os.path.join(self.skill_dir, "_history") | |
| os.makedirs(self.hist_dir, exist_ok=True) | |
| self.journal_path = os.path.join(self.base, "journal.jsonl") | |
| self.index_path = os.path.join(self.skill_dir, "index.json") | |
| self.memory_path = os.path.join(self.base, "memory.json") | |
| self.cfg = dict(DEFAULT_CFG) | |
| self.cfg.update(cfg or {}) | |
| self.llm_fn = llm_fn | |
| self.run_lock = threading.Lock() | |
| self.io_lock = threading.Lock() | |
| self.contexts = {} | |
| self.mem = self._read_json(self.memory_path, {}) | |
| self.skill_index = self._read_json(self.index_path, {}) | |
| self.calls = 0 | |
| self.deadline = None | |
| self._used = set() | |
| self._dirty = False | |
| self.repl = None | |
| self._jcache = (0, None) | |
| # -- small io helpers --------------------------------------------------- | |
| def _read_json(path, default): | |
| try: | |
| with open(path, "r", encoding="utf-8") as fh: | |
| return json.load(fh) | |
| except (OSError, ValueError): | |
| return default | |
| def _write_json(self, path, data): | |
| with self.io_lock: | |
| tmp = path + ".tmp" | |
| with open(tmp, "w", encoding="utf-8") as fh: | |
| json.dump(data, fh, ensure_ascii=False, indent=1, default=str) | |
| os.replace(tmp, path) | |
| def _flush_index(self): | |
| if self._dirty: | |
| self._write_json(self.index_path, self.skill_index) | |
| self._dirty = False | |
| def bind(self, llm_fn): | |
| self.llm_fn = llm_fn | |
| # -- model access ------------------------------------------------------- | |
| def _ask(self, messages, max_tokens=None): | |
| if self.llm_fn is None: | |
| raise RLMError("no model is attached to the RLM engine") | |
| if self.calls >= int(self.cfg["max_calls"]): | |
| raise RLMBudget("model-call budget exhausted (%d)" % self.cfg["max_calls"]) | |
| if self.deadline and time.time() > self.deadline: | |
| raise RLMBudget("time budget exhausted (%ss)" % self.cfg["max_seconds"]) | |
| self.calls += 1 | |
| text = self.llm_fn(messages, int(max_tokens or self.cfg["sub_tokens"])) or "" | |
| text = THINK_RE.sub("", str(text)) | |
| if text.lstrip().startswith("<think>"): # unclosed block | |
| text = text.split("</think>")[-1] if "</think>" in text else "" | |
| return text.strip() | |
| def _begin(self): | |
| self.calls = 0 | |
| self.deadline = time.time() + float(self.cfg["max_seconds"]) | |
| self._used = set() | |
| # -- journal ------------------------------------------------------------ | |
| def _log(self, kind, **fields): | |
| row = {"kind": kind, "ts": time.strftime("%Y-%m-%dT%H:%M:%S"), **fields} | |
| with self.io_lock: | |
| with open(self.journal_path, "a", encoding="utf-8") as fh: | |
| fh.write(json.dumps(row, ensure_ascii=False, default=str) + "\n") | |
| return row | |
| def _journal(self, limit=2000): | |
| rows = [] | |
| try: | |
| with open(self.journal_path, "r", encoding="utf-8") as fh: | |
| for line in fh: | |
| try: | |
| rows.append(json.loads(line)) | |
| except ValueError: | |
| continue | |
| except OSError: | |
| return [] | |
| return rows[-limit:] | |
| def episodes(self, n=30): | |
| rows = self._journal() | |
| fb = {r["episode"]: r for r in rows if r.get("kind") == "feedback"} | |
| eps = [] | |
| for r in rows: | |
| if r.get("kind") == "episode": | |
| r = dict(r) | |
| if r["id"] in fb: | |
| r["score"] = fb[r["id"]].get("score", r["score"]) | |
| r["note"] = fb[r["id"]].get("note", "") | |
| eps.append(r) | |
| return eps[-n:] | |
| def add_lesson(self, text, source="manual", task=""): | |
| text = " ".join(str(text).split())[:400] | |
| if not text: | |
| return None | |
| return self._log("lesson", text=text, source=source, task=str(task)[:200]) | |
| def feedback(self, episode, score, note=""): | |
| eps = {e["id"]: e for e in self.episodes(2000)} | |
| if episode not in eps: | |
| raise RLMError("no episode %r (see status for recent ids)" % episode) | |
| score = max(0.0, min(1.0, float(score))) | |
| self._log("feedback", episode=episode, score=score, note=str(note)[:400]) | |
| if note and score < 0.6: | |
| self.add_lesson("%s" % note, source="feedback", task=eps[episode].get("task", "")) | |
| return {"episode": episode, "score": score} | |
| def _experience(self, task): | |
| rows = self._journal(600) | |
| fb = {r["episode"]: r for r in rows if r.get("kind") == "feedback"} | |
| items = [] | |
| for r in rows: | |
| if r.get("kind") == "episode": | |
| if r["id"] in fb: | |
| r = dict(r, score=fb[r["id"]].get("score", r["score"])) | |
| items.append(r) | |
| elif r.get("kind") == "lesson": | |
| items.append(r) | |
| if not items: | |
| return "" | |
| dim = int(self.cfg["dim"]) | |
| q = V.embed(task, dim) | |
| scored = [] | |
| for it in items: | |
| key = it.get("task") or it.get("text") or "" | |
| if it.get("kind") == "lesson": | |
| key = (it.get("task", "") + " " + it.get("text", "")) | |
| scored.append((V.cosine(q, V.embed(key, dim)), it)) | |
| scored.sort(key=lambda p: -p[0]) | |
| eps = [it for s, it in scored if it["kind"] == "episode" and s > 0.15][:3] | |
| les = [it for s, it in scored if it["kind"] == "lesson" and s > 0.05] | |
| les = les[:int(self.cfg["lessons_k"])] | |
| lines = [] | |
| for e in eps: | |
| if e.get("score", 0) >= 0.7: | |
| lines.append("- worked (%.1f) on '%s': %s %s" % ( | |
| e["score"], _clip(e.get("task", ""), 90), e.get("approach", ""), | |
| ("| recipe: " + e["recipe"][:260].replace("\n", "; ")) if e.get("recipe") else "")) | |
| else: | |
| lines.append("- struggled (%.1f) on '%s': %s" % ( | |
| e.get("score", 0), _clip(e.get("task", ""), 90), | |
| "; ".join(e.get("errors", []))[:200] or e.get("note", "no final answer"))) | |
| for l in les: | |
| lines.append("- lesson: " + l["text"]) | |
| return "PAST EXPERIENCE (use it, do not repeat mistakes):\n" + "\n".join(lines) if lines else "" | |
| # -- namespace ---------------------------------------------------------- | |
| def _make_ns(self, text, depth=0, repl_box=None): | |
| ns = {"__name__": "rlm_repl", "re": re, "json": json, "math": math, | |
| "statistics": statistics, "collections": collections, | |
| "itertools": itertools, "random": random} | |
| ns.update(V.VEC_API) | |
| holder = repl_box if repl_box is not None else {"final": {"done": False, "value": None}} | |
| c = V.Ctx(text, "context") | |
| ns["context"], ns["ctx"], ns["contexts"], ns["mem"] = text, c, self.contexts, self.mem | |
| limit = int(self.cfg["sub_chars"]) | |
| def llm_query(prompt, text="", max_tokens=None): | |
| body = str(prompt) | |
| if text: | |
| body += "\n\n---\n" + str(text)[:limit] | |
| return self._ask([{"role": "system", "content": SUB_SYSTEM}, | |
| {"role": "user", "content": body}], | |
| max_tokens or self.cfg["sub_tokens"]) | |
| def llm_map(prompt, items, max_tokens=None): | |
| return [llm_query(prompt, it, max_tokens) for it in items] | |
| def rlm_query(task, text="", max_iters=None): | |
| if depth + 1 >= int(self.cfg["max_depth"]): | |
| return llm_query(task, text) | |
| return self._solve(task, str(text), depth + 1, max_iters, record=False)["answer"] | |
| def store(key, value): | |
| json.dumps(value, default=str) | |
| self.mem[str(key)] = value | |
| self._write_json(self.memory_path, self.mem) | |
| return True | |
| def recall(key=None, default=None): | |
| return dict(self.mem) if key is None else self.mem.get(str(key), default) | |
| def FINAL(value): | |
| holder["final"]["done"], holder["final"]["value"] = True, value | |
| raise _Final() | |
| def FINAL_VAR(name): | |
| if name not in ns: | |
| raise NameError("no variable %r" % name) | |
| FINAL(ns[name]) | |
| def show_vars(): | |
| skip = set(RESERVED) | {"__name__", "__builtins__"} | |
| return {k: "%s(%s)" % (type(v).__name__, len(v) if hasattr(v, "__len__") else "") | |
| for k, v in ns.items() | |
| if k not in skip and not k.startswith("_") and not callable(v) | |
| and k not in self.skill_index} | |
| def skill_save(name, code, description="", tests=""): | |
| return self.save_skill(name, code, description, tests) | |
| def skills(): | |
| return self.list_skills() | |
| ns.update(llm_query=llm_query, llm_map=llm_map, rlm_query=rlm_query, | |
| store=store, recall=recall, FINAL=FINAL, FINAL_VAR=FINAL_VAR, | |
| show_vars=show_vars, skill_save=skill_save, skills=skills) | |
| ns["_holder"] = holder | |
| self._load_skills(ns) | |
| return ns | |
| def _new_repl(self, text, depth=0): | |
| box = {"final": {"done": False, "value": None}} | |
| ns = self._make_ns(text, depth, box) | |
| repl = Repl(ns) | |
| repl.final = box["final"] | |
| return repl | |
| # -- skills ------------------------------------------------------------- | |
| def _wrap(self, name, fn): | |
| def wrapper(*args, **kwargs): | |
| meta = self.skill_index.get(name) | |
| self._used.add(name) | |
| try: | |
| result = fn(*args, **kwargs) | |
| except Exception: | |
| if meta is not None: | |
| meta["uses"] = meta.get("uses", 0) + 1 | |
| meta["errors"] = meta.get("errors", 0) + 1 | |
| self._dirty = True | |
| raise | |
| if meta is not None: | |
| meta["uses"] = meta.get("uses", 0) + 1 | |
| self._dirty = True | |
| return result | |
| wrapper.__name__ = name | |
| wrapper.__doc__ = fn.__doc__ | |
| wrapper.__wrapped__ = fn | |
| return wrapper | |
| def _skill_path(self, name): | |
| return os.path.join(self.skill_dir, name + ".py") | |
| def _load_skills(self, ns): | |
| for name, meta in sorted(self.skill_index.items()): | |
| if meta.get("disabled"): | |
| continue | |
| try: | |
| with open(self._skill_path(name), "r", encoding="utf-8") as fh: | |
| code = fh.read() | |
| exec(compile(code, "<skill:%s>" % name, "exec"), ns) | |
| if callable(ns.get(name)): | |
| ns[name] = self._wrap(name, ns[name]) | |
| meta.pop("load_error", None) | |
| except Exception as exc: # noqa: BLE001 | |
| meta["load_error"] = "%s: %s" % (type(exc).__name__, exc) | |
| self._dirty = True | |
| def save_skill(self, name, code, description="", tests=""): | |
| name = str(name).strip() | |
| if not SKILL_NAME.match(name): | |
| return {"ok": False, "error": "name must be lowercase snake_case, 3-41 chars"} | |
| if name in RESERVED: | |
| return {"ok": False, "error": "%r is a reserved REPL name" % name} | |
| try: | |
| tree = ast.parse(code) | |
| except SyntaxError as exc: | |
| return {"ok": False, "error": "SyntaxError: %s (line %s)" % (exc.msg, exc.lineno)} | |
| fn = next((n for n in tree.body | |
| if isinstance(n, ast.FunctionDef) and n.name == name), None) | |
| if fn is None: | |
| return {"ok": False, "error": "code must define a top-level function named %r" % name} | |
| if not ast.get_docstring(fn) and not description: | |
| return {"ok": False, "error": "give the function a docstring or pass a description"} | |
| sig = "%s(%s)" % (name, ast.unparse(fn.args)) | |
| tested = bool(str(tests).strip()) | |
| repl = self._new_repl("", 0) | |
| res = repl.run(code + "\n\n" + str(tests or ""), timeout=15) | |
| if res["error"]: | |
| return {"ok": False, "error": "test run failed: " + _clip(res["error"], 600)} | |
| with self.io_lock: | |
| old = self.skill_index.get(name) | |
| version = (old.get("version", 0) + 1) if old else 1 | |
| if old and os.path.exists(self._skill_path(name)): | |
| os.replace(self._skill_path(name), | |
| os.path.join(self.hist_dir, "%s.v%d.py" % (name, old.get("version", 1)))) | |
| with open(self._skill_path(name), "w", encoding="utf-8") as fh: | |
| fh.write(code) | |
| self.skill_index[name] = { | |
| "description": (description or ast.get_docstring(fn) or "").strip().splitlines()[0][:160], | |
| "signature": sig, "version": version, "tested": tested, | |
| "uses": 0, "errors": 0, "disabled": False, | |
| "created": (old or {}).get("created", time.strftime("%Y-%m-%dT%H:%M:%S")), | |
| "updated": time.strftime("%Y-%m-%dT%H:%M:%S")} | |
| self._dirty = True | |
| self._flush_index() | |
| if self.repl is not None: # hot-add to the live REPL | |
| try: | |
| exec(compile(code, "<skill:%s>" % name, "exec"), self.repl.ns) | |
| self.repl.ns[name] = self._wrap(name, self.repl.ns[name]) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| return {"ok": True, "name": name, "version": version, "tested": tested, | |
| "signature": sig} | |
| def list_skills(self): | |
| return {n: {k: m.get(k) for k in ("signature", "description", "version", | |
| "tested", "uses", "errors", "disabled")} | |
| for n, m in sorted(self.skill_index.items())} | |
| def show_skill(self, name): | |
| if name not in self.skill_index: | |
| raise RLMError("no skill %r" % name) | |
| with open(self._skill_path(name), "r", encoding="utf-8") as fh: | |
| return fh.read() | |
| def delete_skill(self, name): | |
| if name not in self.skill_index: | |
| raise RLMError("no skill %r" % name) | |
| try: | |
| os.replace(self._skill_path(name), | |
| os.path.join(self.hist_dir, "%s.deleted.py" % name)) | |
| except OSError: | |
| pass | |
| del self.skill_index[name] | |
| self._dirty = True | |
| self._flush_index() | |
| if self.repl is not None: | |
| self.repl.ns.pop(name, None) | |
| return True | |
| def prune_skills(self): | |
| dropped = [] | |
| for name, m in self.skill_index.items(): | |
| uses = m.get("uses", 0) | |
| if (not m.get("disabled") and uses >= int(self.cfg["prune_min_uses"]) | |
| and m.get("errors", 0) / uses > float(self.cfg["prune_error_rate"])): | |
| m["disabled"] = True | |
| dropped.append(name) | |
| self._dirty = True | |
| if self.repl is not None: | |
| self.repl.ns.pop(name, None) | |
| self._flush_index() | |
| return dropped | |
| def _skill_block(self): | |
| live = [(n, m) for n, m in sorted(self.skill_index.items()) if not m.get("disabled")] | |
| if not live: | |
| return "" | |
| return "SAVED SKILLS (callable by name in the REPL):\n" + "\n".join( | |
| "- %s %s [uses %d, errors %d]" % (m.get("signature", n), m.get("description", ""), | |
| m.get("uses", 0), m.get("errors", 0)) | |
| for n, m in live[:25]) | |
| # -- context + exec ----------------------------------------------------- | |
| def load_context(self, name, text=None, path=None): | |
| if text is None: | |
| if not path: | |
| raise RLMError("give text or path") | |
| size = os.path.getsize(path) | |
| if size > int(self.cfg["max_load_bytes"]): | |
| raise RLMError("%s is %d bytes; limit is %d" % (path, size, self.cfg["max_load_bytes"])) | |
| with open(path, "rb") as fh: | |
| text = fh.read().decode("utf-8", errors="replace") | |
| name = str(name or "context") | |
| c = V.Ctx(text, name) | |
| self.contexts[name] = c | |
| if self.repl is None: | |
| self.repl = self._new_repl(text) | |
| self.repl.ns.update(context=text, ctx=c) | |
| return {"name": name, "stats": c.stats(), "outline": c.outline(12), | |
| "head": c.head(240)} | |
| def exec(self, code, timeout=None): | |
| with self.run_lock: | |
| self._begin() | |
| if self.repl is None: | |
| self.repl = self._new_repl("") | |
| self.repl.final["done"], self.repl.final["value"] = False, None | |
| res = self.repl.run(code, timeout or self.cfg["exec_timeout"]) | |
| if res["final"]: | |
| res["final_value"] = _to_str(self.repl.final["value"]) | |
| self.repl.final["done"] = False | |
| res["calls"] = self.calls | |
| self._flush_index() | |
| return res | |
| def reset(self): | |
| self.repl = None | |
| self.contexts.clear() | |
| # -- the recursive solver ----------------------------------------------- | |
| def _blocks(reply): | |
| out = [] | |
| for lang, body in FENCE.findall(reply): | |
| if lang.lower() in ("", "python", "py", "repl", "python3"): | |
| out.append(body) | |
| return out | |
| def solve(self, task, text="", max_iters=None, verify=None): | |
| with self.run_lock: | |
| self._begin() | |
| try: | |
| return self._solve(task, str(text or ""), 0, max_iters, record=True, verify=verify) | |
| finally: | |
| self._flush_index() | |
| def _solve(self, task, text, depth, max_iters, record=True, verify=None): | |
| t0 = time.time() | |
| cfg = self.cfg | |
| limit = int(max_iters or cfg["max_iters"]) | |
| verify = cfg["verify"] if verify is None else bool(verify) | |
| repl = self._new_repl(text, depth) | |
| ctx = repl.ns["ctx"] | |
| system = RLM_SYSTEM.replace("__SUB__", str(cfg["sub_chars"])) | |
| if depth == 0: | |
| extra = [self._experience(task), self._skill_block()] | |
| system += "\n" + "\n\n".join(x for x in extra if x) | |
| st = ctx.stats() if text else None | |
| intro = "TASK: %s\n\n" % task | |
| if text: | |
| intro += ("`context` is a str of %d chars / %d lines / ~%d tokens.\nOutline: %s\n" | |
| "Start: %r\nWrite code to begin." % ( | |
| st["chars"], st["lines"], st["approx_tokens"], | |
| ctx.outline(8) or "none detected", ctx.head(200))) | |
| else: | |
| intro += "`context` is empty; no input was supplied. Write code or call FINAL(...)." | |
| messages = [{"role": "system", "content": system}, {"role": "user", "content": intro}] | |
| answer, forced, errors, approach, recipe = None, False, [], "", "" | |
| verified, fixed, last_reply, i = False, False, "", 0 | |
| trace, note = [], "" | |
| try: | |
| while i < limit: | |
| i += 1 | |
| reply = self._ask(messages, cfg["step_tokens"]) | |
| last_reply = reply | |
| blocks = self._blocks(reply) | |
| if i == 1: | |
| approach = _clip(" ".join(FENCE.sub("", reply).split()) or | |
| (blocks[0].strip().splitlines() or [""])[0], 160) | |
| if not blocks: | |
| m = FINAL_TEXT.search(reply) | |
| if m: | |
| answer = m.group(1).strip() | |
| elif i == 1 or not text: | |
| answer = reply | |
| else: | |
| messages += [{"role": "assistant", "content": reply}, | |
| {"role": "user", "content": "No ```python block found. Write code, or call FINAL(...)."}] | |
| trace.append("iter %d: no code" % i) | |
| continue | |
| else: | |
| outs = [] | |
| for b in blocks: | |
| r = repl.run(b, cfg["exec_timeout"]) | |
| bad = bool(r["error"]) | |
| if bad: | |
| errors.append(r["error"].splitlines()[0][:160]) | |
| elif b.strip(): | |
| recipe = b.strip() | |
| trace.append("iter %d: %s %s" % (i, "ERR" if bad else "ok", | |
| _clip(b.strip().splitlines()[0], 70))) | |
| outs.append(r["output"] + (("\nERROR: " + r["error"]) if bad else "")) | |
| if repl.final["done"]: | |
| break | |
| if repl.final["done"]: | |
| answer = _to_str(repl.final["value"]) | |
| else: | |
| messages += [{"role": "assistant", "content": reply}, | |
| {"role": "user", "content": "Output:\n" + _clip( | |
| "\n".join(outs).strip() or "(no output)", cfg["out_chars"])}] | |
| continue | |
| # an answer exists: optionally verify once at the top level | |
| if verify and depth == 0 and not verified and answer: | |
| verified = True | |
| verdict = self._ask([ | |
| {"role": "system", "content": "You are a strict verifier."}, | |
| {"role": "user", "content": "TASK: %s\n\nANSWER: %s\n\nRecent evidence:\n%s\n\n" | |
| "Reply 'OK' if the answer is supported and complete, otherwise " | |
| "'FIX: <what is wrong or missing>'." % ( | |
| task, _clip(answer, 1500), | |
| _clip("\n".join(m["content"] for m in messages[-2:]), 1500))}], | |
| 200) | |
| if verdict.upper().startswith("FIX"): | |
| fixed = True | |
| note = verdict[:200] | |
| messages += [{"role": "assistant", "content": last_reply}, | |
| {"role": "user", "content": "Verifier: %s\nCorrect it, then FINAL again." % verdict}] | |
| answer = None | |
| repl.final["done"] = False | |
| limit += 2 | |
| continue | |
| break | |
| except RLMBudget as exc: | |
| note = str(exc) | |
| trace.append("budget: " + note) | |
| except RLMError as exc: | |
| note = str(exc) | |
| trace.append("error: " + note) | |
| if answer is None: | |
| forced = True | |
| try: | |
| answer = self._ask(messages + [{"role": "user", "content": | |
| "Out of steps. Give the best final answer now from what you found. Plain text."}], | |
| cfg["step_tokens"]) | |
| except RLMError: | |
| answer = last_reply or "(no answer produced)" | |
| score = 0.3 if forced else max(0.4, 1.0 - 0.1 * len(errors)) | |
| if fixed: | |
| score = max(0.3, score - 0.1) | |
| if note.startswith(("model-call", "time budget")): | |
| score = min(score, 0.2) | |
| result = {"answer": answer, "score": round(score, 2), "iterations": i, | |
| "calls": self.calls, "errors": len(errors), | |
| "seconds": round(time.time() - t0, 2), "trace": trace[-12:], | |
| "forced": forced, "note": note} | |
| if record: | |
| eid = uuid.uuid4().hex[:8] | |
| self._log("episode", id=eid, task=str(task)[:500], depth=depth, iters=i, | |
| calls=self.calls, errors=errors[:3], score=result["score"], | |
| seconds=result["seconds"], approach=approach, recipe=recipe[:600], | |
| skills=sorted(self._used), context_chars=len(text), | |
| answer=_clip(answer, 300), note=note) | |
| result["episode"] = eid | |
| return result | |
| # -- self-improvement --------------------------------------------------- | |
| def improve(self, focus="", attempts=2): | |
| with self.run_lock: | |
| self._begin() | |
| try: | |
| return self._improve(focus, attempts) | |
| finally: | |
| self._flush_index() | |
| def _improve(self, focus, attempts): | |
| eps = self.episodes(30) | |
| bad = [e for e in eps if e.get("score", 1) < 0.7] | |
| pool = (bad or eps)[-6:] | |
| if not pool and not focus: | |
| return {"status": "nothing to learn from yet: run rlm_solve first or pass a focus"} | |
| digest = "\n".join( | |
| "- score %.1f | %s | approach: %s | errors: %s | recipe: %s" % ( | |
| e.get("score", 0), _clip(e.get("task", ""), 120), e.get("approach", ""), | |
| "; ".join(e.get("errors", []))[:160] or "none", | |
| (e.get("recipe") or "")[:200].replace("\n", "; ")) | |
| for e in pool) or "(no episodes yet)" | |
| skills = ", ".join(n for n, m in self.skill_index.items() if not m.get("disabled")) or "none" | |
| prompt = (IMPROVE_PROMPT.replace("__SKILLS__", skills).replace("__FOCUS__", focus or "general") | |
| .replace("__EPISODES__", digest)) | |
| messages = [{"role": "system", "content": "You write small, correct Python helpers."}, | |
| {"role": "user", "content": prompt}] | |
| report = {"saved": None, "lesson": None, "attempts": 0, "error": None, "pruned": []} | |
| for attempt in range(max(1, int(attempts))): | |
| report["attempts"] = attempt + 1 | |
| try: | |
| reply = self._ask(messages, 1800) | |
| except RLMError as exc: | |
| report["error"] = str(exc) | |
| break | |
| m = re.search(r"^LESSON:\s*(.+)$", reply, re.M) | |
| if m and not report["lesson"]: | |
| report["lesson"] = m.group(1).strip() | |
| self.add_lesson(report["lesson"], source="improve", task=focus) | |
| desc = re.search(r"^DESC:\s*(.+)$", reply, re.M) | |
| fences = FENCE.findall(reply) | |
| code = next((b for l, b in fences if l.lower() in ("python", "py")), "") | |
| tests = next((b for l, b in fences if l.lower() in ("test", "tests")), "") | |
| if not tests: | |
| py = [b for l, b in fences if l.lower() in ("python", "py")] | |
| tests = py[1] if len(py) > 1 else "" | |
| fn = None | |
| try: | |
| fn = next((n.name for n in ast.parse(code).body if isinstance(n, ast.FunctionDef)), None) | |
| except SyntaxError: | |
| pass | |
| if not fn: | |
| report["error"] = "reply had no parsable helper function" | |
| else: | |
| res = self.save_skill(fn, code, desc.group(1).strip() if desc else "", tests) | |
| if res["ok"]: | |
| report["saved"], report["error"] = res, None | |
| break | |
| report["error"] = res["error"] | |
| messages += [{"role": "assistant", "content": reply}, | |
| {"role": "user", "content": "That failed: %s\nFix it and reply in the same form." % report["error"]}] | |
| report["pruned"] = self.prune_skills() | |
| self._log("improve", saved=(report["saved"] or {}).get("name"), lesson=report["lesson"], | |
| attempts=report["attempts"], error=report["error"], pruned=report["pruned"]) | |
| return report | |
| # -- status ------------------------------------------------------------- | |
| def status(self): | |
| eps = self.episodes(500) | |
| scores = [e.get("score", 0) for e in eps] | |
| def avg(xs): | |
| return round(sum(xs) / len(xs), 3) if xs else None | |
| live = [n for n, m in self.skill_index.items() if not m.get("disabled")] | |
| return {"episodes": len(eps), "avg_score": avg(scores), | |
| "recent10": avg(scores[-10:]), "previous10": avg(scores[-20:-10]), | |
| "skills": len(live), "disabled_skills": len(self.skill_index) - len(live), | |
| "lessons": sum(1 for r in self._journal() if r.get("kind") == "lesson"), | |
| "contexts": {k: len(v) for k, v in self.contexts.items()}, | |
| "recent_ids": [e["id"] for e in eps[-5:]], "base": self.base, | |
| "limits": {k: self.cfg[k] for k in ("max_depth", "max_iters", "max_calls", "max_seconds")}} | |
| # --------------------------------------------------------------------------- | |
| # Self-test (also called from local_agent --selftest) | |
| # --------------------------------------------------------------------------- | |
| def selftest(ok): | |
| import tempfile | |
| import shutil | |
| tmp = tempfile.mkdtemp(prefix="rlm_test_") | |
| try: | |
| # vector math | |
| ok("rlm: cosine of identical vectors is 1", abs(V.cosine([1, 2, 3], [1, 2, 3]) - 1) < 1e-9) | |
| ok("rlm: matmul", V.matmul([[1, 2], [3, 4]], [[5, 6], [7, 8]]) == [[19, 22], [43, 50]]) | |
| sol = V.solve([[2, 1], [1, 3]], [3, 5]) | |
| ok("rlm: solve linear system", abs(sol[0] - 0.8) < 1e-9 and abs(sol[1] - 1.4) < 1e-9, str(sol)) | |
| w, b = V.linreg([[1], [2], [3], [4]], [3, 5, 7, 9]) | |
| ok("rlm: linreg recovers y=2x+1", abs(w[0] - 2) < 1e-4 and abs(b - 1) < 1e-3, "%s %s" % (w, b)) | |
| pts = [[0, 0], [0.1, 0], [0, 0.1], [9, 9], [9.1, 9], [9, 9.1]] | |
| labels, _ = V.kmeans(pts, 2, seed=1) | |
| ok("rlm: kmeans separates two blobs", | |
| len(set(labels[:3])) == 1 and len(set(labels[3:])) == 1 and labels[0] != labels[3]) | |
| _, proj = V.pca([[1, 1], [2, 2], [3, 3], [4, 4]], 1) | |
| ok("rlm: pca finds the axis", abs(abs(proj[0][0]) - abs(proj[-1][0])) < 1e-3 and abs(proj[0][0]) > 1) | |
| docs = ["the cat sat on the mat", "quantum chromodynamics lecture", "dogs and cats play"] | |
| top = V.embed("cat on a mat") | |
| ok("rlm: embed ranks the related doc first", | |
| V.topk(top, V.embed_many(docs), 1)[0][0] == 0) | |
| ok("rlm: bm25 ranks lexical match", V.bm25_rank("quantum", docs, 1)[0][0] == 1) | |
| # context helpers | |
| body = "\n".join("line %d filler text" % n for n in range(400)) | |
| body = body[:2000] + "\nSECRET_TOKEN=abc123\n" + body[2000:] | |
| c = V.Ctx(body) | |
| hit = c.grep("SECRET_TOKEN") | |
| ok("rlm: ctx.grep finds the needle", len(hit) == 1 and "abc123" in hit[0][2]) | |
| ok("rlm: ctx.chunk covers everything", "".join(c.chunk(500, 0)) == body) | |
| # REPL + timeout + FINAL | |
| eng = Engine(tmp, cfg={"verify": False}) | |
| r = eng.exec("x = 21\nx * 2") | |
| ok("rlm: exec echoes last expression", r["output"].strip() == "42" and not r["error"], str(r)) | |
| r = eng.exec("print(x)") | |
| ok("rlm: REPL state persists", r["output"].strip() == "21", str(r)) | |
| r = eng.exec("while True:\n pass", timeout=1) | |
| ok("rlm: runaway loop is interrupted", bool(r["error"]) and "Timeout" in r["error"], str(r)) | |
| r = eng.exec("FINAL('done')") | |
| ok("rlm: FINAL stops the block", r.get("final_value") == "done", str(r)) | |
| r = eng.exec("1/0") | |
| ok("rlm: errors are reported not raised", "ZeroDivisionError" in (r["error"] or "")) | |
| # recursive solve with a scripted model | |
| info = eng.load_context("doc", text=body) | |
| ok("rlm: load_context returns stats", info["stats"]["lines"] > 400) | |
| script = [ | |
| "Plan: grep for the token.\n```python\nh = ctx.grep('SECRET_TOKEN=')\nprint(h[0][2])\n```", | |
| "```python\nv = llm_query('extract the value after =', h[0][2])\nFINAL(v)\n```", | |
| ] | |
| seen = [] | |
| def fake(messages, max_tokens): | |
| seen.append(messages) | |
| if messages[0]["content"].startswith("You are a precise reading"): | |
| return "abc123" | |
| return script.pop(0) if script else "FINAL: fallback" | |
| eng.bind(fake) | |
| res = eng.solve("Find the secret token", body) | |
| ok("rlm: solve recurses and answers", res["answer"] == "abc123" and res["iterations"] == 2, str(res)) | |
| ok("rlm: solve journals the episode", len(eng.episodes()) == 1 and "episode" in res) | |
| # self-improvement: lesson + tested skill | |
| eng.feedback(res["episode"], 0.4, "grep first, then confirm with llm_query") | |
| helper = ("DESC: pull KEY=VALUE pairs from text\nLESSON: parse KEY=VALUE lines with kv_pairs\n" | |
| "```python\ndef kv_pairs(text):\n \"\"\"Return dict of KEY=VALUE pairs.\"\"\"\n" | |
| " return dict(re.findall(r'(\\w+)=(\\w+)', text))\n```\n" | |
| "```test\nassert kv_pairs('A=1 B=2') == {'A': '1', 'B': '2'}\n```") | |
| eng.bind(lambda m, n: helper) | |
| rep = eng.improve("key value extraction") | |
| ok("rlm: improve saves a tested skill", bool(rep["saved"]) and rep["saved"]["tested"], str(rep)) | |
| eng.bind(lambda m, n: "```python\nprint(kv_pairs('Z=9'))\nFINAL(kv_pairs('Z=9'))\n```") | |
| res2 = eng.solve("extract key value", "Z=9") | |
| ok("rlm: saved skill is callable in a fresh run", "Z" in res2["answer"] and "kv_pairs" in res2["trace"][0] or "Z" in res2["answer"], str(res2)) | |
| ok("rlm: skill usage is tracked", eng.skill_index["kv_pairs"]["uses"] >= 1) | |
| bad = eng.save_skill("broken_one", "def broken_one(x):\n return x\n", "d", "assert broken_one(1) == 2") | |
| ok("rlm: failing tests reject a skill", not bad["ok"] and "broken_one" not in eng.skill_index) | |
| seen.clear() | |
| eng.bind(lambda m, n: (seen.append(m), "FINAL: ok")[1]) | |
| eng.solve("extract key value pairs again", "A=1") | |
| sysmsg = seen[0][0]["content"] | |
| ok("rlm: next run is shown lessons and skills", | |
| "kv_pairs" in sysmsg and "PAST EXPERIENCE" in sysmsg) | |
| eng2 = Engine(tmp) | |
| ok("rlm: state survives a restart", "kv_pairs" in eng2.skill_index and eng2.status()["episodes"] >= 2) | |
| eng.bind(lambda m, n: "```python\nraise ValueError('x')\n```") | |
| eng.cfg["max_calls"] = 3 | |
| res3 = eng.solve("budget test", "abc") | |
| ok("rlm: call budget stops runaway recursion", res3["calls"] <= 3 and res3["score"] <= 0.3, str(res3)) | |
| finally: | |
| shutil.rmtree(tmp, ignore_errors=True) | |
| if __name__ == "__main__": | |
| _res = {"p": 0, "f": []} | |
| def _ok(label, cond, detail=""): | |
| if cond: | |
| _res["p"] += 1 | |
| print(" PASS " + label) | |
| else: | |
| _res["f"].append(label) | |
| print(" FAIL %s %s" % (label, detail)) | |
| selftest(_ok) | |
| print("\n%d passed, %d failed" % (_res["p"], len(_res["f"]))) | |
| sys.exit(1 if _res["f"] else 0) | |