Stop Writing Prompts. Design Loops That Make AI Iterate Until It's Right.
Foreword: Today I learned a concept that 'reshaped my worldview' — the AI Loop. The teacher said a single tweet attracted 7 million views, and the core idea was one sentence: Stop writing prompts for AI; you should be designing Loops. The author of Claude Code also said: I don't write prompts either, I Loop. After hearing this, I had an epiphany: the 'manual loop' method I had been using all along was the least efficient.
1. You're Already 'Manually Looping' Every Day, You Just Don't Realize It
1.1 What is a Loop?
The teacher said:
"A Loop is one of the most fundamental capabilities of a computer. A Loop consists of three things: where to start, what to repeat, and when to stop."
Checking and reformatting ten thousand rows of data line by line takes a human forever, but a loop program finishes it in seconds.
But a Loop isn't just a tool for processing data; it is also the underlying logic of AI training.
"All the AI we use today was produced by Loops. DeepSeek, Claude, Qwen… the underlying logic of their training is the same: show a batch of data to the model, calculate how much it got wrong, adjust the parameters, and do another round. After trillions of cycles, the AI learns to converse and collaborate."
AI itself is a product of Loops. Without loops, there would be no ChatGPT, Claude, or DeepSeek today.
1.2 The Way You Collaborate with AI is Also a Loop
Think about how you usually use AI:
Write prompt → See result → Not satisfied → Modify prompt → See result again → Still not satisfied → Modify again…
This is a 'Manual Loop.' You are the 'loop controller' — judging whether the result is good each time, and continuing the loop if it's not.
The teacher said:
"The work is handed over to the AI, but you have to watch the AI work. A Loop can pull us out of that."
The problem with a Manual Loop: you have to constantly monitor it, costing time and effort. The advantage of an AI Loop: it removes the 'human' from the loop, letting the AI run on its own.
Of course, there is a downside: Token explosion. Each cycle consumes tokens, and running too many hurts your wallet.
2. The Core of an AI Loop: Generate → Check → Loop
2.1 Three Steps
The core logic of an AI Loop is just three steps:
| Step | Function | Description |
|---|---|---|
| Completion (Generate) | AI works | Generates content based on the task description |
| Check (Inspect) | AI checks | Validates the generated content against rules |
| Loop (Cycle) | Redo if unsatisfied | Check fails → Regenerate → Check again |
This is like hiring an employee (AI) and a quality inspector (also AI):
- The employee writes the copy.
- The quality inspector checks the copy.
- Not up to standard? Send it back for a rewrite.
- Passed? Deliver it.
You (the human) only need to define the task and the rules; leave the rest to the Loop.
2.2 Three Safety Valves: Preventing Token Explosion
The teacher said a Loop has a fatal flaw — Token explosion. Without limits, the AI will loop indefinitely, draining your wallet.
So you must set 'safety valves':
const limit = {
maxRound: 5, // Run at most 5 rounds
maxToken: 2000, // Consume at most 2000 tokens
sameStop: 2 // Stop if the same content is generated 2 times in a row
}
| Safety Valve | Function | Analogy |
|---|---|---|
maxRound |
Limits the number of loop rounds | Let the employee revise at most 5 times; if it's still not good, forget it |
maxToken |
Limits token consumption | The budget is only this much; stop when it's spent |
sameStop |
Detects duplicate output | If the employee submits the same thing twice in a row, they're stuck; don't let them continue |
These three safety valves are the 'braking system' of the Loop. Who dares drive a car without brakes?
3. Practical Application: Implementing an AI Loop with DeepSeek
3.1 Project Configuration
The dependencies in package.json are simple:
{
"dependencies": {
"dotenv": "^17.4.2",
"openai": "^6.43.0"
}
}
openai: The OpenAI SDK, compatible with DeepSeek's API.dotenv: Manages the API Key.
3.2 Initializing the Client
import { OpenAI } from 'openai';
import dotenv from 'dotenv';
dotenv.config();
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: process.env.DEEPSEEK_API_BASE_URL
});
DeepSeek's API is compatible with the OpenAI format, so you can use the openai SDK directly and just change the baseURL.
This is like using an Apple charger to charge an Android phone — it's not the original, but the interface is compatible, so you can just plug it in and use it.
3.3 Defining Tasks and Rules
const task = {
desc: "Xiaohongshu beauty copywriting",
rules: [
"Title contains numbers",
"Body text < 300 characters",
"Viral hit style",
"Ends with a call to action"
]
}
The task description + rule list are the 'goal' and 'acceptance criteria' of the Loop.
desc: Tells the AI what to do.rules: Tells the quality inspector what standards to check against.
This is like placing an order with a renovation company:
desc: "Help me decorate a Nordic-style living room."rules: ["Budget under 50,000", "Construction period 1 month", "Use eco-friendly materials", "Must have storage space"].
3.4 Safety Valves: Determining When to Stop
let round = 0, totalToken = 0, lastText = "", sameCount = 0;
function needLoop() {
return round >= limit.maxRound ||
totalToken >= limit.maxToken ||
sameCount >= limit.sameStop;
}
Three conditions; the loop stops if any one is met:
- The number of rounds is exceeded.
- The token limit is exceeded.
- The same content is generated consecutively (meaning the AI is stuck).
3.5 Generation Function: AI Writes Copy
async function gen() {
const res = await client.chat.completions.create({
model: 'deepseek-v4-flash',
messages: [{
role: "user",
content: `Assume you are a senior Xiaohongshu beauty blogger,
write a piece of ${task.desc}, strictly following:
${task.rules.join("、")}, output only the copy`
}]
});
console.log(res.usage.total_tokens,
res.choices[0].message.content);
return {
text: res.choices[0].message.content.trim(),
token: res.usage.total_tokens
}
}
The generation function does one thing: makes the AI write copy based on the task description and rules.
Returns the copy content and the number of tokens consumed.
3.6 Check Function: AI as Quality Inspector
async function check(text) {
const res = await client.chat.completions.create({
model: process.env.DEEPSEEK_API_MODEL,
messages: [{
role: "user",
content: `Verify the copy: ${text}
Rules: ${task.rules.join("、")},
Output only JSON {pass: Boolean, fail: Array}`
}]
});
return JSON.parse(res.choices[0].message.content.trim());
}
The check function does one thing: makes another AI act as a quality inspector, validating the copy against the rules.
Requires strict JSON output:
pass: true/false: Whether all rules passed.fail: ["Rule 1", "Rule 2"]: A list of rules that failed.
Having AI check AI's work — this is the essence of the AI Loop.
3.7 Main Loop: Stringing Everything Together
async function runLoop() {
console.log('AI Loop started');
while (!needLoop()) {
round++;
console.log(`Round ${round}`);
// 1. Generate copy
const { text, token } = await gen();
totalToken += token;
// 2. Detect duplicates
sameCount = text === lastText ? sameCount + 1 : 0;
lastText = text;
// 3. Check rules
const { pass, fail } = await check(text);
if (pass) {
console.log(`All rules passed, loop ended`);
console.log(`Final copy: ${text}`);
return;
}
console.log(`Failed: ${fail}`);
}
console.log(`\n Brake triggered, forced stop. Last content: ${lastText}`);
}
runLoop();
The execution flow of the entire Loop:
Start
↓
Generate copy (gen)
↓
Detect duplicates → Duplicate count exceeded? → Stop
↓
Check rules (check)
↓
All passed? → Output result, end
↓
Failed → Go back to "Generate copy"
↓
Round/Token limit exceeded? → Force stop
The human only needs to define 'what is wanted' and the 'acceptance criteria'; the Loop runs automatically until satisfied.
4. The Essence of the AI Loop: From 'Manual Loop' to 'Automated Pipeline'
4.1 Comparison of Two Collaboration Modes
| Comparison Item | Manual Loop (Traditional) | AI Loop (Automated) |
|---|---|---|
| Process | Human writes prompt → Human sees result → Human modifies prompt | AI generates → AI checks → Automatic loop |
| Human's Role | Loop controller (must participate every time) | Rule maker (participates only once) |
| Efficiency | Low (human operation required for every cycle) | High (unattended automatic operation) |
| Cost | High time cost | High token cost |
| Applicable Scenarios | Simple tasks, exploratory tasks | Repetitive tasks, tasks with clear standards |
4.2 The Philosophy of the AI Loop
The teacher said something particularly profound:
"Write a prompt, see the result, not satisfied, change it, do it again — manual collaboration with AI. A Loop can pull us out of that."
Traditional way: Humans revolve around the AI. AI Loop: The AI revolves by itself; humans just set the rules.
This is like upgrading from 'hand-washing clothes' to a 'washing machine':
- Hand-washing: You have to scrub, rinse, and wring every piece of clothing yourself.
- Washing machine: You throw the clothes in, set the mode, press start, and wait to get clean clothes.
A Loop is the 'washing machine' of the AI era.
5. Summary: Designing Loops is More Important Than Writing Prompts
| Knowledge Point | Description |
|---|---|
| AI Loop | Generate → Check → Loop until conditions are met |
| Completion | AI generates content based on a task description |
| Check | AI validates content against rules, outputs JSON |
| maxRound | Maximum number of loop rounds |
| maxToken | Maximum token consumption |
| sameStop | Stop on consecutive identical outputs |
| DeepSeek API | Compatible with the OpenAI SDK |
| dotenv | Manages API Keys |
The future of AI collaboration is not 'one question, one answer,' but 'designing Loops.' You define the goal and acceptance criteria, and the AI runs the loop itself until it produces a satisfactory result.
This is not just an efficiency boost, but an upgrade in mindset — from 'operator' to 'designer.'
Afterword
The biggest takeaway today was understanding the concept of the AI Loop. Before, when using AI, it was always a 'manual loop' — write a prompt, see the result, not satisfied, change the prompt, look again… Now I know this loop can be automated.
Next time an interviewer asks you: 'How do you understand the AI Loop?'
You can calmly say:
"An AI Loop is an automated AI collaboration model. The core is three steps: Generation (Completion), Check, and Loop. After the AI generates content, another AI or rule engine checks it. If it fails, it regenerates until conditions are met or a safety valve is triggered. Safety valves include maximum rounds, maximum token consumption, and duplicate detection. This method frees people from the 'manual loop,' transforming them from operators into rule designers."
Then watch the interviewer's surprised expression, and silently think to yourself: This move, solid again.
All code examples in this article are from classroom learning materials and are genuinely runnable.