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

本机月报、缺失月份与执行反馈

PYTHONCPython 3.12,本机隔离数据;术语工作树练习使用 Gitarchitecture.py
architecture.py159 行
"""Trace the five functional layers with local files and an auditable workflow."""
from datetime import date
from html import escape
from pathlib import Path
import csv
import json
import re
import sys
import xml.etree.ElementTree as ET

from lab_tools import run_exercise

KNOWLEDGE = {
    "POL-12": "Quarterly sales reports must state missing months.",
    "POL-18": "Expenses require a separate approval.",
}
FIXTURE_FORECAST = {"Harbor":"rain", "Hill":"clear"}
TOKENIZER = re.compile(r"[A-Za-z]+|[ ]|[^A-Za-z ]")


def toy_tokens(text):
    return TOKENIZER.findall(text)


def select_context(query, budget):
    matches = []
    for key, sentence in KNOWLEDGE.items():
        if query.casefold() in sentence.casefold():
            message = f"{key}: {sentence}"
            size = len(toy_tokens(message))
            if size <= budget:
                matches.append(message)
                budget -= size
    return matches


def dispatch(request):
    if not isinstance(request,dict) or set(request) != {"name","args"} or request["name"]!="forecast":
        raise ValueError("unsupported tool request")
    args=request["args"]
    if not isinstance(args,dict) or set(args)!={"city"} or type(args["city"]) is not str:
        raise ValueError("city is required")
    return FIXTURE_FORECAST.get(args["city"],"no local observation")


def load_sales(file):
    with file.open(encoding="utf-8",newline="") as stream:
        reader=csv.DictReader(stream)
        if reader.fieldnames!=["month","units"]:
            raise ValueError("unexpected column names")
        totals={}
        for row in reader:
            if None in row or row["month"] is None or row["units"] is None:
                raise ValueError("incomplete sales row")
            month=date.fromisoformat(row["month"]+"-01")
            if month.strftime("%Y-%m")!=row["month"]:
                raise ValueError("invalid month")
            units=int(row["units"])
            if units<0:
                raise ValueError("this report accepts nonnegative counts")
            totals[row["month"]]=totals.get(row["month"],0)+units
        return totals


def report_task(root,month_range,budget):
    trace=["input","explore","plan"]
    context=select_context("sales",100)
    for name in ("draft.csv","sales.csv")[:budget]:
        trace.append(f"try:{name}")
        try:
            totals=load_sales(root/name)
        except FileNotFoundError:
            trace.append("missing_source")
        else:
            if not totals:
                return {"status":"no_records","trace":trace}
            break
    else:
        return {"status":"budget_exhausted","trace":trace}

    missing=[month for month in month_range if month not in totals]
    maximum=max(totals.values())
    leaders=sorted(month for month,units in totals.items() if units==maximum)
    summary=dict(totals=dict(sorted(totals.items())),highest=leaders,missing=missing,context=context)
    chart=root/"monthly.svg"
    rows=[]
    for index,(month,units) in enumerate(summary["totals"].items()):
        label=escape(month)
        y=68+index*45
        width=units*350/maximum if maximum else 0
        rows.append(f'<text x="28" y="{y+16}">{label}</text>'
                    f'<rect data-month="{label}" x="145" y="{y}" width="{width:g}" height="20" fill="#176d93"/>'
                    f'<text x="{158+width:g}" y="{y+16}">{units}</text>')
    graph = ('<svg xmlns="http://www.w3.org/2000/svg" width="690" height="210" viewBox="0 0 690 210">'
             '<rect width="690" height="210" fill="#f1f7fb"/>'
             '<g font-family="Segoe UI,sans-serif" font-size="17" fill="#173655">'
             '<text x="28" y="38" font-size="24">Monthly sales (units)</text>'
             + "".join(rows) +
             f'<text x="28" y="174">Missing months: {escape(", ".join(missing))}</text></g></svg>')
    chart.write_text(graph,encoding="utf-8")
    trace.extend(("check","save"))
    summary["trace"]=trace
    target=root/"report.json"
    target.write_text(json.dumps(summary,sort_keys=True),encoding="utf-8")
    return {"status":"saved","file":target.name,"chart":chart.name}


def exercise(checks,root,chart_output=None):
    expect=checks.expect
    example="Harbor, 港!"
    tokens=toy_tokens(example)
    expect("architecture_tokens",example,"Apply an illustrative tokenizer and verify round trip",
        [["Harbor",","," ","港","!"],example,12],
        [tokens,"".join(tokens),len(example.encode("utf-8"))])
    expect("architecture_context","sales", "Retrieve a source and fit it within an illustrative token limit",
        [[],["POL-12: Quarterly sales reports must state missing months."]],
        [select_context("sales",1),select_context("sales",100)])
    expect("architecture_missing_context","inventory", "Read an empty retrieval result and abstain from a sourced answer",
        [],select_context("inventory",100))
    expect("architecture_tool", {"name":"forecast","args":{"city":"Harbor"}},
        "Validate the structured request and execute a local tool","rain",dispatch({"name":"forecast","args":{"city":"Harbor"}}))
    try:
        dispatch({"name":"forecast","args":{"city":17}})
    except ValueError as error:
        invalid=str(error)
    else:
        invalid="accepted"
    expect("architecture_tool_guard",17,"Reject a non-string city before dispatch","city is required",invalid)
    fixture=root/"sales.csv"
    fixture.write_text("month,units\n2025-01,5\n2025-01,3\n2025-03,8\n",encoding="utf-8")
    months=["2025-01","2025-02","2025-03"]
    exhausted=report_task(root,months,1)
    expect("architecture_budget",1,"Try only missing draft when budget is one",
        ["budget_exhausted",False],[exhausted["status"],(root/"report.json").exists()])
    done=report_task(root,months,2)
    expect("architecture_workflow",months,"Retry by selecting an allowed file, then render and save reports",
        {"status":"saved","file":"report.json","chart":"monthly.svg"},done)
    saved=json.loads((root/done["file"]).read_text(encoding="utf-8"))
    expect("architecture_months",months,"Read saved totals, tied leaders and missing months",
        [{"2025-01":8,"2025-03":8},["2025-01","2025-03"],["2025-02"]],
        [saved["totals"],saved["highest"],saved["missing"]])
    expect("architecture_trace",2,"Verify the stored plan, observed failure, retry and output sequence",
        ["input","explore","plan","try:draft.csv","missing_source","try:sales.csv","check","save"],saved["trace"])
    graph=ET.parse(root/done["chart"]).getroot()
    bars=graph.findall(".//{http://www.w3.org/2000/svg}rect[@data-month]")
    expect("architecture_chart",["monthly.svg",8],"Parse actual SVG and verify its bars scale equally",
        [["2025-01","350"],["2025-03","350"]],[[r.attrib["data-month"],r.attrib["width"]] for r in bars])
    if chart_output is not None:
        chart_output.write_bytes((root/done["chart"]).read_bytes())


if __name__=="__main__":
    if len(sys.argv)==1:
        run_exercise(exercise)
    elif len(sys.argv)==3 and sys.argv[1]=="--chart-output":
        run_exercise(lambda checks,root: exercise(checks,root,Path(sys.argv[2])))
    else:
        raise SystemExit("usage: architecture.py [--chart-output SVG]")
本例需在 CPython 3.12,本机隔离数据;术语工作树练习使用 Git 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,本机隔离数据;术语工作树练习使用 Git

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 architecture.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,本机隔离数据;术语工作树练习使用 Git。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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