Назад к подкастамClaude
Запустите своего первого Managed Agent
All right.
Итак.
Hello everyone.
Привет всем.
It's great to see you all here today for our session on shipping your first manage agent.
Очень рада видеть вас здесь сегодня на нашей сессии по созданию вашего первого Managed Agent.
Let's go ahead and get started.
Давайте начнём.
My name is Isabella He.
Меня зовут Isabella He.
I'm a member of technical staff at Anthropic on the Applied AI team.
Я сотрудник технического персонала Anthropic в команде Applied AI.
The Applied AI team at Anthropic sits at the intersection of products, research, and our customers, which means that I get to contribute internally to products at Anthropic like Claude code and our Claude harnesses, as well as work externally with our customers that are building on top of Claude and on top of our harnesses.
Команда Applied AI в Anthropic находится на пересечении продуктов, исследований и работы с клиентами, а это значит, что я участвую во внутренних продуктах Anthropic, таких как Claude Code и наши харнессы Claude, а также работаю с нашими клиентами, которые строят решения на основе Claude и наших харнессов.
So, my goal today is to get you all hands-on with actually building on top of manage agents, understanding how the harness works under the hood, and getting you ready to actually ship your first incident response management.
Итак, сегодня моя цель состоит в том, чтобы дать вам всем возможность практически поработать с Managed Agents, понять, как харнесс работает изнутри, и подготовить вас к тому, чтобы действительно запустить ваш первый инструмент управления инцидентами.
So, the quick overview of today's agenda.
Итак, краткий обзор сегодняшней повестки.
We're going to cover first a quick refresher of Claude manage agents.
Сначала мы сделаем быстрое повторение Claude Managed Agents.
I want to talk you through a little bit about how this harness works under the hood and what makes it so special.
Я хочу немного рассказать вам о том, как работает этот харнесс изнутри и что делает его таким особенным.
Our team put a lot of thought into the architectural design of Claude manage agents to make sure that it runs ready and reliably for production-ready agents.
Наша команда вложила много усилий в архитектурное проектирование Claude Managed Agents, чтобы убедиться, что он работает надёжно и готов к использованию в продакшене.
So, I want to talk you through a little bit of how that works so that then when we transition to the second portion here, which is the hands-on workshop, you'll actually understand what each of the primitives you're building actually mean for your agents under the hood.
Итак, я хочу немного рассказать о том, как это работает, чтобы потом, когда мы перейдём ко второй части, а именно к практическому воркшопу, вы действительно понимали, что означает каждый из примитивов, которые вы строите, для ваших агентов изнутри.
So, for the majority of today's session, I want you all to actually have your laptops open, building alongside me, actually working inside of a repository, and getting you ready to actually spin up a working incident response agent.
Итак, бо́льшую часть сегодняшней сессии я хочу, чтобы все вы открыли свои ноутбуки, строили вместе со мной, реально работали внутри репозитория и были готовы запустить работающего агента для управления инцидентами.
Lastly, we'll talk a little bit about beyond the basics.
Наконец, мы немного поговорим о том, что выходит за рамки основ.
Today's session is the first session of a couple of other ones that will build on top of this on Claude manage agents.
Сегодняшняя сессия является первой из нескольких других, которые будут строиться поверх этой по Claude Managed Agents.
Specifically, right after this one, I think there's another session on dreaming, which is one of my favorite new features with Claude manage agents for self-improving agents and memory built into the harness.
Конкретно сразу после этой, по-моему, будет ещё одна сессия по dreaming, что является одной из моих любимых новых функций Claude Managed Agents для самоулучшающихся агентов и встроенной в харнесс памяти.
So, encourage everyone to dive in a little bit deeper into what else is in the box after we set you all up for success today with a quick introduction.
Так что советую всем погрузиться немного глубже в то, что ещё есть в арсенале после того, как мы сегодня подготовим вас к успеху с помощью краткого введения.
So, let's first touch a little bit about how we got here with Claude manage agents.
Итак, давайте сначала немного поговорим о том, как мы пришли к Claude Managed Agents.
When we first released the very first Claude back in 2023, we released a messages API alongside access to Claude.
Когда мы выпустили самый первый Claude в 2023 году, мы одновременно выпустили Messages API с доступом к Claude.
This provided raw model access to all Claude models.
Это обеспечивало прямой доступ к модели для всех моделей Claude.
This became the very first way that people could programmatically build on top of Claude and essentially gave a way for people to access tokens in and tokens out via our Claude models.
Именно это стало первым способом, благодаря которому люди могли программно строить решения на основе Claude, и по сути дало возможность получать токены на входе и на выходе через наши модели Claude.
This also meant that for everyone building on top of Claude models, they had to implement all the various primitives themselves.
Это также означало, что всем, кто строил решения на основе моделей Claude, приходилось самостоятельно реализовывать все различные примитивы.
Things like context management, the actual agent loop, compaction, etc.
Такие вещи, как управление контекстом, собственно цикл агента, компакция и тому подобное.
All the primitives that come alongside making the agent work.
Все примитивы, необходимые для работы агента.
When models were less intelligent back in the early days of let's say 2023, some of these primitives were much simpler because agents could simply do less.
Когда модели были менее интеллектуальными в ранние дни, скажем, 2023 года, некоторые из этих примитивов были гораздо проще, потому что агенты могли делать значительно меньше.
But, as we evolved into now with higher model intelligence and as agents are able to take on more complex tasks and actually take actions within environments and come to actually do entire tasks for humans, the primitives that come alongside context management and managing an agent's ability to execute API calls and tool calls becomes much more complex.
Но по мере того, как мы эволюционировали к нынешнему более высокому уровню интеллекта моделей, и агенты начали брать на себя более сложные задачи, реально выполнять действия в средах и выполнять целые задачи для людей, примитивы управления контекстом и управления способностью агента выполнять вызовы API и инструментов стали значительно сложнее.
So, that's when we moved to the agent SDK, which became a harness that allows you to programmatically call Claude code, one of our agents at Anthropic.
Вот тогда мы перешли к Agent SDK, который стал харнессом, позволяющим программно вызывать Claude Code, одного из наших агентов в Anthropic.
So, Claude code is something that an agent has access to a computer and takes actions within file system.
Claude Code является агентом, у которого есть доступ к компьютеру и который выполняет действия в файловой системе.
So, the agent SDK became a way for you to make Claude much more powerful by leveraging the power of Claude code within a harness.
Так что Agent SDK стал способом сделать Claude значительно более мощным, используя возможности Claude Code внутри харнесса.
The main thing here though is that with the agent SDK, developers still had to manage hosting and scaling on their own and making sure that the agent SDK would be safe to run within their containers.
Главное здесь, однако, то, что с Agent SDK разработчикам всё равно приходилось самостоятельно управлять хостингом и масштабированием, а также следить за тем, чтобы Agent SDK можно было безопасно запускать внутри их контейнеров.
That's only then evolved into Claude managed agents, which is the first harness to be able to handle scaling and production ready components for you by Anthropic, providing things like a purpose-built harness, sandboxing, observability, tool runtime, all within a managed infrastructure system.
Это эволюционировало только потом в Claude Managed Agents, первый харнесс, способный взять на себя масштабирование и готовые к продакшену компоненты, предоставляя такие вещи, как целенаправленный харнесс, изоляция, наблюдаемость, среда выполнения инструментов, всё в рамках управляемой инфраструктурной системы от Anthropic.
This means that developers can focus on task and agent configuration, custom tool logic, the things that actually matter for bringing domain expertise and customizability to your agents, where you're handing off the rest of all the primitives and core compute and primitives of essentially managing the basics of agent running to Anthropic.
Это означает, что разработчики могут сосредоточиться на конфигурации задач и агента, на логике пользовательских инструментов, на том, что действительно важно для привнесения доменной экспертизы и настраиваемости в ваших агентов, передавая всё остальное, примитивы, вычисления и управление основными аспектами работы агента, в руки Anthropic.
So, that brings me to managed agents as the fastest way to build production ready agents on Claude.
Итак, это подводит меня к Managed Agents как к самому быстрому способу создания готовых к продакшену агентов на Claude.
We've seen people build 10 to 15 times faster to production with Claude managed agents by leveraging our purpose-built harness.
Мы видели, как люди достигают выхода в продакшен в 10–15 раз быстрее с Claude Managed Agents, используя наш целенаправленный харнесс.
Part of the reason why we built Claude managed agents is because is because harnesses should evolve alongside your agents.
Часть причины, по которой мы создали Claude Managed Agents, заключается в том, что харнессы должны развиваться вместе с вашими агентами.
For example, back when we were building ourselves on top of models like Sonnet 4.5, we noticed that Sonnet 4.5 emitted a particular behavior called context anxiety.
Например, когда мы сами строили решения на основе таких моделей, как Sonnet 4.5, мы заметили, что Sonnet 4.5 демонстрировал особое поведение, которое мы назвали context anxiety.
This meant that with Sonnet 4.5, Claude started wrapping up tasks early even when it still had room to spare in its context window.
Это означало, что с Sonnet 4.5 Claude начинал завершать задачи раньше времени, даже когда в его контекстном окне ещё оставалось место.
To manage that in our harness, we then added some mitigations to combat against this early stopping behavior.
Для управления этим в нашем харнессе мы добавили ряд мер для борьбы с таким поведением раннего останова.
But, when Opus 4.5 then came out, we actually saw this behavior go away, making all that work we had done inside of the harness essentially obsolete because Claude had evolved beyond that behavior that we had built into the harness to manage.
Но когда вышел Opus 4.5, мы фактически увидели, что это поведение исчезло, сделав всю работу, которую мы проделали внутри харнесса, по сути устаревшей, потому что Claude эволюционировал за пределы того поведения, которое мы встроили в харнесс для управления им.
So, the takeaway there is that it's a lot of work to maintain harnesses and make sure that they actually evolve alongside your agents, which is why with Claude managed agents, we want to make it really easy for Claude and Anthropic to handle all the complexities that come with compaction, caching, things like context anxiety, all these various primitives that come with actually making agent production ready and getting the most out of Claude.
Итак, вывод здесь таков: поддерживать харнессы и следить за тем, чтобы они действительно развивались вместе с вашими агентами, это большой труд, и именно поэтому с Claude Managed Agents мы хотим максимально упростить для Claude и Anthropic обработку всех сложностей, связанных с компакцией, кэшированием, такими вещами, как context anxiety, всеми этими различными примитивами, которые сопровождают реальную подготовку агента к продакшену и максимальное использование возможностей Claude.
So again, you can focus on the tasks, tools, and things that actually matter for building agents on Claude.
Так что снова: вы можете сосредоточиться на задачах, инструментах и том, что действительно важно для создания агентов на Claude.
So three primary resources go into building on Claude managed agents.
Итак, три основных ресурса уходят на создание решений на Claude Managed Agents.
First is the agent's endpoint, which is the persona and capabilities.
Первый: конечная точка агента, то есть его личность и возможности.
This is the core system prompt that powers your agent.
Это основной системный промпт, который питает вашего агента.
Essentially here, you're defining the model, the MCP servers, the skills, the various components that your agent can actually leverage when it's able to run in that agent loop.
По сути, здесь вы определяете модель, MCP-серверы, навыки, различные компоненты, которые агент реально может использовать, когда ему дают возможность работать в цикле агента.
The next is the environments.
Следующее: среды.
You can think of this as the hands of the agent, where the previous one is the brain of the agent where the agent is thinking through what to execute, and then it's using an environment to actually have a space and a container to actually take action on your behalf.
Можно думать о них как о руках агента, тогда как предыдущее является мозгом агента, где агент обдумывает, что выполнить, а затем использует среду, чтобы иметь пространство и контейнер для реального совершения действий от вашего имени.
Sessions are next the way to tie together agents and environments.
Сессии идут следующими: способ связать вместе агентов и среды.
A single session has a spun up on an agent instance within an environment.
Единственная сессия запускается на экземпляре агента внутри среды.
So you can connect the two together and actually stream events back to your user and start to take action on behalf of your humans as part of a Claude powered agent.
Так вы можете соединить их вместе и реально передавать события обратно вашему пользователю, начиная совершать действия от имени ваших людей как часть агента, работающего на Claude.
A key thing here, as I alluded to briefly before, Claude managed agent has the agent loop run server side.
Ключевой момент здесь, на который я кратко намекала раньше: в Claude Managed Agents цикл агента работает на стороне сервера.
This means that a lot of the complexities that come with managing hosting and scaling are abstracted away.
Это означает, что многие сложности, связанные с управлением хостингом и масштабированием, абстрагированы.
And when you close your laptop or you hit hard refresh on your agent that you're building on Claude managed agents, everything is maintained and you don't have to worry about durability, reliability, all these various aspects that usually come to bite you when you're trying to turn your agent from a prototype into production.
И когда вы закрываете ноутбук или нажимаете принудительное обновление в вашем агенте, который вы строите на Claude Managed Agents, всё сохраняется, и вам не нужно беспокоиться о долговечности, надёжности и всех этих аспектах, которые обычно дают о себе знать, когда вы пытаетесь превратить агента из прототипа в продакшен.
And lastly here, before we dive into the hands-on portion, is I want to talk you through a key design decision that went into Claude managed agents.
И наконец, перед тем как мы погрузимся в практическую часть, я хочу рассказать вам о ключевом дизайнерском решении, которое легло в основу Claude Managed Agents.
Previously, with a lot of agent harnesses, we saw the agent loop coupled tightly with tool execution.
Раньше, со многими харнессами для агентов, мы видели, что цикл агента был тесно связан с выполнением инструментов.
This design pattern made sense and still makes sense for some agents because you want to give the agent powerful abilities to actually take action within the environment.
Этот паттерн проектирования имел смысл и до сих пор имеет смысл для некоторых агентов, потому что вы хотите дать агенту мощные возможности для реального совершения действий в среде.
For instance, with Claude Code, we want the agent to be able to access various files on your computer, take action within a file system, and therefore it makes sense for the agent to have access to all those tools spun up on every container.
Например, с Claude Code мы хотим, чтобы агент мог обращаться к различным файлам на вашем компьютере, выполнять действия в файловой системе, и поэтому имеет смысл, чтобы у агента был доступ ко всем этим инструментам, запущенным в каждом контейнере.
But, we also realized there are some constraints for this, especially with some agents where you essentially want to be able to decouple the hands from the brains of the agents.
Но мы также осознали, что для этого существуют некоторые ограничения, особенно с некоторыми агентами, где вы по сути хотите иметь возможность разделить руки и мозг агентов.
For instance, credentials and uh credentials and security became a huge concern.
Например, учётные данные и безопасность стали огромной проблемой.
With the ability to have the agent access your file system, you can actually add very distinct sandboxing by decoupling these two components, where the agent is no longer able to access the actual credentials without encryption by decoupling the hands from the sandbox of the agent.
Имея возможность предоставить агенту доступ к вашей файловой системе, вы можете реально добавить очень чёткую изоляцию, разделив эти два компонента так, чтобы агент больше не мог получить доступ к реальным учётным данным без шифрования, отделив руки от песочницы агента.
The other aspect here is actually you can see huge benefits by doing these decoupling on things like time to first token and latency.
Другой аспект состоит в том, что вы можете увидеть огромные преимущества от такого разделения в плане времени до первого токена и задержки.
Previously, with the agent loop into execution in the same box, you had to spin up containers for every single session that you're spinning up in the agent, which contributed to additional latency from a time to first time to first token perspective.
Раньше, когда цикл агента и выполнение находились в одном контейнере, вам приходилось разворачивать контейнеры для каждой сессии, которую вы запускали в агенте, что вносило дополнительную задержку с точки зрения времени до первого токена.
But, with this now decoupled, our teams actually saw reductions in time to first token along the lines of over 90% reduction in TTFT for our P95 metrics on latency.
Но теперь, с этим разделением, наши команды реально увидели снижение времени до первого токена порядка более чем 90% в метриках P95 по задержке.
So, here you can start to see the power of this design decision coming through from the perspective of safety, reliability, latency, and everything else that you care about when it comes to building production-ready agents.
Итак, здесь вы начинаете видеть мощь этого дизайнерского решения с точки зрения безопасности, надёжности, задержки и всего остального, что вас волнует при создании готовых к продакшену агентов.
All right, so now it's time for the exciting part of today's session, which is where I want you all to open up your laptops and go to this URL here to actually clone a repository, and let's start to actually feel the magic of everything that I just talked through.
Хорошо, итак, настало время захватывающей части сегодняшней сессии, где я хочу, чтобы все вы открыли ноутбуки и перешли по этому URL, чтобы реально клонировать репозиторий, и давайте начнём ощущать магию всего того, о чём я только что рассказала.
So, I'm going to give everyone a second to just go over to that URL there and just spin up the repository that we have ready for you.
Итак, я дам всем секунду, чтобы перейти по этому URL и развернуть репозиторий, который мы для вас подготовили.
All right, so here are some additional commands that I want you all to run to make sure this is all set up on your computers.
Хорошо, вот несколько дополнительных команд, которые я хочу, чтобы все вы выполнили, чтобы убедиться, что всё это настроено на ваших компьютерах.
So, the first step many of you might have done already, but just take that repository, hit the URL, get clone it, and then I want you to CD into the specific repository for the session, which is ship your first manage agent.
Итак, первый шаг многие из вас, возможно, уже сделали, но просто возьмите тот репозиторий, перейдите по URL, клонируйте его, а затем я хочу, чтобы вы перешли в конкретный репозиторий для сессии под названием «ship your first manage agent».
And then, if you're on Mac, you'll see those two commands on the side, the Python and the source.
Если вы на Mac, вы увидите эти две команды сбоку: Python и source.
Um, there's a command there for Windows as well.
Там есть и команда для Windows.
And you'll just do the rest there where you want to install the requirements, copy over the environment key into your .env file.
И вы просто выполните остальные шаги: установите требования, скопируйте переменные среды в файл .env.
Um, here you'll put in the Anthropic API key that hopefully all of you also received from the QR code for free credits earlier.
Здесь вы введёте ключ Anthropic API, который, надеюсь, все вы также получили по QR-коду для бесплатных кредитов ранее.
And lastly, we'll just run the app.
И наконец, просто запустим приложение.
All right, let's go ahead and dive in, but as I mentioned before, let me just show everyone where these instructions are.
Хорошо, давайте погрузимся, но, как я упоминала раньше, позвольте мне просто показать всем, где находятся эти инструкции.
If you go into the repository in the link and then go to ship your first manage agents, you scroll down on the read me, you'll see all the setup instructions here.
Если вы зайдёте в репозиторий по ссылке, а затем перейдёте в «ship your first managed agents» и прокрутите вниз README, вы увидите там все инструкции по настройке.
So, feel free to do this, um, as we go along or even in your own time later today and continue playing around with it, but as I mentioned before, everything will be also shown on the screen to follow along with.
Не стесняйтесь делать это по ходу или даже позже сегодня в своё время и продолжать с этим играться, но, как я упоминала раньше, всё будет показано на экране, так что вы сможете следить.
So, do not worry if you did not have time to fully get it set up on your laptop.
Так что не волнуйтесь, если у вас не было времени полностью настроить это на вашем ноутбуке.
Without further ado, let's go ahead and dive in.
Без лишних слов, давайте погрузимся.
So, once you run streamlit run app.py, you should be able to see a URL that looks like this and a page that looks like this.
Итак, после запуска streamlit run app.py вы должны увидеть URL и страницу вот такого вида.
What we're doing here is we're going to be simulating an agent, um, interaction here where we have an incident that's going to come up.
Что мы здесь делаем: мы собираемся симулировать взаимодействие с агентом, где у нас возникнет инцидент.
A lot of you who might be software engineers in the room will be intimately familiar with the pain that comes alongside incident response.
Многие из вас, кто, возможно, является программистами, хорошо знакомы с болью, которая сопровождает реагирование на инциденты.
If you are software engineer, you might be woken up at, let's say, 3:00 a.m. in the morning, 2:00 a.m. in the morning when you're out around on on vacation as you're on call, and this is usually a very painful portion of a software engineer's life, uh, because when you're on call, it means that if a server goes down or a service goes down, you have to be immediately the one there to respond and tackle the incident.
Если вы программист, вас могут разбудить, скажем, в 3 ночи или в 2 ночи, когда вы отдыхаете в отпуске на дежурстве, и это обычно очень болезненная часть жизни программиста, потому что, когда вы на дежурстве, это значит: если сервер или сервис падает, вы должны немедленно отреагировать и разобраться с инцидентом.
Usually for a human, this means diving into metrics and logs and deployments.
Обычно для человека это означает погружение в метрики, логи и деплойменты.
You can actually investigate what's going on.
Вы можете реально расследовать, что происходит.
And so, what we're going to do is we're going to now have an agent run on Claude manage agents to do all this for us.
И вот что мы собираемся сделать: теперь мы заставим агента работать на Claude Managed Agents, чтобы делать всё это за нас.
So, that when we get woken up by 3:00 a.m., we can hand it off to an agent, or maybe we don't even get woken up at all if Claude is able to do everything for us.
Так что, когда нас разбудят в 3 ночи, мы можем передать это агенту, или, может быть, нас вообще не разбудят, если Claude сможет сделать всё за нас.
Okay.
Хорошо.
So, let's now go ahead and dive into the code here.
Итак, давайте теперь погрузимся в код.
What we're going to open up here is we have the agent.py file on the left and the agent complete on the right.
Что мы здесь откроем: у нас слева файл agent.py, а справа agent complete.
If you want to challenge yourself, you can of course try to implement everything yourself here or with Claude.
Если хотите бросить себе вызов, вы, конечно, можете попробовать реализовать всё самостоятельно или с помощью Claude.
Um but, what we're going to do just for simplicity's sake is just copy over various elements from the completed file onto the incomplete file one by one.
Но для простоты мы просто будем по очереди копировать различные элементы из готового файла в незавершённый.
So, you can see how these primitives compose our agent one piece at a time.
Так вы сможете увидеть, как эти примитивы составляют нашего агента шаг за шагом.
So, let's go ahead and start off with this very first part, which is the agent.
Итак, давайте начнём с самой первой части, с агента.
We mentioned before that the agent is the one that defines the persona and the capabilities of the agent here.
Мы уже упоминали, что агент определяет личность и возможности агента.
So, that's model, the system prompts, and the tools in our case for our agent here.
Это модель, системные промпты и инструменты, в нашем случае для нашего агента.
So, let me go ahead and copy over what we see there on the screen.
Итак, давайте скопируем то, что мы видим на экране.
And you can see here that we're defining the SRE agent.
И здесь вы можете видеть, что мы определяем SRE-агента.
We're going to use Claude Opus 4.7 here.
Мы будем использовать здесь Claude Opus 4.7.
And I've preconfigured a system prompt and tools for the agent.
И я заранее настроила системный промпт и инструменты для агента.