"""Local reasoning patterns over a fictional ferry maintenance workflow."""
from collections import deque
from dataclasses import dataclass
from itertools import islice
from lab_tools import run_exercise
from planning_search import search_cases
@dataclass(frozen=True)
class Observation:
tool: str
value: str
def react(actions, tools, stop, limit):
observations = []
for action in islice(actions, limit):
if action not in tools:
return "denied", observations
result = Observation(action, tools[action]())
observations.append(result)
if stop(result):
return "complete", observations
return "budget_or_input_exhausted", observations
def execute_plan(steps, approved):
completed = []
for name, approval_needed, action in steps:
if approval_needed and name not in approved:
return "approval_required", completed
if not action():
return "step_failed", completed
completed.append(name)
return "complete", completed
def find_route(graph, start, target, breadth_first):
frontier = deque([(start,)])
expanded = set()
while frontier:
path = frontier.popleft() if breadth_first else frontier.pop()
node = path[-1]
if node in expanded:
continue
if node == target:
return list(path)
expanded.add(node)
edges = graph.get(node, ())
frontier.extend((*path, child) for child in (edges if breadth_first else reversed(edges)))
return None
def run_with_feedback(send, attempts):
memory = []
for _ in range(attempts):
method = "utf8-json" if memory else "legacy-form"
ok, message = send(method)
if ok:
return "complete", memory
if message != "expected application/json":
return "unrecognized_failure", memory
memory.append(message)
return "budget_exhausted", memory
def exercise(checks, _):
expect = checks.expect
expect("planning_arithmetic", {"available": 18, "reserved": 5, "added": 3},
"Compute checkable intermediate quantities and final count",
[13, 16], [18 - 5, 18 - 5 + 3])
attempts = []
def sensor():
attempts.append("sensor")
return "unknown"
def work_order():
attempts.append("work_order")
return "confirmed"
tools = {"sensor":sensor, "work_order":work_order}
done = lambda observation: observation.value == "confirmed"
route = ["sensor", "work_order"]
status, history = react(iter(route), tools, done, 2)
expect("planning_react_complete", route, "Run allowed observations until confirmed",
["complete", [["sensor","unknown"],["work_order","confirmed"]]],
[status, [[row.tool,row.value] for row in history]])
attempts.clear()
status, history = react(iter(["sensor","sensor","work_order"]), tools, done, 2)
expect("planning_react_budget", ["sensor","sensor","work_order"], "Run two actions with no final confirmation",
["budget_or_input_exhausted", ["sensor","sensor"], 2], [status, attempts.copy(), len(history)])
attempts.clear()
expect("planning_react_denied", ["broadcast"], "Reject a tool that is absent from the allowed set",
[("denied", []), []], [react(iter(["broadcast"]), tools, done, 1), attempts.copy()])
events = []
def step(name, ok=True):
def perform():
events.append(name)
return ok
return perform
plan = [("read",False,step("read")), ("handoff",True,step("handoff"))]
expect("planning_approval_required", ["read","handoff"], "Execute a plan without handoff approval",
[("approval_required", ["read"]), ["read"]], [execute_plan(plan,set()),events.copy()])
events.clear()
expect("planning_approved", ["handoff"], "Execute the same plan with explicit local approval",
[("complete", ["read","handoff"]), ["read","handoff"]],
[execute_plan(plan,{"handoff"}),events.copy()])
events.clear()
failing = [("read",False,step("read",False)),("handoff",True,step("handoff"))]
expect("planning_step_failure", ["read:false","handoff:approved"], "Stop before a later approved operation",
[("step_failed", []), ["read"]], [execute_plan(failing,{"handoff"}),events.copy()])
graph = {"dock":("east","west"),"east":("loop",),"loop":("dock","stairs"),"stairs":("gate",),"west":("gate",)}
expect("planning_bfs_dfs", graph, "Search the same cyclic route graph by breadth and depth",
[["dock","west","gate"], ["dock","east","loop","stairs","gate"], None],
[find_route(graph,"dock","gate",True),find_route(graph,"dock","gate",False),
find_route(graph,"dock","missing",True)])
formats = []
def fixture(method):
formats.append(method)
return (True, "accepted") if method == "utf8-json" else (False, "expected application/json")
expect("planning_feedback_retry", "mock MIME mismatch", "Use specific feedback to switch request format once",
[("complete", ["expected application/json"]), ["legacy-form","utf8-json"]],
[run_with_feedback(fixture,2), formats.copy()])
expect("planning_unknown_feedback", "denied", "Stop on a failure with no known recovery",
("unrecognized_failure", []), run_with_feedback(lambda method:(False,"denied"),2))
if __name__ == "__main__":
def complete_exercise(checks, workspace):
exercise(checks, workspace)
search_cases(checks)
run_exercise(complete_exercise)
本例需在 CPython 3.12;本地树、工具和审批数据,不调用模型或真实业务接口 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12;本地树、工具和审批数据,不调用模型或真实业务接口
入口文件:projects/ai-agent-reasoning-planning/reasoning_planning.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
reasoning_planning.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12;本地树、工具和审批数据,不调用模型或真实业务接口。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3106.zip