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

档案研究智能体与本机审批

PYTHONCPython 3.12.14,jsonschema 4.26.0、SQLite,OpenAI 3.46.0 / httpx2 2.16.0 固定回包。agent_intro.py
agent_intro.py271 行
"""Validate a bounded tool loop and approval using owned local fixtures."""
from datetime import date, datetime, timedelta, timezone
from hashlib import sha256
from importlib.metadata import version
import json
import sqlite3

from jsonschema import Draft202012Validator

from lab_tools import run_exercise


DAY = "2026-08-21"
NOTES = {
    "archive basics": [("G1", "夜间读档须先登记批次。")],
    "archive handling": [("G1", "夜间读档须先登记批次。"), ("G2", "移交后核对两份清册。")],
    "equipment basics": [("E1", "仪器归还前记录编号。")],
}


def object_schema(properties, required):
    return {"type": "object", "properties": properties, "required": required, "additionalProperties": False}


TOOL_SCHEMAS = {
    "archive_search": object_schema({"query": {"type":"string","minLength":1,"maxLength":80},
        "num_results":{"type":"integer","minimum":1,"maximum":5,"default":2}}, ["query"]),
    "museum_weather": object_schema({"city":{"enum":["海滨城","山谷镇"]},
        "day":{"type":"string","pattern":r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$"},
        "unit":{"enum":["celsius","fahrenheit"],"default":"celsius"}}, ["city","day"]),
    "subtotal": object_schema({
        "quantity":{"type":"integer","minimum":1,"maximum":100},
        "unit_price_cents":{"type":"integer","minimum":0,"maximum":30000},
        "shipping_cents":{"type":"integer","minimum":0,"maximum":30000}},
        ["quantity","unit_price_cents","shipping_cents"]),
}


def unique_object(items):
    result = {}
    for key, value in items:
        if key in result:
            raise ValueError("duplicate_key")
        result[key] = value
    return result


def parse_call(name, raw):
    if name not in TOOL_SCHEMAS:
        raise ValueError("tool_denied")
    if len(raw) > 400:
        raise ValueError("arguments_too_long")
    try:
        args = json.loads(raw, object_pairs_hook=unique_object)
    except json.JSONDecodeError as error:
        raise ValueError("invalid_json") from error
    if not Draft202012Validator(TOOL_SCHEMAS[name]).is_valid(args):
        raise ValueError("invalid_arguments")
    if name == "subtotal" and any(type(value) is not int for value in args.values()):
        raise ValueError("integer_encoding_required")
    if name == "museum_weather":
        try:
            date.fromisoformat(args["day"])
        except ValueError as error:
            raise ValueError("invalid_calendar_day") from error
    return args


def dispatch(name, raw):
    args = parse_call(name, raw)
    if name == "archive_search":
        return [list(row) for row in NOTES.get(args["query"], [])[:args.get("num_results", 2)]]
    if name == "museum_weather":
        samples = {("海滨城", DAY):26, ("山谷镇", DAY):25}
        celsius = samples.get((args["city"], args["day"]))
        if celsius is None:
            return None
        unit = args.get("unit", "celsius")
        return [celsius if unit == "celsius" else round(celsius * 9/5 + 32, 1), unit]
    return args["quantity"] * args["unit_price_cents"] + args["shipping_cents"]


def propose(task, payload):
    routes = {"search":"archive_search", "weather":"museum_weather", "calculate":"subtotal"}
    if task not in routes:
        return {"status":"direct_response","text":"请给出明确的档案、天气或预算任务。"}
    name = routes[task]
    raw = json.dumps(payload, ensure_ascii=False)
    return {"status":"observed","tool":name,"result":dispatch(name,raw)}


def next_day(now, city):
    if now.tzinfo is None or city not in {"海滨城","山谷镇"}:
        raise ValueError("missing_location_or_timezone")
    local = now.astimezone(timezone(timedelta(hours=8)))
    return (local.date() + timedelta(days=1)).isoformat()


def recommend(celsius, items, budget_cents):
    if celsius is None:
        return "missing_weather", None
    if celsius <= 25:
        return "threshold_not_met", None
    valid = [item for item in items if 0 <= item[1] <= budget_cents]
    return ("approval_needed", min(valid,key=lambda row:(row[1],row[0]))) if valid else ("out_of_budget", None)


def digest(payload):
    return sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True).encode()).hexdigest()


