← все видео

Loop Engineering explained in 20 mins.

Mayank Aggarwal · 2026-06-26 · 19м 43с · 11 346 просмотров · YouTube ↗

Топики: ai-loop-engineering

🎧 Аудио

📝 Summary

model=deepseek-v4-flash · prompt=summary-v7 · 6 775→2 583 tokens · 2026-07-20 11:52:50

🎯 Главная суть

Loop engineering — это автоматизация промптинга: вместо того чтобы вручную давать задание AI-агенту, проверять результат и снова отправлять на доработку, разработчик проектирует цикл, который сам запускает агента, оценивает выход, сохраняет историю попыток и повторяет до выполнения условия останова. Это не замена prompt engineering, а его надстройка: качество цикла напрямую зависит от качества исходных промптов.

Что такое loop engineering и чем оно не является

Концепция родилась из твита, набравшего 8,4 миллиона просмотров: «Не промпть агентов — проектируй циклы, которые промптят агентов». Вопреки шумихе, loop engineering не является принципиально новой технологией. Это, по сути, automated prompt engineering — автоматизированный повтор промптов с обратной связью. Тривиальный пример: человек задаёт задачу «присылать мне новости об AI каждый день в 9 утра». Агент запускается по расписанию, собирает новости и отдаёт результат. Если же требуется, чтобы агент сам проверял качество новостей и переделывал, пока они не станут «достаточно хорошими», — в дело вступает цикл с верификацией и состоянием.

Основные компоненты любого цикла: Trigger – Action – Verification – State

Любой цикл строится из четырёх частей, аналогичных круиз-контролю в автомобиле:

Объективные и субъективные задачи: как задавать проверку

Успех цикла упирается в то, насколько чётко сформулирован критерий успеха. Объективные задачи легко верифицируются: «сделать код быстрее» измеряется в миллисекундах, «отвечать на все непрочитанные письма» — числом оставшихся писем, «пройти тесты» — зелёной галочкой. В таких случаях AI может проверять себя автоматически.

Субъективные задачи (написать хороший LinkedIn-пост, подобрать «интересные» новости) требуют внешнего судьи. Здесь возможны варианты: использовать второй LLM с другим набором весов, привлекать человека в цикл (human-in-the-loop) или опираться на метрики вовлечённости (лайки, просмотры), которые собираются после публикации. Для субъективных задач обязательно нужен механизм сохранения контекста — например, предыдущие посты пользователя и их статистика, чтобы агент понимал, что значит «хорошо» именно для этого автора.

Четыре типа проверок (checks) для цикла

Не всякая задача требует одного и того же вида верификации. Автор выделяет четыре класса:

  1. Run test suite — запуск набора тестов (npm test, Pass/Fail). Чисто численная проверка.
  2. Check if UI looks right — визуальная проверка с помощью другого LLM как судьи. Не требуется точной метрики, достаточно «выглядит правильно».
  3. Subjective judgment — оценка творческого результата (качество статьи, интересность новостей). Обычно требует внешнего датасета или человеческой обратной связи.
  4. Human in the loop — на определённом шаге цикл останавливается и ждёт решения человека (например, «отправить это письмо?»). Человек утверждает или отклоняет, после чего цикл продолжается.

Пошаговый метод построения рабочего цикла

Прежде чем автоматизировать, нужно убедиться, что задача вообще решаема AI. Рекомендуемая последовательность:

  1. Сделать вручную — дать агенту одно задание, посмотреть, способен ли он выполнить его приемлемо. Без этого шага цикл будет бессмысленно гонять ошибки.
  2. Оформить как скилл (skill) — записать промпт в виде готовой инструкции, которую можно переиспользовать (у Claude есть Creator Skill, у других AI — аналоги).
  3. Добавить триггер — поставить выполнение на расписание или событие. На этом этапе это ещё не цикл, а простая автоматизация.
  4. Добавить верификацию и состояние — агент выполняет задачу, проверяет результат, сохраняет, что было сделано, и, если критерий не достигнут, запускает новую итерацию с учётом предыдущего опыта. Именно этот шаг превращает автоматизацию в настоящий цикл.

