写代码前如何为多智能体工作流规划重试

带验证与人工审核的多智能体重试逻辑
以一个由三个部分构成的研究助手为例:监督者、研究智能体和工具执行器。
我之所以选择研究助手这个例子,是因为作为一名刚毕业的计算机科学专业学生,我在做毕业论文时曾与研究导师合作、参与研究工作。
研究智能体的任务很简单。当研究智能体拿到一个主题时,它应当找到相关内容,并就该主题提交一份简报,其中包含摘要和来源链接。监督者把任务交给研究智能体,后者随后向搜索工具发出调用,再由工具执行器执行该调用。
第一次搜索请求超时。
智能体仍然给出了回复。摘要里有两句话,来源列表为空,complete 标志被设为 false。该标志被读取后,监督者把任务退回给研究智能体。
第二次尝试与第一次非常相似。搜索请求再次超时,智能体又给出了一份不完整的回答。
到了这个阶段,工作流中的一个问题很容易被忽视。监督者知道上一次尝试失败了,但研究智能体并不知道先前的错误,它只拿到最初的任务。它没有其他数据可供参考,而搜索工具仍然不可用。
这个过程可能在两者之间来回重复,直到重试逻辑之外的某个因素将其终止。
在做我的毕业论文——一个欺诈检测模型——时,我和导师来回沟通了很多次,却始终不太清楚问题出在哪里。他对这个模型有各种意见,但从没告诉我具体是什么。那是我大学期间最令人困惑的时刻之一。
如果智能体在同一份单薄的回答中把 complete 设为 true,导师本会接受这个答案。判断结果只有一种方式:智能体对自己工作的评价。
这个设计缺失了若干决策。导师必须有明确的尝试次数上限。下一次尝试必须包含足够的信息,以判断哪里出了问题。应用还应判断再一次尝试是否可能有所帮助,以及在接受返回的简报之前,判断它是否满足标准。
与其在实现编排器时一次次靠失败去发现,不如在蓝图中把这些事情定下来。
所以本文讲的是在编码之前有意识地做出这些决策,并以一种队友可以阅读和讨论的方式呈现。我把这种形式称为蓝图:流程的图示,加上它所依赖的状态。
我并不觉得图示在每个项目上都是必需的第一步。一个没有分支的两步流水线放在脑子里就够了,画出来多半只是走个形式。收益要从分支、共享状态和失败路径开始累积时才显现,因为在那些情况下,一次运行可能已经出了问题却仍在继续。
我为毕业论文构建的东西就是这么复杂。它涉及多个用户和角色,包括管理员、分析师和监管机构,而且它会根据支付媒介——电汇、卡支付或销售点(POS)机——采用不同的指标来判定欺诈。所以用例图非常重要。它帮我理解了项目的各个方面。这样的规划让我在调试时省去了很多不必要的压力,因为我可以直接去看我的图,准确追踪该从哪里下手,而不是把一切推倒重来。
流程很直接:画出控制流,命名状态以及拥有该状态的组件,写下什么样的答案算是可接受的,然后编写编排器。
把想法变成蓝图
我用 Mermaid 来画这些图,因为它更简洁,也让我的工作更有条理。我可以轻松地修改,或者回到之前做过的内容,要么改代码,要么手动添加。我还可以在导出前调整尺寸,这样出来的图片效果更好。图只由文本构成,因此它和代码一起存放在 Markdown 文件中;如果设计发生变化,改动会出现在拉取请求里,供他人查看。
在动手画任何图之前,值得先理清两件容易被图混为一谈的事。控制流决定下一个要执行的组件,而数据流指的是组件之间的数据流动(例如上下文、结果、工具输出和错误)。一张图可能把前者画对了,却漏掉了后者。
把失败的任务返回给智能体是一个很好的控制决策。但除非把之前的错误也返回给智能体,否则它会重复同样的错误,而这两种情况下的图看起来是一样的。
这是一个 supervisor 的初版方案,它能够把工作路由给研究智能体或编码智能体,二者都可能调用工具。这是按人们在初稿中通常的画法绘制的,我特意让它保持不完整。
第一张蓝图:supervisor 把每个任务分配给研究(或编码)智能体,在重试预算仍有剩余时,无效的回复会被退回 supervisor。图片由作者提供。
从上往下读,任务进来,supervisor 选择一条分支。这是 supervisor 唯一要做的事。智能体负责处理任务,如果某个智能体需要工具,调用会发往工具执行器,执行器再把结果或错误返回给同一个智能体。我喜欢这一点,因为 supervisor 不必了解任何工具的行为方式。
校验本身就是一个步骤,属于应用层。校验之后,这次运行要么返回结果,要么回环到 supervisor,同时还有一条转交人工的出口。
指向状态的那些虚线是有意加入的。当人们读到“共享状态”一词时,脑海里会浮现出每个智能体都能编辑每个字段的画面,而我认为这是错的。在这里,编排器独占拥有权威状态,也就是尝试计数器、状态以及累积的错误。
我构建的系统也是同样的运作方式。管理员、分析师和监管机构各自都有能做的事和不能做的事。分析师只能查看并了解某笔交易被标记时发生了什么。管理员可以录入详细信息并运行批处理流程,例如把一份交易 CSV 文件放进系统并拿到结果。只有监管机构能够决定被标记交易的处理结果:是被批准,还是被转交给另一个部门做调查。它们的权限并不相同,而这正是关键所在。
智能体接收输入并返回响应。工具调用及其结果属于发起它们的那个智能体,只在智能体的回复中才被加入工作流。如果某个智能体能编辑自己的尝试次数计数器,它也可以自行决定自己永远不会用完尝试次数。
图里还有一些没有说明的地方。重试节点只询问是否还有剩余预算,却没有说明这个预算计的是什么。返回监督者的循环不携带任何信息,因此第二次尝试开始时掌握的信息与第一次相同。
每一种失败都被同等对待,尽管有些失败无论重复多少次操作都无法修复。图中也没有提到工具产生的错误是如何传递到验证步骤的。
这个工作流需要一份记忆来填补这些缺口,而且它不需要很大。这就是我会作为起点的状态,它被拆分,从而清晰地分成两种不同的东西:编排器的字段和智能体的回复。
from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Optionalclass Status(Enum): RUNNING = "running" # 在 record_attempt 之后,仍为 RUNNING 意味着“再次路由” SUCCEEDED = "succeeded" NEEDS_REVIEW = "needs_review"@dataclass(frozen=True)class ToolOutcome: tool: str output: Any = None error: Optional[str] = None # 由执行器根据我们的错误策略填充,绝不由智能体猜测。 # 策略未作规定的任何内容都保持 False,并转交人工处理。 retryable: bool = False @property def failed(self) -> bool: return self.error is not None@dataclass(frozen=True)class AgentReply: agent: str answer: dict[str, Any] tool_outcomes: tuple[ToolOutcome, ...] = ()@dataclassclass WorkflowState: task_id: str task: str status: Status = Status.RUNNING attempts: int = 0 max_attempts: int = 3 # 总尝试次数,包含首次尝试 replies: list[AgentReply] = field(default_factory=list) # 纯字符串,因此可以直接放入下一次尝试的上下文中。 errors: list[str] = field(default_factory=list) def __post_init__(self) -> None: if self.max_attempts < 1: raise ValueError("max_attempts must be at least 1")
原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。
查看英文原文(How to Plan Retries for Multi-Agent Workflows Before You Write Code)
Multi-Agent Retry Logic With Validation and Human Review
Take a research assistant made up of three elements: supervisor, research agent, and tool executor.
I picked a research assistant because, as a recent computer science graduate, I worked with research supervisors and on research work for my final-year thesis.
The research agent's task is easy. When the research agent is given a topic, it should find content and present a briefing on the topic with a summary and links to the sources. The supervisor gives the task to the research agent, which then sends a call to the search tool, which is then executed by the tool executor.
The first search request times out.
The agent still provides a reply. There are two sentences in the summary, an empty sources list, and a complete flag set to false. The flag is read, and the task is returned to the research agent by the supervisor.
The second attempt is very similar to the first. The search request times out once again, and the agent provides yet another partial answer.
At this stage, an issue in the workflow can be easily overlooked. The supervisor is aware that the previous attempt was a failure, but the research agent does not know about the previous error and gets only the original task. It does not have any other data to refer to, and the search tool is still unavailable.
This process may be repeated back and forth between the two until something outside the retry logic stops it.
While working on my final-year thesis, a fraud detection model, I kept going back and forth with my supervisor and did not really know where the issue was. He had different issues with it, but he never told me what they were. That was one of the most confusing moments of my time at university.
The supervisor would have accepted the answer if the agent had set complete to true in the same thin answer. There was only one way to judge the outcome: the agent's opinion of its own work.
This design has a number of missing decisions. The supervisor must have a clear number of attempts. The next attempt has to include sufficient information to determine what is not working. The application should also determine whether another attempt is likely to help, and whether the returned briefing satisfies the criteria before accepting it.
It would be better to get those things settled in a blueprint than to find out one failure at a time while implementing the orchestrator.
So this article is about making those decisions deliberately, prior to coding, in a way that a teammate can read and debate. I will call that form a blueprint: a drawing of the flow, plus the state it relies on.
I do not feel like a diagram is a necessary first step on every project. A two-step pipeline with no branching will fit in your head, and drawing it is mostly ceremony. The payoff begins when branches, shared state, and failure paths accumulate, because in those situations a run can go wrong and still keep going.
What I built for my thesis was complicated in that way. It had several users and roles, including admins, analysts, and regulatory bodies, and it used different metrics for determining fraud depending on the payment medium: wire transfer, card payment, or point-of-sale (POS) machine. So the use case diagram was very important. It helped me understand various aspects of the project. Planning like that saves me a lot of unnecessary stress when debugging, because I can easily go to my diagram and trace exactly where to work instead of tearing everything down.
The process is straightforward: draw the control flow, name the state and the component that owns it, write down what an acceptable answer would be, and then write the orchestrator.
Turning the Idea into a Blueprint
I use Mermaid for these diagrams because it is cleaner and keeps my work organized. I can easily make changes or go back to something I did, either by correcting the code or by adding something manually. I can also resize it before I export it, so the image comes out better. The diagram consists only of text, so it is stored in a Markdown file with the code, and if the design changes, the change appears in the pull request, where someone can look at it.
Before making any drawing, it is worthwhile to untangle two things that diagrams tend to blur together. Control flow determines the next component to be executed, while data flow refers to the flow of data between components (for example, context, results, tool outputs, and errors). A diagram may depict the first one right and leave out the second one.
Returning a failed task to an agent is a fine control decision. But unless the previous error is returned to the agent as well, it will repeat the same mistake, and the diagram looks the same in both cases.
Here is a first pass for a supervisor that is able to route work to a research agent or a coding agent, both of which may call tools. It is drawn as one normally would in a first draft, and I have intentionally left it incomplete.

