"""Run bounded search, feedback and plan revision over local fieldwork fixtures."""
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from threading import Barrier, get_ident
from lab_tools import run_exercise
from planning_search import search_cases
from reasoning_planning import run_with_feedback
def validate_balance(start, received, sent, claimed):
subtotal = start + received
remainder = subtotal - sent
return [subtotal, remainder], [subtotal, remainder] == claimed
def beam_search(graph, scores, start, goal, *, width, depth):
if width < 1 or depth < 0:
raise ValueError("positive width and non-negative depth required")
frontier = [(start,)]
kept = [[start]]
if start == goal:
return "complete", [start], kept
for _ in range(depth):
candidates = [(*route, edge) for route in frontier for edge in graph.get(route[-1], ())
if edge not in route]
if not candidates:
return "no_candidates", None, kept
ranked = sorted(candidates, key=lambda route: (-scores[route[-1]], route))
frontier = ranked[:width]
kept.append([route[-1] for route in frontier])
for route in frontier:
if route[-1] == goal:
return "complete", list(route), kept
return "depth_exhausted", None, kept
def leaves(name, children, trail=()):
if name in trail:
raise ValueError("cycle: " + " -> ".join((*trail, name)))
descendants = children.get(name)
if descendants is None:
return [name]
if not descendants:
raise ValueError("empty composite: " + name)
return [leaf for child in descendants for leaf in leaves(child, children, (*trail, name))]
def parallel_reads(inputs):
barrier = Barrier(len(inputs), timeout=3)
def read_sensor(name, value):
barrier.wait()
return name, value, get_ident()
with ThreadPoolExecutor(max_workers=len(inputs)) as workers:
futures = [workers.submit(read_sensor, *pair) for pair in inputs]
records = [job.result(timeout=4) for job in futures]
return [[name, value] for name, value, _ in records], len({thread for _, _, thread in records})
@dataclass(frozen=True)
class Step:
key: str
kind: str
needs: tuple = ()
def execute_plan(plan, handlers, fallback, max_replans):
pending = deque(plan)
completed = {}
events = []
replans = 0
while pending:
step = pending.popleft()
if step.key in completed:
continue
if not set(step.needs) <= completed.keys():
return "blocked", events
handler = handlers.get(step.kind)
if handler is None:
return "unknown_operation", events
result = handler(step.key)
events.append([step.key, result])
if result == "ok":
completed[step.key] = result
continue
if result != "retryable":
return "failed", events
if replans >= max_replans:
return "replan_budget", events
replans += 1
pending = deque(fallback(step, tuple(completed)))
return "complete", events
def exercise(checks, _):
expect = checks.expect
expect("implementation_balance_trace", [14,7,4], "Calculate and verify two public arithmetic steps",
([21,17],True),validate_balance(14,7,4,[21,17]))
expect("implementation_balance_examples", [[9,3,5],[13,8,6]], "Check one worked trace and reject the next wrong subtotal",
[([12,7],True),([21,15],False)],
[validate_balance(9,3,5,[12,7]),validate_balance(13,8,6,[20,15])])
branches = {"base":("bridge","ridge"),"bridge":("dead-end",),"ridge":("shelter",),
"dead-end":("base",)}
scores = {"bridge":9,"ridge":5,"dead-end":8,"shelter":10,"base":0}
expect("implementation_beam_width", [1,2], "Compare candidate pruning on a finite route with a cycle",
[("no_candidates",None,[["base"],["bridge"],["dead-end"]]),
("complete",["base","ridge","shelter"],[["base"],["bridge","ridge"],["shelter","dead-end"]])],
[beam_search(branches,scores,"base","shelter",width=w,depth=4) for w in (1,2)])
expect("implementation_beam_depth", 1, "Stop before expanding the second layer",
("depth_exhausted",None,[["base"],["bridge","ridge"]]),
beam_search(branches,scores,"base","shelter",width=2,depth=1))
expect("implementation_beam_root_goal","base", "Finish at depth zero when the root already satisfies the goal",
("complete",["base"],[["base"]]),beam_search(branches,scores,"base","base",width=1,depth=0))
tasks = {"survey":("prepare","measure"),"prepare":("read-map","set-markers"),
"measure":("read-east","read-west")}
expect("implementation_recursive_leaf","survey","Flatten a hierarchical plan in the defined child order",
["read-map","set-markers","read-east","read-west"],leaves("survey",tasks))
for graph,message in (({"survey":("survey",)},"cycle: survey -> survey"),
({"survey":()},"empty composite: survey")):
observed = None
try:
leaves("survey",graph)
except ValueError as error:
observed = str(error)
name = "implementation_recursive_cycle" if graph["survey"] else "implementation_recursive_empty"
expect(name,graph,"Reject an unbounded or empty recursive split",message,observed)
inputs = [("read-east",18),("read-west",22)]
expect("implementation_parallel_reads",inputs,
"Rendezvous both independent jobs at a thread barrier before returning their results",
([["read-east",18],["read-west",22]],2),parallel_reads(inputs))
formats = []
def send(content_type):
formats.append(content_type)
if content_type == "legacy-form":
return False,"expected application/json"
return True,"accepted"
result=run_with_feedback(send,2)
expect("implementation_reflexion_retry",["legacy-form","utf8-json"],
"Carry the recognized error into the next attempt and switch serialization",
[("complete",["expected application/json"]),["legacy-form","utf8-json"]],[result,formats.copy()])
expect("implementation_reflexion_budget",1,"Stop after the first unsuccessful attempt",
("budget_exhausted",["expected application/json"]),run_with_feedback(send,1))
expect("implementation_reflexion_denied","denied","Do not retry an unknown or denied operation",
("unrecognized_failure",[]),run_with_feedback(lambda _: (False,"denied"),2))
initial = (Step("read","query"),Step("bridge","tool",("read",)),Step("publish","code",("bridge",)))
operations = {"query":lambda key:"ok","tool":lambda key:"retryable" if key=="bridge" else "ok",
"code":lambda key:"ok"}
replacement=(Step("read","query"),Step("ridge","tool",("read",)),Step("prepare","code",("ridge",)))
expect("implementation_replan_replaces_tail",["read","bridge","publish"],
"Replace the actual remaining queue and keep successful read without running it again",
("complete",[["read","ok"],["bridge","retryable"],["ridge","ok"],["prepare","ok"]]),
execute_plan(initial,operations,lambda _failed,_done:replacement,1))
expect("implementation_replan_budget",0,"Stop before constructing a fallback with zero replan budget",
("replan_budget",[["read","ok"],["bridge","retryable"]]),
execute_plan(initial,operations,lambda *_:replacement,0))
expect("implementation_replan_dependency",["prepare without ridge"],"Reject the blocked replacement step",
("blocked",[["read","ok"],["bridge","retryable"]]),
execute_plan(initial,operations,lambda *_:(Step("prepare","code",("ridge",)),),1))
expect("implementation_replan_unknown",["unknown handler"],"Reject an operation outside the handler registry",
("unknown_operation",[]),execute_plan((Step("external","unregistered"),),operations,lambda *_:(),1))
search_cases(checks)
if __name__ == "__main__":
run_exercise(exercise)
本例需在 CPython 3.12.14,本机固定工具、树、数据、随机种子与线程。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14,本机固定工具、树、数据、随机种子与线程。
入口文件:projects/ai-agent-python-reasoning/python_reasoning.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python_reasoning.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14,本机固定工具、树、数据、随机种子与线程。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3102.zip