Когда имеет смысл строить цикл (а когда — нет)

Не каждая задача требует цикличности. Прежде чем проектировать сложную систему, стоит ответить на вопросы:

Если на все ответ «да» — цикл строить стоит. Если нет — проще сделать одноразовый промпт или простую автоматизацию без итераций.

Практические рекомендации и типичные ошибки

Демонстрация: пример с loop library

Автор показывает работу простой библиотеки (доступна публично). Цикл запускается командой с целью: «Исследовать loop engineering и подготовить markdown-файл для новичков». Библиотека на основе цели сама определяет шаги, задаёт уточняющие вопросы, выполняет веб-поиск, сохраняет промежуточные результаты и останавливается по достижении критерия (например, «файл создан»). В основе библиотеки лежит шаблон Ralph loop — стандартный паттерн с persistent memory (сохранение через файлы), stop hook и completion promise. Важно: цикл не заменяет промпт-инжиниринг — он просто повторяет промпты, пока не сойдётся к цели.

📜 Transcript

en · 4 213 слов · 42 сегментов · clean

Показать текст транскрипта
Prompt engineering is red and you should just try for loop engineering. So I'm pretty sure that many of you must have heard the same. Well, all of this started from this one tweet. Here's your monthly reminder that you shouldn't be prompting agents. You should be designing loops that prompts your agents. So this one tweet, everyone has got 8.4 million views. And many people were thinking that, Hey, what is now this new loop engineering come in? I think we all started as I covered in my last video of harness engineering from prompt and context, then harness engineering. And of course now people are also discussing about loop engineering. So on the same, most people are still pressing, let's say the base button on their AI loop engineering kind of just allow them to put everything on an autopilot. So this very nice thing I've created, which would be pretty helpful everyone. So loop is like a cruise control for your AI agent. So we will quickly see that what exactly it is, why it is not that big of a deal and something which is actually just prompt engineering or automated prompt engineering. As I like to say, how can we do the same? We have a loop library as well, which is going to be pretty awesome to look at. and of course some resources which will be helpful for you to master the same so with that everyone let's now start uh let's first let's try to understand what are a few of the things which people have built and the best part uh someone actually also created a loop library as you can see in here which i will be also using in a bit and you can of course get access to and you can just do any of these things so linkedin article writer inbox try age road or rebuild in code so any error or anything which you want to look at the whole idea becomes everyone is that These are the major steps in any loop. So a loop basically is a trigger, then an action, and then a stop condition. So by itself, it is not anything new. You will be having a quick trigger, everyone. This trigger will then do some action. And then, of course, we will be having a stop condition. So just like how a normal loop works. So in that way, the whole approach is same. But the best part is that how now you can move around this. So let me just try it like this. Yeah. And this is how it will work. Right. So that is all about the loop engineering in a very much nutshell, but still let's see that then why people are saying my account engineering is dead and how we can use the same. Okay. So the very first thing, right, we have to see that how it will get triggered. So whatever you have created, it will get triggered. Then it will basically execute. And when I say it here, I mean around the agent. or whatever tool you are using of course all of this had to do with ai and agents so majorly what happened is that we humans we are very good at defining the task right so if you say that hey i want say all the latest ai news every day at 9 am now what will happen everyone is that this particular task how can we solve the same by a loop engineering is we will be having a trigger i think the trigger is very very clear in here it is just something which starts every day at 9 am right along with that if we just quickly think about the same then we will of course also we have that how we have to execute the same because in a loop engineering as well the initial part is very very simple and it is how things are getting executed Now, once the same is executed, this is where your normal flow stops, right? So this is where we have seen that either you will reprompt. So if I ask it that, hey, I want this at every day at 9 a.m., it will run at 9 a.m. and then make sure that it is able to get me some news. And the whole case also, see, it is scheduling the same itself. I can just say a quick yes. The whole case, everyone in here is that it is here. Just provide me with the news, right? But what if I have to update the same? What if I have to? go and make sure that okay research the same and provide from bigger companies or the new should be very very valid right so all these are the things everyone which will come and play a role in this verification part now something to understand which many people are missing it is exactly the same task just that you will be prompting again and again on the task until and unless the same is done so the next part everyone becomes verification the verification is where let's say if we take a quick example of the car with which i started so you press the set at your current speed the car adjust throttle to the hold that speed the agent does the actual work editing building drafting getting the news and everything so it can be something related to a linkedin article getting the latest ai news solving the test case making your application faster then when we move a step ahead everyone then sensor checks your real speed against the target in a similar way ai agent loop test run output gets checks against what that means So in here, everyone, you will have to define that, Hey, what are the good news? And that is where you might have to save or have the state as well. Now we will talk about like, what are the best way of handling the same, because they can either be very fuzzy or they can be having very subjective or objective as well. For example, if we take it defining that, what I want in my code to work is pretty good. Like, because we have test cases, we can just check if it is becoming faster. something like inbox strategy is also pretty easy to define that. Hey, there should be no unread inbox. You should write emails for each and every one of them. So that is the code. So it will take up a email, write for the same, and then it will run the same in the loop. This is where it becomes a little bit fuzzy that, Hey, what do you mean by a good LinkedIn article? Or what do you mean by a good news? So are you providing me the previous articles, which I've done pretty better? So are we, I am, am I having this thing? And this is what most people miss out that how, this whole approach, right? The verification part is very, very important because we humans are very good at defining the task that, hey, I want to become rich. But then if AI is telling you some step, what are the effects it is having? Hey, can you make my application faster? Okay. It got two millisecond faster. Then it got one millisecond, five millisecond. That is very objective. So the task or the verification also has a role to play here, everyone. And then finally, this state, so it remembers your logged in speed, the whole drive. a log of what was tried, what worked and what to do next. So if it gave me something and I said that, Hey, this is wrong. I should in loop engineering because it's in looping, right? I should maintain that. Hey, this was bad. This was good. This is what you should continue with. And I think that is where your loop will then become an automated way of running and doing the steps. And you will surely see that many people are running like one agent. It is having four or five agents running underneath and seeing that as loop engineering. Well, that was not the case. you can actually have a loop engineering with a single agent without any agent as well for that matter. And of course, with having teams of agent, it can run on very objective use case, which I just told you with this big to say inbox triage or anything related to your code. And it can be very fuzzy as well, just like getting the news or writing a good LinkedIn article. Okay. So now let's move forward everyone and try to see a few more things and why it works. So the real path to a working loop, like what exactly, and I've kept it very, very logical too. remove any ambiguity and anything. There are some pretty awesome things and this is a very good definition. Loop engineering is replacing yourself as the person who prompts the agent. You design the system. What does it instead? A loop here can be thought of as a recursive goal where you define a purpose and the AI iterates until complete. But most people, they are thinking of it as a completely new terminology or new work of basically technology. But that is not the case. Let's now see what exactly or how can you achieve the same improvement. The very first thing, if you want to do anything, if you want to loop anything or want to make sure that use it while you can earn money so that your AI is working, do it manually. So confirm the AI can even do the task at all by hand, no automation yet. So it can be drawing something, drawing you a thumb lane, making sure that it is working on your code and fixing that error. Next, everyone is turn it into a skill. Now, this is something we just suggested. Rather than you providing those instructions again and again, I think till now, all of us know how can we create a skill using Claude. So Claude has an awesome, awesome skill, creator skill. And the same is there for other libraries, sorry, other AIs as well, with respect to codex or perplexity. Everyone like now is having that approach. Next, everyone is the trigger. Now it runs on a schedule or an event. It is still not a loop yet. It is just an automation. So as of now, it starts, it runs and all is done. Based on a trigger, it starts and it is just stopping. The loop starts when you are adding the verification plus state. So it gets verified, save the state, and then looks that, hey, can I improve on that? So if it is giving me some, let's say, news, can I make it better? It can check that, hey, in the last run, I got it faster by one millisecond. Now can I make it more faster if it is a code? Hey, in the last run, I replied to five emails, but there are still 300. So should I work on and making sure? So the state is also very, very important everyone. And this is what now creates a loop. Okay. Now let's try to understand that why the same is getting exploded and why it is helpful. Why you will see many people just like how Peter and many people like are actually now writing all the code with using these loop technologies. And we will also see the quick demo as well. And again, of course, lots of articles. this complete loop library. The whole idea, everyone, is that AI is pretty good in giving you a very good head start. So many of us have seen that how whenever you're doing something with AI, you get a very good head start. So yeah, you can actually start from 40%. But let's say that if you're putting in and doing loop engineering, you can make sure that you are doing a little bit of head start with respect to the work with defining a skill and everything. Then rather than you spending your time on all these steps, so rather than you spending these times doing all the different different prompting here why can't we just spend an initial time make it a little bit and normally we have seen that it starts a lot better with that and then we can let ai take care of the rest but of course we will have to provide the state the verification what do i mean by better so that it can actually keep on prompting itself and reach to our goal so that is where everyone the whole benefit of loop lies that Once we have got this headstart, how can I make AI by giving it a complete details so that I don't have to do anything. So that is how you have to think about loop engineering. And now let's see that exactly. Should you even build one? Because many people I know will just build loop or just like try to do it left, right, and center, create multiple agents, have everything like, as I will show you the demo as well, but it is costly. The whole idea is that, uh, Peter Spielberg, this, uh, Peter Steinberg, he is able to, like, I read somewhere that he spent 1 million worth of tokens, right? So again, and you can see that, okay, Dover, LinkedIn will now start a new fad and everything. Okay. And yes, it will be take three months until it's there. So good thing that you are learning the same with me. It is very, very important that we actually understand if we can do something or not. Like for an example, make me rich, not a very good. loop like you cannot of course like no matter how much time it runs unless you have specified that hey what is working what is not providing it proper resources it will not be able to help you out so does it repeat or take many unpredictable steps just like the last one well okay i can say yes if it is the case can the ai check done by itself so can you throw in another ai can you have a human in the loop is there any metric on top of which it can work if there is that everyone then on all do a yes then you can build it if on any of your tasks so again you can just check it out for any task which you have in mind let's say that i want to do my house chores does the task repeat or take many steps you can't fully predict in advance so yes like it is the case which i cannot do so just prompt it faster or let's say that i want to develop something which can make me rich so is it repeat not really or take many steps you can't predict in advance i cannot predict these steps so that is the case okay So pretty good flow chart for you to play around with this. Now let's see everyone, the four checks, which your task actually needs. So overall, I think till now the whole idea is very clear in loop engineering. We are just providing it a task. We are along with the task. We are providing it, how it should, or what is the success criteria. Now that can actually be based on number of runs as well. So let me just show you this one and it will help you a lot now, because these are pretty helpful. So which of the four check does your task actually need run the test suite. So let's say that. you run npm test or you just check if all the test cases are passing very very objective numerical where you can actually see that hey something is happening it is running in five seconds i made it four seconds pretty good check if the ui looks looks right so either here you can have someone as the judge ideally any other llm or you can have human in the loop here is when so if i ask ai that hey Can you create this complete and this, I have actually also created via AI only. I just run it in the loop and made sure that, Hey, make sure that it is having these complete flow chart, everything, which is interactive. And I will be sharing the same with you as well. Then let's say if something is very, very objective or sorry, subjective or fuzzy, like LinkedIn posts, like news articles, like anything which you cannot actually define if it will work. So I can ask you to write a LinkedIn post, but then I should have some proper judgment criteria. How many likes is this getting? few previous how the previous posts have worked so all of this also decide to take me in action and then again deciding whether to send an email or not so that is where again you as a human in the loop come into picture of course i cannot do that right so if you say that hey you do all the steps but in some step you are someone who it is required then of course loop engineering you will have to come in similarly if there is something where you want some extra data just like the linkedin or the article example i gave Then whenever this state is there, if it write an article, and if you ask it to make it better, et cetera, it should know that he, how many likes it got, how many views it got. So that is again, everyone, how the complete loop engineering things work. And yes, these are the four quick pieces, which we can quickly run through again. Then basically just, we can define the trigger. Okay. Execution. It nudges a throttle or a break. The agent tries one charge, different algorithm, cache, tweak, loop structure. Verification actually measures the runtime number before and all these things. And then finally the state. So making sure that everything is getting maintained because when something is running in a loop, you should be having the result of the previous one. When your very basic loop runs with I as well, that I is kind of a state there. So where it is getting increased and you know that, hey, this is the value. So this is actually everyone how, in a very real sense, I have explained you loop engineering, like what exactly and how can it be useful? So beyond all the hype, beyond any jargons or anything. That is actually how you can use loop engineering. And now coming to the demo, everyone, I think it's pretty, pretty simple. We just have to define that like task or a goal properly. So I can just say research loop engineering, produce a decision ready markdown file for, let's say, maybe starters, starter people. So if that is the case, and I can just copy all of this, just have this in goal and paste it. So there's a goal command, which Kind of, as you can see, it can take the condition and stuff. So I can just enter this. And now what will happen, everyone? So based on all of my input and everything, again, it's a very, very basic example. I have just taken it from here only, right? The loop library. It will just start working and making sure that I can get the full results. So see, it is asking us for a few things. But the whole part is that how it will now run on loop because I have given it a goal. Of course, when the loop will be there, you have to have the stop condition. You have to make sure that it... Now don't keep on running for long because of course you will have lots of token then, right? So I think I'm not sure how many tokens I have left. So it is just running some command and everything. And of course I can automate this by providing that, Hey, you can do all of these things on a server or something. So in that way, it will be all pretty good and able to do this. So I can say allow the web search for this project, right? I can just provide each and everything here and it will keep on running in a similar manner. There are multiple examples from engineering evaluation. but I think the way I've defined you, and there is one more thing, which I would love that you read about because that is kind of on what it is based. So it is a Ralph loop. Everyone, a very similar thing, completion promise, the stop hook, persistent memory through files so that it can never do the same. And the loop will continue based on the same. So the loop continues. It understands what exactly was my goal, but I feel like this, the way I've explained you here with all the steps that is more than enough. So this was your do and don't start with one small repeatable task, just like I have done here. Pick the right check type. You don't default to functional. Always set a maximum of times. So I should make sure that, Hey, when it is approving this thing up for me, it is not just keep on running for like, let's say infinity, right? Because then it will be very, very costly. Use a separate agent to create subjective work. Now, what I meant here is that normally AI is very bad at creating its own work. So if you ask Claude, Hey, how is the code you have written? How is the article you have written? It's not pretty good. So just use any other agent with any other brain. and don't have 24-7 forms of agent, prompting agent, that is going to just cost you a lot and that would be very bad. And I think I read somewhere that many people are saying prompt engineering is dead, but prompt engineering is like algebra without which you cannot do calculus. So similarly, you cannot do loop engineering without prompting. It is just prompt which is going again and again, just that you are not writing it. Then letting it run with no stop limit, something which I've explained about. Trusting looks done with no real check. So in the end, if your AI is saying that, hey, I have created the best artifact, I think we can run the same. Okay. Uh, we can just check the same looping of one of tasks. You could just prompt so many people now they will have a goal for this very simple of a task. Okay. Which can be done with a simple, simple prompt. So I think, uh, practically everyone, this was all about loop engineering beyond the hype, beyond anything, just explaining it, how you can use the same. There are some awesome articles. This one is from Akshay and he writes pretty good articles. You can read the same out as well. What exactly is basically the loop. And again, I think. kind of what all i've explained in the last video and everything so just the best step as well keeping context clean what tools it can use and all these things and i think this diagram is pretty good so if you will see context the model okay tool call and tools a little bit i think it's going into the uh whole execution but overall these are few good articles and i of course read a lot of them and this is a good library which you can have a look and i think it will be having each and everything in there so with that i hope you like this complete video everyone do make sure that you share it Don't be forget or swayed up by all these new, new things. If your basics are right, I think everything should be very clearly understood by you. So now, yeah, do subscribe to my channel so that you don't miss out on all these new, new updates and share it with everyone so that I can reach out to the maximum of people because I love explaining these things in a very easy to understand thing without any hype. Okay. And yeah, as you can see, so it has given the same, but it is still making sure that it can run it out. And still it is actually running and giving me that, Hey, how it should work on the same. Okay. So cool. Now let's meet in the next video everyone. Thanks a lot.

