跳到正文
Agent Field Notes
课程目录展开方向,选择要学习的课程。

SYSTEMATIC LEARNING / 分层专题

备用模型的能力与状态契约

考察多模型适配、能力矩阵、失败分类和降级。

学习目标:切换模型改变决策器,不能重置已执行事实、授权与预算。备用模型只有满足任务所需能力和消息语义,才是可执行的降级路径。

内容核对2026-10-03 · 每层有独立讲解、任务与检查

按这个知识点的熟悉程度选择起点。当前层:初级 · 完成实现。完成任务后可以继续下一层;阅读与自检不自动代表掌握。

本层学习目录

先补齐必要概念

适合:学习 Agent 应用开发的后端开发者。

备用模型的能力与状态契约
切换模型改变决策器,不能重置已执行事实、授权与预算。备用模型只有满足任务所需能力和消息语义,才是可执行的降级路径。

原理怎样一步步成立?

逐步解释原理
  1. 主模型返回拒答后应该自动换模型绕过吗?

    切换动机需区分临时故障与禁止行为。

  2. 切换时工具调用 ID 怎么处理?

    更换消息格式后仍要保存真实动作关联。

  3. 备用模型也限流怎么办?

    备用也失败时需要全局停止规则。

初级 · 完成实现

完成实现 · 备用模型的能力与状态契约

本层目标:能区分临时限流、参数错误和权限拒绝,不一律切模型。

图解 · 模型降级保留业务事实

模型降级保留业务事实

此路由夹具不执行写入。模型临时故障只能在保留回执、业务身份、能力与共享限制后,成为考虑降级的理由。 点图可打开原图放大查看。

独立路由函数与输出协议

在fallback_student.py实现route(runtime, request, state, event, capabilities)。request/state/event/capabilities均不得修改。起始runtime.now=0;固定输入如下。

request = {"business_id": "biz-77", "required_caps": ["tools", "json"],
           "deadline": 5, "max_model_calls": 2}
state = {"business_id": "biz-77", "write_state": "none", "receipt": None,
         "facts": [{"kind": "tool_result", "operation_id": "read-op-1", "data": "confirmed"}],
         "used_calls": 1}
event = {"kind": "rate_limited", "http_status": 429, "wait_units": 2}
capabilities = ["tools", "json"]
receipt = {"business_id": "biz-77", "receipt_id": "receipt-1", "status": "committed"}
now = 0

结构合法是前提:state.write_state为none/unknown/committed;committed的可信receipt已在上游核实,且business_id一致;facts为已执行事实。本实训不验证真实回执来源。request与state的business_id不一致时抛ValueError;deadline、max_model_calls、used_calls必须为非负严格int,bool无效,在任何运行时操作前校验。

运行时API:wait(units)推进整数逻辑时钟并记录动作;call_fallback(business_id, facts)返回固定draft事件或unavailable事件,并保存传入事实;lookup(business_id)查询模拟账本;submit_write(business_id)会制造一个非幂等模拟副作用,用于暴露错误重放。此次路由任何分支都不得调用submit_write。备用事件为零时长夹具;因此now+wait_units等于deadline时本模拟器允许取该即时结果,真实网络请求需要单独的剩余时间合同。

按以下优先级实现合同:

  1. 输入校验后,committed直接返回committed/existing_receipt,保留原receipt,不等待、不调用模型。
  2. unknown先按同business_id调用lookup。找到回执返回committed/reconciled_receipt;没找到返回reconcile_required/receipt_not_found_is_not_proof_of_no_write。查不到不构成未写入证明,也不能新提交。
  3. invalid_parameters返回permanent_error/invalid_parameters;permission_denied或safety_refusal返回denied/对应kind。换模型不能绕过权限或拒绝。
  4. 只有kind=rate_limited且http_status=429可继续备用路径;其他事件返回paused/unsupported_failure。
  5. 缺少required_caps时返回capability_blocked,reason为missing:加排序后的缺失项,以逗号分隔;不等待或调用。
  6. used_calls>=max_model_calls时返回budget_exhausted/model_call_budget_exhausted,不调用。used_calls=1代表题目已给出的主调用,备用最多一次,两者共用预算。
  7. 已决定备用时校验wait_units为非负严格int;若now+wait_units>deadline,返回deadline_exceeded/backoff_exceeds_remaining_time,不等待。否则wait该单位,再以同business_id和完整facts调用一次fallback。
  8. 固定draft事件返回draft_ready/fallback_draft和原text;备用unavailable返回paused/fallback_unavailable,不能再循环切换。

