用 Python 实现有预算的推理与规划
运行观察驱动的工具循环、候选搜索、失败重试和保留已完成步骤的重新规划。
学完这一章,你能够
- 运行观察驱动的工具循环、候选搜索、失败重试和保留已完成步骤的重新规划。
按工具观察决定下一步
ReAct 将决策、工具行动和观察连成循环。本站先读取传感器,读数已确认便结束,读数不确定才检查维护日志。工具由程序的允许列表分派,结果进入下一轮上下文。没有可用动作和步数耗尽是两个独立状态。
这种循环适用于查资料、逐步澄清问题和探索未知状态。模型可提出动作,但应用负责校验参数、控制权限与调用成本。本站程序使用确定的策略和本机工具,可复现直接确认、不确定后补证、离线后停止和预算不足四种路径。
用可检查的步骤验证答案
早期 Zero-shot CoT 研究在无示例提示中加入分步要求。Few-shot CoT 则先提供带可核验中间量的示范,再请求解决新问题。两种做法的效果依模型、任务和评估标准而变。公开步骤可帮助定位误差,无法据此观察模型内部过程。
本站练习把库存分成期初量、入库和出库,先计算小计,再核对结余。期初 14、入库 7、出库 4 得到小计 21、结余 17。给出同样的结余却写错小计时,仍应让校验失败。这里验证的是 Python 算术和校验器,模型提示效果须另做对照实验。
按层扩展候选并保留回溯路径
Tree of Thoughts 以多个候选状态探索问题。每一层从保留的候选扩展新分支,按可解释的评分排序,保留有限数量,找到目标时根据父路径返回结果。创作、路线和多方案决策都可以用候选与评分分开表达。
本站练习从营地出发,桥面评分较高却走进死路,山脊评分较低却能到避难所。宽度为 1 时山脊被剪掉。宽度为 2 时程序保留两条路线并找到避难所。路径内排除环,深度只允许一层则尚未到达。下图回放实际保留的分支与结果。
生成分支数量、每层保留宽度和最大深度是不同的预算。本例固定候选和评分,便于观察剪枝。遇到没有候选时返回独立终止状态。模型生成的候选质量和评价可靠性需要分别验证。
用 MCTS 估计有限状态下的动作收益
MCTS 的一次迭代包含选择、扩展、模拟和反向传播。UCT 可以按平均收益加探索项选择已访问的子节点。初次访问先走未访问子节点,避免除以零。节点已扩展的条件需要考虑合法动作是否用尽,仅看已有子节点不能判断全部动作已扩展。
模拟从新状态出发,用本地固定随机种子选动作,达到已定义终点后记录奖励。沿当次搜索路径回传奖励并增加访问次数。本站复用上一处课程中的有限单人树,根节点两条分支的访问数相加等于模拟次数。64 次在固定种子下选择坡道,1 次只访问第一条分支。
本例按访问次数选择根动作,探索项的系数固定。外部实现若提供可配置常数,计算中应真正使用它。有限时间的结果是抽样估计。一般任务应检查循环、终止、模拟成本与状态表示,双人对抗还需明确收益视角。
用反馈决定是否再尝试
Reflexion 将失败反馈保存为下一次可读的经验。应用先评审结果,再记录可执行的修正建议和重试条件。错误不明或权限被拒时停止并保留原记录。文本反馈不会改变模型权重。
本站复用已验证的格式修复函数。第一次用旧表单格式失败,收到要求 JSON 的明确反馈后改用 UTF-8 JSON。把总尝试次数限制为一次时,程序保留反馈并停在预算耗尽。无法识别的错误不会触发盲目重试。真实模型生成反思的质量需另行评估。
用依赖区分递归、层次与并行
把巡查目标分成准备与读数,再拆成可执行的叶任务。递归展开沿既定顺序输出叶子,层次结构保留父任务和子任务关系。复合任务为空或沿路径再次出现同一任务时,应给出错误,避免无进展递归。
只有依赖满足且任务独立时才能并行。本站把东西两个模拟读数交给两个线程,通过汇合屏障确认两个任务同时进入,再按提交顺序收集读数。线程启动顺序、结果归并顺序与真实共享资源并发是不同条件。
重新规划时替换待执行队列
Plan-and-Execute 先定步骤与依赖,执行器逐项分派查询、工具和本站本地计算操作。单纯在 for 循环中把 plan 变量指向新计划,循环仍会沿原有迭代器继续。本站明确替换待执行队列,并用稳定步骤 ID 保存已成功结果。
本站先读记录,桥面操作出现可恢复问题后改走山脊。旧队列里的发布步骤不再执行,重复出现在新计划中的读记录也不会重跑。缺少山脊前置结果、超出重规划预算和未知操作分别停止。示例中的 publish 与 prepare 是本机标签,未产生发布行为。
ReAct 按观察决定下一步,先规划再执行可以把依赖写清楚。两种模式都能设计成遇到变化时修订路径。真实副作用需要审批、幂等、结果核对与持久化状态,再决定可否重试或回滚。
比较候选宽度与真实队列替换
展开查看收起
"""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)
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
运行四组规划对照
ZIP 包含本站 Python 实例、复用的有限搜索模块和本机结果回放。
本章附件与实例包
常见错误与边界检查
- 较高评分的当前分支可能没有可行后续。
- 重新规划要替换待执行步骤并检查已完成前提。
技术规范与官方资料
练习与参考解答
查看参考解答
宽度为 1 时山脊分支被剪掉。重规划预算为 0 时只记录读资料和桥面失败。