def queue_draft(db, action_id, payload, permit):
    if permit != (action_id, digest(payload)):
        return "approval_required"
    serialized = json.dumps(payload, ensure_ascii=False, sort_keys=True)
    with db:
        cursor = db.execute("INSERT OR IGNORE INTO draft_queue VALUES (?,?)", (action_id, serialized))
        if cursor.rowcount:
            return "queued_locally"
        previous, = db.execute("SELECT payload FROM draft_queue WHERE action_id=?", (action_id,)).fetchone()
        return "already_queued" if previous == serialized else "action_id_conflict"


def research(topic, budget, *, search, cancel_after=None):
    records, events = {}, []
    remaining = ["basics", "handling"]
    for step in range(budget):
        if cancel_after is not None and step >= cancel_after:
            return "cancelled", events, list(records)
        goal = remaining[0]
        query = f"{topic} {goal}"
        for attempt in (1, 2):
            try:
                hits = search(query)
                break
            except TimeoutError:
                events.append(dict(goal=goal, action=query, observation="temporary_timeout", attempt=attempt))
        else:
            return "failed_timeout", events, list(records)
        events.append(dict(goal=goal, action=query, observation=[item[0] for item in hits], attempt=attempt))
        if not hits:
            return "failed_missing_evidence", events, list(records)
        new_facts = {key: text for key, text in hits if key not in records}
        if not new_facts:
            return "failed_no_progress", events, list(records)
        records.update(new_facts)
        remaining.pop(0)
        if not remaining:
            report = "\n".join(f"- [{key}] {text}" for key,text in records.items())
            return "completed", events, report
    return "budget_exhausted", events, list(records)


def select_research_path(required, proposals):
    return max(proposals, key=lambda plan:(len(required.intersection(plan)), -len(plan)))


def recall(db, actor, term):
    return [row[0] for row in db.execute(
        "SELECT note FROM memory WHERE actor=? AND topic=? ORDER BY seq DESC LIMIT 2", (actor, term))]