输出恰含business_id/status/receipt/facts/reason/draft;receipt仅提交已知时有值,draft仅draft_ready时有值,其余为None;facts始终保留。原输入输出如下。

{
    "business_id": "biz-77",
    "status": "draft_ready",
    "receipt": None,
    "facts": [{"kind": "tool_result", "operation_id": "read-op-1", "data": "confirmed"}],
    "reason": "fallback_draft",
    "draft": "fixture draft",
}

先生成模板并保存红灯;模板预期0/17、退出1,重复scaffold拒绝覆盖、退出2。

python3 fallback_lab.py scaffold --out fallback_student.py
python3 fallback_lab.py grade --module fallback_student.py --out fallback-template-report.json

模板正文:

def route(runtime, request, state, event, capabilities):
    """Return business_id/status/receipt/facts/reason/draft, with exactly those keys.
    Validate IDs and strict integer budgets before actions (bool is invalid).
    Preserve completed/unknown writes before considering another model call.
    Only the authored rate_limited/429 fixture permits fallback, at most once.
    No branch of this routing exercise may call submit_write.
    Return draft_ready for a fixture draft; it does not mean business completion.
    """
    raise NotImplementedError("implement route")

本人完成后用以下命令交付,预期17/17、退出0。grader实际import并调用模块,改变业务ID、事实、能力顺序、时钟及故障,检查调用序列、lookup参数、wait、模型预算、原输入与账本。只返回一个漂亮JSON但没有执行要求的lookup/fallback会失败。5秒worker限时仅防挂起。

python3 fallback_lab.py grade --module fallback_student.py --out fallback-report.json

可复制客户端夹具与验收器

保存下列代码为fallback_lab.py,与HTTPS资源内容一致。代码包含固定guided、未完成模板与公开固定反例;通用route由学员填写,没有未见随机题。

