"""Execute validated local tool requests, retain state and gate a local outbox."""
from contextlib import closing
from datetime import date, datetime, timedelta, timezone
import json
import sqlite3
from lab_tools import run_exercise
WEATHER = {
("Harbor", "2025-06-02"): "rain",
("Hill", "2025-06-02"): "clear",
}
KNOWLEDGE = {
"KB-1": "For trips with rain, pack a waterproof jacket.",
"KB-2": "Departures open for boarding fifteen minutes early.",
}
TOOL = {
"name": "forecast",
"parameters": {"type": "object", "properties": {"city": {"type": "string"},
"day": {"type": "string", "format": "date"}},
"required": ["city", "day"], "additionalProperties": False},
}
def tomorrow(at):
if at.tzinfo is None:
raise ValueError("Timezone required")
return (at.date() + timedelta(days=1)).isoformat()
def execute(raw):
request = json.loads(raw)
if not isinstance(request, dict) or request.keys() != {"name", "arguments"} or request["name"] != TOOL["name"]:
raise ValueError("Unknown or malformed tool request")
args = request["arguments"]
if not isinstance(args, dict) or args.keys() != {"city", "day"} or any(type(v) is not str for v in args.values()):
raise ValueError("Invalid argument fields")
if date.fromisoformat(args["day"]).isoformat() != args["day"]:
raise ValueError("Expected ISO calendar date")
return WEATHER[(args["city"], args["day"])]
def retrieve(term):
return {key: text for key, text in KNOWLEDGE.items() if term.casefold() in text.casefold()}
def forecast_request(city, day):
return json.dumps({"name": "forecast", "arguments": {"city": city, "day": day}})
def run_agent(db, city, day, recipient, allowed, confirmed, budget):
# The decision policy is an explicit rule; a real model adapter would propose calls.
trace = ["input"]
if budget < 1:
return "budget", trace
trace.extend(("plan", "forecast"))
try:
observed = execute(forecast_request(city, day))
except KeyError:
trace.append("unknown_forecast")
return "failed", trace
trace.append(observed)
db.execute("INSERT INTO checkpoints VALUES (?,?,?)", (city, day, observed))
if observed == "clear":
return "done_no_action", trace
if not allowed or not confirmed:
return ("blocked" if not allowed else "needs_confirmation"), trace
if budget < 2:
return "budget", trace
trace.append("local_outbox")
result = db.execute("INSERT OR IGNORE INTO outbox VALUES (?,?,?)", (city, day, recipient))
return ("recorded" if result.rowcount else "already_recorded"), trace
def exercise(checks, workspace):
expect = checks.expect
instant = datetime(2025, 6, 1, 23, 30, tzinfo=timezone(timedelta(hours=8)))
day = tomorrow(instant)
expect("core_date", instant.isoformat(), "Resolve tomorrow using the supplied local time zone",
"2025-06-02", day)
request = forecast_request("Harbor", day)
expect("core_schema", request, "Validate named fields against the local forecast contract and read fixture",
"rain", execute(request))
errors = []
for invalid in ('{"name":"send","arguments":{}}', forecast_request("Harbor","2025-02-30"),
'{"name":"forecast","arguments":{"city":"Harbor","day":2}}'):
try:
execute(invalid)
except ValueError:
errors.append("rejected")
expect("core_bad_request", "unknown name, invalid date, non-string day", "Reject three requests before tool use",
["rejected"] * 3, errors)
hits = retrieve("rain")
expect("core_retrieval", "rain", "Select the applicable source from the local knowledge base",
["KB-1"], list(hits))
answer = " / ".join(f"{key}: {text}" for key, text in hits.items()) or "No supporting passage"
expect("core_grounded", ["rain","subway"], "Build an answer from retrieved passages and abstain on no hit",
["KB-1: For trips with rain, pack a waterproof jacket.", "No supporting passage"],
[answer, " / ".join(retrieve("subway").values()) or "No supporting passage"])
db_path = workspace / "checkpoint.sqlite"
with closing(sqlite3.connect(db_path)) as db:
db.executescript("CREATE TABLE checkpoints(city, day, weather);"
"CREATE TABLE outbox(city, day, recipient, UNIQUE(city,day,recipient));")
checks_by_branch = (
("core_allow", "Harbor", True, True, 2, "recorded"),
("core_idempotency", "Harbor", True, True, 2, "already_recorded"),
("core_clear", "Hill", True, True, 2, "done_no_action"),
("core_denied", "Harbor", False, True, 2, "blocked"),
("core_confirmation", "Harbor", True, False, 2, "needs_confirmation"),
("core_budget", "Harbor", True, True, 1, "budget"),
("core_no_calls", "Harbor", True, True, 0, "budget"),
("core_failure", "Unknown", True, True, 2, "failed"),
)
for name,city,allowed,confirmed,budget,expected in checks_by_branch:
state,trace = run_agent(db,city,day,"demo-recipient",allowed,confirmed,budget)
expected_trace = {
"core_allow": ["input","plan","forecast","rain","local_outbox"],
"core_idempotency": ["input","plan","forecast","rain","local_outbox"],
"core_clear": ["input","plan","forecast","clear"],
"core_denied": ["input","plan","forecast","rain"],
"core_confirmation": ["input","plan","forecast","rain"],
"core_budget": ["input","plan","forecast","rain"],
"core_no_calls": ["input"],
"core_failure": ["input","plan","forecast","unknown_forecast"],
}[name]
expect(name, [city,allowed,confirmed,budget], "Run the local controller and examine transitions",
[expected,expected_trace], [state,trace])
db.commit()
with closing(sqlite3.connect(db_path)) as db:
expect("core_memory", "reopen persisted SQLite after loop", "Read outbox and checkpoints independently",
[[["Harbor", day, "demo-recipient"]], ["clear", "rain"]],
[[list(row) for row in db.execute("SELECT * FROM outbox")],
[row[0] for row in db.execute("SELECT DISTINCT weather FROM checkpoints ORDER BY weather")]])
if __name__ == "__main__":
run_exercise(exercise)
本例需在 CPython 3.12 标准库,独立临时文件和 SQLite,本机显式规则决策 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12 标准库,独立临时文件和 SQLite,本机显式规则决策
入口文件:projects/ai-agent-foundations/core.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
core.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12 标准库,独立临时文件和 SQLite,本机显式规则决策。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a3082.zip