def exercise(checks, workspace):
    expect = checks.expect
    for schema in TOOL_SCHEMAS.values():
        Draft202012Validator.check_schema(schema)
    expect("agent_intro_schema", ["archive_search","museum_weather","subtotal"], "Validate three schemas in JSON Schema 2020-12",
           [["archive_search","museum_weather","subtotal"],"4.26.0"], [list(TOOL_SCHEMAS),version("jsonschema")])
    catalog = propose("search", {"query":"archive basics"})
    weather = propose("weather", {"city":"海滨城","day":DAY,"unit":"fahrenheit"})
    total = propose("calculate", {"quantity":3,"unit_price_cents":250,"shipping_cents":40})
    plain = propose("reply", {})
    expect("agent_intro_routes", ["search","weather","calculate","reply"], "Choose allowed tools, execute and return observations",
           [["archive_search",[["G1","夜间读档须先登记批次。"]]], ["museum_weather",[78.8,"fahrenheit"]],
            ["subtotal",790], "direct_response"],
           [[row["tool"],row["result"]] for row in (catalog,weather,total)] + [plain["status"]])

    rejected = [("archive_search",'{"query":"a","query":"b"}'), ("archive_search",'{"query":"x","num_results":6}'),
                ("museum_weather",'{"city":"海滨城","day":"2026-02-29"}'),
                ("museum_weather",'{"city":"海滨城","day":"2026-08-21","unit":"kelvin"}'),
                ("subtotal",'{"quantity":true,"unit_price_cents":1,"shipping_cents":1}'),
                ("subtotal",'{"quantity":3.0,"unit_price_cents":1,"shipping_cents":1}'),
                ("subtotal",'{"expression":"__import__(x)"}'), ("send_email","{}"),
                ("archive_search", "{" + " " * 400), ("archive_search", "{")]
    outcomes = []
    for tool, raw in rejected:
        try:
            parse_call(tool, raw)
        except ValueError as error:
            outcomes.append(str(error))
        else:
            outcomes.append("accepted")
    expect("agent_intro_rejections", rejected, "Reject duplicate JSON, bad types, limits, impossible dates, expressions and unknown tools",
           ["duplicate_key","invalid_arguments","invalid_calendar_day","invalid_arguments","invalid_arguments",
            "integer_encoding_required","invalid_arguments","tool_denied","arguments_too_long","invalid_json"], outcomes)

    now = datetime(2026,8,19,17,30,tzinfo=timezone.utc)
    city = "海滨城"
    summary = {"city":city,"resolved_day":next_day(now,city)}
    expect("agent_intro_memory_summary", [now.isoformat(), city, "明天"], "Resolve tomorrow in the declared local time and preserve confirmed facts",
           {"city":"海滨城","resolved_day":DAY}, summary)
    items = [("薄衫",26000),("厚衫",31000),("备用衫",29000)]
    recommendations = [recommend(value,items,30000) for value in (25,26,None)]
    expect("agent_intro_threshold", [25,26,None,30000], "Check strict weather threshold and the spending bound",
           [("threshold_not_met",None),("approval_needed",("薄衫",26000)),("missing_weather",None),("out_of_budget",None)],
           [*recommendations,recommend(26,items,25000)])

    db = sqlite3.connect(workspace/"exercise.sqlite3")
    try:
        db.execute("CREATE TABLE memory (seq INTEGER PRIMARY KEY, actor TEXT, topic TEXT, note TEXT)")
        db.execute("CREATE TABLE draft_queue (action_id TEXT PRIMARY KEY, payload TEXT)")
        db.executemany("INSERT INTO memory VALUES (?,?,?,?)",[
            (1,"reader-a","weather","已确认海滨城"),(2,"reader-b","weather","私有地区"),(3,"reader-a","weather",DAY)])
        db.commit()
        expect("agent_intro_scoped_memory", ["reader-a","weather"], "Read exact scoped records with a short-window limit",
               [[DAY,"已确认海滨城"], []], [recall(db,"reader-a","weather"),recall(db,"reader-a","orders")])
        action, payload = "review-1", {"item":"薄衫","price_cents":26000}
        permit = (action,digest(payload))
        tests = [queue_draft(db,action,payload,None),queue_draft(db,action,dict(payload,price_cents=27000),permit),
                 queue_draft(db,action,payload,permit),queue_draft(db,action,payload,permit)]
        modified = dict(payload,price_cents=27000)
        tests.append(queue_draft(db,action,modified,(action,digest(modified))))
        written = db.execute("SELECT payload FROM draft_queue").fetchall()
        expect("agent_intro_approval", action, "Bind approval to the exact payload and ensure idempotent local insertion",
               ["approval_required","approval_required","queued_locally","already_queued","action_id_conflict",[payload]],
               [*tests,[json.loads(value) for value, in written]])
    finally:
        db.close()
    db = sqlite3.connect(workspace/"exercise.sqlite3")
    try:
        expect("agent_intro_reopen_memory", "reader-b", "Reopen persisted memory and apply actor scope",
               ["私有地区"], recall(db,"reader-b","weather"))
    finally:
        db.close()

    queries = []
    def local_search(query):
        queries.append(query)
        return NOTES.get(query,[])

    ok = research("archive", 2, search=local_search)
    expect("agent_intro_research", ["archive",2], "Plan, search, observe and report only deduplicated verified fixture records",
           ["completed",["archive basics","archive handling"],"- [G1] 夜间读档须先登记批次。\n- [G2] 移交后核对两份清册。"],
           [ok[0],queries,ok[2]])
    stopped = [research("archive",1,search=local_search)[0], research("archive",2,search=local_search,cancel_after=1)[0],
               research("unknown",2,search=local_search)[0],
               research("archive",2,search=lambda _:NOTES["archive basics"])[0]]
    expect("agent_intro_stop_modes", ["short budget","cancel after first step","unknown","duplicate"],
           "Distinguish exhaustion, cancellation, missing evidence and no progress",
           ["budget_exhausted","cancelled","failed_missing_evidence","failed_no_progress"], stopped)
    visited = []
    def unstable(query):
        visited.append(query)
        if len(visited)==1:
            raise TimeoutError("fixture")
        return NOTES.get(query,[])
    result = research("archive",2,search=unstable)
    def unavailable(_):
        raise TimeoutError("fixture")
    failed = research("archive",2,search=unavailable)
    expect("agent_intro_retry", ["recover once","persistent timeout"], "Retry only temporary reads and stop after the second failure",
           ["completed",["temporary_timeout",["G1"],["G1","G2"]],"failed_timeout",2],
           [result[0],[event["observation"] for event in result[1]],failed[0],len(failed[1])])
    expect("agent_intro_plan_choice", ["catalog","calendar"], "Compare candidate paths with explicit coverage and length",
           ["catalog","calendar"],select_research_path({"catalog","calendar"},
               [["catalog"],["catalog","calendar","send"],["catalog","calendar"]]))


if __name__ == "__main__":
    run_exercise(exercise)
本例需在 CPython 3.12.14,jsonschema 4.26.0、SQLite,OpenAI 3.46.0 / httpx2 2.16.0 固定回包。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12.14,jsonschema 4.26.0、SQLite,OpenAI 3.46.0 / httpx2 2.16.0 固定回包。

入口文件:projects/ai-agent-intro/agent_intro.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 agent_intro.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12.14,jsonschema 4.26.0、SQLite,OpenAI 3.46.0 / httpx2 2.16.0 固定回包。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI(人工智能)

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

下载课程关联工程包:AI(人工智能)

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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