#!/usr/bin/env python3
"""Authored fallback fixtures, Python 3.9+ standard library. Zero provider/model calls.

Independent API: route(runtime, request, state, event, capabilities) -> decision dict.
The grader exercises actual learner code and checks fixture calls/ledger. No general
routing implementation is provided; scaffold is unfinished. Guided code is one case.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import platform
import subprocess
import sys

# CLI runtime and learner imports share one canonical module and exported types.
if __name__ == "__main__":
    sys.modules["fallback_lab"] = sys.modules[__name__]


class RoutingRuntime:
    def __init__(self, now=0, ledger=None, fallback_event=None):
        self.now = now
        self.ledger = copy.deepcopy(ledger or [])
        self.calls = []
        self.fallback_event = copy.deepcopy(fallback_event or {"kind": "draft", "text": "fixture draft"})

    def wait(self, units):
        if type(units) is not int or units < 0:
            raise ValueError("invalid_wait")
        self.now += units
        self.calls.append({"action": "wait", "units": units})

    def call_fallback(self, business_id, facts):
        self.calls.append({"action": "fallback", "business_id": business_id, "facts": copy.deepcopy(facts)})
        return copy.deepcopy(self.fallback_event)

    def lookup(self, business_id):
        self.calls.append({"action": "lookup", "business_id": business_id})
        matches = [r for r in self.ledger if r["business_id"] == business_id]
        return copy.deepcopy(matches[-1]) if matches else None

    def submit_write(self, business_id):
        """Deliberately non-idempotent fixture to expose replay; not a real external write."""
        receipt = {"business_id": business_id, "receipt_id": "receipt-" + str(len(self.ledger) + 1), "status": "committed"}
        self.calls.append({"action": "write", "business_id": business_id})
        self.ledger.append(receipt)
        return copy.deepcopy(receipt)

    def audit(self):
        return {"now": self.now, "calls": self.calls, "ledger": self.ledger}


REQUEST = {"business_id": "biz-77", "required_caps": ["tools", "json"], "deadline": 5, "max_model_calls": 2}
FACTS = [{"kind": "tool_result", "operation_id": "read-op-1", "data": "confirmed"}]
STATE = {"business_id": "biz-77", "write_state": "none", "receipt": None, "facts": FACTS, "used_calls": 1}
EVENT = {"kind": "rate_limited", "http_status": 429, "wait_units": 2}
RECEIPT = {"business_id": "biz-77", "receipt_id": "receipt-1", "status": "committed"}
TEMPLATE = '''def route(runtime, request, state, event, capabilities):
    """Return business_id/status/receipt/facts/reason/draft, with exactly those keys.
    Validate IDs and strict integer budgets before actions (bool is invalid).
    Preserve completed/unknown writes before considering another model call.
    Only the authored rate_limited/429 fixture permits fallback, at most once.
    No branch of this routing exercise may call submit_write.
    Return draft_ready for a fixture draft; it does not mean business completion.
    """
    raise NotImplementedError("implement route")
'''


def decision(request, state, status, reason, receipt=None, draft=None):
    return {"business_id": request["business_id"], "status": status, "receipt": receipt,
            "facts": copy.deepcopy(state["facts"]), "reason": reason, "draft": draft}


def case_data(name):
    req, state, event, caps = copy.deepcopy(REQUEST), copy.deepcopy(STATE), copy.deepcopy(EVENT), ["tools", "json"]
    now, ledger, fallback_event = 0, [], None
    status, reason, receipt, draft, actions = "draft_ready", "fallback_draft", None, "fixture draft", ["wait", "fallback"]
    if name == "invalid_parameters":
        event = {"kind": "invalid_parameters", "http_status": 400}
        status, reason, draft, actions = "permanent_error", "invalid_parameters", None, []
    elif name == "capability_missing":
        caps = ["tools"]
        status, reason, draft, actions = "capability_blocked", "missing:json", None, []
    elif name == "committed":
        state.update(write_state="committed", receipt=copy.deepcopy(RECEIPT))
        ledger = [copy.deepcopy(RECEIPT)]
        status, reason, receipt, draft, actions = "committed", "existing_receipt", copy.deepcopy(RECEIPT), None, []
    elif name in ("unknown_found", "unknown_missing"):
        state["write_state"] = "unknown"
        actions, draft = ["lookup"], None
        if name == "unknown_found":
            ledger = [copy.deepcopy(RECEIPT)]
            status, reason, receipt = "committed", "reconciled_receipt", copy.deepcopy(RECEIPT)
        else:
            status, reason = "reconcile_required", "receipt_not_found_is_not_proof_of_no_write"
    elif name in ("permission_denied", "safety_refusal"):
        event = {"kind": name}
        status, reason, draft, actions = "denied", name, None, []
    elif name == "deadline_exceeded":
        now = 4
        status, reason, draft, actions = "deadline_exceeded", "backoff_exceeds_remaining_time", None, []
    elif name == "budget_exhausted":
        state["used_calls"] = 2
        status, reason, draft, actions = "budget_exhausted", "model_call_budget_exhausted", None, []
    elif name == "fallback_unavailable":
        fallback_event = {"kind": "unavailable", "http_status": 429}
        status, reason, draft = "paused", "fallback_unavailable", None
    elif name == "changed_input":
        req["business_id"] = state["business_id"] = "order-909"
        state["facts"] = [{"kind": "tool_result", "operation_id": "stock-check-9", "data": {"quantity": 4}}]
        caps = ["json", "unused", "tools"]
        event["wait_units"] = 1
    elif name == "at_deadline":
        now = 3
    elif name == "other_failure":
        event = {"kind": "transport_error"}
        status, reason, draft, actions = "paused", "unsupported_failure", None, []
    elif name == "bool_budget":
        req["max_model_calls"] = True
        actions = []
    elif name == "mismatched_business_id":
        state["business_id"] = "wrong-business"
        actions = []
    elif name == "bool_deadline":
        req["deadline"] = True
        actions = []
    expected = decision(req, state, status, reason, receipt, draft)
    return req, state, event, caps, now, ledger, fallback_event, expected, actions


CASES = ["rate_limited", "invalid_parameters", "capability_missing", "committed", "unknown_found",
         "unknown_missing", "permission_denied", "safety_refusal", "deadline_exceeded", "budget_exhausted",
         "fallback_unavailable", "changed_input", "at_deadline", "other_failure", "bool_budget",
         "mismatched_business_id", "bool_deadline"]


def load_learner(path):
    spec = importlib.util.spec_from_file_location("learner_under_test", path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module.route


def grade_case(path, name):
    req, state, event, caps, now, ledger, fallback_event, expected, actions = case_data(name)
    originals = copy.deepcopy([req, state, event, caps])
    rt = RoutingRuntime(now, ledger, fallback_event)
    result, caught, errors = None, None, []
    try:
        result = load_learner(path)(rt, req, state, event, caps)
    except BaseException as exc:
        caught = exc
    invalid = name in ("bool_budget", "mismatched_business_id", "bool_deadline")
    if invalid:
        if not isinstance(caught, ValueError) or rt.calls:
            errors.append("invalid_input_must_raise_before_actions")
    else:
        if caught:
            errors.append("unexpected_exception:" + type(caught).__name__ + ":" + str(caught))
        if result != expected:
            errors.append("decision_contract_mismatch")
        actual_actions = [c["action"] for c in rt.calls]
        if actual_actions != actions:
            errors.append("actual_call_sequence_mismatch")
        expected_now = now + (event["wait_units"] if "wait" in actions else 0)
        if rt.now != expected_now or rt.now > req["deadline"]:
            errors.append("shared_time_budget_mismatch")
        for call in rt.calls:
            if call["action"] in ("fallback", "lookup", "write") and call["business_id"] != req["business_id"]:
                errors.append("business_id_changed")
            if call["action"] == "fallback" and call["facts"] != originals[1]["facts"]:
                errors.append("executed_facts_lost_or_changed")
            if call["action"] == "wait" and call["units"] != event["wait_units"]:
                errors.append("authored_backoff_policy_not_followed")
        fallback_count = sum(c["action"] == "fallback" for c in rt.calls)
        if state["used_calls"] + fallback_count > req["max_model_calls"]:
            errors.append("model_call_budget_exceeded")
    if rt.ledger != ledger or any(c["action"] == "write" for c in rt.calls):
        errors.append("routing_replayed_or_created_write")
    if [req, state, event, caps] != originals:
        errors.append("input_was_mutated")
    return {"case": name, "pass": not errors, "errors": errors, "result": result,
            "exception": None if caught is None else type(caught).__name__ + ":" + str(caught), "audit": rt.audit()}


def guided(variant="reference"):
    # Each walkthrough is fixed; neither implements the general learner route().
    req, state = copy.deepcopy(REQUEST), copy.deepcopy(STATE)
    if variant == "reference":
        rt = RoutingRuntime()
        rt.wait(2)
        response = rt.call_fallback(req["business_id"], state["facts"])
        result = decision(req, state, "draft_ready", "fallback_draft", draft=response["text"])
        checks = {"same_business_id": result["business_id"] == "biz-77",
                  "facts_preserved": rt.calls[-1]["facts"] == FACTS, "no_write": not rt.ledger,
                  "bounded_calls": len([c for c in rt.calls if c["action"] == "fallback"]) == 1}
    else:
        state.update(write_state="committed", receipt=copy.deepcopy(RECEIPT))
        rt = RoutingRuntime(ledger=[RECEIPT])
        if variant == "broken":
            rt.submit_write("biz-77-retry")  # Deliberate reset/replay after a 429 fixture.
            response = rt.call_fallback("biz-77-retry", [])
            result = decision(req, state, "draft_ready", "fallback_draft", draft=response["text"])
        else:
            result = decision(req, state, "committed", "existing_receipt", receipt=state["receipt"])
        checks = {"one_effect": len(rt.ledger) == 1,
                  "same_receipt": result["receipt"] == RECEIPT,
                  "no_new_model_or_write": not rt.calls,
                  "facts_preserved": result["facts"] == FACTS}
    return {"scenario": "guided_429" if variant == "reference" else "guided_committed_then_429",
            "time_basis": "integer_logical_time", "provider_calls": 0, "variant": variant,
            "checks": checks, "pass": all(checks.values()), "result": result, "audit": rt.audit()}


def grade(path):
    cases = []
    for name in CASES:
        try:
            run = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--mode", "grade-case",
                                  "--learner", str(Path(path).resolve()), "--case", name],
                                 text=True, capture_output=True, timeout=5)
            row = json.loads(run.stdout.splitlines()[-1])
            row["worker_exit_code"] = run.returncode
            if run.returncode != (0 if row.get("pass") else 1):
                row["pass"] = False
                row["errors"].append("worker_exit_code_mismatch")
        except (subprocess.TimeoutExpired, ValueError, IndexError) as exc:
            row = {"case": name, "pass": False, "errors": ["worker_failed:" + type(exc).__name__]}
        cases.append(row)
    return {"mode": "grade", "time_basis": "integer_logical_time", "provider_calls": 0,
            "worker_timeout_seconds": 5, "worker_timeout_purpose": "hang_guard_not_performance_gate",
            "python": platform.python_version(), "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "learner_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(),
            "module_sha256": hashlib.sha256(Path(path).read_bytes()).hexdigest(), "module_path": str(Path(path).resolve()),
            "passed": sum(c["pass"] for c in cases), "total": len(cases),
            "pass": all(c["pass"] for c in cases), "cases": cases}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("command", nargs="?", choices=["guided", "scaffold", "incident", "explain", "grade"])
    parser.add_argument("--mode", choices=["reference", "template", "debug", "grade", "grade-case"])
    parser.add_argument("--variant", choices=["broken", "repaired"], default="broken")
    parser.add_argument("--learner", "--module", dest="learner")
    parser.add_argument("--case", choices=CASES)
    parser.add_argument("--out")
    args = parser.parse_args()
    modes = {"guided": "reference", "scaffold": "template", "incident": "debug", "explain": "debug", "grade": "grade"}
    if args.command:
        if args.mode:
            parser.error("use a command or --mode, not both")
        args.mode = modes[args.command]
        if args.command == "explain":
            args.variant = "repaired"
    if args.mode is None:
        parser.error("choose guided/scaffold/incident/explain/grade")
    if args.mode == "template":
        if not args.out:
            parser.error("template requires --out")
        path = Path(args.out)
        if path.exists():
            parser.error("refusing to overwrite learner file")
        path.write_text(TEMPLATE, encoding="utf-8")
        result = {"mode": "template", "path": str(path), "pass": True}
    elif args.mode in ("reference", "debug"):
        result = guided("reference" if args.mode == "reference" else args.variant)
    else:
        if not args.learner or (args.mode == "grade-case" and not args.case):
            parser.error("grade requires --learner; grade-case also requires --case")
        result = grade_case(args.learner, args.case) if args.mode == "grade-case" else grade(args.learner)
    output = json.dumps(result, ensure_ascii=False, sort_keys=True)
    if args.out and args.mode != "template":
        Path(args.out).write_text(output + "\n", encoding="utf-8")
    print(output)
    return 0 if result["pass"] else 1


if __name__ == "__main__":
    sys.exit(main())

有界退避与幂等前提;Function calling关联;实训源码。

逐步实例:一次429、三道门与一份草稿

图解 · 为biz-77发起降级调用前逐项判断

为biz-77发起降级调用前逐项判断

编写的窄引导演练,提供商调用为零。此分支须先完成校验与写状态对账。逻辑时间和夹具响应不能衡量真实网络截止时间。 点图可打开原图放大查看。

这是在RoutingRuntime上实际执行的窄分支引导,不是学员独立解答,也不是真实模型响应。前置条件:身份和严格整数预算已校验;write_state=none;永久失败、committed/unknown写已按下文有序协议处理。输入为business_id=biz-77、required_caps=['tools','json']、used_calls=1、max_model_calls=2、deadline=5、now=0、event={kind: rate_limited, http_status: 429, wait_units: 2}。保留事实为{kind: tool_result, operation_id: read-op-1, data: confirmed}。business_id标识业务动作,operation_id关联已执行证据,不能拿它替换业务身份或提供商call ID。

第1步:能力只有['tools']时,排序后缺失项为['json'];返回capability_blocked/missing:json,calls []、now0、ledger []。第2步:恢复两项能力,但令used_calls=2;共享额度已用完,返回budget_exhausted/model_call_budget_exhausted,calls []。备用模型名称不同,并不产生一份新额度。第3步:恢复used_calls1,但从now4开始;4+2>5,所以在等待前返回deadline_exceeded/backoff_exceeds_remaining_time,calls []、now4。

原始now0/used_calls1且能力齐全时,0+2≤5,实际只执行wait(2)和call_fallback('biz-77', facts)。审计动作依次wait、fallback,now2,账本无行。结果是draft_ready/fallback_draft,receipt=None、draft='fixture draft'且facts不变。主模型已用1次加降级1次等于总额度2;函数不改写state.used_calls。如果这唯一备用返回unavailable,相同两次动作后停在paused/fallback_unavailable,不能继续第三次模型尝试。这里只得到草稿,并未证明业务完成。

具体反例:先调用备用、事后才检查能力,禁用的调用已经花出去了;切换备用时清零used_calls同样突破共享预算。invalid_parameters/400、权限拒绝与安全拒绝也不能进入这条429分支。声明的能力只通过夹具门槛,不能证明真实适配器或模型能完成任务。

实际窄引导源码、实际调用、输入与输出、未改运行时。两份Python文件放同目录运行python3 -B guided_depth_trace.py > guided-depth-output.json。该引导没有调用case_data,期望值本身不算执行。提供商调用为零,不能证明真实429处理、网络延迟、模型质量或学员17例通过。夹具里的备用响应耗时为零,恰好等于deadline也不构成真实HTTP时间保证。

接入同一实战:备用继承同一退货事实

Harness 连续实战把 fallback 接进真实退货路径:人工预设的主模型 429 进入有界备用,保留任务与业务身份、实际工具事实;候选仍须经过证据、提案、审批,商家才能写入。先读路由走读,下载源码。

运行 python3 -B journey.py scenario --name fallback_blocked --work /tmp/journey-fallback。权限拒绝、模型拒绝、永久参数错误、能力不足、额度或期限耗尽,都不能转化成换模型的许可。写入 unknown 后应按原操作键核对,不能让新模型再创建一次操作。这些是人工编写的离线决定,provider calls 为零。

继续阅读连续项目文章,对照可执行源码入口。

代码示例

实际路由调用验收

模板0/17退出1;本人route需17/17。grader检查真实wait/fallback/lookup参数及账本,而不是只读取成功字段。

本层验收任务

独立实现route;保留模板0/17失败,再提交本人模块17/17及实际calls/ledger和module/source SHA。

逐条验收自评

正在读取此浏览器记录…

收起答案,检查理解

返回draft_ready但没调用fallback,验收器会通过吗?

延伸原理与知识练习

遇到不熟悉的原理,先阅读实现、连续追问和迁移案例,再独立说明前提与边界。作答与笔记保存到原有账号记录。

本专题的全部关联解析与练习(1 道)

依据与验证范围

原理依据来自公开资料;数字、案例和任务是本站教学设计。离线实验验证本页注明的范围,学习效果仍需通过独立任务与反馈判断。