"""Run a local plan, tool calls, memory and an approval-gated preview."""
from datetime import datetime, timezone
from inspect import signature
import json
from bounded_math import calculate
from lab_tools import run_exercise
WEATHER = {("潮湾", "明天"): {"condition": "雨", "mm": 6},
("山城", "明天"): {"condition": "晴", "mm": 0}}
LISTINGS = {"灯塔": "周六开放 09:00–16:00"}
TRIP = ["确认同行者", "列出交通和住宿选项", "预留雨天安排"]
def checked_text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 120:
raise ValueError("expected nonempty text of at most 120 characters")
return value.strip()
def call(tool, **args):
return {"tool": tool, "args": args}
def unique_fields(pairs):
fields = {}
for key, value in pairs:
if key in fields:
raise ValueError("duplicate field")
fields[key] = value
return fields
def read_call(raw):
if not isinstance(raw, str) or len(raw) > 1024:
raise ValueError("call exceeds input limit")
try:
item = json.loads(raw, object_pairs_hook=unique_fields)
except (json.JSONDecodeError, RecursionError) as error:
raise ValueError("invalid call JSON") from error
if not isinstance(item, dict) or set(item) != {"tool", "args"}:
raise ValueError("expected tool and args")
if not isinstance(item["tool"], str) or not isinstance(item["args"], dict):
raise ValueError("invalid tool or args")
return item
class Agent:
def __init__(self):
self.contacts = {"值班员": "fixture-desk"}
self.history = []
self.todos = []
self.outbox = {}
self.tools = {
"weather": self.weather, "remind": self.remind, "search": self.search,
"schedule": self.schedule, "time": self.time, "calculate": calculate,
"add_todo": self.add_todo, "show_todos": self.show_todos,
}
@staticmethod
def weather(city, day):
key = checked_text(city), checked_text(day)
return dict(WEATHER[key]) if key in WEATHER else {"condition": "未知", "mm": None}
def remind(self, city, day, contact, approved, *, scratch):
if type(approved) is not bool:
raise ValueError("approval must be boolean")
city, day, contact = map(checked_text, (city, day, contact))
if (city, day) not in scratch:
return "weather_required"
weather = scratch[city, day]
if weather["condition"] != "雨":
return "no_rain" if weather["condition"] == "晴" else "weather_unknown"
if not approved:
return "awaiting_approval"
target = self.contacts.get(contact)
if target is None:
return "unknown_contact"
key = (city, day, target)
if key in self.outbox:
return "already_queued"
self.outbox[key] = f"{city}{day}预计降雨 {weather['mm']} 毫米,请核对出行安排。"
return "queued_local_preview"
@staticmethod
def search(query):
return LISTINGS.get(checked_text(query), "no_record")
@staticmethod
def schedule(steps):
if not isinstance(steps, list) or not 1 <= len(steps) <= 8:
raise ValueError("expected 1 to 8 steps")
return [f"{index}. {checked_text(text)}" for index, text in enumerate(steps, 1)]
@staticmethod
def time():
return datetime(2026, 11, 10, 8, 30, tzinfo=timezone.utc).isoformat()
def add_todo(self, item):
if len(self.todos) >= 8:
raise ValueError("todo list is full")
self.todos.append(checked_text(item))
return len(self.todos)
def show_todos(self):
return list(self.todos)
def run(self, goal, calls, *, approved=False, budget=4):
goal = checked_text(goal)
if type(budget) is not int or not 0 <= budget <= 8:
raise ValueError("budget must be an integer from 0 to 8")
scratch = {}
trace = []
state = "answered" if not calls else "complete"
for index, raw in enumerate(calls):
if index == budget:
state = "step_limit"
break
name = None
try:
step = read_call(raw)
name, args = step["tool"], step["args"]
if name not in self.tools:
raise ValueError("unknown tool")
target = self.tools[name]
if name == "remind":
if set(args) != {"city", "day", "contact"}:
raise ValueError("approval is supplied by the caller")
args = {**args, "approved": approved, "scratch": scratch}
try:
signature(target).bind(**args)
except TypeError as error:
raise ValueError("invalid tool arguments") from error
output = target(**args)
if name == "weather":
scratch[args["city"].strip(), args["day"].strip()] = output
trace.append({"tool": name, "output": output})
except ValueError as error:
trace.append({"tool": name, "error": str(error)})
state = "tool_error"
break
if len(self.history) == 8:
self.history.pop(0)
self.history.append({"goal": goal, "state": state})
return {"state": state, "trace": trace, "history_count": len(self.history)}
def execute(agent, goal, steps, **options):
return agent.run(goal, [json.dumps(step) for step in steps], **options)
def forecast(city, day="明天", contact="值班员"):
return [call("weather", city=city, day=day), call("remind", city=city, day=day, contact=contact)]
def exercise(checks, _):
expect = checks.expect
agent = Agent()
wet = execute(agent, "查询潮湾出行天气", forecast("潮湾"))
expect("python_agent_rain_waits", ["潮湾","明天",False], "Observe the forecast, then require local approval",
[{"condition":"雨","mm":6},"awaiting_approval",0],
[*(row["output"] for row in wet["trace"]),len(agent.outbox)])
allowed = execute(agent, "批准潮湾提醒预览", forecast("潮湾"), approved=True)
duplicate = execute(agent, "再次运行同样的目标", forecast("潮湾"), approved=True)
expect("python_agent_local_outbox", [True,True], "Read the first queued preview and suppress the duplicate",
["queued_local_preview","already_queued",["潮湾明天预计降雨 6 毫米,请核对出行安排。"]],
[allowed["trace"][-1]["output"],duplicate["trace"][-1]["output"],list(agent.outbox.values())])
dry = execute(agent, "查询山城", forecast("山城"), approved=True)
unknown = execute(agent, "查询无记录城市", forecast("空港"), approved=True)
stranger = execute(agent, "查询潮湾但无联系人", forecast("潮湾",contact="访客"), approved=True)
expect("python_agent_weather_branches", ["山城","空港","访客"], "Run dry, unknown and missing-contact cases",
["no_rain","weather_unknown","unknown_contact",1],
[dry["trace"][-1]["output"],unknown["trace"][-1]["output"],stranger["trace"][-1]["output"],len(agent.outbox)])
fresh = execute(agent, "新一轮直接申请提醒", forecast("潮湾")[1:], approved=True)
expect("python_agent_scratch_isolation", "next turn without lookup", "Verify that previous observations cannot authorize a new action",
"weather_required",fresh["trace"][-1]["output"])
planner = Agent()
result = execute(planner, "制定旅行清单", [call("schedule",steps=TRIP),call("search",query="灯塔"),call("time")])
expect("python_agent_travel_time", TRIP, "Format the sequence, consult the local directory and read a fixed clock",
[["1. 确认同行者","2. 列出交通和住宿选项","3. 预留雨天安排"],"周六开放 09:00–16:00","2026-11-10T08:30:00+00:00"],
[row["output"] for row in result["trace"]])
expect("python_agent_search_miss", "车站", "Use a query with no fixture record", "no_record",
execute(planner,"查询车站",[call("search",query="车站")])["trace"][0]["output"])
calc = execute(planner, "算平方与分数", [call("calculate",expression="15**2+20/3")])
expect("python_agent_calculate", "15**2+20/3", "Dispatch a bounded decimal expression and read its result",
"231.6666666666667",calc["trace"][0]["output"])
arithmetic = ["3 + 5 * 2", "-(3 + 5)/2", ".10 + .2", "1/0", "2**9", "6//2", "__import__('os')", "9"*65]
observed = []
for sample in arithmetic:
row = execute(planner,"核对算术",[call("calculate",expression=sample)])["trace"][0]
observed.append(row.get("output",row.get("error")))
expect("python_agent_math_limits", arithmetic, "Dispatch arithmetic plus unsupported or excessive input",
["13","-4","0.3","division by zero","power outside exercise range","unsupported arithmetic operator",
"only decimal numbers and arithmetic operators are allowed","expected 1 to 64 characters"],observed)
expect("python_agent_history_limit", "several turns with the same instance", "Keep a bounded record of observed turns",
[8,"核对算术",0],[len(planner.history),planner.history[-1]["goal"],len(Agent().history)])
todo = Agent()
first = execute(todo,"添加待办",[call("add_todo",item="核对船期")])
second = execute(todo,"查看待办",[call("show_todos")])
expect("python_agent_todos", ["add","list","new instance"], "Observe two turns and verify a new instance starts empty",
[1,["核对船期"],2,[]],
[first["trace"][0]["output"],second["trace"][0]["output"],second["history_count"],Agent().show_todos()])
invalid = [
'{"tool":"erase","args":{}}',
'{"tool":"weather","args":{"city":"潮湾"}}',
'{"tool":"time","tool":"search","args":{}}',
'{"tool":',
'{"tool":"remind","args":{"city":"潮湾","day":"明天","contact":"值班员","approved":true}}',
'{"tool":"schedule","args":{"steps":[]}}',
]
statuses = []
for raw in invalid:
result = todo.run("拒绝非法调用", [raw,json.dumps(call("add_todo",item="不应写入"))])
statuses.append([result["state"],result["trace"][0]["error"]])
expect("python_agent_json_gate", invalid, "Stop on malformed, forbidden or unauthorized tool requests",
[[["tool_error",error] for error in ("unknown tool","invalid tool arguments","duplicate field","invalid call JSON",
"approval is supplied by the caller","expected 1 to 8 steps")],["核对船期"]],[statuses,todo.todos])
a = execute(todo,"直接反馈",[])
b = execute(todo,"限制步数",[call("time"),call("add_todo",item="不应写入")],budget=1)
expect("python_agent_stop", [0,1], "Compare direct answer with the loop reaching its budget",
["answered",[],"step_limit",1,["核对船期"]],[a["state"],a["trace"],b["state"],len(b["trace"]),todo.todos])
if __name__ == "__main__":
run_exercise(exercise)
本例需在 CPython 3.12、OpenAI SDK 3.46.0、httpx2 2.16.0、隔离样本和 Edge。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、OpenAI SDK 3.46.0、httpx2 2.16.0、隔离样本和 Edge。
入口文件:projects/ai-agent-python-agent/agent_loop.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
agent_loop.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、OpenAI SDK 3.46.0、httpx2 2.16.0、隔离样本和 Edge。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3100.zip