The first blueprint: the supervisor assigns each task to the research (or coding) agent, and an invalid reply goes back to the supervisor while retry budget remains. Image by author.
Reading it from top to bottom, a task comes in, and the supervisor selects one branch. That is the only thing the supervisor does. The agents take care of the task, and if one requires a tool, the call goes to a tool executor, which returns a result or an error to the same agent. I like that, as the supervisor does not have to know how any tool behaves.
Validation is a step in itself that belongs to the application. After it, the run either returns a result or loops back to the supervisor, and there is an escape to a human.
The dashed lines leading to the state have been intentionally included. When people read the words “shared state” they visualize each agent being able to edit each field, and I think that is wrong. Here, the orchestrator has sole ownership of the authoritative state, which is the attempt counter, the status, and the accumulated errors.
The system I built worked the same way. The admins, analysts, and regulatory bodies each had what they could do and could not do. Analysts could only view and understand what was going on when a transaction got flagged. The admin could input details and run batch processes, for example, putting a CSV file of transactions into the system and getting the results. The regulatory bodies were the only ones able to decide what happened to a flagged transaction: whether it got approved or was pushed on to another section for investigation. They did not all have the same power, and that was the point.
The agent receives input and returns a response. Tool calls and their results are part of the agent that made them, and are only added to the workflow in the agent's reply. If an agent had the ability to edit its own attempt counter, it could also decide that it will never run out of attempts.
There are also some things the diagram does not say. The retry node only asks if there is still budget remaining, but does not specify what the budget counts. The loop back to the supervisor carries no information, so the second attempt starts with the same information as the first.
Each failure is dealt with equally, although some failures will never be fixed by repeating the action. There is also no mention of how an error from a tool gets passed to the validation step.
The workflow requires a memory to close these gaps, and it does not need to be much. This is the state I would begin with, split so that there are clearly two different things: the orchestrator's fields and the agents' replies.
from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Optionalclass Status(Enum): RUNNING = "running" # after record_attempt, still RUNNING means "route again" SUCCEEDED = "succeeded" NEEDS_REVIEW = "needs_review"@dataclass(frozen=True)class ToolOutcome: tool: str output: Any = None error: Optional[str] = None # Filled in by the executor from our error policy, never guessed by the agent. # Anything the policy has no opinion on stays False and goes to a person. retryable: bool = False @property def failed(self) -> bool: return self.error is not None@dataclass(frozen=True)class AgentReply: agent: str answer: dict[str, Any] tool_outcomes: tuple[ToolOutcome, ...] = ()@dataclassclass WorkflowState: task_id: str task: str status: Status = Status.RUNNING attempts: int = 0 max_attempts: int = 3 # total attempts, first try included replies: list[AgentReply] = field(default_factory=list) # Plain strings so they can go straight into the next attempt's context. errors: list[str] = field(default_factory=list) def __post_init__(self) -> None: if self.max_attempts < 1: raise ValueError("max_attempts must be at least 1")
The task, the counter and its limit, the accumulated errors, and the replies so far must survive each handoff, because each one is used in a subsequent decision. AgentReply and ToolOutcome are frozen, so their fields cannot be reassigned. That implies that agents and the executor create values and leave workflow state alone.
I think this is a difference that is not often mentioned: an agent generating an output is a different thing from the system accepting that output. An agent may return text that looks complete while skipping a field the task requires, or while a tool call underneath it failed. So acceptance gets its own function.
I had the same split in what I built. When the model flagged a transaction as fraud, it got sent to the regulatory bodies, which in my project's design were the likes of the CBN (Central Bank of Nigeria) and the NDIC (Nigeria Deposit Insurance Corporation). They determined whether it should be approved, investigated, or blocked completely, because sometimes it might not be fraud per se, and other things can build up to a flag. The model could be trusted to make some kinds of decisions on its own, but a flagged transaction usually went to the regulatory bodies, the humans in the loop, before anything final happened.
REQUIRED = ("summary", "sources")def why_rejected(reply: AgentReply) -> list[str]: # Structure and tool failures only. A reply can pass this and still be wrong. reasons = [] for name in REQUIRED: value = reply.answer.get(name) if not value or (isinstance(value, str) and not value.strip()): reasons.append(f"missing or empty: {name}") reasons += [f"tool {o.tool} failed: {o.error}" for o in reply.tool_outcomes if o.failed] return reasons
If the list is empty, the reply is accepted. By the time a reply reaches this function, it has already been parsed into a dict, so format validity is assumed to have been checked upstream. A blank required field is treated as a missing field, and any failed tool call fails the attempt. That last rule is a policy decision, because a real system might let an agent recover from a tool error within its own loop.
And a reply whose sources have nothing to do with its summary passes without any complaints. This check does not determine whether the reply is correct, only whether it has the right shape.
What the First Blueprint Missed
Return to the opening, back to the research assistant. That run is about what you see when a team constructs the first diagram as drawn and adds any missing pieces along the way: the agent's own flag is the only thing that decides what counts as complete, there is no clear limit on the number of times a retry could be attempted, and the retry carries only the original task.
The real problem is the orchestration. No one specified what an acceptable reply looked like in terms the application can check, what the counter counted, what to do when it ran out, or what information the next attempt should get about the previous one.
The updated version keeps track of all the attempts made and validates the reply before anything else. It keeps the errors so they can go back with the retry, it distinguishes between failures that should be retried and failures that should not, and it gives a run that has exhausted its retries someplace to go.
The revised blueprint: each attempt is recorded and validated, errors are retained, and a non-retryable failure or a used-up budget goes to human review, with the reason recorded. Image by author.
A couple of edges carry more meaning than the diagram can fit. The path from the retryability check to human review means a non-retryable failure, while the path from the attempt check means the budget has been exhausted. The code records which one it was. On the retry path back to the supervisor, the accumulated errors and the task state go along, so the next attempt can see what went wrong.
There are two questions here that can get confused. why_rejected determines whether or not an attempt is accepted. is_retryable is only asked after a rejection, and it determines whether another attempt is allowed.
The policy is conservative on purpose. If a rejection has no failed tool calls, such as a missing field, it is considered retryable, on the assumption that a new attempt with the errors in context might produce a different answer. There is always a possibility that the assumption is incorrect. A permanent structural problem would consume the entire budget before escalating, and there is no check here on whether repeating an attempt would duplicate a side effect from the previous one.
If tool calls are failing, each of them has to be marked retryable, or the task will not be retried. If even one failed call is not marked retryable, the task goes to a person.
So, a question arises as to where retryable comes from. The tool executor is the obvious place to set it, as it has access to the exception or status code, but it cannot determine by itself whether that error is retryable. The application has a classification policy, for example, a mapping of error types to flags per tool, and the executor applies it to the errors. Anything the policy does not cover reverts to non-retryable.
Its default value is False because a failed call gives no indication of what a repeat would do. There are three situations which appear similar on the outside and require different solutions. A transient failure, such as a timeout or a dropped connection, can succeed without modification, as can a rate limit after the caller has waited long enough. A failure that requires a change in the request (such as incorrect arguments) or a change in the surrounding conditions (such as a missing permission or an expired credential) will keep failing until that change actually happens, so retrying it only consumes budget. But the call with side effects is the dangerous one. Once a write times out, you might not know whether it happened, so a repeat may send a second e-mail or add a second record to the database, unless the operation is safe to repeat or can be checked first.
I once had this happen at a sporting goods store. I was paying for some things I bought, and the payment just timed out for no reason. I did not know if the money had gone or not, and the cashier had not seen the payment, so I could not leave with the goods. I waited, and nothing came through. The cashier also checked, so I tried again. It turned out the payment had gone to the store twice, so I had paid twice for the same goods. I had to alert them, and they gave me a refund for the double payment.
These are all judgements about each tool, and retryable is only a label. Other features, like delays, deduplication of side effects, and retry safety, all live in code the snippet does not contain. The whole purpose of the label is to determine whether there will be another attempt. Retrying by mistake may repeat an action, while escalating by mistake only costs some human effort, which is why anything not classified goes to a human.
Here is the decision logic in code.
def is_retryable(reply: AgentReply) -> bool: # One failed call that is not marked retryable is enough to stop. # A rejection with no failed calls (a missing field, say) counts as retryable. return all(o.retryable for o in reply.tool_outcomes if o.failed)def record_attempt(state: WorkflowState, reply: AgentReply) -> None: if state.status is not Status.RUNNING: raise RuntimeError(f"{state.task_id} already finished: {state.status.name}") state.attempts += 1 # count before validating, so every finished attempt is counted state.replies.append(reply) reasons = why_rejected(reply) if not reasons: state.status = Status.SUCCEEDED return state.errors += [f"attempt {state.attempts}: {r}" for r in reasons] # Non-retryable is checked first so the audit trail names the real cause. if not is_retryable(reply): cause = "non-retryable failure" elif state.attempts >= state.max_attempts: cause = "retry budget exhausted" else: return # still RUNNING; the supervisor routes again with state.errors in hand state.errors.append(f"escalated after attempt {state.attempts}: {cause}") state.status = Status.NEEDS_REVIEW
Retry, escalate, or stop is a real choice, and I am not going to pretend that there is a single right answer. A retry is expensive, both in time and money, and only worthwhile when the next attempt differs from the previous one, either because the error is now in context or because the failure came from variable behavior.
I work the same way with AI tools. When ChatGPT or Claude gives me a bad answer, I do not just hit regenerate, because that is just doing the same thing and you will not really get any results. For example, when I generate a cover image for one of my articles, I look at what it did with my first input and assess the result. Then I rework the prompt. I note what it did wrong, or what it overdid, point it to that particular part, and tell it what it did wrong and how I want it done differently.
Escalation uses human attention but keeps work that may be salvaged. Early quitting is an inexpensive approach, but it throws away whatever a second try might have fixed. I do not agree with the notion that every unfinished result deserves another try.
None of this deals with hallucination, and it is important to note that. Explicit control flow makes it easier to find and fix orchestration defects like a missing retry limit, an ambiguous routing rule, or a wrong state transition. A fabricated claim that conforms to the schema is another issue. Catching it takes evidence checks against retrieved sources, verification of tool results, domain-specific validation, or a human.
You can only tell that ChatGPT or Claude has made a mistake if you have an idea of what you are doing. If you do not, you go in blindly and take whatever answer it gives you.
Translating the Blueprint into Code
The blueprint maps onto code pretty directly, whether the model calls go through a managed API or a self-hosted open-weight model like Reflection's Beam, which I wrote about recently. Some of that mapping is already on the page. The state object is the authoritative state, why_rejected is the validation kept separate from the agent, and record_attempt holds the retry policy and the terminal status in one place.
Tool handoffs must have an interface that specifies the validated arguments that should be passed in and a result type that carries errors back out. Timeouts and tool errors each need their own recovery path, with a retryable or non-retryable label that originates from the application's policy.
A diagram outlines what should occur when an attempt fails, but remains silent on an unreachable state store, a hanging tool call, or two workers grabbing the same task. Those cases require their own design, enforcement in code, and tests.
So, before I start composing any orchestration code, I want to know what decides the next step at each branch, what state passes through each handoff and who it belongs to, what is required for a reply to be considered acceptable, which errors can be attempted again, and what to do when the attempts run out.
If you are thinking about running agents like these on a self-hosted model, my piece on Reflection's Beam looks at what it actually takes to host a 501B open-weight model, and why the 23B active parameters are not the whole story.
The majority of the problems in the research assistant from the start had little to do with the model and more to do with the workflow. The agent returned a thin answer once, and each subsequent pass returned the same answer, since the workflow never decided what answer would be considered acceptable, what information the second attempt should include, or when it should stop. These are questions of design, and a diagram is an inexpensive way to ask them.
Having a blueprint brings the missing decisions to the surface while it is still relatively inexpensive to change them. Showing that the system works still takes implementing it in code and testing it at runtime.
I write about AI and ML engineering, and about what new model releases mean for the people who build with them. You can subscribe to my newsletter if you would like more of that.
Add architectural guardrails around how agents read untrusted sources and use them in the workflow.
October 10, 20266 min read
Is Your Notebook Too Large?
October 17, 20224 min read
Building products without the coding part
March 19, 202612 min read
How to define recurring work, give AI the right context, explain what high-quality work looks like, and decide where human judgment is still needed.
July 16, 20269 min read
A separation of powers for control of autonomous agents
October 27, 20268 min read
Agents got good. The hard part now is everything around them.
October 13, 20268 min read
Practical example of balancing model performance and computational resource limitations - with code and visualization
August 28, 202111 min read
Exploring GitHub, Docker, and Heroku
April 13, 20218 min read
The most powerful systems on Earth, such as human brains, financial markets, and swarms, work well because no signal part is in charge of others. This is exactly the secret behind the success of Deep Neural Networks.
December 12, 202510 min read
原文为英文,正文由自动抓取并保留原文。
原文发布于 Towards Data Science(How to Plan Retries for Multi-Agent Workflows Before You Write Code),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。