Agentic Context Engineering: Build Self Improving AI Agents
AI Anytime · 2025-10-23 · 17м 18с · 6 981 просмотров · YouTube ↗
Топики: ai-loop-engineering
🎧 Аудио
📝 Summary
model=deepseek-v4-flash · prompt=summary-v7 · 5 506→1 907 tokens · 2026-07-20 12:02:53
🎯 Главная суть
Agentic Context Engineering (ACE) — это фреймворк для проектирования контекста, который позволяет AI-агентам эволюционировать: агент динамически обновляет собственный «плэйбук» (JSON-словарь) на основе предыдущих взаимодействий, используя трёхагентную схему «генератор → рефлектор → куратор». Вместо статического накопления контекста ACE вводит итеративное уточнение: контекст изменяется только когда это действительно нужно, что решает проблему «потери в середине» и деградации точности.
Проблема статического контекста в AI-агентах
Большинство современных AI-систем устроены статически: принимают запрос, генерируют ответ и забывают контекст. Если же контекст просто накапливать (например, в SQL, JSON, Markdown), он быстро становится слишком большим. Это приводит к контекстному коллапсу: точность падает, знания устаревают, а LLM начинают хуже рассуждать. Согласно исследованиям Стэнфорда, существует эффект «lost in the middle» — модель теряет способность использовать информацию, находящуюся в середине длинного контекста. ACE решает эту проблему, превращая контекст в активно управляемый плэйбук, который обновляется только при необходимости.
Архитектура ACE: три специализированных агента
Фреймворк состоит из трёх под-агентов, работающих последовательно:
- Generator (создатель) — принимает запрос пользователя и текущий плэйбук, генерирует структурированный ответ, ссылаясь на существующие инструкции в плэйбуке.
- Reflector (аналитик) — анализирует качество ответа, выявляет инсайты: была ли получена новая информация, нужно ли адаптировать подход для конкретного типа пользователя.
- Curator (архивариус) — на основе выводов рефлектора формирует «дельта»-операции (create, read, update, delete) и применяет их к плэйбуку, обновляя его с новыми правилами и стратегиями.
Такая тройная петля обратной связи позволяет агенту самообучаться без переобучения модели: плэйбук эволюционирует с каждым диалогом.
Playbook и CRUD-операции
Playbook — это структурированное хранилище контекста, реализованное как JSON-словарь (или персистентный файл). Каждая запись содержит ID, раздел, содержание и опциональные guardrails (например, маркировка «explicit», «harmful», «neutral»). Фреймворк выполняет полные CRUD-операции:
- add — добавить новую стратегию, если встречается новый паттерн запроса.
- update — изменить существующую запись на основе обратной связи.
- remove — удалить устаревшую или неверную информацию.
Ключевое правило: плэйбук не обновляется на каждый запрос — только тогда, когда рефлектор обнаруживает, что текущие инструкции недостаточны или могут быть улучшены. Это предотвращает раздувание контекста.
Демонстрация работы с ADK от Google
Фреймворк реализован поверх Google Agent Development Kit (ADK) с моделью Gemini 2.5 Flash. Весь код организован в папке agent/ с подпапками sub_agent/ и schemas/.
Первый запрос: «Какие лучшие стратегии для управления ежедневными задачами?»
Агент заглядывает в плэйбук и выдаёт готовый ответ (планирование, приоритезация, фокус). Поскольку плэйбук уже содержит общие советы, обновлений не происходит.
Второй запрос (в новой сессии): «Составь трёхмесячный план по изучению AI-агентов для человека, который уже знает ML и DL.»
Агент использует плэйбук, но рефлектор замечает, что запрос требует специализированного роадмапа для продвинутых пользователей — таких инструкций в плэйбуке пока нет. После генерации ответа куратор добавляет новую запись: «Стратегия ответов для пользователей с продвинутыми знаниями ML/DL: фокус на специализацию, практические проекты, MLOps, интерпретируемость». Последующий ответ уже учитывает этот новый пункт.
Структура кода и ключевые компоненты
В проекте используются Python, PyDantic для валидации данных, а также встроенные механизмы сессий ADK.
- generator.py — класс
Generator, описывается как агент ADK. На вход принимает user_query и current_playbook, возвращает структурированный ответ. - reflector.py — класс
Reflector, принимает user_query, generator_output и playbook, анализирует и выдаёт инсайты. - curator.py — класс
Curator, принимает reflector_output и playbook, применяет мутации (дельта-операции). - schemas/playbook.py — классы
PlaybookEntry(ID, section, content) иPlaybook(набор entry и CRUD-методы). - schemas/delta.py — класс
DeltaBatchиDeltaOperation, представляющие одно или несколько изменений для плэйбука. - agent.py — файл оркестрации: создаёт экземпляры трёх под-агентов и координирует их вызов в правильном порядке.
Playbook хранится в памяти сессии ADK (словарь), но может быть легко персистирован в виде JSON-файла для сохранения обучения между сессиями.
📜 Transcript
en · 3 148 слов · 40 сегментов · clean
Показать текст транскрипта
hey how it's going guys in this video we are going to look at a new concept named agentic context engineering so context engineering is one of the most important topics right now in the agentic ai ecosystem and there is a new paper that has been released called agentic context engineering it's a very interesting concept that how we can create context you know when we are working on working for uh you know building an agentic workflow so let's jump in and see what this concept is all about so if you look at here on my screen i'm going to use this agentic context engineering or ace or ace framework with adk which is by google google has created agent development kit and right now you can see i'm using their web ui okay before i show you all of these things right i wanted to highlight first this new concept called agentic context engineering evolving context for self improving language models. Now, if you look at the latest, you know, podcast or latest thoughts by veterans like Andres Carpathy and other scientists, they all have said that the context is really important. And if you don't design and develop or implement the context right way. uh it might not be it might backfire because let's say if your context becomes bigger and bigger okay and you basically use that uh in your memory uh memory design or state uh that's also uh break the identity flows how the model reason and think in identity flow right so too much of context is also not good that's what i'm trying to say so how do we now design context in a better way that's what identity context engineering is all about this is the paper uh that you see it over here and we have implemented this so this is how you know i'm gonna show you all the code and this code will be available uh you can go through it and i'm running this here in this agent development kit you can see it's called ace underscore agent so it's an ace agent And I also have a notion page where you can just go through some of the theories if you want. Right. So every interaction that you have with your AI agent, you know, it becomes smarter and smarter. That's what it is. OK, so we have been using it through Google Agent Development Kit, ADK, that provides some web UI to kind of work and find out how it's working. So this basically follows this simple principle. okay so if you come back here this follows this principle so i just make this a page fit now this is a this is what uh the underlying concept the as framework is all about you know you have a generator you have a reflector and you have a curator so it's a trial generator reflector and curator right and it's had it has an iterative refinement uh mechanism built into this because it has something called content playbook So this content playbook is nothing but a JSON right now. It's basically a dictionary. You can also persist that locally or right now it's stored in the system state of agent development kit, but it's a playbook and this playbook gets updated if only it's required. Because let's say if you are just designing a context, you see context is a database right now. That's how we see it. Memory systems are DBS, right? You use SQL, no SQL, you use JSON, TXT, Markdown, whatever. It's a database file format, right? now if you don't have an intelligent way to store your context it will become bigger and bigger right in your file system whatever it's a db whatever you have been using now that's important that you don't update the playbook every time you only update when it is required so those kind of intelligence is like done through this ace frame also the specialized component that you see here generator reflector and curator that's what it is and i have created it over here as well you know that that's how it works why current ai systems don't learn because of the static nature of most ai rather take your input generate an answer and forget the context afterwards right if not designed properly so this term called context collapse you know the accuracy drops knowledge decays over a period of time right and even if the context is too big uh you know lm's kind of start uh finding problems they cannot reason well because context is too much so there's a problem of lost in middle kind of a thing right there's paper by stanford so it's a big problem okay so an empty context engineering a design pattern it's a design pattern i just said right how do we design context that lets ai system evolve their own playbook based on past performance so the playbook will get updated so basically you perform crud operations create read update delete on the playbook So that's how it works in a generator, which is having a role of creator reflector, which is having a role of analyst and curator, which is having a role of archivist that archive your archivist, which archives your playbook, updates playbook with insights and feedback. So basically this form of feedback loop and over here, if you see this iterative refinement, so it basically becomes a loop, right? That's why it is. and you can follow all this code okay uh you can just go through it let me just ask this question here that okay i've come back here i asked the question you can see i'm asking what are the best strategies for managing daily tasks now having an interaction with the agent right so what does agent do here you can see they starts running okay uh it takes a little bit of time i'm running this locally that you can see okay over here and i'll also walk you through the entire code okay uh there are a couple of things that you should go through the code over here you can see it over here they say uh the users query asks for best strategies for managing daily tasks which is a general advice seeking questions i will consult the playbooks i already have the playbook i have been testing it for guidance on how to respond so you can see it immediately goes to the playbook that playbook that we have and you can find out uh final answer over here affecting managing daily tasks involve a combination of planning prioritizations focused executions and so on and so forth right you can find out and it does not update the playbook because there is no changes required okay so this is this is how cool it is right and you can keep on asking a lot of other questions okay uh from this uh over here so let's create a new session and i'm gonna ask create a roadmap for learning ai agents in three months this is a new question that i'm asking so if you come over here you can find out that uh it works on ssc like how agent development kit works i have a couple of videos on agent development kit if you are not aware of adk you can uh watch that videos as well so i'll just give a quick walkthrough while it's generating the output okay over here so if this is how the code looks like We have an agent folder. In this agent folders, we have a couple of other subfolders. We have sub underscore agent, and we have schemas. If you look at the schemas, we have a couple of files, delta.py and playbook.py. And in the sub agents, we have the three agents that we talked about, the generator, the curator, the reflector. So if you look at the generator, we are using the agent module from Google ADK, and we use PyDentake for data validations. some config config we have pretty simple straightforward you know we have our Gemini 2.5 flash model for the config okay and the model comes from that enb file where we have our API keys right so make sure that we have the API keys let's come back to generator we have a generator output class if you look at the description it says provide step-by-step reading process in the format of step-by-step thought process blah blah blah basically for your pydentic thingy And here we define our generator that generates answers and traces using playbook. If you look at here, it's a name generator. We have a model that we are using for this, configured generator model, which is Gemini 2.5 less. Description of this. Solve problems by referencing the playbook and return structured final answers. And here the instruction goes. We have a user query and we have the current playbook. So this app colon playbook that you see is nothing but the dictionary as a playbook that completely stays stored in the current session. okay of that adk that provides the agent development it provides uh state sessions to manage you can also persist that locally through a json and then read that file and give it over here as well and you can find it out and it has some other things like some other uh quarks and arcs over here for generator same goes to curator in curator also the same things happens we take the if you first have to go to reflector excuse me in the reflector sees in the reflectors we have uh this is fine come over here so in reflector what we are doing we're taking the user query and taking the generator output the previous output of the agent and then we are having in the playbook the same goes over here for a reflector that reflects basically and then we go into the curator part which is the last agent you can see it over here where goes the reflector output and then playbook so very is very good in terms of how we create an iterative refinement of this you can see it over here it generated a response says three months roadmap for learning ai agents you can see it says i will consult the playbook for guidance on handling general queries you know it takes it gives you some output it gives you the final answer three months roadmap for learning ai agents week one two and a week three four uh and so on and so forth right and in in the find the output below right so So this is how it works. We have the curator.py over here. So these are the three agents. Now if you look at the playbook, let me show you the playbook. In this, we have a bullet class, that single playbook entry, which has ID, section, content, and a couple of, we can also have guardrails thingy, you know, explicit content, harmful, neutral, so on and so forth. In this playbook class, it basically says, structured context store as defined by AS framework. right you pass the bullet sections and you have id and then here you perform the crud utilities create read update delete in the playbook right you can add you can update you can remove and you can do so on and so forth so very interesting concept right how do you manage it it takes as a bullet point so which is interesting only keeping the information which might be important for the agents you know to define uh and it takes a little bit of time to run it okay so let's wait for it then we'll come back This is the playbook. Here we have Delta. Let you see. It says some mutation to apply to all the playbook. It's a single mutation. We perform a Delta operation. You can see it says class Delta batch, bundle of curator reasoning and Delta operations. So this is our Delta.py. We have a playbook.py, which is in the schemas. So very modular in the sense. We have a subagent, generator, reflector, and curator. And in agent.py, we have our agent.py. We have a... this is fine this all in this slide you can see this is where i was saying right app call on call on playbook so basically a dictionary that you can see pb dot to underscore dict we are not persisting it if you want you can persist as well right and you can see this is what it is the first question i'm also going to ask here uh what if i already know the machine learning and deep learning concept concept how will the road map look now for three months i'm asking this you come back here so i keep you uh you know so you can look at the orchestration here we are having the orchestration in the agent.py because this agent.py file basically orchestrate so if you come here in the notion also you will find out the same thing you can see it says core files under the hood Agent.py basically orchestrates the three-agent workflow. Generator.py, reflector.py, and curator.py. So these three agents that you see, the generator basically handles structured generation logic. Reflector basically analyzes the quality and identifies insights. And curator updates the playbook with learning deltas. Okay, so delta is basically the learning kind of, how should I put it? It's like a parameter that you can see, right? That basically... use to update the playbooks and then config where you can customize your models and agent behaviors so playbook is nothing but a json file which is a dictionary and then you can persist that you know if you want so this is how it is currently and you can go through it there are some real world huge cases like productivity coach code review agent customer support and research assistant so i'll give you this of course this notion so you can go through it and if you want to learn more you can learn it also look at the research paper which is really interesting that how this new framework has come up right so this is fine there are some you can see it over here now i have asked and you can see playbook changes have also been done it says add response generation strategy for advanced mldl users because in the previous output if you see and i just ask a generic question okay give me three months learning roadmap now i in the next question that i asked to the agent i said hey look i already know machine learning and deep learning concepts because you know i'm an already an advanced user when it comes to ml and dl so now it has to create a roadmap for that particular user who has fundamental knowledge or understanding so now if you look at the output it changes the final answer it says Given your solid foundation in ML and DL concepts, a three-month roadmap should focus on specialization, advanced application, and practical implementation to deepen your expertise. Now, here is the possible structure. Specialized and advanced concept, identify a niche like subfield, NLP, Graph Neural Network, explainable AI, and then go through it. Hands-on implementation, month two advanced project. You can do an end-to-end project. you look at the interpretability robustness mlops so it's asking to learn deployment optimization and mlop things because i already know the fundamentals so this is very interesting and if you come down it gives you the reasoning that why i think well reasoning is very important right uh uh to reduce or cut slash the hallucination now if you look at this here add a new bullet point to guide responses for users with advanced mld knowledge focusing on the specialization blah blah blah these gates updated in the playbook so if you look at the playbook changes it says add response generation strategy for advanced mldl users tailor roadmaps to specializations practical applications advanced concepts and ml of with clear sequential phases fantastic so it's working fine right and in this agent development kit you can find out your all your events that has gone all the states that you see over here and all your states that i mean persisted at least in that session storage uh you can find out all your sessions there is no e-value strategy we can set any value strategies if you want so i'll give you this code so you can go through it uh you know and find out how it works you can see uh fast api also runs on 8080 so if you just come on like let's say If I just come on localhost 8080, my bad. Okay. And likely two docs here. I am doing something wrong here with this. Failed to load API definitions internal server. That is fine. We can still fix this. There's something wrong with the swagger UI, but we can get it. If you look at here, that's the output it says. That's okay. So I'll give this code, have a look at this framework. Very interesting. I wanted to highlight this framework so you can learn a new. new concept that has arrived a new framework uh that might might be helpful of you know for your use cases if you are if you're working on some in-depth context design pattern right the in production and stuff you can try it out and let us know uh what do you think of this framework right if you have any question thoughts or feedback let me know in the comment box you can also reach out to me through my social media channel guys find those information on channel banana channel about us if you want to learn agentic ai i have identity ai toolkit i will give that link in description uh you can get that and let me know what you think of that if you also want already built SAS project using AI agents, you know across radiology across stock market and across agentic in your optimization or SEOs. I have a bundle kit of six SAS projects that is available for you to download and use it. It's available in the description as well. If you like the video, please hit the like icon. If you haven't subscribed the channel yet, guys, please subscribe the channel that helps me to create more such videos in your future. That's all for this video. Thank you so much for watching. See you in the next one.
⚙️ Pipeline jobs
| Stage | Status | Att. | Updated | Error |
|---|---|---|---|---|
| download | done | 2/3 | 2026-07-20 12:01:58 | |
| transcribe | done | 1/3 | 2026-07-20 12:02:33 | |
| summarize | done | 1/3 | 2026-07-20 12:02:53 | |
| embed | done | 1/3 | 2026-07-20 12:02:54 |
📄 Описание YouTube
Показать
In this video, I’ll show you how I built a self-improving AI agent using Agentic Context Engineering (ACE) + Google’s Agent Development Kit (ADK). What You’ll See 💡 Build an AI that learns from every interaction ⚙️ See how the Generator–Reflector–Curator cycle works 📚 Watch the playbook evolve in real time 🧠 Understand how it gets better with every use 💻 All running locally on your own machine You’ll Need 🐍 Python 3.12+ 🔑 Google API Key ⏱️ 10 minutes setup If you enjoyed this project, drop a like 👍, comment 💬 what you’ll build with it, and subscribe 🔔 for more AI dev breakdowns every week! Get the Agentic AI Master Bundle Kit: https://aianytime5.gumroad.com/l/uqmyk GET THE 6 IN 1 AI AGENTS SAAS PRODUCT BUNDLE: https://aianytime5.gumroad.com/l/fbeifc GitHub: https://github.com/AIAnytime/agentic-context-engineering Notion Doc: https://truthful-viburnum-525.notion.site/Building-Self-Improving-AI-Agents-with-ACE-ADK-295a6390e711803e8abfc97201620f10?pvs=74 Build real-world AI with tutorials, tools, and research from India’s fastest-growing AI community. 👤 Creator’s LinkedIn (Sonu Kumar) Portfolio Site: https://sonukumar.site/ 🌐 AI Anytime's Website: https://aianytime.net/ 🗓️ Office Hours (AI Consulting): https://officehours.aianytime.net/ 👥 LinkedIn (Community Page): https://www.linkedin.com/company/ai-anytime/ 💬 Join Our Discord: https://discord.com/invite/4aGc9PSMgE 👤 Creator’s LinkedIn (Sonu Kumar): https://www.linkedin.com/in/sonukr0/ 🎁 Support the Channel 💸 UPI ID: sonu1000raw@ybl ₿ Bitcoin Wallet: bc1qsneqznxpzyxzzv006jthz4c8v8h5cs57myw342 ✅ Join this Channel for Perks Get access to members-only content and community perks: https://www.youtube.com/channel/UC-zVytOQB62OwMhKRi0TDvg/join #contextengineering #adk #aiagents