Getting started with loops —— Anthropic如何设计循环

发布时间:2026/7/8 13:15:26
Getting started with loops —— Anthropic如何设计循环 There’s a lot of talk right now about designing loops instead of prompting your coding agent. If you spend some time on X trying to pin down what a loop actually is, youll come across multiple different answers.眼下关于“设计循环”designing loops而非仅仅向编码智能体coding agent发送提示词prompting的讨论十分热烈。如果你花点时间在 X原 Twitter上试图弄清楚“循环”究竟是指什么会发现各种各样的说法。On the Claude Code team, we defineloops as agents repeating cycles of work until a stop condition is met. We categorize a few different types of loops based on:How they are triggeredHow they are stoppedWhat Claude Code primitive is usedWhat type of task is most appropriate for each.在 Claude Code 团队中我们将“循环”定义为智能体agent重复执行工作周期直到满足停止条件为止。我们根据以下标准对几种不同类型的循环进行了分类触发方式停止方式所使用的 Claude Code 原语primitive最适用的任务类型We’ll cover the main loop types, when to use each, and how to maintain code quality while managing token usage. Not all tasks require complex loops; start with the simplest solution and use these patterns selectively.我们将介绍主要的循环类型、各自的适用场景以及如何在控制 Token 用量的同时保持代码质量。并非所有任务都需要复杂的循环建议从最简单的方案入手并有选择地运用这些模式。Turn-based loops回合制循环Triggered by: A user prompt.Stop criteria: Claude judges it has completed the task or needs additional context.Best used for:Shorter tasks that are not part of a regular process or schedule.Managed usage by:Write specific prompts and improve verification using skills to reduce the number of turns.触发方式用户提示词。停止条件Claude 判定任务已完成或需要更多上下文信息。适用场景不属于常规流程或固定日程的短时任务。使用管理编写具体的提示词并利用各项技能加强验证从而减少交互轮数。Every prompt you send starts a manual loop with you directing each turn. Claude gathers context, takes action, checks its work, repeats if needed, and responds. We call this the agentic loop.For example, ask Claude to create a like button. It reads your code, makes the edit, runs the tests, and hands back something itbelievesworks. You then manually check the work, and write the next prompt.You can improve the verification step by encoding your manual steps as a SKILL.md so Claude can check more of its own work, end-to-end. This should include tools or connectors to allow Claude tosee,measureorinteractwith the result. The more quantitative the checks are, the easier it is for Claude to self-verify.For example, in your SKILL.md file you may specify:--- name: verify-frontend-change description: Verify any UI change end-to-end before declaring it done. --- # Verifying frontend changes Never report a UI change as complete based on a successful edit alone. Verify it the way a human reviewer would: 1. Start the dev server and open the edited page in the browser. 2. Interact with the change directly. For a new control (button, input, toggle): click it, confirm the expected state change, and screenshot before/after. 3. Check the browser console: zero new errors or warnings. 4. Use the Chrome Devtools MCP, run a performance trace and audit Core Web Vitals. If any step fails, fix the issue and rerun from step 1 — do not hand back partially verified work.Goal-based loop (/goal)基于目标的循环 (/goal)Triggered by: A manual prompt in real-time.Stop criteria: Goal achieved OR maximum number of turns reached.Best used for:Tasks that have verifiable exit criteria.Managed usage by:Setting a specific completion criteria and explicit turn caps, “stop after 5 tries.”触发方式实时手动提示。停止条件达成目标或达到最大轮次限制。适用场景具有可验证结束标准的任务。管理方式设定明确的完成标准和轮次上限例如“尝试 5 次后停止”。Sometimes, a single turn is not enough, especially for more complex tasks. Agents do better when they can iterate. You can extend how long Claude keeps iterating by defining what done looks like with /goal.When you define the success criteria, Claude doesn’t have to make a determination on what is “good enough” and end the loop early. Each time Claude tries to stop, an evaluator model checks your condition and sends it back to work until the goal is met or a number of turns you define is reached.有时单轮交互并不足以完成任务尤其是面对较复杂的任务时。如果能够进行迭代智能体Agent的表现会更出色。你可以通过 /goal 指令定义“任务完成”的标准从而延长 Claude 的迭代过程。一旦设定了成功标准Claude 就不必自行判断何为“足够好”并过早结束循环。每当 Claude 试图停止时评估模型都会根据你设定的条件进行检查若未达到目标或未达到你指定的轮数限制它便会指示 Claude 继续工作。This is why deterministic criteria, such as number of tests passed or clearing a certain score threshold, are so effective.For example:/goal get the homepage Lighthouse score to 90 or above, stop after 5 tries.Time-based loop (/loop and /schedule)基于时间的循环/loop 和 /scheduleTriggered by: A specified time interval.Stop criteria: You cancel it, or the work completes (the PR merges, the queue is empty).Best used for:For recurring work, or interfacing with external environments / systems.Managed usage by:Set longer intervals or react based on events rather than time.触发条件指定的时间间隔。停止条件您手动取消或任务完成例如 PR 已合并、队列已清空。适用场景周期性任务或与外部环境/系统进行交互。使用管理建议设置较长的时间间隔或基于事件而非时间进行响应。Some agentic work is recurring: the task stays the same and only the inputs change. For example, summarizing Slack messages every morning. Other work depends on external systems, and a simple way to interface with one is to check it on an interval and react to what changed. For example, a PR which may receive code reviews or fail CI.For these, you can trigger when Claude runs with /loop which re-runs a prompt on an interval. For example:/loop 5m check my PR, address review comments, and fix failing CI/loop runs on your computer, so if you turn it off, it stops. You can move the loop to the cloud by creating a routine with /schedule.Proactive loops主动式循环Triggered by: An event or schedule, with no human in real time.Stop criteria: Each task exits when its goal is met. The routine itself runs until you turn it off.Best used for:Recurring streams of well-defined work: bug reports, issue triage, migrations, dependency upgrades, etc.Managed usage by:Routing routines to smaller, faster models and using the most capable model for judgment calls.触发方式由事件或预定计划触发无需人工实时介入。停止条件各项任务在达成目标后即结束例行程序本身则持续运行直至您将其关闭。适用场景重复性的、定义明确的工作流例如错误报告、问题分拣、数据迁移、依赖项升级等。管理方式将例行程序分流至更小、更快的模型并利用能力最强的模型进行需要判断决策的任务。The primitives above, along with other Claude Code features likeauto modeanddynamic workflows(research preview) can be composed into a loop for long-running work.For example, to handle incoming feedback, you can use:/schedule(research preview) to run a routine that checks for new reports/goalto define what done looks andskillsto document how to verify itDynamic workflowsto orchestrate agents that triage each report, fix it, and review the fixAuto modeso the routine runs without stopping to ask for permissionPutting it together, a prompt could look like this:/schedule every hour: check #project-feedback for bug reports. /goal: dont stop until every report found this run is triaged, actioned, and responded to. When fixing a bug, use a workflow to explore three solutions in parallel worktrees and have a judge adversarially review them.Maintaining code qualityThe quality of a loop’s output depends on the system around it. When designing the system:Keep the codebase itself clean: Claude follows patterns and conventions that already exist in your codebase.Give Claude a way to verify its own work: Encode what good looks like for you and your team with skills.Make docs easy to reach:Frameworks and libraries docs have up-to-date best practices.Use a second agent for code reviews: A reviewer with fresh context is less biased and not influenced by the main agent’s reasoning. You can use the built-in /code-review skill or Code Review for Github.When an individual result doesn’t meet the standard, don’t stop at fixing the individual issue, try to encode it to improve the system for all future iterations.Managing token usageTo manage token usage, loops should have clear boundaries:Choose the right primitive and model for the job:Smaller tasks don’t need multiple agents or loops. Some tasks can use cheaper and faster models.Define clear success and stop criteria:Be specific about what done looks like so Claude can arrive at the solution sooner (but not too soon).Pilot before a large run:Dynamic workflows can spawn hundreds of agents. Gauge usage on a smaller slice of the work first.Use scripts for deterministic work: Running a script is cheaper than reasoning through the steps. For example, a PDF skill can ship a form-filling script that Claude runs each time, instead of re-deriving the code.Don’t run routines more often that you need to:Match the interval to how often the thing you’re watching changesReview usage:The /usage command breaks down recent usage by skills, subagents, and MCPs, /goal with no arguments shows number of turns and token usage so far, /workflows shows each agent’s token usage and you can stop an agent at any time.Getting startedTo summarize:LoopYou hand offUse it whenReach forTurn-basedThe checkYoure exploring or decidingCustom verification skillsGoal-basedThe stop conditionYou know what done looks like/goalTime-basedThe triggerThe work happens outside your project on a schedule/loop,/scheduleProactiveThe promptThe work is recurring and well-definedAll of the above, and dynamic workflowsTo get started with loops, look at the work you already do. Pick one task where you’re the bottleneck and ask which piece you could hand off: can you write the verification check? Is the goal clear enough? Does the work arrive on a schedule?Once you have an idea, run the loop, observe the results like where it stalls or over-reaches, and don’t be afraid to iterate on it.For more information, read the Claude Code docs on running agents in parallel, as well as the loop, schedule, goal, and dynamic workflows pages.This article was written by Delba de Oliveira and Michael Segner# Overview - Claude Code Docs# 安装 Claude Codecurl -fsSL https://claude.ai/install.sh | bashClaude Code is an agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your development tools. Available in your terminal, IDE, desktop app, and browser.Claude Code is an AI-powered coding assistant that helps you build features, fix bugs, and automate development tasks. It understands your entire codebase and can work across multiple files and tools to get things done.Claude Code 是一款具备自主能力的编程工具能够读取代码库、编辑文件、执行命令并与您的开发工具集成。它支持在终端、IDE、桌面应用及浏览器中使用。Claude Code 是一款由 AI 驱动的编程助手旨在帮助您构建功能、修复错误并实现开发任务自动化。它能够理解您的整个代码库并跨多个文件和工具协同工作以完成任务。--Getting started with loops | Claude by Anthropic