Chapter 09 · Domain 1(本章 skill 权重合计 4.9%)
Agent 模式与框架先画 control flow,再决定 loop、delegation、memory 与框架
TS 1.3 考的是 agent pattern 与 framework 的适配,不是 API 函数背诵。本章先推导 tool-use loop、subagents、memory 与 context-window management 的职责,再用同一组选择轴比较 Strands、LangGraph 与 PydanticAI。
一、Tool-use loop:模型提议,应用执行,结果回到下一轮
最小 agent loop 不是「让模型一次答完」,而是一个可重复的控制环:应用把目标与当前状态交给模型;模型或者给出 final response,或者请求调用 tool;应用执行 client tool,把结果作为新证据回传,然后再调用模型。Claude 的 client-tool 往返正是 stop_reason: "tool_use" / tool_use → 应用执行 → tool_result;client tool 与 server tool 的执行者也不同,不能把结构化调用误当成已完成的副作用。
state = initial_goal
repeat until budget exhausted:
response = model(state)
if response is final: return response
validate requested tool and arguments
result = execute tool with timeout and idempotency guard
append request + result to state
return controlled_failure
Strands 的官方描述也把 agent loop 收成同一原则:调用模型、检查是否要用 tool、执行后带 result 再调用,直到 final response。框架可以封装循环,但不会替开发者决定生产边界;max turns、tool-call / time / cost budget、timeout、retry policy、idempotency 与审计字段仍应显式进入 loop contract。这里的 P3 是「真的能停、能拒绝、能追踪」,而不是 prompt 里一句“请勿失控”。
Loop seam 应用要能回答 失败时的受控结果
Model decision 这是 final response 还是 tool request? 未知 response shape 不执行副作用
Tool boundary 名称、arguments、authority 是否通过 schema 与 policy? 拒绝或把有界错误作为 result 回传
Iteration budget 还剩多少 turns、time、tokens 与 money? 停止并返回可诊断的 budget exhaustion
Side effect 重试是否会重复扣款、发信或改状态? 用 idempotency key 或人工恢复路径收口
二、Subagents:先证明分工边界,再支付协调成本
子代理(subagent)适合有清晰专业边界、可并行证据面或需要隔离工作上下文的任务。parent agent 不应只发一句「帮我研究」;delegation contract 至少给出目标、输入边界、允许的 tools / sources、budget、完成条件与返回 schema。delegate 返回的是待整合的 evidence,不是自动取得更高可信度的结论。
任务形状 优先模式 理由 常见误用
步骤短、共享状态多、每一步强依赖上一轮 单 agent + tool-use loop 状态不必跨边界复制,trace 最短 按 tool 数量拆 agent,制造 handoff
证据面独立,可同时检索、测试或审查 并行 subagents + parent synthesis 以独立结果换 wall-clock,parent 统一裁决冲突 让多个 agent 同时写同一 mutable artifact
任务需不同 authority 或 context 隔离 有界 delegation 每个 agent 只拿完成职责所需的最小能力与上下文 把全部 secrets、history 与 tools 广播给每个 agent
固定 business stages,需可复现 transition 显式 workflow / graph 由应用保存状态与下一步规则,模型只处理适合判断的节点 让自由 handoff 代替确定性业务规则
还要先辨认 control handback。PydanticAI 文档中的 agent delegation 是 delegate 完成后把控制权交回 calling agent;Strands 对 Graph、Swarm、Workflow 的比较则把「execution path 如何确定」列为关键差异。考试场景若规定 parent 负责复核、汇总或继续后续步骤,就选能回到 parent 的 delegation;若强调固定 transition,就别用更自由的协作形态掩盖 control-flow requirement。
P10 的拆分门槛 — 只有当 specialization、parallelism、authority isolation 或 context isolation 的收益大于 coordination、duplicate work 与 conflict resolution 成本时,subagent 才比单 loop 更合适。
三、Memory 是读写协议;context window 是每轮预算
作为 agent pattern,memory 要回答三件事:记什么、记在哪、何时读回 。Claude Messages API 本身是 stateless,应用每次请求都要提供完整 conversational history;因此跨调用 state 的持久化、筛选与重新组装属于应用或 agent framework,而不是服务端自动替你保管的隐式会话。
Memory layer 存什么 何时读回 写入 gate
Working state 当前 goal、plan、尚未解决的问题、最近 tool results 当前 loop 的每次必要决策 只保留仍影响下一步的状态
Task / episodic memory 已完成步骤、artifact pointer、失败与恢复点 resume、retry 或 parent synthesis 时 带 task namespace、时间与来源
Durable semantic memory 经批准的用户偏好、稳定 domain facts、长期约束 新任务确实匹配 scope 时检索 校验来源、权限、TTL 与可删除性
Strands 把 loop 中累积的 conversation history 称为任务 working memory,并说明 conversation manager 会在保留相关信息的同时把 history 控制在 context window 内。这揭示了 memory 与 context 的边界:memory store 可以比一次调用大得多,但每轮 context 只能装当前决策需要的 evidence。合理模式是从外部 memory 检索有来源的少量记录,与当前 goal、最近 tool result 和必要 summary 组装本轮输入;不是把整个 history 仓库反复塞回 prompt。
P4 先决定状态应住在 current messages、workflow state 还是 durable store;P9 再管理被选入本轮的内容。ch09 只定义这条 read / write / retrieve pattern;pruning、compaction 与 context drift 的具体工程手法留到 ch11。
四、三种框架:比较 control ownership,不背函数名
Exam Guide 以 “e.g.” 点名 Strands、LangGraph、PydanticAI,意味着它们是 agentic abstraction framework 的例子,不是封闭清单。选型时把同一个 workload 沿 control flow、state lifetime、type boundary 与 operational recovery 对表;不要因为 framework 名出现在题干就自动选择它。
Framework 官方定位所揭示的抽象重心 更匹配的问题形状 选择前要证明
Strands 以 model → tool → result → model 的 agent loop 为中心;多 agent 形态按 execution path 如何确定来区分 核心是 model-driven tool use,希望从直接 loop 起步,再按 path ownership 选择协作形态 tool boundary、iteration budget 与 path ownership 是否足够明确
LangGraph 面向 long-running、stateful agents 的 low-level orchestration;同一 graph 可混合 deterministic 与 LLM-driven steps 状态 transition、resume point 与可审计的确定性步骤是问题主体,同时少数节点需要模型判断 团队是否真的需要并愿意维护显式 state graph
PydanticAI typed、extensible 的 Python agent loop;支持把 delegate agent 当作有返回控制权的协作单元 Python 服务把 type contract 当主要边界,并希望从单 agent 逐步加入 delegation type safety 与 Python integration 的收益是否高于引入框架的成本
LangGraph 官方定位明确强调 low-level、long-running 与 stateful,也明确强调在一个 graph 中混合 deterministic 与 agentic steps;因此它的强项与代价来自同一个地方:开发者取得更细 control,也要拥有更多 orchestration state。PydanticAI 的定位强调 typed、extensible Python agent loop;若题干的主要约束是 Python type boundary,它才是相关杠杆。Strands 则适合从 loop 与 execution-path ownership 推导。三者都不能代替需求分析、权限边界或 eval。
五、从场景推导:先选 pattern,再验证 framework fit
把选型压缩成五问:任务是否需要多轮 tool evidence?子任务是否真能独立并行或隔离 authority?状态要活多久、由谁持久化?哪些 transition 要保持 deterministic?Python type contract、显式 graph 或 model-driven loop,哪一个才是主要约束?答案先决定 pattern,framework 只是承载该 pattern 的候选。
题干信号 先推导的 pattern 候选落点
一次请求内反复查库存、报价,拿到足够 evidence 即停止 有预算与 tool boundary 的单 agent loop custom loop 或 Strands;先选更薄的实现
流程跨数小时,可从 checkpoint 恢复;合规步骤固定,分析步骤由模型判断 long-running state graph,deterministic / agentic 分节点 LangGraph 的定位最贴合
现有 Python 服务以 typed domain models 交接,先做单 agent,后续才可能 delegation typed loop,保持渐进式复杂度 PydanticAI 的定位更相关
四个独立数据源可并行核验,最终由一个 owner 解决冲突 有界 subagents + parent synthesis 先定义 delegation contract,再选支持该 control flow 的框架
最后做一个 thin spike:用同一真实任务测 completion quality、tool errors、turns、token / time cost、resume behavior 与 trace readability。若单 loop 已过 gate,就保留较薄抽象;若失败集中在 state transition、delegation 或 type boundary,再引入直接解决该失败面的 framework。这个顺序把 P1 与 P10 合在一起:按约束选最小充分结构,而不是先买复杂度再寻找理由。
考点回链 — 本章覆盖:TS 1.3(tool-use loops、subagents、memory 的 write / store / retrieve pattern、context-window management,以及 Strands、LangGraph、PydanticAI 的 abstraction fit)。相邻考点:workflow vs. agent、Agent SDK、managed deployment 与 hooks 见
ch08 ;pruning、compaction、drift 与 subagent context isolation 的具体 context-engineering 手法见
ch11 ;tool schema 与 dispatch 实现见
ch12 。
本章题组
QUESTION 01 · TS 1.3 · TOOL-USE LOOP
A refund agent's first model response has stop_reason: "tool_use" and requests the client tool lookup_order. No order lookup has run yet. The service has a six-turn budget and the tool may time out. What should the developer implement next?
A Treat tool_use as completed, render the refund, and retain the tool request as audit evidence for any later dispute.
B Send the unchanged tool_use block back to Anthropic and wait for the service to call the company's private order API, treating every client tool as a server tool once its schema is accepted.
C Treat tool_use as a pending client action: validate input and authorization, execute it, return the matching tool_result, and call the model again until a final response or the six-turn limit.
D Decompose the flow into planner, tool-runner, timeout-reviewer, and answer-writer agents, using typed handoffs and a parent coordinator to isolate failures, assign retry ownership, and keep each role's context narrowly scoped.
正确 C tool_use 是执行请求,不是执行结果。应用先校验并运行 client tool,再用 tool_result 进入下一轮;final response 与 six-turn budget 都是明确 stop condition。
D6 半对半错 违反 P5 A :结构化 request 确实存在,但它没有证明 lookup 或 refund 已发生;把 request body 当 result 偷换了机制职责。
D1 凭空捏造 违反 P5 B :client tool 由应用执行,schema 被接受不会把私有 API 自动变成 Anthropic 执行的 server tool。
D7 过度工程 违反 P10 D :题干只有一个已知 loop seam,没有证据表明四个 subagents 能改善正确率或恢复性;它先增加协调边界。
QUESTION 02 · TS 1.3 · SUBAGENT FIT
A release check must inspect four independent repositories. Each read-only inspection takes about eight minutes, the final decision must arrive within twelve minutes, and only one owner may edit the release record. Which design best fits these constraints?
A Inspect the four repositories sequentially with one agent and let it write each result directly to the release record.
B Run four scoped read-only subagents in parallel; require one evidence schema from each, then let only the parent resolve conflicts and write the release record.
C Run four agents in parallel and give every agent write access to the same release record, allowing whichever finishes first to publish while the others append corrections concurrently.
D Deploy an autonomous swarm with unrestricted repository and production credentials, no per-agent completion contract, and no parent synthesis because agent collaboration itself guarantees a consistent final decision.
正确 B 四个 evidence 面彼此独立且 sequential time 已超 SLA,适合并行;统一 return schema 与 single-writer parent 又守住冲突裁决和唯一写 owner。
D2 无关杠杆 违反 P1 A :single writer 是真实约束,但不要求 read phase 也串行;32 分钟直接越过 12 分钟 gate。
D6 半对半错 违反 P1 C :并行检查满足 latency,但把唯一写 owner 变成 concurrent writers,只通过了一半约束。
D7 过度工程 违反 P10 D :题干只需要四个有界并行检查与一次 synthesis;unrestricted swarm 增加 authority 和协调成本,还丢掉明确 owner。
QUESTION 03 · TS 1.3 · MEMORY LIFECYCLE
A stateless Messages API service must remember an approved user's preferred report format across sessions, while keeping each request's temporary investigation plan task-scoped. Which memory design is most appropriate?
A Persist the approved preference under a user-scoped key with source metadata; keep the investigation plan in task state, retrieve only relevant records per call, and expire the task state separately.
B Store neither value because the Messages API automatically retains every user's conversation state across calls and will distinguish durable preferences from temporary plans without application code.
C Maintain a user-level transcript archive and prepend every prior session to each request, allowing the model to recover durable preferences and task history directly without a separate retrieval index.
D Put both values in a global system prompt loaded on each request, using prompt position to persist and isolate them across tenants.
正确 A Messages API 是 stateless,所以应用拥有 state lifecycle。durable preference 与 task plan 依据 scope 分层保存,再按当前任务检索,分别回答「记在哪」和「何时读回」。
D1 凭空捏造 违反 P5 B :API 不会自动保留跨调用会话,也不会替应用区分 durable 与 task-scoped memory。
D5 错层承载 违反 P9 C :durable store 可以保留历史,但每轮 context 只该读取相关记录;全量 transcript 把预算当仓库。
D5 错层承载 违反 P4 D :tenant-scoped durable state 与 task state 都不该住在全局 prompt;共享载体还破坏 scope。
QUESTION 04 · TS 1.3 · CONTEXT-WINDOW MANAGEMENT
After 60 tool turns, an incident agent spends 70% of its input tokens on old raw logs. Verified findings and artifact locations are already stored in task state, but two unresolved constraints still affect the next decision. What should the loop assemble for the next call?
A Keep only the latest user request so the compact prompt leaves the model room to reconstruct the prior tool-loop state.
B Keep all 60 turns and move to the largest available context window, treating additional capacity as proof that raw tool output no longer has an attention or token-budget cost.
C Spawn a new subagent but send it the complete 60-turn transcript plus every raw log, assuming a separate agent identity creates context isolation without reducing the supplied context.
D Assemble the current goal, both unresolved constraints, verified findings, and artifact pointers; keep raw logs outside the prompt and rehydrate only by relevant pointer.
正确 D working context 保留当前决策所需的 goal、未决约束和已验证结论;raw logs 仍可按 pointer 取回,却不必每轮重复消费 context。
D6 半对半错 违反 P9 A :减少旧内容方向正确,但删掉仍影响下一步的约束会让 agent 丢失必要状态;预算管理不是无差别清空。
D2 无关杠杆 违反 P9 B :更大 window 没有让 70% 的旧日志变得相关,也没有消除 token 与 attention 成本。
D6 半对半错 违反 P9 C :subagent 可用于 isolation,但复制同一份完整 transcript 没有隔离任何 context;身份变化不是 pruning。
QUESTION 05 · TS 1.3 · STRANDS FIT
A TypeScript prototype has three client tools and needs a model-driven loop that chooses a tool, consumes its result, and stops with a final answer. Jobs finish within 20 seconds; there is no resume requirement or predefined state graph. Which framework direction is the best first fit?
A Start with a thin Strands spike for the model-driven tool path; keep explicit tool and turn budgets, and compare its measured gates with the direct loop before adding workflow state.
B Use LangGraph to represent tool selection, result handling, and finalization as explicit state transitions, adding checkpoints and resume support as an operational foundation for tracing retries and future workflow growth.
C Rewrite the service in Python to adopt PydanticAI, so every agent step gains first-class typed models and validated outputs end to end.
D Integrate Strands, LangGraph, and PydanticAI simultaneously and compare their answer by majority vote on every request, before measuring whether the direct tool loop meets any acceptance gate.
正确 A 题干的主要形状就是 model → tool → result → model,且无 long-running graph 约束;先用贴合 loop 的薄实现验证,符合 P1 与 P10。
D2 无关杠杆 违反 P1 B :LangGraph 的 stateful graph 是真实定位,但题干没有持久 transition 或 resume constraint。
D2 无关杠杆 违反 P1 C :typed Python loop 是 PydanticAI 的相关定位,却不是本题的约束;语言重写还引入额外迁移面。
D7 过度工程 违反 P10 D :三个 framework 的 per-request ensemble 不解决已知的 loop fit,且在 thin spike 尚未失败前增加三套集成。
QUESTION 06 · TS 1.3 · LANGGRAPH FIT
An insurance workflow can run for eight hours. Eligibility and approval transitions must be deterministic and auditable, one analysis node is LLM-driven, and the process must resume after a worker restart. Which framework best matches this problem shape?
A Use Strands for the model-driven analysis node and express eligibility and approval routing through agent tools plus conversation state, keeping one model-directed loop with centralized tool traces and retry policies.
B Use PydanticAI so typed Python models serve as the workflow-state contract, relying on validated agent outputs and serialized run records to provide recovery, auditability, and deterministic transitions over the eight-hour process.
C Use one unbounded chat loop and replay the full eight-hour transcript after every restart, storing workflow position only in prose so no explicit orchestration state has to be maintained.
D Use LangGraph to model persisted state and explicit transitions, keeping required steps deterministic and the analysis node agentic.
正确 D long-running、stateful orchestration 与 deterministic / agentic steps 混合,逐条对应 LangGraph 的定位和题干约束。
D6 半对半错 违反 P1 A :tool-use loop 能承载 analysis node,但把所有 transition 留给 conversation 未满足 deterministic、audit、resume 三条硬约束。
D1 凭空捏造 违反 P5 B :type annotation 不会自动产生 durable workflow state 或 deterministic transition;它把真实的 typing 定位扩成了未证明职责。
D5 错层承载 违反 P4 C :可恢复的 workflow position 应住在显式 state,而不是只靠长 transcript 中的 prose 暗示。
QUESTION 07 · TS 1.3 · PYDANTICAI FIT
A Python service already exchanges typed domain models at every boundary. Its agent jobs finish in under 30 seconds, require no persisted graph, and may later delegate one bounded research task before returning control to the parent. Which choice best matches the stated shape?
A Adopt LangGraph and represent every typed domain boundary as a persisted state node, using graph checkpoints to standardize the future research handoff and preserve an auditable transition history.
B Use PydanticAI: its typed Python agent-loop focus matches the main boundary, and its delegation model can return control to the parent.
C Select Strands and expose the bounded research task as a tool, using its model-driven loop to coordinate the lookup and return a synthesized result to the parent.
D Use a dependency-light custom loop that converts the service's typed domain models to JSON dictionaries for each agent step and validates the assembled result once at the outer boundary.
正确 B 本题的 dominant constraint 是 typed Python boundary,且未来协作仍要回到 parent;PydanticAI 的官方定位与 delegation 语义正对这两条。
D7 过度工程 违反 P10 A :题干没有 long-running state、resume 或复杂 transition,按每个 type 造 graph node 是先买复杂度。
D6 半对半错 违反 P1 C :tool loop 是真实需求的一部分,但它没有覆盖题干唯一强调的 typed service boundary。
D2 无关杠杆 违反 P1 D :减少 dependency 并非题干目标,反而主动拆掉明确的 typed integration contract。
QUESTION 08 · TS 1.3 · LIGHTEST SUFFICIENT ABSTRACTION
A 40-line custom loop with two client tools passes 99.4% of the frozen eval set, stays below the 500 ms p95 gate, and records every tool request and result. The product needs no subagents, cross-session memory, or resume. A framework spike adds 90 ms without improving pass rate. What should the developer ship?
A Replace the loop with LangGraph because a low-level orchestration framework always provides more useful control, regardless of the measured latency regression and absent state-graph requirement.
B Adopt PydanticAI with three typed subagents for evaluation, tool execution, and verification, establishing explicit delegation contracts, independent traces, and role-specific contexts that can absorb later decomposition without redesign.
C Ship the bounded custom loop that passed all gates; retain its trace and evals, and revisit frameworks when a new requirement creates a real abstraction gap.
D Move to a Strands loop and remove explicit turn and tool policies because reaching a framework-managed final response guarantees that every runaway or unauthorized action is prevented.
正确 C custom loop 已通过 quality、latency、trace 三条 gate,且没有复杂 pattern requirement;保留最小充分结构,并以未来真实 gap 触发重选。
D2 无关杠杆 违反 P1 A :更细 graph control 不是本题目标,实测只带来 90 ms regression,也没有改善 pass rate。
D7 过度工程 违反 P10 B :为没有出现的 future delegation 预建三 agent 系统,跨过了已经过线的轻量实现。
D6 半对半错 违反 P3 D :Strands 确实封装 agent loop,但 final response 不等于 enforceable turn、tool 或 authority control;删除硬边界使系统更弱。