蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

用真实文件、冻结快照和SQLite检索拆开学习循环

PYTHONWindows、CPython 3.12.14与内置SQLite FTS5;本站机制实验,不运行完整Hermes应用。learning_loop.py
learning_loop.py67 行
"""Owned mechanism exercise: bounded notes, frozen snapshots, actual FTS5, explicit skill revision."""
from contextlib import closing
from hashlib import sha256
import json
from pathlib import Path
import sqlite3
from tempfile import TemporaryDirectory

class Notes:
    def __init__(self,folder,limit=64):
        self.path=Path(folder)/"owned-notes.json";self.limit=limit
        self.live=json.loads(self.path.read_text(encoding="utf8")) if self.path.exists() else []
        self.snapshot=tuple(self.live)
    def add(self,text):
        if text in self.live:return False
        candidate=[*self.live,text]
        if len("\n".join(candidate))>self.limit:raise ValueError("owned character budget exceeded")
        self.path.parent.mkdir(parents=True,exist_ok=True)
        self.path.write_text(json.dumps(candidate,ensure_ascii=False),encoding="utf8")
        self.live=candidate
        return True

def exercise(root):
    root=Path(root);cases=[]
    def check(name,inputs,operation,expected,actual):
        assert expected==actual,(name,expected,actual)
        cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual))
    notes=Notes(root/"review")
    note="Review two examples."
    added=notes.add(note)
    check("frozen",dict(note=note),"write owned note, compare live state with the earlier immutable snapshot",
        [True,[note],[]],[added,notes.live,list(notes.snapshot)])
    next_session=Notes(root/"review")
    check("reopen",dict(new_object=True),"open the same actual file as a new session snapshot",
        [note],list(next_session.snapshot))
    before=notes.path.read_bytes()
    check("duplicate",dict(note=note),"repeat the exact owned note and compare file bytes",
        [False,True],[notes.add(note),before==notes.path.read_bytes()])
    try:notes.add("X"*80)
    except ValueError:rejected=True
    else:rejected=False
    check("capacity",dict(limit=64,new_note_chars=80),"reject over-budget addition and retain prior file",
        [True,True],[rejected,before==notes.path.read_bytes()])
    separate=Notes(root/"research")
    check("separate",dict(other_directory=True),"load a different owned profile without copying notes",[],list(separate.snapshot))
    with closing(sqlite3.connect(root/"owned-history.sqlite3")) as db:
        db.execute("CREATE VIRTUAL TABLE messages USING fts5(session,content)")
        db.executemany("INSERT INTO messages VALUES (?,?)",[("review","sapphire record checked"),("research","other subject")])
        db.commit()
    with closing(sqlite3.connect(root/"owned-history.sqlite3")) as db:
        result=db.execute("SELECT session,content FROM messages WHERE messages MATCH ?",("sapphire",)).fetchall()
    check("fts",dict(query="sapphire"),"create an actual SQLite FTS5 index, close it, reopen and query",
        [["review","sapphire record checked"]],[list(r) for r in result])
    skill=root/"skills"/"review"/"SKILL.md";skill.parent.mkdir(parents=True)
    skill.write_text("---\nname: review\ndescription: Review owned examples.\n---\nCheck one example.\n",encoding="utf8")
    old=sha256(skill.read_bytes()).hexdigest()
    skill.write_text(skill.read_text(encoding="utf8").replace("one example","two examples"),encoding="utf8")
    check("explicit_skill_revision",dict(author="owned Python code"),"explicitly revise a local skill file and compare current source hash",
        [True,True],[old!=sha256(skill.read_bytes()).hexdigest(),"two examples" in skill.read_text(encoding="utf8")])
    return dict(cases=cases,sqlite_version=sqlite3.sqlite_version,
        scope="Owned prototype only. Native Hermes memory, automatic skill creation, model inference and gateway are not executed.",
        files=sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()))

if __name__=="__main__":
    with TemporaryDirectory(prefix="mbsky-hermes-mechanisms-") as root:result=exercise(root)
    print(json.dumps(result,ensure_ascii=False))
本例需在 Windows、CPython 3.12.14与内置SQLite FTS5;本站机制实验,不运行完整Hermes应用。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、CPython 3.12.14与内置SQLite FTS5;本站机制实验,不运行完整Hermes应用。

入口文件:projects/hermes-intro/learning_loop.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 learning_loop.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、CPython 3.12.14与内置SQLite FTS5;本站机制实验,不运行完整Hermes应用。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Hermes Agent

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a194.zip

下载课程关联工程包:Hermes Agent

课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a184.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习