Agentes que escrevem suas próprias ferramentas em tempo de execução — Sandhya Subramani, AWS
Autoria: AI Engineer · Assistir no YouTube
Vídeo de autoria do canal indicado, não da IANIA; todos os direitos pertencem ao criador. Transcrição, resumo e tradução gerados automaticamente; o conteúdo no idioma original é preservado na versão em idioma original.
Idioma original: inglês
Vídeo original: Agents That Write Their Own Tools at Runtime — Sandhya Subramani, AWS · Canal: AI Engineer · 20:19 · Assistir no YouTube
Tópicos: Agentes de IA, Avaliação e benchmarks de IA, Segurança de IA
Sandhya Subramani demonstra como um agente pode criar ferramentas durante a execução e usá-las sem reiniciar, além de gerar subagentes para tarefas específicas. A apresentação mostra como implementar essa abordagem de meta tooling com Strands Agents, usando um system prompt e ferramentas de edição, shell e carregamento dinâmico. A palestrante também aborda evals para verificar resultados e uso de ferramentas, além de medidas de segurança como ambientes isolados e permissões restritas. Por fim, relata a evolução do projeto, que chegou a atualizar o próprio código-fonte.
Pontos-chave
Seção intitulada “Pontos-chave”- O agente de demonstração começa sem ferramentas específicas e cria novas ferramentas sob demanda, como uma calculadora e um contador de caracteres.
- O meta tooling é implementado com um system prompt que define o formato das ferramentas e três ferramentas: editor, shell e carregador de ferramentas.
- Strands Agents permite trocar o modelo sem reescrever toda a arquitetura ou o system prompt.
- O agente pode criar subagentes para dividir uma tarefa, como planejar uma viagem em etapas.
- A demonstração de planejamento de viagem não acessa informações em tempo real sem uma ferramenta conectada a APIs externas.
- Evals podem verificar a realização do objetivo, a qualidade das respostas, a escolha de ferramentas e parâmetros e a comunicação entre agentes.
- Agentes capazes de criar ou modificar ferramentas também precisam de proteções contra alterações e exclusões indesejadas.
- As medidas de segurança citadas incluem isolar o ambiente de execução, restringir ferramentas e permissões e manter observabilidade.
- A palestrante descreve a evolução de agentes que criam ferramentas para agentes que criam agentes e atualizam o próprio código.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:01 | Demonstração de ferramentas criadas em tempo de execução | A palestrante apresenta um agente que cria ferramentas, como uma calculadora e um contador de caracteres, e as usa sem reiniciar. |
| 05:12 | Implementação de meta tooling com Strands Agents | A apresentação explica o papel do system prompt e das ferramentas de edição, shell e carregamento dinâmico. |
| 10:27 | Criação de agentes e subagentes | A demonstração mostra um agente que cria subagentes para planejar uma viagem e descreve padrões de colaboração entre agentes. |
| 15:07 | Evals e proteções para agentes autônomos | A palestrante aborda avaliações de resultados e uso de ferramentas, além de isolamento, restrições de permissão e observabilidade. |
| 17:43 | Segurança e evolução de Strands | A apresentação conclui com medidas para proteger a execução e com o relato de agentes que passaram a atualizar o próprio código. |
Citações
Seção intitulada “Citações”Ele sabe que precisa fazer isso e está fazendo. — 04:39
É isso que permite ao agente executar dinamicamente as ferramentas que gerou. — 07:51
Com grande poder também vem uma responsabilidade ainda maior. — 15:07
Este é o começo dos agentes que se aprimoram e evoluem sozinhos. — 18:46
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- meta tooling (conceito): Abordagem em que um agente cria e carrega ferramentas de forma dinâmica durante a execução.
- Strands Agents (ferramenta): Framework open source apresentado para executar agentes com diferentes modelos e ferramentas.
- AWS (empresa): Empresa onde trabalha a palestrante e que mantém Strands Agents.
- Sandhya Subramani (pessoa): Palestrante da apresentação, que trabalha na AWS.
- MCP (conceito): Recurso mencionado como compatível com Strands Agents.
- swarm (conceito): Padrão multiagente em que subagents trabalham em paralelo em diferentes partes de uma tarefa.
- graph (conceito): Padrão em que o resultado de um subagent é passado a outro por meio de etapas conectadas.
- evals (conceito): Avaliações usadas para verificar resultados, respostas, uso de ferramentas e colaboração entre agentes.
- sandbox (conceito): Isolamento do ambiente em que o código é executado para limitar efeitos sobre outros ambientes e arquivos.
- Python (conceito): Linguagem usada na versão de Strands que, segundo a palestrante, gerou a versão em TypeScript.
- TypeScript (conceito): Linguagem da versão de Strands que, segundo a palestrante, foi escrita pela versão em Python.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:01 [música] Oi, pessoal. Bem-vindos, bem-vindos. Agents que criam as próprias ferramentas. O que há de tão bom nisso? O Claude Code não consegue fazer isso? Ou o Cursor, ou seus editores de código, eles não conseguem todos criar as próprias ferramentas? Então, do que estou falando aqui? Por que isso é tão
00:32 importante? Certo? Quer dizer, todos os seus agents conseguem criar ferramentas sozinhos. Mas quantos agents você conhece que conseguem corrigir código em runtime? Digamos que você tenha algo em produção. Está funcionando. Tudo parece ótimo, mas algo está falhando. E aí, o que acontece? Provavelmente você precisa desligar, corrigir por conta própria, reiniciar e então trabalhar com o Claude Code ou com o editor que estiver usando para colocar tudo de volta no ar, certo? Mas imagine se
01:02 seu agent fosse inteligente o suficiente para perceber: “Puxa, há um bug aqui. Algo não está funcionando. Estou caindo em um erro. Preciso me corrigir.” E ele entende o que pode fazer para se corrigir. Cria as próprias ferramentas, cria os próprios agents e se corrige. Que legal seria isso, né? E é sobre isso que vim falar com vocês hoje. Deixe-me mostrar rapidamente uma demonstração, porque gosto de começar com demonstrações para que vocês saibam no que estão se metendo.
01:32 Então, vamos começar por aí. Certo. Tenho um agent aqui, e vocês conseguem ver minha tela. Espero que esteja grande o suficiente; posso ampliar. Certo. Tenho aqui um agent simples chamado agents.py. Podemos analisar o código daqui a pouco, mas esse agent não tem nada. Ele só tem um system prompt bem legal, que é chamado, e três ferramentas. Se vocês olharem o pacote de ferramentas, não há nenhum arquivo de ferramenta criado. Então, tecnicamente, esse agent
02:04 não tem capacidade própria, certo? Tecnicamente, não deveria conseguir fazer nada, certo? Tudo o que deveria fazer é alucinar por causa do LLM que está rodando por baixo dos panos. Mas digamos que eu diga algo como… Primeiro, vou iniciar a execução para sabermos que está rodando. Certo. Agora ele está rodando em runtime. Agora vou dizer: “Ei, sabe de uma coisa? Ajude-me a calcular uma equação matemática complexa.”
02:37 Quando digo isso, este agent, que tecnicamente não tem nada disponível, vai chamar as três ferramentas que possui — vamos ver quais são daqui a pouco — e vai dizer: “Ah, sabe de uma coisa? Vou criar uma ferramenta de calculadora matemática, porque é isso que você está pedindo.” E não vai apenas criá-la: vai me deixar usar essa ferramenta que estou criando agora, em runtime, sem precisar executá-lo novamente. Certo. Ele claramente foi lá e criou. Vamos olhar as ferramentas de novo. Criou a ferramenta de calculadora matemática
03:09 e está dizendo: “Certo, faço todas estas coisas. Tenho min, max, blá-blá-blá.” Ele foi lá e criou uma ferramenta inteiramente nova. Está dizendo que consegue fazer todas estas coisas, certo? Então, digamos: “Calcule… ah, nossa… qual é o quadrado de blá-blá-blá, algum número?” Estou digitando um número aleatório. Agora ele está chamando a ferramenta de calculadora matemática que acabou de criar sozinho e me dando a resposta. E não é só isso. Digamos que eu dê a ele
03:39 algo completamente inesperado e diga: “Legal, tanto faz, conte o número de caracteres da minha palavra.” Então, ele verifica se consegue usar alguma das ferramentas a que tem acesso no momento. Não consegue. Então, diz: “Certo, vou escrever uma ferramenta para contar o número de caracteres que você quer”, porque claramente sabe que não tem essa capacidade. E então começa a
04:09 criá-la. Aí está. Antes mesmo de eu terminar de falar, ele criou um contador de caracteres para nós. Digamos que eu peça para fazer isso com esta palavra. E nem é uma palavra. Vou simplesmente colocar coisas aleatórias. Sabe de uma coisa? Eu devia ter escolhido algo que pudesse contar para validar o resultado. Mas o fato é que ele está chamando uma ferramenta. Está chamando a ferramenta de contador de caracteres e me dizendo que há 28 letras. Vamos fazer algo que possamos testar. Vou fazer isso com estas três letras, certo? Vamos ver se
04:39 ele sabe. Nem estou dizendo a ele o que fazer. Só estou digitando três letras. Ele sabe que precisa fazer isso e está fazendo. Quão poderoso é isso? O que quero deixar para vocês hoje é mostrar como podem criar algo assim e usar. Acho que é bastante poderoso e quero mostrar como podemos implementar isso no nosso trabalho do dia a dia. É bem específico. Agora vamos ao código. Esta ideia se chama meta-tooling, e estou usando um framework open source chamado Strand Agents. Meu
05:12 nome é Sandy e trabalho na AWS. Nós, na AWS, criamos o Strand Agents como um harness agêntico open source que vocês podem usar para executar seus LLMs, certo? E então, levantem a mão: quantos desenvolvedores temos na sala? Uma rápida olhada. Ah, a maioria. Ótimo. Estou falando com o público certo. Se não, vou adaptar um pouco. Então, se vocês gostam de entrar no código, venham comigo. Certo. O principal de que precisamos aqui para os agents — e tenho uma apresentação que acompanha isso — são apenas três tipos de ferramentas: o editor, o shell e a ferramenta load, além do system prompt que nos permite implementar essa função. Vou abrir rapidamente minha apresentação, que nos ajuda a entender melhor. Como mencionei, este é o Strand Agents. Este é nosso harness de IA agêntica, e vocês podem usar seus próprios LLMs, trazer seus próprios modelos. Outra coisa legal, por ser um
05:45 harness, é que vocês podem usar seus próprios LLMs, trazer seus próprios modelos. Outra coisa legal, por ser um
06:16 O harness é o fato de que, se amanhã surgir um novo LLM de última geração, você não precisa reescrever todo o seu system prompt. Não precisa reescrever a estrutura. Não precisa mudar toda a sua arquitetura. Você pode mantê-la como está e simplesmente substituir o modelo que estiver usando. Assim, você também pode experimentar o desempenho dos modelos sem precisar reescrever toda a sua arquitetura. Isso é muito, muito poderoso. Dá suporte a MCP e a todas essas coisas legais. Tem vários provedores de modelos. Você pode começar a usar. Então…
06:47 O que fazemos? Muito simples, certo? Cinco linhas de código. Importe agent e, em seguida, importe shell. Shell é a primeira ferramenta de que precisamos, porque temos que dar acesso ao diretório. Precisamos dar acesso. Ele precisa saber o que está executando, onde está executando e onde sua base de código está localizada. Então, essa é apenas uma das ferramentas de que você precisa. E, se você perguntar o que ele pode fazer, ele entende o que está acontecendo nos bastidores. Assim, tecnicamente, você já pode começar a usá-lo na hora, certo? Então, vamos falar do que eu realmente…
07:19 …acabei de criar alguns minutos atrás e mostrei aqui. O que estou tentando fazer? A ideia é que, como isso é conduzido pela comunidade, a AWS gerencia e mantém tudo para você. As pessoas escrevem muitas ferramentas integradas pré-criadas, mas também há ferramentas criadas pela comunidade. Então, você só precisa de três ferramentas para começar a implementar metatooling. Do que você precisa? Primeiro, é preciso ter um system prompt que diga ao seu agent como é uma boa ferramenta. Como…
07:51 …isso funciona? Temos que começar com a função decoradora @tool. É assim que ele sabe que aquilo é uma ferramenta. Desculpe. É assim que ele sabe que aquilo é uma ferramenta. E então você diz a ele como é uma ferramenta e onde ela deve ser armazenada, certo? E é aí que você chama o system prompt. É só isso que você diz. Depois, pode dar acesso a diferentes ferramentas. Destaquei load tools from directory = true porque é isso que permite que você habilite o agent a começar a executar as ferramentas que ele…
08:22 gerada dinamicamente em tempo de execução. Mais tarde, decidimos transformar isso em uma ferramenta divertida por si só. Então, agora ela virou a ferramenta de carregamento. Assim, quando você disser: “Ei, crie duas — crie cinco — ferramentas novas para você e comece a usá-las”, ela vai saber o que fazer. Então, vamos voltar ao código que mostrei antes, certo? É a mesma coisa. Ele tem o system prompt e aqui estou dizendo: “Você é o agent de metaprogramação que cria suas próprias ferramentas e ferramentas personalizadas em tempo de execução”. Então, estou definindo o modelo de ferramenta e
08:53 dizendo a ele como é uma ferramenta. Estou fornecendo a especificação da ferramenta, indicando como ela deve ser. Depois, estou dando regras sobre o que ela deve fazer e onde deve escrever. Também estou dizendo para sempre verificar se ela já existe ou não. Só se não existir, deve escrever uma ferramenta nova. Estou dando a ela três ferramentas: editor, que permite escrever; shell, que mostra o que ela tem; e a ferramenta de carregamento, que permite carregar a ferramenta do diretório
09:25 dinamicamente. E é só disso que você precisa; basta uma linha de código, certo? system prompt igual a system prompt, três ferramentas diferentes. E isso é apenas código para que eu possa conversar com ela continuamente. Então, quando faço isso, ela consegue começar a executar: “Crie cinco ferramentas aleatórias para você”. E aí ela começa a criar essas cinco ferramentas novas. E o poder disso, como eu disse, é que, quando
09:56 você está implantando código em produção, pode querer uma maneira de o agent ser inteligente o bastante para descobrir o que está errado e conseguir responder às próprias perguntas. Digamos que você esteja criando um aplicativo que deveria reservar passagens aéreas para voos domésticos, mas que um usuário diga: “Não, não, quero uma passagem de avião da, sei lá, Índia para Hong Kong”. E seu agent desiste porque não foi programado explicitamente para fazer isso, ou não foi treinado para ter acesso e conseguir fazer isso. Mas você quer simplesmente
10:27 que ele falhe? Quer que ele encontre um erro? Quer encaminhar isso para sua equipe de engenharia e esperar duas semanas para receber uma resposta? Não. Você quer conseguir resolver o problema. Então, essa é uma das maneiras de lidar com isso, certo? Então, vamos voltar ao código, porque ainda temos outras coisas legais por vir. Eu estava falando de ferramentas que este agent pode escrever, das próprias ferramentas dele. Ele também pode escrever os próprios agents? Sim. E tenho outra demonstração disso, mas esperem até os últimos minutos. Certo. Então, quando falamos de agents que
11:00 escrevem os próprios agents, também queremos entender os padrões agentic. Temos três padrões principais. O primeiro é o enxame, em que subagents trabalham juntos em paralelo. Eles trabalham numa tarefa de forma combinada, e cada um assume partes diferentes da tarefa. Depois, temos um grafo, em que o resultado de um subagent é passado para outro subagent, ocorre uma transferência de controle e também podemos ter workflows que combinam tudo isso. Certo? Então,
11:31 com o workflow, você pode ter um conjunto paralelo de subagents chamando uns aos outros. E pode haver nós, grafos e todas essas coisas legais. E tudo isso pode ser criado pelo próprio agent. Não precisamos fazer isso. Podemos fazer por conta própria, mas não necessariamente precisamos. Então, vamos conferir rapidamente como isso fica. É exatamente a mesma coisa. Isto é para meus agents de metaprogramação. Estou fazendo exatamente a mesma coisa. Dei a ele
12:02 três ferramentas aqui. Na verdade, se você olhar o arquivo dos meus agents, ele está quase vazio, e estou dizendo que agent é o modelo do arquivo da ferramenta. Então, estou dizendo para dividir em dois a quatro subagents. Vou manter as coisas simples. Sem enxame, nada sofisticado aqui. Uma demonstração simples, e pronto. Esta é a especificação da ferramenta que define como deve ser um agent. E posso compartilhar o código com vocês depois, certo? Estas são as regras que ele segue. Mesma coisa, certo? Basta uma linha: system prompt igual a system prompt, três ferramentas, e então dizer… Então, vou
12:33 começar a executar isso agora: python 3 agent.py pie. Então, estou voando para o Havaí, ou para algum outro lugar… para o Havaí. Vamos dizer Havaí. “Ajude-me a planejar meu itinerário.” Certo. É só isso que estou dizendo. Nem estou dizendo: “Ei, crie seu próprio agent” ou “crie sua própria regra”. É só isso que estou dizendo. É assim que seus clientes conversariam com ele,
13:03 certo? Eles só dizem qual é o problema e esperam que você descubra como resolvê-lo. Certo? Então, este agent vai dizer: “Ah, ótimo. Aqui, vou imprimir… vou criar três subagents especializados: o agent de voos, o agent de atividades e o agent de itinerário”, e vai chamar a ferramenta de edição três vezes, uma para cada um deles. Vejo que ele já criou o de atividades. Sim, está criando… É bem rápido. Está criando o agent de atividades. Criou, tipo, um agent de voos que está fazendo
13:33 alguma coisa. Criou um agent de itinerário. Deixe-me destacar que, no momento, uma coisa que ele não consegue fazer é acessar informações em tempo real, porque não dei a ele uma ferramenta que tenha acesso a uma API do mundo real. Certo? Então, supondo que você adicione isso, pode perguntar como está o tempo, e ele vai dizer: “Sabe de uma coisa? Vou escrever uma ferramenta que sempre consiga buscar a previsão do tempo mais recente para qualquer local e recomendar coisas”. Com base nisso, ele criou esses agents. E, se você olhar aqui, tecnicamente, ele deveria estar chamando esses agents. Aí está. Vejam,
14:04 ele está chamando os agents de atividades. E então diz: “Estes são os principais aeroportos. Estas são as melhores praias. É isto, e é isto que você precisa fazer”. E quão incrível é poder ter agora seu agent? Seu foco não é mais apenas criar um bom sistema agentic que consiga concluir a tarefa. Talvez você também queira começar a pensar em autorreparação, em escrever código que se autorrepare, em criar um agent que possa examinar a si mesmo, ver quais bugs existem e corrigi-los
14:35 sozinho. Se esta fosse uma sessão mais longa — geralmente faço sessões mais longas —, eu pediria ao público que mandasse o agent fazer coisas malucas, e eu tentaria quebrá-lo. E o que acontece é que ele acaba quebrando. Vocês veriam vários erros aparecendo, enquanto ele fica falando sem parar. Então, provavelmente preciso definir o número máximo de tokens em algum lugar aqui, mas ele acaba dando erro e quebrando. Só que percebe que está dando erro e diz: “Ah, não, estou dando erro. Deixe-me me corrigir”. Aí ele corrige essa mesma ferramenta, ou
15:07 agent, que está aqui. Então, se eu disser: “Não quero ir para o Havaí. Por que você planejou uma viagem para o Havaí? Faça para outro lugar”, ele vai dizer: “Claro, deixe-me fazer isso. Vou atualizar o agent”. Então, é superpoderoso. Mas, ainda assim, precisamos ter em mente que ele está fazendo coisas de forma autônoma. Com grandes poderes vêm grandes responsabilidades — responsabilidades ainda maiores. Então, o que precisamos fazer com isso? Certo? Precisamos de evals. Quais são algumas das evals integradas do str agent? Temos, ao todo, oito evals diferentes. A primeira é em um…
15:38 no nível geral da sessão. Queremos descobrir se, quando eu digo: “Ei, reserve minhas passagens aéreas”, ele realmente faz a reserva. Ele atingiu o objetivo final? Essa é a primeira parte, certo? Atingir o objetivo final. A segunda coisa que queremos analisar é o nível do trace. Ele foi realmente útil? Se eu perguntar “qual é o meu saldo?” e ele disser “seu saldo é de 500 dólares”, esse é o tipo de resposta esperado? Essa é a primeira parte. A segunda: ele inventou a resposta? Essa é a resposta que deveria ser dada? Você precisa conseguir avaliar isso. Mas não para por aí. E quanto ao acesso às ferramentas?
16:10 Ele usou a ferramenta certa para chegar à resposta ou usou a ferramenta errada? E, dentro dessa ferramenta específica, usou o parâmetro correto? O ID da conta é mesmo 1, 2, 3, ou deveria ser outro? Ele está se confundindo? Queremos entender o que está acontecendo para podermos confiar nele e dar acesso a ele com segurança. Mais uma vez, não para por aí. Também queremos entender as dependências entre agents. Quando estamos criando sistemas multi-agent, queremos analisar o resultado geral e
16:41 a resposta geral, para ver se correspondem ao que você queria. Queremos garantir que ele chame as diferentes ferramentas e os diferentes subagents na sequência correta. Também queremos investigar mais a fundo como são as mensagens e a comunicação entre agents, e se estão à altura do esperado. Tudo isso, em conjunto, nos dá a conversa completa do agent, de ponta a ponta, dentro da nossa sessão. Isso nos dá visibilidade. Mais uma vez, isso também não basta, certo? Queremos garantir que ele não cause danos
17:11 indevidos. Se essa metacamada de ferramentas ou esse meta-agent pode criar ferramentas e agents, também pode modificá-los e excluí-los. Quero que ele apague meus dados? Quero que apague coisas que me esforcei tanto para criar? Não. Então, o que eu faço? Preciso implementar proteções. Há quatro tipos diferentes de proteções. A primeira é o ambiente. Precisamos garantir que o ambiente esteja em sandbox. E, quando digo colocar o ambiente em sandbox, não me refiro ao sandbox típico, em que o agent fica em um contêiner e você o
17:43 protege do resto do mundo. Queremos que o ambiente em que esse código é executado fique em sandbox. Há algumas semanas, acho, a Strands lançou um recurso que permite colocar o ambiente de execução do código em sandbox. Isso garante que ele não interfira nos outros ambientes de execução do código, não bagunce todo o resto, não grave nos lugares errados nem apague coisas dos lugares errados. Certo. Em seguida, precisamos restringir as ferramentas. Precisamos
18:14 restringir as permissões. Precisamos restringir quem tem acesso, quem pode fazer perguntas a ele e que tipos de perguntas podemos fazer, além de garantir a observabilidade. Todos os seus evals, seu OTel, sua telemetria, todos esses dados precisam estar disponíveis para que seja possível dizer, com confiança: “Ei, acho que posso criar um sistema agentic que pense por conta própria e faça mais do que simplesmente
18:46 foi projetado para fazer, porque consegue corrigir problemas na hora, durante a execução, e lidar com mais capacidades do que aquelas para as quais foi inicialmente treinado. Esse é o começo dos agents que se aprimoram e dos agents que evoluem por conta própria. Em algum momento, estou convencida de que eles vão dominar o mundo, e eu corro risco. Mas, até lá, acho isso incrível. E, se eu pudesse deixar vocês com alguma coisa, gostaria de deixar vocês
19:16 com uma ideia rápida de onde a Strands está, de onde a Strands começou e onde estamos agora. Começamos criando nossas próprias ferramentas. Depois, passamos a fazer com que eles criassem agents por conta própria. Agora, eles chegaram a um ponto em que conseguem atualizar o próprio código-fonte. Curiosidade: criamos os Strands agents internamente há três anos. Era para ser algo interno, antes mesmo de agents serem uma coisa. E era tão poderoso que dissemos: “Sabe de uma coisa? Vamos torná-lo open source e devolvê-lo à comunidade.” E escrevemos a versão em Python da Strands.
19:47 E a versão em Python da Strands escreveu sozinha a versão em TypeScript da Strands. Então, ela atualizou o próprio código-fonte. É bem poderosa. Estou empolgada. E, se isso servir como meu convite à ação, se parecer interessante para você, entre em contato comigo. Escaneie estes códigos e podemos conversar depois. Terei prazer em compartilhar meus slides e meu código com você. Podemos conversar depois. Muito obrigada. Este é o meu LinkedIn. Nós
20:19 temos mais 30 segundos, acho.
Transcrição original
[00:01] [music] Hi everyone. Um, welcome, welcome. Agents that forge their own tools. What is so great about this? Can’t your claw code do this? Or can’t your cursor or your code editors, can’t they all write their own tools? So what am I even talking about here? Why is this such a
[00:32] big deal? Right? Like any all of your agents can write tools by themselves. But how many agents do you know that can fix code at runtime? Let’s say you’ve got something in production. It’s running. Everything looks great, but something is failing. Then what happens? you have to probably bring it down, fix it by yourself and then restart it and then work with your clot code or whichever editor you’re using and then bring it back up, right? But imagine if
[01:02] your agent was smart enough to figure out, oh man, there is a bug here. Something’s not working. I’m falling falling into an error. I need to fix myself. And it realizes what it can do to fix itself. Writes its own tools all writes its own agents and fixes itself. How cool would that be, right? And that’s what I’m here to talk to you about today. Let me quickly show you a demo because I think I like leading in with demos so you know what you’re
[01:32] getting into. So, let’s start with that. Right. So, here I have a and you can see my screen. I’m hoping it’s big enough I can zoom in. Okay. So, I have a simple agent here called agents.py. This agent, we can go over the code in a bit, but this agent has nothing. It’s just got it’s just got a pretty cool system prompt and then it’s calling the system prompt and it’s got three tools and if you look at the tools package there are actually no tools files that are written. So technically this agent
[02:04] has no capability by itself, right? It shouldn’t be able to do anything, right? All it should technically hallucinate because of the LLM that is running under the hood. But let’s say I say something like okay so first I’m going to start running this. So we know it’s running. Okay. So in runtime right now this is running. Now I’m going to say hey you know what um help me calculate something uh some complex math equation right
[02:37] when I say this this agent which technically has nothing available is going to be calling the three tools that it’s got and we’ll look into the tools that it’s got in just a bit and it’s going to say oh you know what let me create a math calculator tool because that’s what you’re asking for. And it’s not just going to create, it’s going to let me use this tool that I’m creating right now at runtime without having to rerun it. So, okay. So, it’s clearly gone ahead and created. So, let’s look at tools again. It’s created the math
[03:09] calculator tool and it’s saying, okay, I do all these things. I’ve got min, max, blah, blah, blah. It’s gone and created this entire new tool. So, it’s saying I can do all these things, right? So, let’s say calculate uh oh yikes uh what’s the square of blah blah blah some number right I’m just typing out a random number so now it’s calling that math calculator tool that it just wrote by itself and it’s giving me the answer not just that right so let’s say I give
[03:39] it something completely out of blue and I say uh cool whatever count number of characters in my word. Okay. So then, so then it’s like, okay, so it’s going to check if it can use any of the tools that it’s currently got access to. It doesn’t. So what it’s saying is, okay, let me write a tool to count the number of characters you want because clearly it knows that it does not have the capability to do it. And so it’s going ahead and it’s
[04:09] creating a there we go. Even before I could finish speaking, it created a character counter for us. So, let’s say um do it for this word. And it’s not even a word. I’m just going to put random things. You know what? I should have actually done something that I could count so I can validate it. But the thing is it’s calling a tool. It’s calling the character counter tool and it’s telling me that it’s got 28 letters. Let’s do it something we can test. So, I’m just going to do it for these three letters, right? We’ll see if
[04:39] it knows. So, I’m not even telling it what to do. I’m just typing three letters. It knows that it has to do it and it’s doing it. How powerful is this? So, what I want to leave you with today is show you how you can build something like this where you can use it. I think it’s pretty powerful and how we can implement it in our work day-to-day work. Very niche. So, now let’s get down to the code. This is an idea called meta tooling. and I’m using an open-source framework called Strand Agents. And my
[05:12] name is Sandy and I work at AWS. And we at AWS built Strand agents as an open-source a aentic harness that you can use to run your LLMs with, right? And so, um, how show of hands, how many developers do we have in the room? A quick show. Oh, most of you. Brilliant. I’m talking to the right audience. If not, I will change things around a little bit. So, if you guys like getting into the code, I’m going to get into the code with me. Right. So, the main thing we need here for agents and I have a
[05:45] slide deck that goes with it is we need just three types of tools. The editor, the shell, and the load tool along with the system prompt that lets us implement this function. So I’m going to quickly go to my slide deck that helps us understand this better. Like I mentioned, this is strand agent. This is our agentic AI harness and you can use your own LLMs, bring your own models. Another cool part because this is uh an
[06:16] harness is the fact that if let’s say tomorrow there’s a new the state-of-the-art LLM that comes out, you don’t have to rewrite all of your system prompt. You don’t have to rewrite the structure. You don’t have to change your entire architecture. you can keep it as it is and whichever model you use you can just replace it. So it also lets you experiment with model performance without really rewriting your entire architecture. So it’s super super powerful. Supports MCP AA all of that cool stuff. Has a bunch of model providers. Um you can get started. So
[06:47] what do we do? Very simple right? Five lines of code. Uh import agent from there import shell. Shell is the very first tool that we need because we need to give it access to the directory. We need to give it access. It needs to know what it’s running, where it’s running, where your codebase is located. So that is just one of the tools that you need. And then if you ask it what can you do, it understands what’s going on under the hood. So to techniques technically start being able to use it on the fly, right? So then let’s get into what I actually
[07:19] just built a couple of minutes ago and I showed you over here. What am I trying to do? The idea because this is communitydriven, AWS manages it and maintains it for you. People write a lot of pre-built inbit tools, but there’s also community written tools. And so all you need is three tools to be able to start implementing matter tooling. So what do you need? First of all, you need to have a system prompt that tells your agent what a good tool looks like. How
[07:51] does that work? We have to start with the at tool decorator function. That’s how it knows it’s a tool. Excuse me. That’s how it knows it’s a tool. And then you tell it what a tool looks like and where it should be stored, right? And so you call the system prompt there. That’s all you say. And then you can give it access to different tools. I highlighted load tools from directory equals true because that is what enables you to enables the agent to start letting it run the tools that it’s
[08:22] generated at runtime dynamically. And we later on decided we should just make this into a fun into a tool by itself. So now that’s become the load tool. So now when you go and say hey create two create five new tools for yourself and start using them it’s going to know what it’s going to do. So let’s go back to the code that I showed you earlier, right? Same thing. It’s got the system prompt and here I’m saying you are the meta tooling agent that creates your own tools and custom tools at runtime. So I’m defining the tool template and
[08:53] telling it what a tool looks like. I’m giving it the tool specification of what it’s supposed to look like. And then I’m giving it rules for what it’s supposed to do and where it’s supposed to write into. And I’m also telling it always check if it if it exists or not. only if it doesn’t exist then write a new tool and I’m telling it so I’m giving it three tools editor which allows it to write the shell tool which shows it what it has and the load tool which allows it to load from the directory the tool from
[09:25] the directory dynamically and this is all you need and it takes just one line of code right system prompt equals system prompt three different tools and this is just code so that I can chat with it continuously. And so when I do this, it’s actually able to start running create five random tools for yourself. And so it’s going to start creating these five new tools. And the power of this is like I said, when
[09:56] you’re deploying code into production, you need you might want a way to for the agent to be smart enough to figure out what’s wrong and to be able to answer questions for itself. Let’s say you’re you’re building this app that’s supposed to book flight tickets domestically, but let’s say you have one user who’s saying, “No, no, I want a flight ticket from, I don’t know, India to Hong Kong.” And your agent gives up because it’s not been explicitly programmed to do that, or it’s not been trained to have access to be able to do that. But do you just
[10:27] want it to fail? Do you want it to run into an error? Do you want to give it back to your deployment to your engineering team and have a turnaround of two weeks and then come back? No. You want to be able to solve it. So this is one of the ways by which you can handle that right. So again let’s get back to the code and we have more cool things coming up. Now I was speaking about tools that can this agent that can write it own write its own tools. Can it also write its own agents? Yes it can. And I have another demo for that but wait until the last few minutes for that. Right. So when we talk about agents that
[11:00] write their own u agents also we want to understand agentic patterns. We have three primary patterns. The first one is swarm where you have sub agents that work with each other in parallel. So they work on a task in a combined fashion and they take different parts of the task themselves. Then you have a graph where the result of one sub aent gets fed into the other sub aent and then there’s a handoff and then you could also have workflows that have a combination of all of these. Right? So
[11:31] with the workflow, you could have a parallel set of sub aents calling each other. And then there could be nodes and graphs and all of that cool stuff. And so this and so they all of this can be created by just the agent itself. We don’t need to. We can do it our own selves, but we don’t necessarily need to. So um let’s quickly go check how that looks. Um so this is the exact same thing. This is for my meta agents. I’m doing the exact same thing. I’ve given
[12:02] it three tools over here. I’m actually if you look at my agents file, it’s pretty empty and I’m saying agent as the tool file template. So I’m saying just break it into two to four sub agents. I’m keeping it simple. No swarm, nothing fancy here. Simple demo and use it. And this is the tool spec for what an agent should look like. And I’m happy to share the code with you after this, right? And these are the rules that it follows. Same thing, right? One line is all it takes. system prompt equals system prompt three tools and then say so I’m
[12:33] going to start running this now python 3 agent.py pie. And so I’m flying to Hawaii or whichever place to some uh to Hawaii. Let’s just say Hawaii. Help me plan my itinerary. Okay. So this is all I’m telling it. I’m not even telling it, hey go make your own agent or go create your own rule. This is all I’m telling it. This is how your customers would chat with it,
[13:03] right? they just tell them what their problem is and they expect you to figure it out. Right? So, this agent is going to be like, “Oh, great. Um, here I’m going to be printing out I’m going to be creating these into three focus sub aents. The flight agent, the activities agent, the itinerary agent, and it’s calling the editor tool three times, one for each of these.” So, I see that it’s already created the activities. Yeah, it’s creating It’s pretty fast. It’s creating the activities agent. It’s created like a flight agent that’s doing
[13:33] something. It’s created an itinary agent. The let me call out that the one thing this can’t currently do right now is access real-time information because I’ve been given it a tool that has access to real world API. Right? So assuming you add that on you can ask it what’s the weather like and it’ll be like you know what let me write a tool that can always grab the latest weather in whichever location and recommend stuff. So based off of that, it created those agents. And if you look at it somewhere here, it should technically be calling those agents. There we go. See,
[14:04] it’s calling the activities agents. And then it’s saying these are the ma main airports. These are the best beaches. These are what it is, and this is what you have to do. And so how amazing is is it that you can now have your agent. So you now your focus is not just building a good agentic system that can get the job done. You would also maybe want to start thinking about healing, writing self-healing code, about creating an agent that can sort of go over itself, look at what bugs are there and fix
[14:35] itself. Had this been a longer session, I usually do longer sessions. I usually ask the audience to ask it to do crazy stuff and I try breaking it. And what happens is this actually ends up breaking. you’ll see a bunch of errors coming up and this thing is just talking chatting away. So I need to probably set the max token somewhere here but um and so it actually ends up erroring and breaking but it recognizes that it’s erroring and it says oh man I’m ering let me fix myself and it would go and fix the same fix this exact same tool or
[15:07] agent that it’s got here. So now if I’m like I don’t want Hawaii why do you make it for Hawaii do for something else going to be like sure let me do it let me update the agent. So it’s super super powerful. But then again we have to keep in mind that this is just autonomously doing things by itself. With great power also comes great responsibility even greater responsibility. So what do we need to do with it? Right? We need a eval. What are some inbuilt evals that str agent has? We we have totally eight different evals. The first one is at an
[15:38] overall session level. We want to figure out if I told it hey book my flight tickets is it actually booking? Did it achieve the end goal? That is part one of it, right? End goal achievement. Second thing we want to look at it is at a trace level. Um was it actually helpful? If I say what is my balance and says my balance is 500 bucks, is that the expected type of answer? Part one. Part two, did it make up the answer? Is that the actual answer that you’re supposed to get? You need to be able to evaluate that. But it doesn’t just end there. What about tool access? Right?
[16:10] What about did it use the right tool to get to that answer or did it use the wrong tool? And within that specific tool, did it use the right parameter? Is the account ID actually one two three or is it supposed to be is it messing up? We want insight into what is going on so that we can trust it and reliably give it access. Again, not just it doesn’t just end there. We also want to understand inter agent dependency. When we’re building multi-agentic systems, we want to look at the overall outcome and
[16:41] the overall response if it’s the way you wanted it to be. You want to make sure that it’s calling the different tools and the different sub aents in the right sequence. And you also want to take a deeper dive into what the messages, the inter agent communication looks like and if that’s up to the mark. All of this together gives us the full end to end agent conversation within our session. This gives us the insight. Again, this also isn’t good enough, right? We want to make sure it doesn’t cause undue
[17:11] damage. If this meta tooling or this meta agent can spin off tools and agents, it can also modify and delete. Do I want it to delete my data? Do I want it to delete stuff that I have put all of my effort into building? No. So, what do I do? I have to have guard rails in place. Four different types of guard rails. The first one is your environment. We need to make sure that we’re sandboxing the environment. And when I say sandboxing the environment, it’s not your typical sandbox where your agent is in one container and you’re
[17:43] protecting it from the rest of the world. We want the environment in which this code is executing to be sandboxed and Strands recently launched a feature about I think a few weeks ago where we can sandbox the code execution environment and that is what guarantees that it doesn’t touch the rest of your code execution environments and it doesn’t mess up everything else and it doesn’t write into wrong places and delete from the wrong places. Right. Next we have to constrain the tools. We
[18:14] have to constrain permissions. We have to constrain the who’s got access and who can ask it questions and what types of questions we need to ask and observability. All of your evals, your hotel, your telemetry, all of that data needs to be there in order to be able to say that, hey, reliably and say, hey, I think I can go ahead and build an agentic system that can think for itself that it can do more than what it’s just
[18:46] been set out to do because it can fix things when things are broken on the fly, on the run, and it can solve more capabilities than it has been initially taught to. This is the starting of self-improving agents and the self- evvolving agents. At some point, I’m convinced they will take over the world and I’m I’m going to be at risk. But until then, I think this is incredible. And if anything, if I want to leave you with anything, I would want you to I would want to leave you
[19:16] with a quick idea of where Strands is, where Strand started with and where we are at now. We started with building their own tools. We we moved to getting them to update uh to create agents by themselves. Now it’s at a point where they can update their own source code. Fun fact, we created Strand agents three years ago internally. It was supposed to be this internal thing before agents was even a thing. And it was so powerful that we said, you know what, let’s just open source it and give it back to the community. And we wrote the Python
[19:47] version of Strands. And the Python version of strands wrote by itself the TypeScript version of Stand. So, it did update its own source code. It’s pretty powerful. I’m pretty psyched. And if if this is my call to action, if uh this sounds interesting to you, reach out to me. Scan these and we can have a conversation later. I’m happy to share my slide deck and my code with you. Um and we can chat offline. Um thank you very much. This is my LinkedIn. Uh, we
[20:19] have 30 seconds to go, I think.