⚙️ Pipeline jobs

StageStatusAtt.UpdatedError
download done 3/3 2026-07-20 11:51:48
transcribe done 1/3 2026-07-20 11:52:20
summarize done 1/3 2026-07-20 11:52:50
embed done 1/3 2026-07-20 11:52:53

📄 Описание YouTube

Показать
Sources used in this video:
https://loop-engineering-with-mayank.netlify.app
Peter Steinberger's original tweet (https://x.com/steipete.com/status/2063697162748260627)
Boris Cherny's interview on Acquired Unplugged, recapped by WorkOS (https://workos.com/blog/boris-cherny-claude-code-acquired-interview-takeaways)
Geoffrey Huntley's original Ralph loop write-up (https://ghuntley.com/ralph/)
https://x.com/kimmonismus/status/2005881569190506724?lang=en
https://x.com/addyosmani/article/2064127981161959567
https://x.com/akshay_pachaar/article/2069118430582866051
https://signals.forwardfuture.com/loop-library/?ref=explainx

Want to go deeper? Agentic 3.0 Course — use code MAYANK for 10% off (https://learn.krishnaikacademy.com/web/checkout/69f857703d5fe9dfcb3f4a31)

WHAT YOU'LL LEARN
— What a loop actually is, in plain words
— The 4 pieces every loop needs, and the one almost everyone skips
— The 4 different ways a loop can check its own work
— A live demo: building a working loop in Claude Code in under a minute
— When NOT to bother building one
— The real path people take to get to a working loop

CHAPTERS :
0:00 The Tweet That Started "Loop Engineering"
0:42 Why Loop Beats the Repeat Prompt Button
1:25 The 3 Steps of Any Loop
2:12 Real Example: Daily AI News at 9 AM
3:20 Why Re-Prompting Isn't Enough
4:01 Same Task, Repeated Until Done
4:14 Verification: Objective vs Fuzzy Goals
6:09 The Role of State in a Loop
6:34 Myth: Loops Need Multiple Agents
7:06 Official Definition of Loop Engineering
7:46 Step 1: Do the Task Manually First
8:06 Step 2: Turn It Into a Skill
8:28 Step 3: Add a Trigger
8:42 Step 4: Add Verification + State
9:15 Why Loop Engineering Is Exploding
9:57 The Head Start Advantage
10:42 Should You Even Build a Loop?
11:19 Decision Checklist: Is It Loopable?
12:27 The 4 Checks Your Task Needs
12:52 Check 1: Run the Test Suite
13:06 Check 2: Visual/UI Judgment
13:28 Check 3: Subjective Fuzzy Criteria
13:52 Check 4: Human-in-the-Loop Decisions
14:27 Recap: The 4 Quick Pieces
15:09 Live Demo: Setting Up a Goal Command
16:02 Demo: Watching the Loop Run
16:29 The RAL Loop Concept
17:01 Do's and Don'ts of Loop Engineering
17:36 Why Prompt Engineering Still Matters
18:08 Final Thoughts & Recommended Reading


CONNECT WITH ME
LinkedIn (https://www.linkedin.com/in/mayank953/)
YouTube (https://www.youtube.com/@tech.mayankagg)
Instagram (https://www.instagram.com/tech.mayankagg/)
Udemy (https://www.udemy.com/user/mayank-aggarwal-197/)

If this helped you, share it with someone who's still typing every prompt by hand. And let me know in the comments — what's the first thing you'd put in a loop?

#ClaudeCode #AIAgents #AgenticAI #LoopEngineering #PromptEngineering #AIAutomation #MCP #LearnAI #AITools #Python #AIProjects