长时运行智能体与持久化执行
原题Long-horizon agents and durable execution
推荐理由持久化执行文章用补货智能体说明故障后的重放、外部交互记录和并发边界;读者可把长任务可靠性从提示词问题还原为运行时与状态模型的设计选择。
读前速览
本文探讨持久化执行模式如何通过保存状态、处理故障并从中断中平稳恢复,帮助长时运行的 AI 智能体在较长时间内可靠地管理复杂的多步骤流程。
持久化执行通过保存状态并从已记录的步骤开始重放,使长时运行的智能体能够从故障中恢复。
每次与外部世界的交互都会作为一个步骤记录下来,并保存其输入和输出。因此,发生崩溃或中断后,智能体可以从最近完成的步骤继续运行,确保持续数天的流程能够延续。
智能体循环由目标、工具、状态和模型构成;工具分为步骤(外部交互)和非步骤(本地状态操作)。
只有与外部世界的交互会经过持久化运行时;像「allowed」和「apply」这样用于处理内部逻辑的方法,会在每次重放时运行,以高效重建状态。
长时运行的智能体会遭遇进程崩溃、API 故障、并发冲突和外部环境变化等独特故障模式。
这些挑战需要在执行框架层显式处理。持久化执行提供活动日志、超时和等待条件等基本机制,帮助管理各种不确定性。
实体工作流在业务实体的整个生命周期内管理该实体,流程工作流则处理单项任务,二者与 Actor 模型的模式相似。
这种区分能够以可扩展的方式管理持久存在的实体(例如 SKU),并让它们在生命周期内创建和监管流程工作流(例如补货订单)。
完整摘要
本文探讨持久化执行这一关键模式,说明它如何帮助长时运行的 AI 智能体应对可能持续数天或数周、且难以预测的多步骤流程。持久化执行是一种编程模型:运行时会记录每次与外部世界的交互,使智能体在发生故障时能够从最近记录的步骤开始重放并恢复。文章以库存补货智能体为例,详细介绍由目标、工具、状态和模型构成的智能体循环,并解释进程崩溃、API 故障和并发问题等分布式系统故障如何中断长时间运行的工作流。文章将持久化执行与预写日志和事件溯源进行比较,并展示 Temporal 和 Cloudflare Workflows 如何通过活动、等待条件和重放机制实现这一模式。文章还区分了处理单个任务的流程工作流,以及在业务实体整个生命周期内管理 SKU 等对象的实体工作流,并将后者与 Erlang 的 Actor 模型进行类比。
目录 · 27 节
几十年来,企业一直围绕人类注意力的稀缺性来设计运营方式。如果一项任务需要占用某人几周时间,只有在回报足以抵偿投入时,才会去做。长周期智能体¹从根本上改变了这种经济格局,让过去不具备经济可行性的工作变得可行。For decades, businesses have designed their operations around the scarcity of human attention. If a task needed someone's time for weeks, it was done only when the return paid for it. Long-horizon agents1 fundamentally change that economics by making previously uneconomical work viable.
1:这里的“长时间跨度”并不是指智能体在不间断的情况下能够持续处理任务多久;后者是前沿模型常用的基准指标之一。1: Here, “long horizon” does not refer to how long an agent can continue working on a task without interruption, which is one of the commonly used benchmark numbers for frontier models.
想想那些因为没人协助完成新手引导而流失的客户:长周期智能体可以耐心地引导他们完成整个流程,让过去只有高价值客户才能享受到的个性化帮助惠及更多人。再想想那些在销售、法务和采购部门之间的衔接缝隙中流失的收入:智能体可以协调各项依赖事项,推动交易达成。还可以想想那些因医疗机构缺乏足够人手、无法引导患者处理各项行政事务而得不到充分护理的患者:智能体可以通过跟进转诊、预约、改期和提交文书来提供帮助。如今,企业中充满了这样的机会。Think of customers who churned because no one helped them through onboarding; long-horizon agents can patiently guide them through it, with personal help previously reserved only for high-value customers. Think of revenue lost in the cracks between sales, legal, and procurement: an agent can shepherd those deals through dependencies to closure. Think of patients missing adequate care because healthcare organizations lack the bandwidth to guide individuals through administrative dependencies; agents can help by tracking referrals, booking appointments, rescheduling, and filing paperwork. Enterprises today are full of such opportunities.
传统软件可以自动化可预测的流程,但这些任务完全无法预测。如今,即使通往目标的路径难以预测,长时程智能体也能自动化地追求这类目标。Traditional software can automate predictable processes, but these tasks are anything but predictable. Long-horizon agents can now automate the pursuit of outcomes in such cases even when the path to those outcomes is unpredictable.
最简单的情况下,智能体会接收用户输入,决定采取什么行动,执行该行动,然后回复用户。我们可以将其视为一个回合。长期运行的智能体通常会在较长时间内进行许多这样的回合,以实现目标。例如,向供应商订购库存的智能体可能会先向供应商询价,等待两天让经理批准价格,随后下单,再等待三周让货物送达。在此期间的大部分时间里,智能体都在等待人员和外部系统的响应,而其间可能会出现许多问题。智能体的进程可能会重启,供应商的电话可能无法接通,消息也可能延迟、重复或遗漏。In its simplest form, an agent listens to a user's input, decides on an action, executes it, and responds to the user. Consider this a single turn. Long-horizon agents typically use many such turns over a longer period to accomplish their goal. For example, an agent ordering stock from a supplier may get quotes from suppliers, wait two days for a manager to approve the price, place the order, and then wait three weeks for the goods to arrive. Much of that time is spent waiting on people and external systems, and a lot can go wrong in the meantime. The agent's process may restart, supplier calls may fail, and messages may be delayed, duplicated, or missed.
持久化执行是一种新兴模式,可帮助智能体从这些故障中恢复并继续追求目标。Durable execution is an emerging pattern that helps agents recover from these failures and pursue their goals.
需要数周才能完成的工作Work that takes weeks
贯穿示例The running example
采购相关术语Terms from purchasing
SKU(库存单位):指一种单独库存商品,例如特定尺寸的零件。SKU (stock-keeping unit): one distinct item that is kept in stock, such as a part in a given size.
安全库存:为应对需求和供应商交货周期的变化而预留的库存。当库存低于这一水平时,就该重新订货了。Safety stock: stock held in reserve against changes in demand and in the supplier's lead time. When stock falls below it, it is time to reorder.
采购订单(PO):买方向供应商下达的订单,其中注明商品、数量、价格和交货日期。Purchase order (PO): the buyer's order to a supplier, with the item, quantity, price and delivery date.
我们的贯穿示例是 Stock Replenisher,也就是上文提到的库存订购代理,它负责确保制造商的零部件库存充足。当某个零部件的库存低于安全库存时,该代理便会尝试补货。它会获取报价、选择供应商、请采购经理批准价格、下订单,并持续跟进,直至货物送达。Our running example is Stock Replenisher, the stock-ordering agent from above, which keeps a manufacturer's parts in stock. When a part falls below its safety stock, the agent attempts to replenish it. It gets quotes, chooses a supplier, asks the procurement manager to approve the price, places the order, and follows it until the goods arrive.
整个过程按实际耗时可能需要几天或几周。其中大部分时间都花在等待经理批准、供应商回复和货物送达上。与此同时,情况也可能发生变化:供应商可能在下单后涨价、提出问题,或者完全不予回复。代理必须在每种情况出现时妥善处理。This can take days or weeks in elapsed time. Most of it involves waiting for the manager's approval, the supplier's response, and the delivery of goods. Meanwhile, things change: the supplier may raise the price after the order is placed, ask a question, or not answer at all. The agent has to handle each case as it arises.
以下是一次补货流程从缺货到货物送达的运行过程。较长的时间段是等待,智能体的操作则是间隔其中的短暂步骤。点击标记即可查看发生了什么,或使用右上角的箭头逐步查看整个流程。Here is one replenishment as it ran, from the shortage to the goods arriving. The long stretches are waits; the agent's steps are the short bursts in between. Click a mark to see what happened, or use the arrows at the top right to step through the run.
智能体循环The agentic loop
大多数智能体——从 Claude Code 这样的编程智能体,到 OpenClaw 这样的个人助理——都围绕同一个循环构建,通常称为智能体循环。它由四个部分组成:Most agents, from coding agents such as Claude Code to personal assistants such as OpenClaw, are built around the same loop, usually called the agentic loop. It has four parts:
- 目标:我们希望智能体实现的结果。对于编程智能体来说,这可能是要编写的程序;对于库存补货员来说,则可能是需要保持库存充足的零件。a goal: the outcome we want the agent to achieve. For a coding agent, this might be a program to write; for Stock Replenisher, a part kept in stock.
- 智能体借以在现实世界中采取行动的工具。对于编程智能体,可以是 read_file、edit_file 和 bash;对于 Stock Replenisher,则可以是 get_quotes 和 place_order。tools through which the agent acts in the world. Think of
read_file,edit_file, andbashfor a coding agent;get_quotesandplace_orderfor Stock Replenisher. - 状态:代理目前为实现目标所知的一切进展信息。state: everything the agent knows about its progress toward the goal so far.
- 一种在每一轮都查看当前状态,并选择下一步使用哪个工具以及传递什么内容给它的模型。a model that, at each turn, looks at the current state and chooses which tool to use next, and what to pass it.
每一轮中,模型都会选择一个工具,周围的代码负责运行该工具,并根据结果更新状态。这段代码通常称为运行框架(harness);例如,Claude Code 就是围绕 Claude 构建的运行框架。当智能体达成目标或放弃时,循环就会结束。当智能体需要来自某个人或外部来源的输入时,它会提出请求并等待答复。At each turn, the model chooses a tool, and the code around it runs the tool and updates the state with the result. That code is often called the harness; Claude Code, for example, is a harness around Claude. The loop ends when the agent reaches the goal or gives up. When the agent needs input from a person or an external source, it asks and waits for an answer.
图 1:循环的两个回合:一个调用工具,一个等待Figure 1: Two turns of the loop: one calls a tool, one waits
以下是库存补货器的代码循环。(所有代码示例均使用 Python。)Here is Stock Replenisher's loop in code. (All code examples are in Python.)
两种模型Two kinds of models
每一轮中,分类模型(此处为 TypeSafe 的 Jev)会从 allowed_tools 中选出下一个工具。分类模型速度更快、成本更低,非常适合用于决策环节。生成模型(此处为 Claude)会阅读供应商的邮件并起草回复。Each turn, a classification model (here, Jev, from TypeSafe) picks the next tool from allowed_tools. Classification models are faster, cheaper, and well-suited for the decision step. A generation model (here, Claude) reads the supplier's email and drafts replies.
GOAL = ("Bring stock back above safety stock: order from a suitable " "supplier, get every price approved by the manager before money " "is committed, and see the order through to delivery.") MAX_TURNS = 30 TOOLS = [ GetQuotes(), DraftPurchaseOrder(), RequestApproval(), WaitForApproval(), PlaceOrder(), WaitForSupplierReply(), ReadSupplierReply(), WaitForGoods(), ClosePurchaseOrder(), Done(), ... ] class Replenish: async def run(self, stock: StockLevel) -> ReplenishmentResult: state = State(stock.sku, stock.on_hand, stock.safety_stock) for turn in range(MAX_TURNS): allowed_tools = [t for t in TOOLS if t.allowed(state)] tool = await self.decider.decide(GOAL, state, allowed_tools) if isinstance(tool, Done): break if isinstance(tool, Wait): try: payload = await asyncio.wait_for( self.inbox[tool.event].get(), timeout=timedelta(days=tool.days).total_seconds()) tool.apply(state, payload) except TimeoutError: tool.apply(state, None) else: result = await tool.execute(state, self.context) tool.apply(state, result) return outcome(state)
decider.decide 是对模型(在我们的例子中是分类模型 Jev)的调用;它会根据 GOAL、补货流程的当前状态(state)以及预先筛选出的允许使用的工具列表 allowed_tools,选择本轮要运行的工具。当模型选择 Done 或达到 MAX_TURNS 时,循环结束。outcome 会显示补货流程的最终结果:已收到、已取消、被经理拒绝或已放弃。decider.decide is the call to the model (in our case, a classification model Jev); it picks the tool to run in the current turn based on the GOAL, the current state of the replenishment run (state), and a prefiltered list of allowed tools allowed_tools. The loop ends when the model selects Done or after MAX_TURNS. The outcome shows how the replenishment concluded: received, cancelled, rejected by the manager, or given up.
每个工具都有名称和描述,模型会根据这些信息进行选择。allowed 方法会根据补货当前的状态,判断该工具是否可用。这样,重要的业务规则就写在代码中,而不是提示词里。例如,在经理批准桌上的价格之前,place_order 工具不可用。execute 方法负责运行工具,例如调用 API、撰写电子邮件等;apply 则根据 execute 的结果更新状态。Each tool has a name and description, which the model uses to make its selection. The allowed method states whether the tool can be used given the replenishment's current state. This way the business rules that matter are in code, not in the prompt. For instance, the place_order tool isn't available until the manager approves the price on the table. The execute method runs the tool, e.g., makes API calls, writes an email, etc., and apply updates state based on the result of execute.
class PlaceOrder(Call):
name = "place_order"
description = "Send the approved purchase order to the supplier."
def allowed(self, state):
return (state.po is not None and state.order is None
and state.approved_up_to is not None
and state.price <= state.approved_up_to)
async def execute(self, state, context):
return await context.supplier.place_order(state.po)
def apply(self, state, ack):
state.order = ack
state 保存代理关于一次补货所掌握的所有信息:报价、采购订单、已批准的价格范围和订单。只有 apply 方法会根据每一轮的结果更新 state。state holds everything the agent knows about one replenishment: the quotes, purchase order, approved price range, and order. Only the apply method updates it based on the result of each turn.
@dataclass
class State:
sku: str
on_hand: int
safety_stock: int
quotes: list[Quote] | None = None
po: PurchaseOrder | None = None
price: float | None = None
approved_up_to: float | None = None
order: OrderAck | None = None
goods: GoodsReceipt | None = None
...
Wait 也是一种用于等待消息(例如经理的决定)或等待超时的工具。只要运行该循环的进程保持运行,它就能正常工作,但在长时间等待期间可能会发生很多问题。智能体需要能够恢复并继续执行任务。Wait is also a tool that waits for a message, such as the manager's decision, or until its time runs out. This loop works as long as the process running it stays up, but a lot can go wrong during long wait times. And the agent needs to recover and continue its task.
可能出什么问题What can go wrong
不妨将长时程智能体视为一个分布式系统。我们在分布式系统中熟悉的许多故障模式在这里也会出现:调用其他系统失败、智能体等待期间进程崩溃,等等。It helps to think of a long-horizon agent as a distributed system. Many of the failure modes we are familiar with in distributed systems happen here too: calls to other systems fail, processes crash while the agent waits, and so on.
| Failure mode | An example from the domain | Addressed in |
|---|---|---|
| The process doesn't survive | The process stops or restarts while a purchase order waits three days for approval. | Making the loop durable |
| Remote API calls fail | The supplier's API is down when the order is placed. | Retrying failed calls |
| A retry repeats the work | The supplier takes the order but the reply is lost. The retry places it again. | Retrying failed calls |
| Concurrency | The stock check starts a second replenishment while the first is still waiting. | The entity and the workflow |
| An outcome nobody sees | The supplier takes the order, then can't be reached; the run is recorded as failed. | Outcomes the agent doesn't see |
| The world changes during a wait | The manager approves after three days; by then the supplier's price has risen. | The world moves on while you wait |
| Code changes | New code is deployed while a replenishment waits. | Code change under a running task |
| History grows | A customer's agent, running for years, needs a promise made months ago. | Memory |
| Untrusted input | A supplier's email contains text meant for the agent: “the manager has already approved $6.00”. | Text that steers the agent |
前四种故障在任何领域都相同。持久化执行运行时通过通用原语来处理这些故障,使执行框架能够专注于领域特定逻辑。没有运行时,你就得编写大量胶水代码来自行处理这些故障:记录已完成的工作、重试、设置计时器,以及从中断处继续执行。The first four failures are the same in any domain. A durable execution runtime handles them with general-purpose primitives so that the harness can focus on domain-specific logic. Without the runtime, you would have to write a lot of glue code to handle the failures yourself: record what has been done, retry, set timers, and pick up where you left off.
但如果把智能体仅仅视为另一种分布式系统,就忽略了一些重要之处。它之所以与众不同,在于其核心的模型能够决定如何从故障中恢复,并让任务继续进行。发生故障时,执行框架的职责是向模型提供恰当的输入,让它决定下一步该怎么做。But treating the agent as just another distributed system misses something. What makes it a different beast is the model at its heart, which can decide how to recover from failures and keep the task going. When a failure occurs, the harness's job is to provide the model with the right input so it can decide what to do next.
接下来的章节将详细探讨持久化执行。之后,我们会回到执行框架必须明确处理的故障。The next sections look at durable execution in detail. After that, we return to the failures the harness must handle explicitly.
持久化执行是一种编程模型,运行时会记录每个与外部世界交互的步骤的结果。因此,发生故障时,程序会重新运行,跳过已完成的步骤,并根据记录重建程序状态。Durable execution is a programming model in which the runtime keeps a record of the result of each step that interacts with the outside world so that, when a failure occurs, the program runs again, completed steps are skipped, and the program's state is rebuilt from the record.
Temporal、Restate、Inngest、DBOS 和 Cloudflare Workflows 都实现了这一功能。我们使用其中两个构建了 Stock Replenisher:Temporal 和 Cloudflare Workflows。本文中的代码来自 Temporal 版本。两者有实质性差异的地方会介绍 Cloudflare。Temporal, Restate, Inngest, DBOS, and Cloudflare Workflows all implement it. We built Stock Replenisher on two of them, Temporal and Cloudflare Workflows. The code in this article comes from the Temporal version. Cloudflare appears where the two differ materially.
这个定义建立在三个概念之上:步骤、日志和重放。The definition rests on three ideas: steps, a log, and replay.
步骤是运行时代表程序对外部世界发起的一次调用:调用 LLM、调用 ERP、向供应商发送消息。任何与外部世界交互的操作都通过一个步骤进行。步骤之间的代码只会读取和写入本地状态。在 Stock Replenisher 中,decider.decide 和每个工具的 execute 都是步骤;allowed 和 apply 则不是。A step is a call to the outside world that the runtime makes on the program's behalf: the LLM call, a call to the ERP, a message to the supplier. Anything that interacts with the outside world goes through a step. The code between steps only reads from and writes to local state. In Stock Replenisher, decider.decide and each tool's execute are steps; allowed and apply are not.
图 2:每次与外部世界交互都是一个步骤Figure 2: Every call to the outside world is a step
现有技术:预写日志Prior Art: Write-Ahead Log
该日志是一种预写式日志(Write-Ahead Log),这一模式源自 Unmesh Joshi 的《分布式系统模式》。数据库会在应用每项更改之前先将其写入日志,这样发生崩溃后,就能通过读取日志来恢复。持久化执行对程序的各个步骤也采用同样的做法。The log is a Write-Ahead Log, a pattern from Unmesh Joshi's Patterns of Distributed Systems. A database writes each change to a log before it applies it, so that after a crash it can recover by reading the log. Durable execution does the same for a program's steps.
在程序继续执行下一步之前,运行时会将该步骤的输入和输出都写入持久化日志。Before the program proceeds to the next step, the runtime writes both the step's input and output to a persistent log.
图 3:一步,特写Figure 3: A step, close-up
崩溃后,程序会从头开始(也就是说,会重新回放)。任何有记录输出的步骤都会从日志中返回该输出,而不会再次运行。步骤之间的代码会重新运行并重建程序状态;在 Stock Replenisher 中,这个状态就是 state。第一个没有记录的步骤会真正执行。After a crash, the program restarts from the top (i.e., it is replayed). Any step with a recorded output returns it from the log rather than running again. The code between steps runs again and rebuilds the program state, which in Stock Replenisher is state. The first step without a record runs for real.
图 4:崩溃后,程序会再次运行;已记录的步骤不会重放Figure 4: After a crash, the program runs again; recorded steps don't
这样,程序在崩溃后只需从日志中重建状态即可。This way the program can just rebuild its state from the log after a crash.
让循环更持久Making the loop durable
以下是前面用 Temporal 原语编写的智能体循环。高亮的行是发生变化的部分。2Here is the agentic loop from earlier, written with Temporal's primitives. The highlighted lines are the ones that change.2
2:以 ... 省略表示的参数是超时和重试策略。2: Arguments elided as ... are timeouts and retry policies.
replenish/workflow.pyreplenish/workflow.py
from temporalio import workflow @workflow.defn class Replenish: @workflow.run async def run(self, stock: StockLevel) -> ReplenishmentResult: state = State(stock.sku, stock.on_hand, stock.safety_stock) for turn in range(MAX_TURNS): allowed_tools = [t for t in TOOLS if t.allowed(state)] tool = await workflow.execute_activity( Decider.decide, args=[GOAL, state, allowed_tools], activity_id=f"decide-{turn}", ...) if isinstance(tool, Done): break if isinstance(tool, Wait): try: await workflow.wait_condition( lambda: self.inbox[tool.event], timeout=timedelta(days=tool.days)) tool.apply(state, self.inbox[tool.event].pop(0)) except TimeoutError: tool.apply(state, None) else: result = await workflow.execute_activity( run_tool, args=[tool, state], activity_id=f"{tool.name}-{turn}", ...) tool.apply(state, result) return outcome(state)
需要注意的关键是,整个智能体循环,也就是 run 方法,都用 @workflow.run 进行了注解。这会将它定义为一个工作流——这是 Temporal 对持久化程序的称呼:发生故障后,Temporal 会重新运行该程序,并根据日志重建其状态。The key thing to notice is that the whole agentic loop, the run method, is annotated with @workflow.run. That makes it a workflow, Temporal's name for a durable program: after a failure, Temporal runs it again and rebuilds its state from the log.
现有技术:事件溯源Prior Art: Event Sourcing
Replay 会像事件溯源那样重建代理的状态。事件溯源系统不需要存储当前状态,只需存储改变状态的事件,然后按顺序应用这些事件即可重建状态。Replay rebuilds the agent's state the way Event Sourcing does. An event-sourced system doesn't need to store its current state; it stores the events that changed it, and can rebuild the state by applying them in order.
每个与外部世界交互的步骤都会通过第二个原语 `workflow.execute_activity` 执行,因此 Temporal 会将该步骤的输入和输出记录到日志中,并使用 `activity_id` 为其指定的名称。Temporal 将这样的步骤称为 activity。循环中的两次调用都是 activity:模型选择下一个工具(`Decider.decide`),以及工具本身(通过 `run_tool` 调用的 `get_quotes`、`place_order`、`close_purchase_order` 等)。Every step that interacts with the outside world goes through a second primitive, workflow.execute_activity, so that Temporal records the step's input and output in the log, under the name activity_id gives it. Temporal calls such a step an activity. Two calls in the loop are activities: the model's choice of the next tool (Decider.decide), and the tool itself (get_quotes, place_order, close_purchase_order and the others, through run_tool).
第三个原语 workflow.wait_condition 会暂停工作流,直到某个条件成立(此处指收件箱中收到消息)或超时。等待过程也会被记录,因此等待期间进程无需一直运行。A third primitive, workflow.wait_condition, suspends the workflow until a condition holds (here, until a message arrives in the inbox) or the timeout passes. The wait is recorded too, so the process doesn't have to stay up while it waits.
其他一切都一样:允许并应用。这就是决策周围的代码,每次重放时都会再次运行。3Everything else is the same: allowed and apply. That's the code around the decision, and it runs again on every replay.3
3:Cloudflare 使用 step.do 替代 execute_activity、使用 step.waitForEvent 替代 wait_condition 来编写相同的循环;Restate、Inngest 和 DBOS 也有对应实现。3: Cloudflare writes the same loop with step.do in place of execute_activity, and step.waitForEvent in place of wait_condition; Restate, Inngest and DBOS have equivalents.
下面展示的是 Temporal 记录的一次补货流程。代理获取了报价,起草了一份采购订单,并请经理审批。在等待期间,流程崩溃并停机了一天,如下方的粉色带所示。流程恢复后,粉色带之前的步骤都没有重新运行:没有获取新的报价,没有生成第二份采购订单,也没有再次向经理提交审批请求。收到批准后,代理便下了订单。Here is one replenishment as Temporal recorded it. The agent got quotes, drafted a purchase order, and asked the manager to approve it. While it waited, the process crashed and stayed down for a day, as shown by the pink band below. When the process came back, nothing before the band ran again: no new quotes, no second purchase order, no second request to the manager. When the approval arrived, the agent placed the order.
实体与工作流The entity and the workflow
我们已经了解了持久化的智能体循环。接下来的问题是,这个循环运行在哪里,以及它如何映射到业务领域。We've seen the durable agentic loop. The next question is where that loop lives and how it maps to the business domain.
库存补货涉及两个循环。其中一个负责单个 SKU 的补货,并跟进整个流程,直至货物收货入库。另一个是 SKU 级循环:它会根据补货策略检查库存,并在需要时逐个触发补货。它也是该 SKU 的联络点:来自经理、供应商和仓库的消息都会发送给它。SKU 在其生命周期内会被补货很多次。Take stock replenishment: there are two loops at play. One handles replenishment for a single SKU and follows the work through until the goods are received. The other is the SKU-level loop. It checks stock against the replenishment policy and triggers replenishment when needed, one at a time. It is also the SKU's point of contact: messages from the manager, the suppliers, and the warehouse come to it. The SKU will be replenished many times over its life.
图 5:每个 SKU 配备一个智能体;一次运行一个工作流Figure 5: One agent per SKU; one workflow at a time
这就是流程工作流与实体工作流之间的区别。This is the distinction between a process workflow and an entity workflow.
流程工作流是一种持久化工作流,用于完成一项工作(例如补货),随后结束。A process workflow is a durable workflow that carries out one piece of work (e.g., a replenishment) and then finishes.
实体工作流是一种持久化工作流,在某个业务实体(例如 SKU)的整个生命周期内代表该实体。它负责维护实体的状态并启动流程工作流。An entity workflow is a durable workflow that represents one business entity (e.g., a SKU) for the lifetime of that entity. It maintains the entity's state and initiates process workflows.
现有技术:Actor 模型与 ErlangPrior Art: Actors and Erlang
每个 SKU 对应一个实体工作流,这就是 Erlang 所实现的 actor 模型(Armstrong,2003):每个实体一个进程,拥有一个地址和一个邮箱,每次处理一条消息。区别在于,Erlang 进程并不持久化。进程崩溃时,监管进程会以全新的状态重新启动它。One entity workflow per SKU is the actor model as Erlang implements it (Armstrong, 2003): one process per entity, with an address and a mailbox, handling one message at a time. The difference is that an Erlang process isn't durable. When it crashes, a supervisor restarts it with fresh state.
在订阅业务中,客户也遵循相同的模式。客户实体工作流维护客户上下文,并启动相应的流程工作流(客户接入、续订、支持等)。这些流程工作流各自完成后,客户实体工作流仍会继续运行。In a subscription business, customers fit the same pattern. The customer's entity workflow maintains the customer context and initiates the appropriate process workflows (onboarding, renewal, support, etc.). Each of those process workflows completes, but the customer entity workflow continues.
实体工作流的首要任务是监控库存并触发补货。The entity workflow's first job is to watch the stock and trigger replenishments.
实体工作流:每个 SKU 一个the entity workflow: one per SKU
@workflow.defn
class SkuAgent:
@workflow.run
async def run(self, sku: str, outcomes: list[ReplenishmentResult]):
stock = await workflow.execute_activity(get_stock, sku, ...)
if stock.on_hand < stock.safety_stock:
self.active = f"replenish-{sku}-{len(outcomes) + 1}"
try:
result = await workflow.execute_child_workflow(
Replenish.run, stock, id=self.active)
except ChildWorkflowError as e:
result = ReplenishmentResult(sku, "failed", str(e.cause))
outcomes.append(result)
self.active = None
else:
await workflow.sleep(CHECK_EVERY)
workflow.continue_as_new(args=[sku, outcomes])
实体工作流的每次运行都会检查一次库存。如果 SKU 的库存低于安全库存,就会启动补货并等待补货完成;否则会休眠,直到下一次检查。随后,continue_as_new 会以相同的 ID 启动一次全新的运行,且历史记录为空;新运行只会收到传递给它的内容,在这里就是 SKU 和目前为止的执行结果。Each run of the entity workflow checks the stock once. If the SKU is below safety stock, it starts a replenishment and waits for it to finish; otherwise it sleeps until the next check. Then continue_as_new starts a fresh run with the same ID and an empty history, which receives only what it is given, here the SKU and the outcomes so far.
实体工作流的第二项职责是接收外部发来的、与 SKU 相关的消息。在该 SKU 的整个生命周期中,它都有一个稳定且唯一的 ID:agent-SKU-123。代理发出的每个请求,例如审批请求或采购订单,都会附带 SKU 或采购订单编号,以便回复能够发送回 agent-SKU-123。审批的经理或回复的供应商无需知道当前正在进行哪次补货;实体会将消息转发给当前的补货流程。The entity workflow's second job is to receive messages for the SKU from the outside world. It has a stable, unique ID, agent-SKU-123, for the SKU's life. Each request the agent sends out, such as an approval request or a purchase order, carries the SKU or the purchase order number so that the answer can be sent back to agent-SKU-123. The manager approving or the supplier replying doesn't need to know which replenishment is running; the entity passes the message on to the current one.
Cloudflare 与 TemporalCloudflare and Temporal
两个平台都以不同的原语以相同方式拆分代理。在 Temporal 中,这两部分都是工作流:实体是一个长期运行的工作流,每次补货都是由它启动的子工作流。Both platforms split the agent the same way, with different primitives. On Temporal, both parts are workflows: the entity is a long-running workflow, and each replenishment is a child workflow it starts.
在 Cloudflare 上,这个实体是一个 Durable Object:一个拥有自身存储的 Cloudflare Worker。每个 SKU 对应一个 Durable Object,并通过其唯一名称访问:发送到 /agents/replenishment-agent/SKU-123 的请求会路由到 SKU-123 的对象。每次补货都是一个 Cloudflare Workflow。On Cloudflare, the entity is a Durable Object: a Cloudflare Worker with its own storage. There is one per SKU, reached by its unique name: a request to /agents/replenishment-agent/SKU-123 goes to SKU-123's object. Each replenishment is a Cloudflare Workflow.
经理的批准,已发送至 SKU-123the manager's approval, sent to SKU-123
await client.get_workflow_handle("agent-SKU-123").signal(
"deliver", args=["approval", {"approved": True}])
实体的地址:来自外部的消息the entity's address: messages from outside
class SkuAgent:
...
@workflow.signal
async def deliver(self, event: str, payload: dict):
if self.active:
await workflow.get_external_workflow_handle(self.active).signal(
Replenish.deliver, args=[event, payload])
补货的收件箱:来自该实体的消息the replenishment's inbox: messages from the entity
@workflow.defn
class Replenish:
@workflow.run
async def run(self, stock: StockLevel) -> ReplenishmentResult:
state = State(stock.sku, stock.on_hand, stock.safety_stock)
for turn in range(MAX_TURNS):
...
return outcome(state)
@workflow.signal
def deliver(self, event: str, payload: dict):
self.inbox[event].append(payload)
发往 SKU-123 的每条消息都会经过 SKU-123 的实体工作流,进入正在运行的补货流程,由该流程逐条处理。Every message for SKU-123 goes through SKU-123's entity workflow to the running replenishment, which applies them one at a time.
在代码中,Stock Replenisher 现在拆分为两个类:SkuAgent(实体工作流)和 Replenish(流程工作流),后者负责运行之前的循环。In the code, Stock Replenisher is now two classes: SkuAgent, the entity workflow, and Replenish, the process workflow that runs the loop from earlier.
这就引出了等待的问题。That brings us to the waiting.
等待人员和系统Waiting for people and systems
正如我们目前所见,长周期智能体的大部分时间都在等待人类或外部系统。持久化执行运行时提供了高效等待的基础机制。在这些智能体等待期间,运行时会确保它们不会占用内存中的进程或消耗计算资源。As we've seen so far, long-horizon agents spend much of their time waiting for humans or external systems. The durable execution runtime provides primitives for waiting efficiently. While these agents wait, the runtime ensures they don't hold a process in memory or use compute.
这很重要,因为按照我们之前看到的实体工作流模式,每个 SKU 都会有自己的工作流,而且只要该 SKU 仍有库存,这个工作流就会持续运行。拥有数千种零部件的制造商将会有数千个代理。在任何给定时刻,它们中几乎所有都处于空闲或等待状态。如果等待会占用进程或内存,那么成本就会随着 SKU 数量和等待时长成比例增加,而不是随着实际完成的工作量增加。This matters because, with the entity-workflow pattern we saw earlier, every SKU will have its own workflow, and that workflow will run as long as the SKU is stocked. A manufacturer with thousands of parts will have thousands of agents. At any given time, almost all of them will be idle or waiting. If a wait holds a process or memory, then the cost increases in proportion to the number of SKUs and the length of the waits, not in proportion to the work actually done.
workflow.wait_condition 会暂停工作流,直到收件箱中出现类型正确的消息,或者超时。等待的计时器也会被记录,结束等待的消息也会被记录。因此,等待和步骤一样,即使发生崩溃也能恢复。workflow.wait_condition suspends the workflow until a message of the right type is in the inbox, or the timeout expires. The wait's timer is also logged, and so is the message that ends it. So a wait survives a crash just as a step does.
先例:Erlang 的 receivePrior Art: Erlang's receive
Erlang 的 `receive ... after Timeout`(Armstrong,2003)与本节中的等待机制类似:进程会取出邮箱中第一条与某个模式匹配的消息,或者在超时后放弃。不匹配的消息会留在邮箱中。区别仍然在于,邮箱和等待都不是持久的。Erlang's receive ... after Timeout (Armstrong, 2003) works like the wait in this section: a process takes the first message in its mailbox that matches a pattern, or gives up when the timeout passes. Messages that don't match stay in the mailbox. The difference, again, is that the mailbox and the wait are not durable.
图 6:等待操作的计时器和消息都会写入日志。Figure 6: The wait's timer and the message both go into the log
唤醒也有成本。重建工作流意味着重放日志,而这项成本会随着日志长度增加。如果唤醒速度慢或成本高昂,那么让数千个代理等待,就和让数千个进程连续运行数周一样不可行。在我们的测试中,唤醒一个工作流耗时不到三秒,CPU 时间为几十毫秒。4Waking up has a cost too. Rebuilding a workflow means replaying the log, and that cost grows with the log's length. If wake-up is slow or expensive, then having thousands of agents waiting is just as infeasible as keeping thousands of processes open for weeks. In our runs, waking a workflow took under three seconds and tens of milliseconds of CPU.4
4:我们测量了 Cloudflare、已部署环境以及本地 Temporal 服务器上的等待时间。等待中的工作流在两者上都不消耗 CPU。仍驻留在内存中的工作流会在毫秒内唤醒(Temporal 上为 14 毫秒,Cloudflare 上约为 0.1 秒);从日志重建的工作流在 Cloudflare 上耗时约两秒,在 Temporal 上不到十分之一秒,而且日志越长,耗时越久。每次唤醒会消耗几十毫秒的 CPU 时间。4: We measured waits on Cloudflare, deployed, and on a local Temporal server. A waiting workflow used no CPU on either. A workflow still in memory woke in milliseconds (14 ms on Temporal, about 0.1 s on Cloudflare); one rebuilt from the log took about two seconds on Cloudflare and under a tenth of a second on Temporal, more as the log grew. A wake used tens of milliseconds of CPU.
如果重放变得太慢,接下来可以尝试使用快照,这样只需重放快照之后的日志。这对实体尤为重要,因为只要 SKU 持续有库存,它的日志就会不断增长。在 Temporal 中,continue_as_new 的作用相同:它会将实体状态带入一个全新的运行实例,且历史记录为空。在 Cloudflare 中,实体是 Durable Object,它会从存储中读取当前状态,不需要重放日志。补货工作流不需要快照,因为运行结束后,日志就不会再增长。If replay gets too slow, the next thing to try is a snapshot, so only the log after it has to be replayed. This matters most for the entity, whose log would keep growing as long as the SKU is stocked. On Temporal, continue_as_new has the same effect: it carries the entity's state into a fresh run with an empty history. On Cloudflare, the entity is a Durable Object, which reads its current state from storage and has no log to replay. A replenishment workflow doesn't need a snapshot. Its log stays short because the run ends.
等待会以两种方式之一结束:收到消息,或者超时。如果供应商在七天内没有回复我们,wait_for_supplier_reply 就会将订单标记为逾期:A wait ends in one of two ways: a message arrives, or the timeout expires. If the supplier hasn't got back to us within seven days, then wait_for_supplier_reply will mark the order as overdue:
class WaitForSupplierReply(Wait):
event, days = "supplier-reply", 7
...
def apply(self, state, payload):
if payload is None:
state.supplier_overdue = True
else:
state.supplier_reply = SupplierReply(**payload).message
class ChaseSupplier(Call):
...
def allowed(self, state):
return (state.supplier_overdue and state.chases < MAX_CHASES
and is_open(state))
这意味着 chase_supplier 是允许的,模型将在下一轮将其视为一个选项。That means chase_supplier is allowed, and the model will see it as an option on its next turn.
在这次流程中,订单下达后供应商就没了动静。找出那个七天后以超时结束的等待,随后是紧接着的催促,以及催促后一天收到的回复。In this run, the supplier goes quiet after the order is placed. Look for the wait that ends with a timeout seven days later, then the chase that follows it, and the reply a day after the chase.
对失败的调用至少重试一次Retrying failed calls, at least once
对外部系统的调用可能因网络问题或接收系统宕机而失败。持久化执行运行时提供了可配置重试策略的原语,用于重试失败的调用,从而避免接收系统过载。Calls to external systems can fail because of network issues or because the receiving system is down. Durable execution runtimes provide primitives to retry failed calls with configurable retry policies, so they don't overload the receiving system.
RETRY = RetryPolicy(maximum_attempts=6, initial_interval=timedelta(seconds=2), backoff_coefficient=2) @workflow.run async def run(self, stock: StockLevel) -> ReplenishmentResult: ... result = await workflow.execute_activity( run_tool, args=[tool, state], activity_id=f"{tool.name}-{turn}", retry_policy=RETRY) ...
运行时无法确保重试是安全的。如果供应商接收了订单,但响应丢失,就不会记录任何结果,因此运行时会再次调用供应商。这称为“至少一次”语义,与“恰好一次”语义相对。如果处理不当,可能会导致重复下单。What the runtime can't do is make a retry safe. If the supplier takes the order and the response is lost, no result is recorded, so the runtime calls the supplier again. This is known as at-least-once semantics, as opposed to exactly-once. This could result in duplicate orders if not handled properly.
现有技术:幂等接收器Prior Art: Idempotent Receiver
接收方是一个幂等接收方,这是 Unmesh Joshi 的《分布式系统模式》中的一种模式。客户端没有收到响应时,无法判断是请求丢失还是响应丢失,因此会重试;接收方必须识别出重复请求,并返回原始结果。The receiver is an Idempotent Receiver, a pattern from Unmesh Joshi's Patterns of Distributed Systems. A client that gets no response can't tell a lost request from a lost response, so it retries, and the receiver must recognise the duplicate and return the original result.
要实现写入恰好一次的效果,接收方必须使用幂等键识别重复请求,而测试框架必须在每次尝试和重放时保持该键不变。To get the effect of exactly once for a write, the receiver must recognise repeats using an idempotency key, which the harness must keep the same on every attempt and replay.
在 place_order 工具中,PO 编号会成为幂等键。In the place_order tool, the PO number becomes the idempotency key.
class PlaceOrder(Call):
...
async def execute(self, state, context):
...
key = state.po.po_number
ack = await context.supplier.place_order(po, idempotency_key=key)
return PlaceOrderResult(placed=True, price=price, ack=ack)
在下面这次运行中,供应商的系统在第一次尝试时宕机。运行时使用相同的 PO 编号作为幂等键进行重试。请查找 place_order 上的两次尝试,以及供应商处的单笔订单。In the run below, the supplier's system is down on the first attempt. The runtime retries with the same PO number as its idempotency key. Look for the two attempts on place_order and the single order at the supplier.
回顾一下,以下是目前在两个平台上使用的基本类型:As a recap, here are the primitives used so far, on both platforms:
| Purpose | Temporal | Cloudflare |
|---|---|---|
The agent: an entity workflow, one per SKU (SkuAgent) |
workflow (long-lived) | Agent (a Durable Object) |
| Start a process workflow: one replenishment | child workflow | runWorkflow |
| A step: run a call, record input and output | execute_activity |
step.do |
| Retry a failed step | RetryPolicy |
retries on step.do |
| Wait for a message | signal + wait_condition |
step.waitForEvent |
| Send a message to a run | signal | sendWorkflowEvent |
| Check on a schedule | workflow.sleep |
scheduleEvery |
| Start a fresh run with an empty history | continue_as_new |
not used: the entity isn't a workflow |
有了这些机制,循环就能在崩溃后继续运行,无需占用进程即可等待,并重试失败的调用。幂等性是执行框架必须明确处理的首要问题,此外还有其他几种类似的故障模式。我们会在下一节介绍它们。With these, the loop survives crashes, waits without holding a process, and retries failed calls. Idempotency is the first thing the harness has to handle explicitly, and there are a few other failure modes like it. We'll see them in the next section.
持久不等于正确。Durable is not the same as correct
本质复杂性与偶然复杂性Essential and accidental complexity
在《没有银弹》(1986)中,弗雷德·布鲁克斯将构建软件的难题分为“本质”,即软件本性所固有的难题;以及“偶然因素”,即当下伴随软件生产过程、但并非其固有属性的难题。In “No Silver Bullet” (1986), Fred Brooks divides the difficulties of building software into “essence, the difficulties inherent in the nature of the software, and accidents, those difficulties which today attend its production but which are not inherent.”
有些故障模式无法仅靠持久化执行来解决。它们源于这样一种固有复杂性:要解决现实世界中的棘手任务,必须与多个人和多个系统交互,而交互方式往往难以预料,任务也可能持续很长时间。另一些则是我们用来解决问题的工具所带来的意外副作用,包括持久化执行本身和模型。Some failure modes can't be solved by durable execution alone. They come from the essential complexity of solving a hard real-world task by interacting with multiple people and systems, often in unexpected ways and over long periods of time. Others are accidental side effects of the tools we use to solve it: durable execution and the model itself.
关键在于理解这些失败模式,并在测试框架中制定务实的策略来缓解它们。这通常需要深入理解业务领域,并做出一些巧妙的权衡。能否恰当地把握这些权衡,决定了长时程智能体在企业中的实用价值,而不仅仅是停留在概念验证阶段。The key is to understand these failure modes and develop pragmatic strategies in the harness to mitigate them. This often requires a deep understanding of the business domain and some clever trade-offs. Getting those trade-offs right defines how useful long-horizon agents are in an enterprise, beyond just a proof of concept.
以下是“可能会出什么问题”中的五项:Here are the five from What can go wrong:
| Failure mode | Kind | Why | Addressed in |
|---|---|---|---|
| An outcome nobody sees | Essential | A supplier takes the order, then can't be reached. | Outcomes the agent doesn't see |
| The world changes during a wait | Essential | Prices change while the manager decides. | The world moves on while you wait |
| Code changes | Accidental: durable execution | Replay runs the new code against a log the old code wrote. | Code change under a running task |
| History grows | Accidental: the model | The model can't see everything on every turn. | Memory |
| Untrusted input | Accidental: the model | The model can't tell the text it reads from its instructions. | Text that steers the agent |
代理看不到的结果Outcomes the agent doesn't see
现有技术:Saga 模式Prior Art: Sagas
在分布式系统中,已经在另一个系统中生效的步骤无法回滚。要撤销它,需要执行一个补偿事务,也就是一个逆转其效果的步骤,例如取消订单。Saga(Garcia-Molina 和 Salem,1987)会为长时间运行事务中的每个步骤配对一个补偿步骤。如果 Saga 中途停止,就会为已完成的步骤执行相应的补偿步骤。In a distributed system, a step that has already taken effect in another system can't be rolled back. It is undone by a compensating transaction, a step that reverses its effect, such as cancelling an order. A saga (Garcia-Molina and Salem, 1987) pairs each step of a long-running transaction with a compensating one. If the saga stops part way, it runs them for the steps that completed.
我们之前看到,智能体如何通过重试和幂等键从调用失败中恢复。但这只解决了部分问题。智能体判定为失败的调用,实际上可能已经完成了工作:供应商可能已经接收了订单,只是响应丢失了。智能体无法分辨两种情况,于是把“我们不知道”当成“它失败了”,并在仿佛订单根本不存在的情况下继续操作。We saw earlier how an agent recovers from failed calls using retries and an idempotency key. This only addresses part of the problem. The call that the agent deemed a failure might still have done its work: the supplier may have taken the order and lost only the response. The agent can't tell the difference, so it turns “we don't know” into “it failed” and proceeds as if no order existed.
这是长期运行的智能体需要解决的常见问题。一种策略是为这些智能体提供缓解措施。例如,cancel_order 工具可以避免意外重复下单。This is a common problem long-horizon agents need to tackle. One strategy is to make mitigating actions available for these agents. For example, the cancel_order tool can mitigate accidental duplicate orders.
class CancelOrder(Call):
name = "cancel_order"
description = ("Cancel an order with its supplier and tell them why, "
"for example a duplicate placed by an earlier run.")
po_number = None # the model's choice, from a list the harness builds
async def execute(self, state, context):
po = self.po_number
# a generation model (here Claude) writes the email
text = await context.writer.write_cancellation(po, state)
sent = await context.supplier.send_message(
po, text, idempotency_key=context.key)
await context.supplier.cancel_order(po, idempotency_key=context.key)
return Cancellation(po, sent)
def apply(self, state, result):
...
在下面这次运行中,供应商 A 接单后便无法联系。之后的重试也都失败了,因为供应商 A 的系统宕机了。place_order 步骤在尝试六次后失败。由于库存仍然不足,代理开始了新一轮补货,并向供应商 C 下单。后来,供应商 A 通过电子邮件确认了第一笔订单。In the run below, supplier A takes the order and then becomes unreachable. Subsequent retries also fail because supplier A's system is down. The place_order step fails after six attempts. Still short on stock, the agent starts another replenishment and orders from supplier C. Later, supplier A confirms the first order via an email.
该代理通过核对 PO 编号发现了错误。如果还来得及,它就会使用 cancel_order 取消此前向供应商 A 下的订单,并说明取消原因。The agent spots the mistake by checking the PO number. If it's not too late, it then uses cancel_order to cancel the earlier order with supplier A, providing an explanation for the cancellation.
代理发现重复项,仅仅是因为供应商 A 写信告知。持久化日志记录的是代理看到的内容,而非实际发生的情况。与供应商 C 重新下单这个决定,从作出的那一刻起就是错误的;代理只是掌握的信息不完整。下一节将讨论另一类决策:作出时是正确的,但代理一直等待,导致所依据的信息过时了。The agent found the duplicate only because supplier A wrote. A persistent log records what the agent saw, not what actually happened. The decision to reorder with supplier C was wrong from the moment it was made; the agent just had incomplete information. The next section is about decisions that were correct when made, but whose inputs went stale as the agent sat around waiting.
在你等待时,世界仍在前进。The world moves on while you wait
长时程智能体在一个时间点做出决策,却可能要到另一个时间点才采取行动,往往相隔数天。在此期间,现实世界不断变化,决策所依据的事实也会过时。例如,经理根据一份可能已有三天之久的报价批准了价格,但等智能体准备下单时,价格可能已经上涨。A long-horizon agent decides at one time and acts at another, often days later. In the meantime, things change in the real world, and the facts behind the decision go stale. For instance, the manager approves a price from a quote that may be three days old, but the price might have gone up by the time the agent is ready to order.
一个实用的长期任务智能体需要能够随着时间推移自主处理此类情况。以下三种模式有助于实现这一目标。A useful long-horizon agent needs to handle such cases autonomously over time. Three patterns help achieve this.
已有技术:乐观离线锁定Prior Art: Optimistic Offline Lock
此处的重新检查是一种乐观离线锁,这一模式出自《企业应用架构模式》。一个跨越多个请求、期间用户会进行思考的业务事务,无法一直锁定它读取的数据。相反,它会在提交时检查数据自读取以来是否发生变化;如果发生了变化,事务就会失败。The re-check here is an Optimistic Offline Lock, a pattern from Patterns of Enterprise Application Architecture. A business transaction that spans several requests, with a user thinking in between, can't hold a lock on the data it read. Instead, it checks when it commits that the data hasn't changed since it was read, and fails if it has.
- 为决策设定一个到期日期。批准在某个日期之前有效;过期后,代理必须重新作出决定。报价通常会注明有效期,批准也可以注明。Give a decision an expiry date. An approval is valid until a certain date; after that, the agent must decide again. Quotes will often state a validity period; an approval can too.
- 提交前再次核查。在采取任何难以撤销的行动(例如下单)之前,重新阅读作为决策依据的事实。如果这些事实发生了变化,就不要行动;重新做出决定。Re-check before committing. Before taking any action that is hard to undo, such as placing an order, re-read the facts on which the decision is based. If those facts have changed, then don't act; decide again.
- 批准一个范围,而不是一个具体数值。为决策留出一定的浮动空间。例如,经理批准一个价格区间,而不是一个具体价格。这样,代理就可以在该区间内自行采取行动,无需再次询问。Approve a range, not a value. Build some variance into the decision. For example, the manager approves a price range instead of a specific price. The agent can then act anywhere in that range without having to ask again.
库存补货员会请经理批准该价格及最高不超过该价格 5% 的额度。随后,place_order 工具会重新获取报价,并与该上限进行比对。如果价格未超过上限,就按该价格下单;如果超过上限,则不会下单,智能体会返回请经理重新批准。请注意,此检查是在工具中执行的;这是一个确定性检查,无论模型如何决定都会运行。Stock Replenisher asks the manager to approve the price and up to 5% above that. The place_order tool then fetches the quote again and checks against that ceiling. If the price is within the ceiling, it orders at that price; if it's above the ceiling, it doesn't order, and the agent goes back to the manager for re-approval. Note that this check is in the tool; it's a deterministic check that runs regardless of what the model decides.
class PlaceOrder(Call):
...
async def execute(self, state, context):
quotes = await context.supplier.get_quotes(state.sku)
price = ... # this supplier's price today, from quotes
if price > state.approved_up_to: # above the range: don't order
return PlaceOrderResult(placed=False, price=price)
... # within the range: order at today's price
在下面这个流程中,经理批准了 4.20 美元,最高可接受 4.41 美元。代理以 4.20 美元下单。随后供应商确认价格为 4.35 美元,仍在可接受范围内,因此代理维持订单,并等待货物送达。如果确认价格为 4.54 美元,则会交由经理处理。In the run below, the manager approves $4.20, up to $4.41. The agent orders at $4.20. The supplier then confirms at $4.35, within the range, so the agent lets the order stand and waits for the goods. A confirmation at $4.54 would have gone back to the manager.
在运行中的任务下更改代码Code change under a running task
我们发现了一些挑战,这些挑战源于智能体需要适应的、意料之外的现实变化。Harness 代码本身也会变化和演进。向 Harness 部署更改会影响那些假定 Harness 版本固定而处于暂停状态的智能体。这是使用持久化执行本身带来的一种偶然复杂性。We saw a few challenges that arise from unanticipated real-world changes the agent is expected to adapt to. The harness code itself will change and evolve. Deploying changes to the harness affects the suspended agents that assume a certain version of the harness. This is an accidental complexity of using durable execution itself.
需要考虑的两种测试框架变更:Two kinds of harness changes to consider:
- 业务规则变更:例如,代理人员只有在获得至少 n 份报价后,才可以起草订单。在一些代理人员等待经理批准期间,n 从 0 提高到了 4。Business rule changes: e.g., the agent is allowed to draft an order only after n minimum quotes. That n went up from 0 to 4 while some agents were waiting for a manager's approval.
- 架构变更:重命名日志中记录的状态相关类和属性。例如,在 Stock Replenisher 中重命名一个步骤、一个工作流或一个状态字段。Schema changes: renaming of classes and attributes related to state recorded in the log. For example, renaming a step, a workflow or a field of the state in Stock Replenisher.
现有技术:事件溯源与不断变化的规则Prior Art: Event Sourcing and rules that change
事件溯源通过重放事件来重建状态,因此在代码发生变化时也会遇到同样的问题。当某条规则随时间变化(“11 月 18 日之前收费 10 美元,此后收费 15 美元”)时,两条规则都会保留在代码中,处理器会根据事件日期选择其中一条,例如使用 Agreement Dispatcher。Event Sourcing rebuilds state by replaying events, so it meets the same problem when code changes. Where a rule changes over time (“charge $10 before November 18 and $15 afterwards”), both rules stay in the code, and the processor picks one by the date of the event, e.g., with an Agreement Dispatcher.
缓解措施的总体思路是将日志视为一个已发布的接口,任何从日志重放数据的代码都需要让多个代码版本并行运行,并在运行时选择适用于特定日志的版本。The general idea behind the mitigation is to treat the log as a published interface, and any code that replays from the log needs to run multiple code versions in parallel and, at runtime, choose the version that applies to a given log.
这被称为并行变更。这种策略分三步实现不向后兼容的变更。首先,在旧规则旁添加新规则;然后,随着新工作流按照新规则启动,现有工作流继续按照旧规则运行直至完成;最后,在没有任何工作流仍在使用旧规则后,将其移除。This is known as Parallel Change. This strategy makes a backwards-incompatible change possible in three steps. First, add the new rule next to the old one; then migrate as new workflows start under the new rule while running ones finish under the old one; finally, remove the old rule once no workflow still uses it.
在 Stock Replenisher 中,SKU-123 正在等待经理批准 PO 4471。代理在获取三份报价后拟好了这份采购订单,而我们此时部署了一条新规则:只有获取四份报价后才能创建草稿。这样的变更在不同运行时中的表现各不相同。在 Temporal 上,SKU-123 悄然按照旧规则继续处理订单,而新规则已不再允许这样做。在 Cloudflare 上,我们的循环会根据当前规则检查每项已记录的决策,因此流程失败了:PO 4471 仍然停留在草稿状态。部署变更之前,我们需要了解运行时的行为,并据此规划部署。In Stock Replenisher, while SKU-123 waits for the manager to approve PO 4471, which the agent drafted after getting three quotes, we deploy the rule that allows a draft only after four quotes. A change like this plays out differently on each runtime. On Temporal, SKU-123 silently continued with the order as per the old rule, which the new rule doesn’t permit. On Cloudflare, where our loop checks each recorded decision against the current rules, it failed: PO 4471 stayed a draft. We need to know how the runtime behaves before we deploy a change, and plan the deploy around it.
规则版本化后,SKU-123 在两个运行时中都会按旧规则完成处理,这是有意为之:With the rule versioned, SKU-123 finishes under the old rule on both runtimes, by design:
一项经过版本管理的业务规则变更a business rule change, versioned
class DraftPurchaseOrder(Call):
def allowed(self, state):
min_quotes = 4 if state.rules_version >= 2 else 0
return (state.quotes is not None and len(state.quotes) >= min_quotes
and state.po is None)
在上述代码中,每次补货都会在 state.rules_version 中记录其开始时使用的规则版本,而 DraftPurchaseOrder 会据此确定最低报价数量。In the code above, each replenishment records the rules version it started under in state.rules_version, and DraftPurchaseOrder derives the minimum number of quotes from it.
记忆:智能体保留什么,以及模型能看到什么Memory: what the agent keeps, and what the model sees
长时程智能体还需要处理不断增长的历史记录。持久化执行运行时会记录智能体执行的所有操作。执行框架决定模型在每一轮中会看到什么。Stock Replenisher 只需要状态:它保存了当前补货的所有信息,这就足以决定下一步操作。SkuAgent 实体会存储以往补货的结果,但模型无需引用这些结果。Long-horizon agents also need to reckon with history that keeps growing. The durable execution runtime logs everything the agent did. The harness decides what the model sees in each turn. Stock Replenisher needs nothing more than state: it holds everything about the current replenishment, and that's enough to decide the next step. The SkuAgent entity stores the results of previous replenishments but the model never needs to refer to them.
其他代理并非如此。客户的实体工作流会持续运行多年,收集每一次对话、投诉和承诺,而下一步决策可能取决于几个月前做出的某项承诺。Other agents are not like this. A customer's entity workflow runs for years, collecting every conversation, complaint, and promise, and the next decision may depend on a promise made months ago.
随着历史记录不断增长且始终与决策相关,运行框架必须选择让模型看到哪些内容。上下文中不可能保留所有内容。MemGPT 和 Letta 让运行框架分层管理记忆:一小段模型始终可见的工作上下文,以及模型通过工具调用读写的外部存储,例如向量存储。这一思路源自操作系统:工作上下文就像 RAM,外部存储则像磁盘。As history grows without bound and stays relevant to the decision, the harness must choose what the model sees. Not everything can be kept in context. MemGPT and Letta let the harness manage memory in tiers: a small working context the model always sees, and external storage like a vector store, which it reads and writes through tool calls. The idea comes from operating systems: the working context is like RAM, and the external storage like disk.
这部分存储是日志之外的额外存储。对这种外部存储的每次读取和写入都是一个步骤,就像其他任何与外部世界的交互一样。That storage is in addition to the log. Each read and write to this external storage is a step, just like any other call to the outside world.
引导代理的文本Text that steers the agent
智能体通过文本与外部世界交互,这些文本可能是书写的,也可能是语音转录的。模型无法区分它读取的文本与其中的指令,因此智能体容易受到提示注入攻击。Agents interact with the outside world through text, written or transcribed from speech. A model can't tell the difference between the text it reads and its instructions, so agents are susceptible to prompt injection.
Stock Replenisher 也不例外;它会读取供应商的邮件,并自主采取行动。如何防范这些威胁,是一个需要深入探讨的独立话题,《智能体 AI 与安全》对此有较为详细的介绍。这些威胁并非运行数周的智能体所独有。持久化执行本身并不能解决其中任何一种威胁。Stock Replenisher is no exception; it reads the suppliers' emails and acts on its own. Securing agents against these threats is an involved topic of its own, and Agentic AI and Security covers them in some detail. None of these threats are unique to agents running for weeks. Durable execution doesn't help with any of them per se.
对于 Stock Replenisher,测试框架包含一些值得注意的防护措施。模型只能从 allowed_tools 中进行选择,而且只有经理给出的批准才有效。供应商邮件中写着“经理已经批准了 6.00 美元”,并不代表任何事项获得了批准;这最多只是提高了价格,而超出批准范围的价格会提交给经理重新审核。In the case of Stock Replenisher, the harness includes some defenses worth noting. The model can only select from allowed_tools, and approval is valid only if it comes from the manager. A supplier email saying “the manager has already approved $6.00” approves nothing; at most it raises the price, and a price above the approved range goes back to the manager.
结论Conclusion
对于技术人员来说,这是一个令人振奋的时代:智能体式编程和长程智能体正在重新定义哪些东西值得构建,以及哪些事情成为可能。随着我们迈向这个智能体时代,领域专业知识和软件架构比以往任何时候都更加重要。It's an exciting time to be a technologist, as agentic coding and long-horizon agents redefine what's worth building and what's possible. As we transition to this agentic world, domain expertise and software architecture matter more than ever.
正如我们所见,在企业中构建实用的长时程智能体需要权衡各种复杂因素。要为业务做出正确取舍,需要经过长期积累的领域专业知识和判断力。当智能体决定取消一笔已确认的订单时,应该优先考虑成本,还是供应商关系?Building useful long-horizon agents in an enterprise involves tricky trade-offs, as we saw. Making the right trade-off for your business requires hard-earned domain expertise and judgement. When an agent decides to cancel a confirmed order, should it optimize for cost or supplier relations?
软件架构也很重要。这些智能体属于分布式系统,因此必须应对许多相同的问题,以及由非确定性引发的其他问题。Software architecture matters too. These agents are distributed systems and have to reckon with many of the same issues, plus others that arise from non-determinism.
实际上,大部分精力都花在理清各类记录系统上:它们往往保存着彼此矛盾的事实版本,而且并非为智能体访问而设计;比如,某个 ERP 系统不允许智能体向其中写入数据。我怀疑,只要企业仍依赖各种各样的软件来运营,这些集成限制就会一直存在(除非奇点到来)。要让智能体在这些限制下运作,需要从架构层面思考,理解各种集成模式。临时修补和凭感觉编程很可能会带来更多问题,而非解决问题,并拖慢迈向智能体时代的步伐。In practice, most of the effort goes into untangling systems of record that often hold conflicting versions of the truth and aren't designed for agentic access; think of an ERP system that doesn't let an agent write to it. I suspect these integration constraints are here to stay (barring a singularity) as long as businesses depend on diverse software to run. Making agents work with these constraints requires architectural thinking: an understanding of integration patterns. Tactical fixes and vibe coding are likely to create more problems than they solve and slow the transition to an agentic era.
这些智能体做出的决策,质量取决于我们为它们提供的上下文。要让客户入职智能体发挥作用,它需要关于客户及其历史记录的准确、整洁的信息。数据产品思维有助于实现这一点。将关键领域信息构建为数据产品,并确保其可发现且可安全访问,就能让这些智能体承担更具挑战性的任务。要做好这件事,需要自动化治理和成熟的数据管理实践,而且这些实践的设计对象不仅要包括人,也要包括智能体。在 Thoughtworks,我们一直在构建一个名为 Agent/works 的平台,以应对此类问题;也许可以把它留作另一篇文章的话题。The decisions these agents make are only as good as the context we give them. For a customer onboarding agent to be effective, it needs clean information about the customer and their history. Data product thinking helps with that. Representing key domain information as a data product, with discoverability and secure access, enables these agents to take on more ambitious tasks. To do this well, you'd need automated governance and mature data management practices designed not only for humans but also for agents. At Thoughtworks, we've been building a platform called Agent/works for problems like these; perhaps that's a topic for another article.