Agent Speedrun — Elizabeth Fuentes Leone e 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: Agent Speedrun — Elizabeth Fuentes Leone & Sandhya Subramani, AWS · Canal: AI Engineer · 59:31 · Assistir no YouTube
Tópicos: Agentes de IA, Engenharia de software com IA, Segurança de IA
Elizabeth Fuentes Leone e Sandhya Subramani conduzem um workshop prático para criar um agente de atendimento ao cliente com Strands Agents, um agent harness open source. A demonstração parte de um agente básico com ferramentas e avança para hooks, skills e steering, mostrando formas de controlar o comportamento do agente. Na etapa final, elas apresentam o deploy do agente no Amazon Bedrock AgentCore Runtime e os recursos de sessões e observabilidade. O workshop também oferece ambientes e código para os participantes experimentarem as etapas.
Pontos-chave
Seção intitulada “Pontos-chave”- Strands Agents permite conectar diferentes provedores de modelos e ferramentas a um agent harness customizável.
- O agente de atendimento usa ferramentas para consultar clientes, verificar pedidos e processar reembolsos.
- O agent loop coordena a entrada do usuário, as chamadas ao LLM, o uso de ferramentas e a resposta.
- Hooks permitem aplicar verificações determinísticas, como limitar a quantidade de chamadas a ferramentas.
- Skills em arquivos Markdown fornecem instruções e contexto relevante quando necessário, sem sobrecarregar o system prompt.
- Steering usa verificações adicionais para orientar ou corrigir as respostas do agente.
- O AgentCore Runtime pode hospedar agentes e oferece recursos de sessões e observabilidade.
- O deploy demonstrado usa a CLI e o AgentCore para preparar e publicar o agente na AWS.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:12 | Apresentação e visão do workshop | As apresentadoras introduzem o objetivo de idear, construir, customizar e publicar um agente. |
| 07:30 | Agenda e preparação do ambiente | O workshop apresenta seus módulos e orienta os participantes a acessar o ambiente de exercícios. |
| 14:12 | Configuração do notebook e escolha do projeto | As apresentadoras mostram como abrir o editor, selecionar o kernel e acompanhar o código. |
| 19:25 | Agente básico de atendimento ao cliente | O grupo cria ferramentas de consulta e reembolso e conecta essas ferramentas ao agente. |
| 25:35 | Hooks e limites para chamadas de ferramentas | A demonstração usa hooks para controlar o fluxo e limitar chamadas repetidas a ferramentas. |
| 33:17 | Skills e steering | As apresentadoras mostram como adicionar instruções especializadas e orientar as respostas do agente. |
| 40:05 | Steering para controlar respostas | O workshop explica como um agente auxiliar pode verificar e corrigir o formato ou o conteúdo de uma resposta. |
| 46:21 | Preparação do deploy com AgentCore | A demonstração passa da gestão de memória para os passos de publicação usando a CLI. |
| 49:30 | Observabilidade e configuração do serviço | A apresentadora mostra configurações necessárias para habilitar a observabilidade do agente no ambiente AWS. |
| 52:06 | Preparação e teste do agente | O código do agente é preparado para o runtime, com uma alternativa para testar localmente. |
| 55:55 | Deploy e invocação do agente | O AgentCore cria os recursos de deploy e a apresentadora testa a invocação do agente publicado. |
| 59:00 | Materiais e encerramento | As apresentadoras indicam os materiais do workshop e encerram a sessão. |
Citações
Seção intitulada “Citações”As ferramentas são a forma de dar ao agente capacidade de executar uma função. — 17:51
Quando você usa um hook, pode ser mais determinístico. — 31:14
Como damos esse conhecimento a ele? Como dizemos a ele como responder? — 35:22
O agente auxiliar verifica, corrige e ajuda a ajustar a resposta. — 40:37
O AgentCore cuida de tudo isso para mim. — 55:55
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- Strands Agents (ferramenta): Agent harness open source apresentado no workshop para criar agentes com modelos e ferramentas configuráveis.
- Amazon Bedrock (ferramenta): Serviço usado na demonstração como provedor de modelos para o agente.
- Amazon Bedrock AgentCore (ferramenta): Conjunto de serviços apresentado para executar agentes e oferecer recursos como runtime, gateway, memória e observabilidade.
- AgentCore Runtime (ferramenta): Ambiente de execução do AgentCore usado no workshop para publicar o agente.
- AgentCore Gateway (ferramenta): Componente descrito como um endpoint para disponibilizar ferramentas e MCP ao agente.
- hooks (conceito): Pontos de execução em que código pode validar ou interromper etapas do agent loop.
- skills (conceito): Instruções e contexto em arquivos, como Markdown, que o agente pode consultar conforme a tarefa.
- steering (conceito): Mecanismo apresentado para avaliar e orientar as respostas do agente com regras ou um agente auxiliar.
- Agent Loop (conceito): Ciclo em que o agente recebe uma solicitação, consulta o LLM, pode chamar ferramentas e produz uma resposta.
- Elizabeth Fuentes Leone (pessoa): Apresentadora do workshop que conduz a construção do agente e explica hooks, skills e steering.
- Sandhya Subramani (pessoa): Apresentadora do workshop que explica recursos do AgentCore e demonstra o deploy do agente.
- AWS (empresa): Empresa responsável pelos serviços de nuvem usados na demonstração.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:12 Meu nome é Sandy, e esta é Elizabeth. Temos o Mike e mais pessoas nos ajudando hoje, caso alguém tenha dúvidas sobre como configurar os ambientes do workshop e executá-lo. Todos aqui são especialistas, inclusive todos que estão nos ajudando. Estamos muito animados para começar hoje. Queremos envolver todos vocês desde a concepção de um agent, passando pela construção, pela adição de muitas personalizações e, depois, pelo deploy.
00:43 Então, queremos começar pela forma mais simples de um agent. Para isso, estamos usando os agents do Strands, um harness de agents open source. Na verdade, ele foi desenvolvido pela AWS, mas é totalmente open source. Vamos passar rapidamente por ele. Vou dar uma breve introdução sobre o que vamos fazer e, depois, podemos ir direto ao código. Todos vocês terão código
01:14 que poderão executar e levar para casa, e poderão executá-lo por dois dias depois deste workshop, certo? Então, vamos começar. O que são Strands Agents? Strands Agents é um harness de agents open source, o que significa que vocês podem trazer o próprio LLM. Podem usar qualquer provedor de LLM, qualquer provedor de modelos, criar um harness de agents em torno dele e controlá-lo de ponta a ponta. Vocês podem personalizá-lo e adicionar as próprias ferramentas. Ele é totalmente open
01:45 source. Há uma comunidade que dá suporte a ele no GitHub, e a AWS o mantém. Ele oferece suporte ao protocolo MCP e ao A2A. É totalmente aberto e flexível, e vocês podem fazer o deploy em qualquer serviço gerenciado. Também podem executá-lo localmente ou hospedá-lo em qualquer lugar. Como eu disse, vocês podem usá-lo com qualquer modelo. Ele funciona nativamente em produção com a AWS, mas vocês podem trazer qualquer modelo que quiserem e executá-lo. Ele também
02:15 tem guardrails e observabilidade integrados. Quando digo que vocês podem executá-lo no Amazon Bedrock, com o AgentCore, também podem usar qualquer um dos outros serviços. Também podem usar um provedor diferente ou, se quiserem, o próprio modelo hospedado que vocês desenvolveram. Ellie. Sim. Como, neste workshop, vocês vão colocar em produção o agent que vamos
02:46 construir, vamos usar o AgentCore. O AgentCore é um serviço da Amazon dedicado exclusivamente a colocar agents em produção. Dentro do AgentCore, temos o Core Runtime, que é o runtime, o contêiner onde vocês vão colocar esse agent. Não importa se vocês estão usando o framework Strands, LangChain ou CrewAI: podem colocar essa aplicação de agent dentro do runtime, do contêiner, e fazer o deploy desse mecanismo em um único comando na CLI. Ao usar o Runtime, vocês têm sessões, e cada sessão pode durar até 15 minutos ou até 8 horas. Assim, vocês têm uma sessão integrada ao contêiner, sem precisar de nenhuma configuração,
03:17 porque ela já está lá, e também têm observabilidade integrada. Portanto, vocês só precisam do código: instalem-no ou coloquem-no dentro do contêiner, e terão memória e observabilidade. E, quando digo observabilidade, não estou falando da observabilidade da RAM nem do comportamento desse contêiner. Estou falando da observabilidade de agents: quantos tokens estou usando nesta aplicação? Qual ferramenta esse agent está usando? O que aconteceu dentro do loop do meu agent? Vocês
03:48 vão poder ver tudo isso na observabilidade do AgentCore, no CloudWatch, na AWS. Também temos o Core Gateway. Às vezes, temos muitas ferramentas e muitos MCPs para nossa aplicação de agents. Então, vocês podem colocar todas essas ferramentas e esses MCPs por trás de um AgentCore Gateway. O Core vai disponibilizar algo como uma API — API não é bem a palavra —, um endpoint que vocês
04:19 podem invocar dentro do loop do agent. Esse endpoint poderá fazer uma busca semântica em todas as ferramentas e em todos os MCPs. Assim, há apenas um endpoint para todos os MCPs e todas as ferramentas, com busca semântica. Isso ajuda a disponibilizar a melhor ferramenta para o loop do agent. Também temos o AgentCore Memory. Quando criamos um agent, temos memória de curto prazo. A memória de curto prazo
04:51 já vem integrada ao runtime. Vocês já sabem disso. Mas o que acontece quando vocês querem uma memória de longo prazo, uma memória que dure mais de oito horas? Vocês podem criar uma memória do Core. Ao criar uma memória do Core, vocês também terão memória semântica. O AgentCore cria para vocês três tipos diferentes de memória. Então, vocês terão, não me lembro do nome da memória, mas terão três prompts diferentes capazes de
05:23 criar os três tipos diferentes de memória. Assim, sempre que recuperarem informações no loop do agent, poderão recuperar essa memória no agent, chamada Memory, que já vem totalmente integrada. Vocês não precisam criar o vector store nem o banco de dados. Não precisam criar nada. Só precisam dizer: “Ei, Core, quero uma memória do Core”. Então, ele faz o deploy da memória para vocês: os três tipos diferentes de memória, memória de árvore personalizada e memória sem construção. E vocês podem criar a própria
05:55 memória personalizada. Vocês podem usar o próprio prompt personalizado para criar sua memória. Assim, sempre que recuperarem informações para esse agent, terão a memória personalizada. Também há o Core Identity e muitos outros recursos do AgentCore, mas só temos uma hora. Neste workshop, vocês vão fazer o deploy do agent no AgentCore Runtime. Já falei disso. E sim, o AgentCore Runtime permite que vocês coloquem o código e
06:26 façam o deploy em produção. Vocês têm segurança de nível empresarial, claro, porque ele é executado na AWS. É totalmente seguro, desde que vocês façam um bom deploy e não compartilhem suas chaves, entre outras coisas, porque ele fica dentro da AWS. Não usamos seus dados para treinar modelos; tudo fica na sua conta e é usado apenas nela. E a escala é automática. Vocês têm o contêiner e não precisam gerenciar a escala, porque o Runtime pode escalar automaticamente para cima se houver muitas sessões e, se houver menos sessões, escalar para baixo.
06:57 Obrigada. Então, hoje, é isso que vamos fazer. Vamos começar com um agent básico. O que é um loop de agent? Como podemos construir um sistema de verdade com ele? E algumas ideias para aprofundar o que realmente faz um bom agent, certo? Vamos falar sobre hooks, skills e direcionamentos. Depois, a Ellie vai falar sobre gerenciamento de sessões e sobre como fazer o deploy no AgentCore.
07:30 Também temos frameworks de evals para agents como parte do workshop. Se tivermos tempo, vamos usá-los. Mas queremos ir com calma e garantir que todos entendam o básico antes de passar para os conceitos avançados. Se não tivermos tempo, vocês ainda poderão usar este link. Ele continuará válido por mais dois dias. Então, podem usá-lo, voltar para casa, executá-lo e concluir todos os módulos. Se tiverem dúvidas, perguntem a qualquer um de nós, e estaremos aqui para ajudar. Então, a primeira coisa
08:02 é acessar o link deste workshop. Ele está habilitado para cerca de 250 participantes. Se houver mais pessoas e algumas tiverem problemas, temos um link de workshop reserva. Por enquanto, acessem este site, que deverá levá-los a um link. A Ellie também pode orientá-los nas etapas, se necessário. Isso vai levá-los a uma conta. Todos têm o link anterior? Querem que eu espere alguns segundos? >> Está ali. Está ali. >> Acho que também está nos próximos
08:34 é, acesse este link do workshop. Isso está habilitado para cerca de 250 participantes. Se houver mais pessoas e alguns de vocês tiverem problemas, temos um link reserva para o workshop, mas, por enquanto, acessem este site e ele deve levar vocês a um link. A Ellie também pode, desculpe, acompanhar vocês passo a passo, se necessário. Então, isso vai levar vocês a uma conta. Todo mundo tem o link anterior? Querem que eu espere alguns segundos? >> Está aí. Está aí. >> Acho que também está nos próximos slides.
09:05 slides. Acho que… então, o que vamos fazer hoje? Vamos acessar esta conta do Workshop Studio. Vocês não precisam criar a própria conta da AWS. Essas contas já foram criadas para vocês, e haverá um formato de notebook Jupyter. A maior parte do código já está lá. Podemos personalizá-lo. Vocês podem executá-lo, baixá-lo e executá-lo nos próprios ambientes, mas, para esta sessão, está tudo pronto para vocês. Então, podem usar e executar diretamente de lá
09:36 de lá. Isso é gratuito. Vocês não vão usar nenhuma das suas contas. Não será solicitado nenhum cartão de crédito. Então, venham conosco e façam tudo passo a passo. Se tiverem alguma dúvida, estamos todos aqui para ajudar. Como eu disse, a primeira coisa é acessar o link deste workshop. Ao acessar esse link, vocês vão abrir um site. A primeira coisa que precisam fazer é
10:07 informar seu e-mail e uma senha de uso único. Então, vocês vão receber um e-mail com… não me lembro quantos números são. Sim, vocês precisam informar seu e-mail e vão receber a senha de uso único. Depois, precisam inserir essa senha na janela, como neste exemplo. >> E, se alguém tiver alguma dúvida, levante a mão. Um de nós vai até vocês e ajudará.
10:38 >> Neste workshop, vocês poderão usar modelos da Anthropic por meio da API do Amazon Bedrock. Acho que… não tenho certeza, mas acho que também poderão usar os novos modelos da OpenAI e, é claro, todos os modelos da Amazon que temos, que vocês podem invocar pela API da Amazon. E poderão usar o Amazon Bedrock AgentCore gratuitamente. Não é tão
11:09 caro. Está bem, eu sei disso, e sei que às vezes as pessoas têm problemas para usar o novo serviço porque… sim, é normal ter… sei lá, custa dinheiro. Mas, se experimentarem o Amazon Bedrock AgentCore na sua conta, vão ver que não é tão caro. Depois, vocês precisam aprovar a próxima janela. >> Todos estão acompanhando? Alguém está tendo dificuldades em alguma etapa até agora? Precisam de ajuda?
11:39 Desculpe. Você está com dificuldade para entrar? Então, você abriu o link do workshop e digitou seu endereço de e-mail e sua senha? >> Certo, acho que o Mike pode ajudar. >> Você está bem. Preciso ver… >> todo mundo. Certo. Mais algum problema? Alguém está tendo alguma dificuldade? Talvez estejamos com um pouco de
12:09 problema no Wi-Fi. Quem imaginaria que uma conferência teria problemas com Wi-Fi? Muita gente está se conectando. Vocês vão demonstrar algumas dessas etapas no palco? >> O quê? >> Vocês vão percorrer as etapas do workshop no palco? Assim, se as pessoas não conseguirem fazer, podem assistir? >> No fim da sessão, vamos compartilhar todos os slides com vocês. Este é um Jupyter. Este é um repo que vocês também podem clonar. Todo este código, tudo o que vamos
12:40 criar aqui não está disponível apenas no estúdio virtual. Como este estúdio virtual ficará aberto por dois dias, provavelmente é melhor começarmos mostrando o que há nele, e vocês podem fazer isso para… para o seu negócio. E vocês podem usar tudo isso. Quando terminarmos a sessão, vou deixar este workshop disponível por três dias. Assim, poderão usar tudo isso gratuitamente por três dias. >> Sim. Que os deuses do Wi-Fi estejam conosco
13:11 hoje também, enquanto fazemos isso com vocês. >> Ah, sim. Se alguns de vocês não estão conseguindo acompanhar por causa de problemas de rede, vamos tentar repassar tudo passo a passo, de novo, tomara que o Wi-Fi funcione. Além dos problemas de rede, alguém está tendo alguma dificuldade para se cadastrar, entrar ou qualquer outra coisa? >> Sim. >> Certo. Antes de começar, tirem uma foto disto. Sim. Porque, se tiverem problemas com a primeira opção, não é um problema de internet. Se estiverem com problemas porque não há
13:42 contas suficientes, é porque a primeira opção está sendo usada por outra conta. Então, podem usar a segunda. >> Então, temos que separar os ambientes de deploy. >> Sim. >> Vamos começar. Certo. Todos estão vendo isto agora, certo? >> Não, não é isso.
14:12 >> Não é isso, certo? Todos deveriam estar vendo isto. À esquerda, vocês terão o passo a passo do trabalho: o que vamos criar e como vamos criar, a configuração de cada um dos módulos. É para vocês acompanharem. Se ficarem em dúvida sobre como começar a executar, este material mostra tudo. Mas, se quiserem começar pelo código, cliquem aqui, em Agent
14:42 Speedrun: da ideia ao código, certo? Cliquem ali. Rolem até o fim e vocês verão a URL do editor de código. Todos estão acompanhando? Cliquem nessa URL. >> Quem está com internet, sim. Todos que têm internet, cliquem neste botão aqui. Rolem até o fim, até a URL do editor de código, e abram. O módulo um deve aparecer. Este é o módulo um. Podem fechar tudo
15:13 isto. A primeira coisa que precisam fazer é selecionar o kernel, certo? Qual kernel devo selecionar? Voltem ao mesmo Workshop Studio, na seção de configuração. Quando começarem e forem para as próximas etapas, isso vai aparecer aqui. Então, selecionem o kernel «Python environments /usr/bin/python 3.13», copiem isso e colem aqui em «Select Kernel». Ele deve fechar
15:44 e selecionar o kernel para vocês. Certo? Vocês precisam fazer isso para cada módulo que forem executar. Então, o que vamos criar hoje? Todos estão me acompanhando? Alguém não está? Ah, muitos de vocês, por causa do Wi-Fi. Há algum outro problema? >> Só o Wi-Fi? >> O que fazemos? Certo, vamos apenas… >> Sim. Obrigado. Nesse caso, vamos percorrer tudo passo a passo. É bem simples
16:16 e vocês podem voltar e tentar de novo. Certo. Vou continuar, e fiquem à vontade para nos fazer perguntas. Então, o que vamos criar hoje? Hoje, vamos criar um agent de atendimento ao cliente usando o agent da Strands, que é um framework de agent harness. Ele funciona basicamente com um agent que tem um loop. O usuário envia a entrada e o contexto, e então temos um LLM que vocês podem fornecer, certo? Porque isso funciona nativamente com a Amazon.
16:48 Temos um modelo hospedado no Bedrock, mas vocês podem usar… Se acessarem o Strands Agents aqui e consultarem os provedores de modelos, poderão usar qualquer um dos seus provedores de modelos favoritos. Podem usar o Llama e, se quiserem hospedá-lo localmente, aqui está como fazer isso. Basta chamar o modelo aqui, defini-lo e, em seguida, no agent, especificar o modelo e o nome do modelo. Podem fazer isso com a OpenAI. Isso é compatível com todos os seus LLMs diferentes. Usem os seus LLMs favoritos, o que quiserem, o Hugging
17:20 Face, todas as suas opções favoritas, certo? Então, usem o modelo que preferirem, tragam sua própria chave de API e conectem-na ao modelo. Aí estaremos prontos para começar. Vamos criar um agent simples de atendimento ao cliente. O que torna o agent poderoso é o loop de raciocínio agentic. Isso significa que, quando o usuário faz uma pergunta e diz: «Estou com este problema, estou tendo esta dificuldade», o agent
17:51 recebe essa entrada. O agent é invocado. O agent chama o LLM, e então o LLM lê a pergunta e chama uma tool. Então, queremos definir um conjunto de tools, porque elas são a maneira de dar ao agent autonomia para executar uma função, já que os LLMs, em geral, só vão prever o próximo token. Não queremos realmente depender do conhecimento básico do LLM sobre qual é a resposta. Queremos fundamentá-lo em uma fonte de
18:22 verdade, em uma fonte de informação. E essas informações podem ser armazenadas no seu banco de dados. Podem ser armazenadas em um arquivo. Podem ser armazenadas em vários formatos diferentes. E isso pode ser escrito dentro de uma tool. E essa tool pode receber acesso. O agent pode receber acesso a essa tool. E o agent decide quando usá-la. O agent também pode ter acesso a várias tools diferentes. E o agent vai descobrir, vai se apoiar na capacidade do LLM,
18:52 na capacidade de raciocínio do LLM para descobrir qual tool usar e chamar a tool, executar a resposta da tool e, potencialmente, de novo, o loop do agent pode ser concluído e, então, ele envia uma resposta. Outra coisa incrível de usar um agent harness é que você pode dar suporte a vários modelos e trocar pelo modelo que quiser sem precisar mudar o system prompt. Você pode, se quiser, mas não precisa mudar o system prompt nem a estrutura ou a arquitetura de como tudo funciona. É isso. E
19:25 então você pode experimentar com qualquer modelo que quiser, e continua funcionando. Continua pronto para uso. Você pode até comparar o desempenho de diferentes modelos com o mesmo código-base. Então é muito poderoso, e aí você recebe uma resposta. Certo. Então, como podemos começar? Primeiro, no módulo um, instalamos o arquivo requirements.ext. Depois, definimos as tools. Está grande o suficiente para todo mundo ver? Preciso aumentar mais o zoom? Certo, ótimo. Estou
19:56 vendo sinal de positivo. Então, o que estamos fazendo aqui? Como estamos criando bots de atendimento ao cliente, primeiro precisamos ter dados. Criamos dados simulados de dois clientes e dos pedidos em suas contas. Eles compraram algo em um site e depois têm perguntas. Querem receber o reembolso do que compraram. Então, como eles fazem isso e como podemos criar um sistema agêntico que ofereça soluções a esses clientes? Eles têm esses pedidos. É só um dicionário. Certo, estes são os clientes e
20:26 estes são os status dos pedidos, e definimos as tools. As tools podem ser escritas como código funcional, mas também podem ser tools do tipo NLP, que você pode gerar. Para definir uma tool, usamos a função decoradora @tool e escrevemos o código. Aqui temos uma tool simples que consulta os clientes. Ela apenas busca o ID do cliente. Depois, temos outra tool que apenas consulta o histórico de pedidos. A terceira tool
20:57 que temos é process refund. Certo? Então, em cada um desses casos, as tools podem ser bem diferentes, mas todas seguem o mesmo formato, o mesmo padrão. Todas usam apenas o decorador @tool. Então, vamos executar isso. Depois, este é nosso código inicial para criar tools. Agora, para criar um agent, precisamos apenas de duas coisas básicas. Uma é o system prompt. A segunda é o LLM,
21:28 o modelo. Neste caso, como estamos usando modelos nativos do Bedrock, modelos hospedados, não precisamos especificar o modelo. Estamos usando o modelo padrão. Mas, como mostrei no site do Strands, você pode escolher o modelo que quiser e adicioná-lo aqui. A terceira coisa que você quer adicionar, além disso, são as tools. Então, você chama o método do agent, informa as três tools que acabamos de definir e, em seguida, cria o system prompt, que diz: você é um
21:58 agent de atendimento ao cliente. E estas são suas diretrizes: sempre verifique o cliente usando a consulta de cliente antes de tomar uma ação. Use os dados das tools para responder às perguntas. Não peça ao cliente informações que você já tem. No system prompt, você diz ao agent, ou seja, diz ao LLM, como usar as tools às quais ele tem acesso e o que fazer com elas. É assim que o LLM e o agent entendem o que precisa ser feito. Então, agora, quando executamos este agent,
22:30 basta dizer: oi, sou tal cliente; pode verificar meus pedidos recentes? E agora ele diz: claro, vou consultar sua conta e o histórico de pedidos. Então, ele invoca a tool um. Faz a consulta do cliente. Depois, chama a tool dois, que consulta o histórico de pedidos, e diz: ah, certo, este é um resumo dos seus pedidos recentes. E então pergunta: tem mais alguma coisa em que eu possa ajudar? Isso é ótimo, mas como podemos descobrir o que realmente está acontecendo por trás dos bastidores? Porque muitas
23:00 vezes, um dos problemas que temos é que meu agent está fazendo coisas e eu não tenho nenhuma visibilidade do que ele está fazendo. Onde está meu controle? Como consigo isso? Certo? Então, vamos inspecionar esse loop do agent. Então, o que… É assim que funciona, certo? Como vimos no diagrama anterior, o usuário envia uma mensagem, ela vai para o LLM, o LLM faz a chamada da tool, recebemos o resultado da tool e, por fim, recebemos uma resposta. Agora podemos examinar as mensagens do agent, a mensagem do agent. Então, este é
23:30 apenas um código para ver como são as mensagens. E isso nos mostra a transferência. Aqui aparece o número total de mensagens: isto é o que o usuário diz. Isto é o que o assistant faz. Depois, aparecem a chamada da tool um e a chamada da tool dois. Então, o usuário não fez mais nada. E o assistant diz: certo, aqui está a resposta. Então, estas são as métricas. Este é o número de tokens que foram usados. Podemos usar mais métricas. Você pode adicionar mais métricas. Faça o que quiser. Além disso, queremos fazer algo simples aqui, certo? Porque é um passo a passo simples. Mas
24:01 também podemos ter conversas com vários turnos. Isto é apenas uma conversa única. Você também pode executar conversas com vários turnos, em que tem um bate-papo mais longo com o agent. Para isso, também pode experimentar estes exemplos. São outros exemplos que fornecemos. Você pode escrever os seus, se a sua conexão com a internet estiver funcionando. Espero que sim. Está? Mas também criamos o arquivo chat.py no mesmo módulo, e temos um arquivo chat.py para cada um desses módulos.
24:32 Então, quando clico em chat.py, este é exatamente o mesmo código subjacente, só que habilitamos as conversas com vários turnos. Você faz a mesma coisa; basta… Quando chegar aqui, o que pode fazer é abrir o terminal e copiar estas duas linhas, porque já estamos nesta pasta específica. Depois, instala os requisitos com pip aqui e então abre
25:04 algo e pode conversar diretamente com ele, se quiser. Aí pode dizer: “Ei, blá, blá, blá”. É só digitar, certo? E você pode ter conversas com vários turnos. Ele vai responder e… pronto. Você pode continuar conversando com ele em vários turnos, com exatamente o mesmo código subjacente, as mesmas tools, e ele consegue conversar com você. 60 linhas de código, menos de 60 linhas de código. Então, esse é o agent básico. Estamos bem?
25:35 Certo, legal. Ótimo. Segunda parte: como podemos melhorar esse agent? O que mais podemos fazer? Isto é o básico, certo? Quem tem acompanhado blogs ou pesquisado na internet provavelmente já sabe fazer isso. Como podemos melhorar? Deixe-me apresentar o que chamamos de hooks. Hooks são incríveis porque… Primeiro, vou abrir isso. Primeiro, vou abrir esse código. Certo, vou fechar isto. Hooks são
26:06 uma forma de impor programaticamente certos comandos e funções. Então, antes… o que você pode fazer é, durante todo esse processo, desde o momento em que seu agent é acionado, quando ele faz as próprias chamadas de ferramentas, recebe respostas e as envia, controlar o que acontece, certo? Desde o momento em que o agent é acionado até antes de a ferramenta ser chamada, ou talvez…
26:38 depois que a ferramenta é chamada e recebe uma resposta. Queremos poder ter bastante controle sobre isso. Talvez queiramos validar quem está usando, como quem são os clientes que estão falando com ele ou que tipo de perguntas estão fazendo. Ele deveria mesmo responder a esse tipo de pergunta? Queremos definir limites de taxa para os tipos de ferramentas chamadas e para o número de vezes que elas são chamadas? Como podemos fazer isso? Com um hook, você pode introduzir seu código neste
27:09 ponto, onde pode ter uma função de asserção ou outro tipo de função que garanta que certas verificações sejam feitas antes de prosseguir para a saída final. Você pode fazer isso antes da invocação, depois da chamada ao LLM, antes da chamada à ferramenta e decidir se quer aprová-la ou cancelá-la. Também pode fazer isso depois da execução da ferramenta, antes de ela enviar a resposta. Então, você pode fazer isso em todos esses pontos, mas também em mais
27:40 lugares. E este é apenas um exemplo. Se formos ao strands agents, veremos todas as maneiras diferentes de impor hooks. Então, é aqui que estou? Não, vou fechar tudo isso. Certo. Então, nos hooks, o que estamos fazendo aqui? Temos os mesmos dados que estamos chamando. Deixe-me executar isto primeiro. Certo. Vá para o notebook. >> Este não é o notebook. >> Não. >> Ah, estas são ferramentas de atendimento ao cliente.
28:10 Certo. Sim, estou no lugar errado. Voltei ao notebook. Temos que instalar os requisitos e escolher nosso ambiente. Como isso funciona? Agora queremos importar strands.hooks e importar HookProvider, HookRegistry e onde queremos chamar esses hooks. No nosso caso, queremos fazer isso antes da
28:40 invocação e também antes da chamada à ferramenta. Vou explicar o que estamos fazendo. Estamos tentando criar um hook de limitador de taxa que garante que, para uma solicitação de usuário, o número de ferramentas invocadas não seja maior que três. Assim, se você tiver um LLM que fica enlouquecido e invoca suas ferramentas sem parar, isso vai custar muitos tokens e, como não está funcionando, você quer criar um limitador de taxa que interrompa a execução e diga: “Mesmo que não esteja funcionando, tudo bem, pare
29:10 em três”, certo? Então, é isso que estamos fazendo. Como podemos criar esse limitador de taxa aqui? Primeiro, definimos o hook de limitador de taxa e dizemos: “Este é o número máximo de chamadas”. Estamos definindo um valor padrão e, depois, precisamos adicioná-lo ao registro. Então, aqui, adicionamos e dizemos: certo, evento antes da invocação. Depois, queremos outro callback, para o evento antes da chamada à ferramenta. Um callback significa que é nesse momento que ele será chamado, porque você o está definindo
29:41 aqui. Então, temos este contador, que é zerado antes de cada resposta — ou seja, sempre que o usuário envia uma nova solicitação —, porque você não quer que o limitador de taxa continue em execução. E definimos uma segunda função chamada check, que verifica o número. Basicamente, é um contador: ele conta quantas vezes suas ferramentas são invocadas. É isso que esta função faz. E então ela verifica
30:12 o número máximo de chamadas e faz o cálculo. Então, definimos nosso limitador de taxa aqui, e esta é a função principal que estamos analisando. A linha extra que adicionamos é a dos hooks, e dizemos: rate limiter hook max calls equals three. Se executarmos, ele chama essas duas e diz: certo, chamada de ferramenta um, chamada de ferramenta dois. Aqui está um resumo dos eventos. Foi isso que aconteceu. Mas vamos testar de verdade. Vamos tentar quebrá-lo e ver se o
30:43 limite de taxa está funcionando mesmo. Certo? Aqui, estou definindo max calls como true. Você quer reduzir o limite para dispará-lo. Aqui, ele está chamando muitas vezes, certo? E, de fato, bloqueou. Aqui, diz “bloquear consulta”, porque o número de vezes foi excedido. Então, quando seu agent começa a ficar descontrolado e todos nós nos preocupamos: “Meu Deus, será que meu agent vai dominar tudo?”, certo? Isso não vai acontecer, porque temos algo chamado hooks. Todo mundo está acompanhando? Estamos bem? Alguém consegue executar junto comigo? Estou indo rápido demais ou estamos só assistindo? Tudo bem. Ah, certo. Que bom. Pelo menos algumas pessoas estão acompanhando. >> Eu gostaria de acrescentar algo sobre os hooks. >> Às vezes, sabe, o hook é melhor porque, quando usamos um LLM com algumas ferramentas, o LLM é probabilístico. >> Sim. Sabe, quando você coloca um prompt dentro da sua aplicação agentic, o prompt é como uma sugestão, sabe? Ele só determina a probabilidade de você receber uma resposta. Então, quando você usa um hook, pode
31:14 alguém consegue executar junto comigo? Estou indo rápido demais ou estamos só assistindo? Tudo bem. Ah, certo. Ótimo. Temos pelo menos algumas pessoas. >> Eu gostaria de acrescentar algo aos hooks. >> Às vezes, sabe, um hook é melhor porque, quando você usa um LLM com algumas ferramentas, o LLM é probabilístico. >> Sim. Sabe, quando você coloca um prompt dentro da sua aplicação agentic, o prompt é como uma sugestão, sabe? Ele só diz respeito à probabilidade de dar uma resposta. Então, quando você usa um hook, pode
31:45 ser mais determinístico. Você pode colocar código dentro do loop do seu agent, como código Python antes ou depois da invocação. Assim, pode interromper… não sei, neste exemplo, você interrompe a invocação de mais de três ferramentas. Mas, por exemplo, se quiser restringir… não sei, algum número de cartão de crédito ou algo assim, pode colocar um hook, um código capaz de identificar certas coisas
32:15 e dizer: “Ei, você pode receber esta informação, então vou bloqueá-la com esta função determinística”. Assim, você não a recebe; o modelo nunca vai receber essa informação. Então, você bloqueia a chamada e não desperdiça tokens. Não precisa invocar o modelo de novo. Você não desperdiça tokens, porque está interrompendo isso. Você envia um hook. E, se não quiser enviar certo tipo de resposta ao cliente do atendimento, também pode interromper essa resposta com um
32:46 hook depois da chamada. >> Exatamente. Obrigado. Certo. Você pode experimentar por conta própria. E, de novo, se quiser conversas com vários turnos, acesse chat.py no segundo módulo, com os hooks habilitados. Você ainda pode continuar conversando com ele. Pode testar e adicionar hooks diferentes em lugares diferentes para ver o que funciona. Você pode tentar bloquear certos clientes ou certos tipos de perguntas. Pense em guardrails, certo? Então, hooks são incríveis
33:17 e queremos usar hooks enquanto criamos bons sistemas agentic. Agora, vamos acrescentar mais uma camada legal a este projeto, certo? Vamos adicionar skills. Vamos adicionar skills e encontrar uma forma de direcionar seu agent e seu LLM, fazendo com que respondam da maneira que queremos. E eu adoro direcionar. Direcionar é demais. Então, vamos falar sobre direcionamento. Alguém tem alguma pergunta? Está todo mundo bem
33:47 com a ideia dos hooks? >> Sim. Então, se… desculpe. >> Ah, certo, certo, certo. Então, a pergunta era… Ah, agora você está com o microfone. Quer…? >> Sim.
34:18 >> Certo, pode perguntar. Ah, isto está errado. Vi que, no exemplo com o hook, o agent continuou executando, mas a chamada à ferramenta foi bloqueada. Como fazemos para parar o agent, para que ele não entre em um loop infinito e continue repetindo? E… >> Ao definir nossos hooks, podemos configurá-los de modo que também encerrem o turno do agent, se quisermos. Para a demonstração, queríamos mostrar como funciona, para podermos ver o limitador de taxa em ação e confirmar que as chamadas não estão sendo executadas várias vezes, certo? Então, o que ele está fazendo é
34:49 Neste caso, ele está tentando chamar a ferramenta porque, como dissemos antes, antes da chamada da ferramenta, ele continuava tentando fazer isso e parava, mas o LLM ainda continuava executando o loop até o fim. Mas, se quisermos, podemos criá-lo de modo que digamos: “Certo, se eu vir isso, apenas interrompa o turno e encerre nesse ponto”. Então, definitivamente podemos personalizar. Só fizemos desse jeito porque queríamos mostrar o funcionamento de ponta a ponta. Obrigada pela pergunta. Certo. Então, skills e direcionamento. Agora, este é um chatbot
35:22 que deve responder a perguntas de atendimento ao cliente, mas as pessoas podem fazer várias perguntas diferentes que o agent talvez não tenha acesso ou conhecimento para responder. Então, como damos esse conhecimento a ele? Como o instruímos a responder? Criamos o que se chama de pasta de skills, um arquivo de skills que potencialmente contém todas as suas informações sobre a sua… sua… sua verdade fundamental, certo? Talvez sua fonte única da verdade sobre o que ele… sobre quais etapas ele realmente precisa seguir.
35:54 E podemos adicionar isso como um arquivo Markdown. E é assim que funciona: aqui, o que ele faria, quando adicionássemos agent skills, seria primeiro procurar a pasta de skills e ler todas as skills, ver qual delas faz sentido e, então, usar essas skills. Vou falar sobre direcionamento daqui a pouco, mas skills são uma forma de dar ao nosso… Deixe-me ir para o terceiro, o terceiro módulo.
36:26 Então, vou executar isto primeiro. Perfeito. Primeiro, quando criamos skills, agora temos três tipos de skills que criamos. Uma é como processar um reembolso. Outra é como rastrear pedidos. E o que fazer se as pessoas fizerem certos tipos de perguntas relacionadas à conta. Minha senha não está funcionando, ou algo assim, um conjunto de perguntas frequentes. Como podemos fazer isso funcionar? Certo? Esta é sobre como lidar com problemas na conta.
36:58 Aqui, estamos criando esses diferentes plugins de skills e podemos chamá-los diretamente. Então, quando abro a pasta de skills aqui, podemos ver exemplos de skills. Este é apenas um arquivo Markdown com skills para solucionar problemas de conta, que fornece contexto, contexto adicional, porque não queremos sobrecarregar o system prompt com todas as informações que temos, já que elas também são consideradas tokens de entrada e podem ser desperdiçadas
37:29 desnecessária e inutilmente. Então, quando fazem um determinado tipo de pergunta, podemos fornecer o contexto relevante para aquele tipo específico de pergunta. Assim, ele tem acesso a todas as informações de que precisa para responder à pergunta corretamente e fazer um bom trabalho. Neste caso, esta skill específica fala sobre como solucionar problemas de conta. O que é necessário para redefinir uma senha? O que fazer quando a conta está bloqueada? E o mesmo vale para o rastreamento de pedidos, certo? O que fazemos? Quais são as etapas que
37:59 precisamos seguir? São instruções que damos ao agent antecipadamente e escrevemos com base no que queremos que ele faça. Então, criamos esses diferentes arquivos de skills, arquivos Markdown, e, quando executamos, além do system prompt, o que damos a ele é acesso ao plugin. Então, agora estamos adicionando mais um parâmetro aqui, chamado plugin, que dá acesso a todas as skills
38:30 plugins, e o plugin de skills aponta para a pasta de skills aqui. Então, agora ele vai chamar as skills necessárias para aquele tipo específico de pergunta. Quando isso é executado e alguém diz: “Gostaria de um reembolso pelos meus fones de ouvido sem fio”, ele está realmente chamando as skills como uma ferramenta. E então diz: “Certo, encontrei sua conta. Veja o que encontrei e como estou fazendo isso”. Assim, o processo fica cada vez mais determinístico. Ele segue uma ordem natural
39:03 e você pode invocar o contexto apenas quando necessário. E você não sobrecarrega o system prompt com muitos tokens toda vez. Isso são skills, mas uma coisa que tenho enfrentado bastante é o direcionamento. Quantas vezes já tivemos dificuldade para fazer nossos agents responderem a uma pergunta em um formato específico, e eles sempre erram? Parece que eles conseguem lidar com todas as perguntas difíceis
39:34 certo. Se eu disser… Então, se eu perguntar: “Qual é o reembolso que devo receber?”, ele me daria um reembolso e diria: “Certo, é este o valor”, mas, em geral, também tende a falar demais e gerar muitos tokens, simplesmente falando livremente. Então, como fazemos para que ele responda no formato que queremos? Como podemos garantir que ele nos dê uma saída estruturada, se é disso que precisamos, ou, por exemplo: “Ei, pare de usar travessões longos o tempo todo”? Queremos continuar dizendo isso? Precisamos conseguir detectar
40:05 isso de forma determinística e garantir que ele faça isso de maneira determinística. Para isso, fazemos algo chamado direcionamento, que ajuda o agent a se orientar na direção que queremos, dando a ele um agent parceiro. Pense nisso como uma parceria, como programação em dupla ou trabalho em dupla: enquanto ele gera uma saída, o agent parceiro observa o que está sendo gerado e, então,
40:37 esse agent parceiro pode dizer: “Ei, não, não é isso que você deveria fazer. Este é o formato em que você deveria fazer isso”. Então, seu agent parceiro verifica, corrige e ajusta o rumo; assim, você obtém a resposta que quer, aquela com a qual realmente fica satisfeito. Quando você está implantando seu código em produção, não há espaço para erros de formato ou estrutura. Você quer que seja de um jeito específico, e o direcionamento pode ajudar nisso. Agora vou fazer… vou fazer isso rapidamente porque quero que Ellie fale sobre deploy, que é como você pode
41:08 garantir que seu agent seja realmente prestativo e útil. Então, uma ideia rápida sobre os handlers de direcionamento. Os handlers de direcionamento funcionam da mesma forma que hooks. Você pode chamá-los, pode invocá-los em diferentes pontos. Pode invocá-los antes do LLM, enquanto o LLM está sendo invocado, antes de uma chamada de ferramenta ou depois de uma chamada de ferramenta. São muito parecidos com hooks, só que, naquele ponto do hook, você também adiciona outro agent
41:38 que pode fazer uma verificação rápida e trabalhar em parceria com este agent para, então, fornecer a saída. Pense nisso como mais uma proteção, se quiser, certo? Então, você pode fazer uma chamada de ferramenta e, depois, isso; e pode ter um guia que diga: “Ah, sabe de uma coisa? Primeiro, consulte isto antes de me dar um reembolso”. Ou pode dizer: “Revise o tom desta mensagem”, se ela estiver enviando uma mensagem, e, depois disso, ela é enviada. Assim, você tem mais controle sobre o que seu agent está gerando. E se
42:10 voltarmos ao direcionamento… Certo. Então, novamente, o que queremos? Queremos importar os direcionamentos aqui. E, daqui, novamente, o handler de direcionamento. E estes são todos os diferentes pontos em que fazemos isso. E você pode fazer isso de diferentes maneiras. Confira a documentação do agent Strands. Os detalhes estarão lá, mas também estarão todos os detalhes no workshop mencionado aqui. Agora criamos um
42:40 handler determinístico. Damos regras a ele e dizemos o que deve fazer. Também pode ser uma função codificada diretamente. Também pode ser outro agent com uma função codificada diretamente que funcione. Podemos fazê-lo… você pode, por exemplo, aplicar imposição de tipo, se quiser que a saída seja apenas de um tipo específico. Você pode aplicar diferentes tipos de imposições aqui. Certo? Então, você cria um agent de direcionamento, e isso é tudo sobre direcionamento. Certo? Então, agora você cria um
43:12 agente de direcionamento, e você cria a barreira de proteção. Aqui, o handler do fluxo de reembolso foi definido e, por fim, você cria a barreira de proteção. Aqui, você está dizendo: “Tudo bem, não prometa demais, não garanta prazos específicos, não culpe o cliente e reconheça a frustração dele”. Esse é o handler de barreira de proteção de tom que estamos criando. Esse é o segundo tipo de agente de direcionamento que criamos. Agora, no código final, além das skills do agent, nós simplesmente chamamos
43:44 esses dois handlers diferentes que definimos, e eles podem ser configurados em pontos diferentes. Podemos dizer “direcionar depois do modelo”, se quisermos, e informar o que fazer neste caso. Mas aqui também podemos fazer direcionamento com data.get, criar um registro para isso e escolher ativá-los em qualquer parte do fluxo agentic em que quisermos. No fim, tudo o que precisamos fazer é dar acesso a esses dois
44:17 handlers de direcionamento. Eles serão ativados e, quando você executar, não será apenas uma chamada a lookup customer e get order history: também veremos que a resposta do agent está sendo avaliada. Assim, antes de enviar a resposta final ao usuário, você pode garantir — e pode fazer isso com total confiança — que a resposta está correta. Você pode dizer com total confiança que o modelo
44:48 e o agent provavelmente vão responder da maneira que você quer, porque estamos estabelecendo todos esses recursos de controle. Você pode experimentar, e agora vou passar rapidamente para Ellie, porque ela vai falar… >> Como temos apenas 12 minutos para colocar esse agent em produção, quero acrescentar algo sobre o direcionamento. Há uma biblioteca open source chamada agent control que você pode adicionar ao seu projeto; ela está na documentação.
45:19 Com agent control, você pode criar regras de direcionamento. Por exemplo, tenho uma demonstração de um sistema de viagens; você pode usar hooks para bloquear números. Por exemplo, se alguém tentar reservar um quarto para mais de cinco pessoas, você pode usar um hook para bloquear a reserva de um quarto para mais de cinco pessoas. Mas, se quiser direcionar o agent para fazer reservas para mais de cinco pessoas, pode criar regras. Assim, sempre que o agent estiver
45:50 recebendo reservas para mais de cinco pessoas, ele vai dizer: se eu receber seis pessoas, posso direcionar a reserva para dois quartos. Você pode criar regras para isso usando a biblioteca agent control. Também pode hospedar essas regras em um banco de dados. Assim, pode criar um banco de dados com todas as regras para direcionar os agents. Sempre que você invocar essa aplicação agentic, pode consultar o banco de dados e verificar as regras. Então, qual é a vantagem
46:21 disso? Você só precisa alterar as regras no banco de dados. Não precisa mudar o código do agent. O agent só precisa saber qual é o endpoint do banco de dados. Assim, sempre que houver uma nova regra, você pode editar o banco de dados e pronto. Agora, vamos colocar esse agent em produção. Aqui temos o gerenciador de sessão, mas não vou mostrar isso. Esse gerenciador de sessão serve para salvar a memória usando um framework. Então,
46:53 você pode fazer isso usando memória sem o framework, e tudo fica no código. Na etapa cinco, para o deploy, não vamos usar um notebook Jupyter, embora também seja possível fazer isso com um notebook Jupyter; vamos usar a CLI, o terminal. Nesta pasta, temos o mesmo mecanismo. Temos as ferramentas de atendimento ao cliente e também as skills. Temos tudo aqui. Para colocar esse mecanismo em produção, você precisa acessar o Workshop Studio. É isso que vamos fazer. Vamos usar a AWS CLI pelo terminal. Vamos executar um ou dois comandos na CLI. Vamos pegar este agent e enviar o código dele para um runtime na AWS. O AgentCore vai fazer o deploy desse código dentro de um container, mas nós
47:23 não vamos cuidar disso, porque o AgentCore vai fazer isso por nós. Também teremos memória sem precisar fazer nada. Vamos ver, vamos seguir as etapas. Este é um ponto importante: quando você cria uma aplicação agentic e quer colocar o código em um runtime do AgentCore, a única diferença que precisa fazer no seu mecanismo é adicionar este decorator, o entry point. O entry point do MPP é a
47:54 única diferença entre executar seu mecanismo no notebook ou no computador e executá-lo em produção. Isso porque o entry point do MTP é o que o runtime identifica. Quando o runtime identifica o entry point do MTP, tudo o que vem depois dele é o agent. Assim, sempre que você invocar esse runtime, o container vai executar o código que vem depois do entry point. Certo. Vamos começar.
48:24 Então, vou até aqui. Desculpe, deixe-me abrir isto. Esta é a biblioteca de que preciso para executar todos os meus comandos da CLI e, bom, espero que a conexão com a internet esteja boa. Está funcionando. Sim. Neste ambiente, você vai poder fazer o deploy do agent e de tudo mais. Mas, se estiver executando localmente, vai
48:58 poder testar o agent antes de colocá-lo na AWS. E, para ter a observabilidade integrada, você precisa fazer algo no console. Deixe-me mostrar. Para acessar o console, abra esta parte, o AWS Console. Isso vai abrir o console que está sendo executado nesta sessão, nesta conta que você tem. Então, você precisa acessar o AgentCore
49:30 Runtime. Não, não é aqui. AgentCore. Melhor: AgentCore. Você pode ver todos os serviços que o AgentCore oferece. Você também pode criar um harness com poucas linhas de código. Runtime, Gateway, Memory e Observability estão bem aqui. Mas é preciso selecionar uma opção. Não me lembro do nome, mas vou mostrar. Deixe-me ver. Aqui, habilitar… Não, não é aqui. Configurar.
50:01 Então, você precisa acessar “Configurar” e habilitar “Transaction Search”. Isso permite ter a observabilidade integrada no runtime. Sem isso, você não vai ver a observabilidade agentic do agent, porque o CloudWatch não vai receber as informações. Outra coisa que você precisa fazer — salvar — é instalar e adicionar às dependências a biblioteca de observabilidade
50:31 que tenho, as dependências de observabilidade. Desculpe. Ah, está pronto. Temos este arquivo de requisitos porque vou usar o AgentCore, e você precisa deste pacote: AWS OpenTelemetry Distro. Se estiver usando outro framework, como LangChain ou CI, há uma biblioteca específica para esse framework, mas será preciso fazer algumas modificações na aplicação agentic. Com Strands, você não precisa
51:04 fazer nada, porque o Strands já vem integrado à AWS. Tudo está configurado. Mas a observabilidade também funciona com outros frameworks, embora seja preciso fazer algumas modificações. Está tudo na documentação, então você pode consultar. Temos a biblioteca. Vamos até…
51:35 Já estou aqui. Então, AgentCore. Ótimo. Ah, vou criar. Não, tudo bem. Eu não salvei. >> Meu nome: vou colocar Ellie, porque sou a Ellie. Aqui, não vou criar um harness. Vou criar um agent. Mas já tenho meu código. Se você escolher “agent”, será criado um agent simples para você. Mas, como já tenho o código, posso pular essa etapa. Ele vai criar o ambiente e tudo de que preciso para colocar o agent que já tenho dentro deste container. Então, vai criar uma pasta para mim. Aqui está a minha pasta, a
52:06 não salvei. >> Então, vou colocar Ellie como meu nome, porque sou a Ellie. E aqui não vou criar um harness. Vou criar um agent. Mas eu tenho meu código. Sabe, se você escolher agent, ele vai criar um agent simples para você. Mas eu tenho o código, então posso pular essa etapa. E ele vai criar o ambiente, tudo de que preciso para colocar esse agent que já tenho dentro deste container. Então, vai criar uma pasta para mim. Aqui está a minha pasta, a
52:39 AgentCore, tudo. Então, todas essas etapas estão aqui no workshop. Meu Deus, cinco minutos. Mas vou fazer isso em cinco minutos. Vou colocar este agent em produção. >> Tudo bem. >> Sim. Então, vou adicionar um agent ao AgentCore, e é isso que temos aqui. Bom, está demorando um pouco. Quando eu fizer isso, ele vai criar o contêiner de que preciso, mas já tenho este agent aqui no meu computador
53:10 porque queria mostrar uma coisa para vocês: o mesmo mecanismo que a Sandy acabou de mostrar. Tenho o repo desse agent aqui no meu computador. Então, deixa eu aumentar isso. É o mesmo, de novo, que está no quinto. Sim, você pode usar o comando agentcore dev para testar o agent localmente. Você não consegue fazer isso no Visual Studio, porque o Visual Studio é uma máquina virtual que
53:43 só permite executar código neste VS Code. Mas, se você estiver executando isso localmente no seu computador, pode usar esse ambiente para testar o agent. Então, é o mesmo agent e, como podem ver, também tenho algumas sessões aqui. Vocês podem ver a quantidade de tokens. Se quiserem explorar o que está acontecendo dentro do agent, podem fazer isso localmente. Mas, como estou usando o Amazon Bedrock como provedor de modelos, estou usando minhas credenciais da AWS. Para usar o Amazon AgentCore, vocês
54:16 precisam de credenciais da AWS se estiverem executando isso localmente, mas, no workshop do Amazon Browser, não precisam. Então, sim, está funcionando. Sim, é exatamente a mesma área, e eu não fiz nada. Então, vamos voltar para o… >> Sim, tenho tudo aqui. >> Sim. >> Então, eu fiz isso. Não lembro se fiz isso. >> Não. Então, CD… >> mais cedo. Então, vou adicionar meu código dentro deste
54:49 aplicativo com agent. Deixa eu ver dentro deste contêiner. Então, no AgentCore, o que eu quero é um agent. Vou clicar em “Bring my own code”, é isso mesmo. Vocês podem usar o deploy direto do código ou um contêiner. Vou usar essa opção. E vocês podem trazer sua própria chave de API para fazer o deploy deste agent usando Anthropic, OpenAI ou o que quiserem, mas vou usar o Amazon Bedrock. Não vou fazer nada aqui.
55:21 Enter. Enter. Pronto. Agora vou mover meu código. Para mover meu código, tenho aqui a opção de copiar e colar. Certo, e agora? Ah, preciso criar isto. Vamos ver. Copiar e colar. Um minuto. Espera. Não vou fazer isso. Então, AgentCore deploy, e um minuto para fazer o deploy, um minuto para
55:55 colocar este agent em produção na AWS. Está em execução. Vai validar e verificar minhas credenciais. Se vocês conhecem a AWS, sabem que, quando criam tudo dentro da AWS, precisam criar a AMI, criar políticas e permissões, permitir que o serviço se conecte a outros serviços. É preciso fazer muita coisa. O AgentCore cuida de tudo para mim. Então, não preciso criar a política, não preciso criar permissões, não preciso criar mais nada. Ele está fazendo tudo para mim, e vocês
56:27 podem ver isso. Como criei tudo localmente, ele está criando uma CloudFormation, uma infraestrutura como código usando CDK. Vocês podem explorar o código do CDK. Se não conhecem o CDK, CDK significa Cloud Development Kit. Com ele, vocês podem criar infraestrutura como código usando linguagens de programação que conhecem, por exemplo, Python, TypeScript ou qualquer outra. Então, ele está fazendo isso para mim. Está criando tudo. Está criando o deploy e tudo mais. E vocês
56:57 podem fazer isso; dá para ver no console. Vamos para o Amazon Bedrock Runtime. Sim. O quê? Não consigo ver nada aqui. Então, ele está criando… Deixa eu mostrar a CloudFormation. Aqui vou ver minha stack. Ah, não, porque esta é a conta do Visual Studio. Desculpem. Vocês podem ver isso aqui. Mas, quando começar a colocar isso no runtime, vou ver aqui.
57:28 >> Aí está. Está aqui, e vocês podem testar o agent. Está pronto. Certo, posso testar o agent agora mesmo. Posso chamar este agent aqui. Como podem ver, tudo é feito no terminal, dentro do repo. Vocês podem encontrar como chamar este agent usando o boto3. A única coisa de que precisam é a ARN, e este agent está funcionando. Certo, acho que está funcionando. Espero que sim.
57:59 >> Está sim. Está chamando o agent. >> Sim. Aqui vocês encontram como chamar este agent usando o SDK. Está me dando a resposta. Vocês podem… >> Funcionou mesmo. Acho que está. Tem mais alguma coisa que eu possa…? >> Sim. Vocês podem chamar este agent usando o SDK. Explorem como chamar este agent usando o SDK e, para ver a observabilidade, podem acessar o runtime. Aqui vocês têm o painel de observabilidade
58:30 e podem ver as sessões, os traces, quantos runtimes estão em execução e quantas sessões vocês têm. Cada sessão é um runtime, um contêiner diferente. Leva um tempo; demora cerca de um ou dois minutos para aparecer tudo ali. Tudo bem. O quê? Sim, sim, terminei. É isso. Por favor, tirem uma foto e compartilhem com os outros amigos.
59:00 Aqui vocês encontram todas as informações. Está tudo aqui: os slides, o workshop, alguns créditos, se vocês tiverem sorte, porque temos cerca de 20 créditos para a AWS. E, por favor, a… Firestar, somos incríveis na internet. Ninguém… de jeito nenhum. [risos] E todas as redes sociais. Se tiverem alguma resposta, estamos no LinkedIn, Twitter e Instagram. Por favor, em
59:31 no código QR está tudo de que vocês precisam para aprender mais sobre Strands e AgentCore. >> Obrigada. >> [música]
Transcrição original
[00:12] Uh my name is Sandy and this is Elizabeth. Um and we have Mike and we have more people helping us today in case any of you have questions with um setting up your workshop environments and running. And everyone here is an expert. everyone helping us. We’re very excited to get started today. We want to get all of you on board right from ideating an agent, building it, adding a
[00:43] lot of customization and then deploying it. So we want to start with the simplest form of an agent. Um, and we for this we’re using Strand’s agents, which is an open- source agentic harness. And this was actually built by AWS. Uh, but this is fully open source. And so let’s walk quickly through it. I’m going to give you a quick introduction on what we’re going to be doing and then we can dive straight into the code and all of you will have code
[01:14] that you can run, take home with you and you can run for two days after this, right? So let’s get started. What is trans agents? Strands agents is an open-source agent harness which means you can you bring your own LLM. You can use any LLM provider model provider and you can build an agent harness around it and you can control it end to end. You can customize it. You can add your own tools to it. There’s this is fully open
[01:45] source. So there’s community supporting this on GitHub and AWS maintains this and it supports MCP protocol. It supports A2A. It’s fully open and flexible and you can deploy it on any managed service. You can do it locally. You can host it anywhere. Um now like I said you can use it with any model. It works natively with uh in production with AWS but you can bring any model you want and you can run it. uh it’s also
[02:15] got guard rails and observability built in. Uh now if when now when I say you can run it on uh a um Amazon bedrock you can with agent core you can also use any of the other services but you can also use a different provider you can also use your own homegrown uh hosted model if you want Ellie. Yes. Uh let’s and because in this workshop you are going to put this agent that we are going to
[02:46] build in production. We are going to use agent core and agent core is a service. Amazon metro aent core is a service dedicated only to put agents in production. So inside aent core we have a core runtime. that is the runtime the container where you are going to put this agent and doesn’t matter if it’s trans the framework if the launch chain if the crew AI doesn’t matter the framework that you’re using you can put
[03:17] this aentic application inside the runtime the container and you are going to deploy this engine in one single life on the CLI and when you are using runtime this runtime have sessions and the session can run up to 15 minutes up to 8 hours. So you can have a session built in inside this container without any uh configuration because it’s inside there and you have observability built
[03:48] into so you only have the code you uh install this code or put this code inside this container and you are going to have memory and observability and when I say observability is not observability about the RAM or what is the behavior for this container. container is about agentic observability. How how many tokens I spending in this application? What is what did what tool is using this agent? What happened inside my agent loop? You
[04:19] are going to able to see all of that inside the agent core observability inside cloudatch in AWS and we have a core gateway. So sometimes we are having a lot of tools a lot of MCP for our aentic application. So you can put all these tool of this MCP behind a aent core gateway and a core is going to be is going to deliver like a API or API is not the word like a endpoint that you
[04:51] can invoke inside your agent loop and this endpoint is going to be able to do like a semantic search for all your tools for all your MCP. So only one endpoint for all your NCP for all your tools and it have semantic search. So it help you to uh deliver the best tool for your agent loop and we have agent core memory because when we create a agent we have shortened memory. The short-term
[05:23] memory is built in the runtime. You already know that. But what happened when you want a a long-term memory, you know, a memory that can last more than eight hours. So you can create a a core memory. So when you uh create a core memory, you are going to have a semantic memory too. So agent core build for you in three different types of memory. So you are going to have like I don’t remember the name of the memory but you have three different prompts capable to
[05:55] build the three different memories. So every time that you retrieve your agent loop you can retrieve this memory inside the agent called memory that is completely built in. You don’t have to build the vector store the database. You don’t have to build anything. You only have to say hey a core I want a core memory. So it’s deploy for you the memory the three different types of memory custom tree memory and no building memory and you can create your
[06:26] own custom memory. You you can you put your custom prompt to build your own memory. So every time that you retrieve the information for this agent, you are going to have your custom memory and there is a core identity and a bunch of more agent core but we only have one hour and in this workshop you are going to deploy your agent in agent core runtime and I already say that and yeah so agent core runtime have uh give you all the that you can put your code and
[06:57] deploy to production. You have the enterprise grade security of course because it’s running on AWS. So it’s completely secure of course if you are doing a good deployment if you don’t share your keys everything because it’s inside AWS and we don’t use your data to train models is in your account and it’s only using there and scale automatically. So you have your container and you don’t have to manage the scaling because runtime can scale
[07:30] automatically up if you have a lot of session if you have recession is scale down. Thank you. So today um this is what we’re going to be doing. We’re going to be starting with a basic agent. What is an agent loop? Um how can we build um an actual system with it? um and some ideas, deeper dive ideas about what actually makes a good agent, right? So, talk about hooks, talk about skills, steerings, and then Ellie’s going to be talking about um session management, and
[08:02] she’s going to be covering how to actually deploy to agent core. We also have evalentic frameworks as part of the workshop. If we have time, we will do it. But because we want to take it slow, we want to take it easy. We want to make sure everyone understands the basics before we get into the advanced concepts. But if we don’t have time, you can still use this link. This is still valid for two more days. So you can still use it. Go back home, run it, complete all of the modules, and ask us ask any of us questions if you have any and we’ll be there to support you. So uh first thing
[08:34] is uh go to this workshop link if uh we have so this is enabled for about 250 participants. If we have more and some of you run into problems we have a backup workshop link but for now uh log this website and it should take you to a link. Uh Ellie can also walk excuse me walk you through the steps if necessary. Um so this is going to take you to an account. Does uh everyone have the previous link? Do you want me to wait a couple of seconds? >> It’s on there. It’s on there. >> I think it’s also there on the next few
[09:05] slides. I think uh so what what are we going to be doing today? We’re going to go to this workshop studio account. Uh you don’t have to so you don’t have to create your own AWS account. Uh these accounts are already created for you and there is going to be like a Jupyter notebook format. Uh most of the code is already in there. We can customize it. You can run it. You can download it. You can run it in your own environments but for this uh session it’s all there for you. So you can directly use and run it
[09:36] from there. Uh this is free of charge. You will not be using any of your accounts. It’s not going to ask for any credit card. So just go walk with us and do it step by step. If you have any questions all of us are here to support you. Um so like I said first thing join this workshop link. So when you go to this link you are this link is going to uh give you a website. The first thing that you need to do is
[10:07] put your email email one time passport OTP. So then it’s going to send you a email with uh I don’t remember how many numbers is that yeah you need to enter your email and then you are going to receive the one time passport and you need to put that password inside the the window as similar to that >> and if any of you have questions please raise your hand and one of us will come find you we’ll work with you
[10:38] >> and in this workshop when you start to either uh you are going to be able to use anthropic models through the Amazon bedroom API and I think I’m not sure I’m think that you are going to be able to use the new open AI models too and of score all the Amazon models that we have that you can invoke through Amazon API and uh you are be able to use a Amazon better agent core for free it’s not so
[11:09] expensive okay I I know that and I know that people is having problems sometimes to use the new service because yeah it’s normal to have I don’t know uh it’s money but if you try Amazon B aent cord in your account you are going to see that it’s not so expensive and then you need to approve the next the next window is >> is everyone with us right now anyone struggling at any step so far you do you
[11:39] need help Sorry. Do you are you having trouble signing in? Um, so you’re you’ve opened that workshop link and then did you type in your email address and your password? >> Okay, I think Mike can help. >> You are okay. I need to see >> everyone else. Okay. Any other >> problems? Is anyone struggling with anything? We might be having a little
[12:09] trouble with wifi. Who would have thought that a conference would have trouble with wifi? A lot of people are getting on. Are you going to be stepping through some of the things on stage there? >> Um what >> you going to are you going to run through the workshop stages on on stage? So if people can’t do it, can they watch >> at the end of the session? Uh we are going to share with you all the slides. This is a Jupiter. This is a repository that you can clone too. you know this this uh this code everything that we are
[12:40] going to build here is not only available in the virtual studio. So because this virtual studio is going to be open for two days so probably it’s better that we start to show what is inside and you can do this >> uh for your you know for your business >> and you can do it and you know I can I then when we finish the session I going to put this workshop for three days. So, so you can be you can use all these for free for 3 days. >> Yeah. And may the Wi-Fi gods be with us
[13:11] as well today while we run it through with you. >> Oh yeah. >> Um so if it’s just network issues because of which some of you are not able to follow along, we will try to go step by step again hopefully with the Wi-Fi is working for us and um any other issues apart from network issues with signing up, signing in, anything at all. >> Yeah. >> Right. So before to start please take a picture to this. Yes. Because if you have problem with the first one you know it’s not a problem of internet. If you are having problem hey there is not
[13:42] enough account is because the first one is running for account. So you can use the second one. >> So we have to uh separate environments deployment. >> Yeah. >> So let’s get started. Okay. So, all of you should be seeing this right now, correct? >> No, that’s not
[14:12] >> this, right? All of you should be seeing this. This is going to be on the left is going to be your stepbystep work um your work through on what what we’re going to be building, how we’re going to be building it. the setup each of the modules. So this is for you to follow along if you’re ever stuck how to actually start running this. Right? So this gives you a full walkthrough. But if you want to get started with the code, click on this over here, the agent
[14:42] speedrun idea to code, right? Click on that. Scroll all the way down and you will see the code editor URL. Everyone with me? Click that URL. >> The people who is having internet. Yes, everyone who’s got internet click like click on this button over here. Scroll all the way to the bottom to the code editor URL and then open that and this should pop up module one for you. So this is module one and you can close all
[15:13] of this. The first thing you will have to do is select your kernel, right? And which kernel do I select? go to the same workshop studio here under setup when you get started and you go to your next steps it’s going to actually show you here right so select kernel python environments USR bin python 3.13 copy that and in your select kernel paste that over here and it should close
[15:44] it and pick it up for you okay so you You need to do this for every module that you’re running. Now, what are we building today? Is everyone with me? Is anyone not with me? Oh, a bunch of you because of Wi-Fi. Is there any other >> just Wi-Fi? >> What do we do? Do we Okay, we’re just >> Yes. Yeah. Thank you. So, if that’s the case, then we’re going to start walking through step by step. It’s fairly simple
[16:16] and you can definitely go back and try it. Okay. So I’m just going to go with it and feel free to ask us any questions. So what are we building today? Today we’re building a customer service agent and we’re building that using Strand’s agent which is an agent harness framework and how that works is it’s basically using an agent with the loop. So the user sends in their input and their context and then you have an LLM which you can provide right because uh this is works natively with Amazon.
[16:48] We have a bedrock hosted model but you can have so if you go to strands agents over here this is the strand agents and you can and you look at model providers you can use any of your favorite model providers you can use your llama and if you want to host it locally and this shows you how to do it all you have to do is call the model here define the model and then under agent you just have to specify model and your model name you can do this with open AAI this supports all of your different LLMs your favorite LLM times use what you will um hugging
[17:20] face all of your favorite things right so use your favorite uh model bring your own uh API key and then connect it to the model and then we we are ready to get started so we are building um a simple customer service agent and what how what makes the agent powerful is the agentic reasoning loop which means when you give it when the user asks a question and says hey I have this trouble, I have this problem. The agent
[17:51] receives that input. The agent gets invoked. The agent calls the LLM and the LLM then reads the question and calls a tool. So we want to define a set of tools because tools are the way by which we give an agent agency to execute a function because LLMs are mostly just going to be predicting the next token. We don’t want to really rely on the LLM’s base knowledge of what the answer is. You want to ground it to a source of
[18:22] truth, to a source of information. And this information can be stored in your database. This can be stored as a file. This can be stored in any different format. And that can be written inside of a tool. And that tool can be given access. The agent can be given access to that tool. And the agent decides when to use that tool. And the agent can have access to a bunch of different tools. And the agent will figure out, it will rely on the LLM, the LLM’s capability,
[18:52] the LLM’s reasoning capability to figure out what to which tool to use and call the tool, run the tools response and potentially again, you know, the agent loop can get completed and then it would send a response. Now, another amazing thing about using an agent harness is because you can support a bunch of different models, you can swap out whichever model you want without really having to change the system prompt. You can if you want to, but you don’t really have to change the system prompt or change the structure or the architecture of how everything works. This is it. And
[19:25] then you can try out with any model you want and then it still works. It’s still good to go. So you can even compare your models different models performances against the same uh boilerplate code. So it’s super powerful and then you get a response. Right. So how can we get started with this? Uh first thing is so uh in your module one we’ve got um we install the requirements.ext file. Then we define tools. Is this big enough for everyone to see? Do I need to zoom it in further? Okay, good. I’m
[19:56] seeing thumbs up. So what are we doing here? because we’re doing customer service bots. First thing is we need to have data. So we’ve create mock data of two customers and their account orders. So they’ve ordered something off of a website and then they want questions. They want to get refunds on whatever they’ve ordered. So how are they going about this and how can we build an agentic system that can offer solutions to these customers? So they have these orders. Uh it’s just like a dictionary. Okay, so these are the customers and
[20:26] these are the order statuses and we define tools. Tools can be written it can be uh it can be a functional code but it can also be uh like an NLP type of a tool that you can have generated. The way to define a tool is by using the at tool decorator function and you write a code. So here we’ve got a simple tool that’s doing a lookup on customers. That’s just doing a get customer ID. Then we’ve got another tool that’s just doing get order history. The third tool
[20:57] we’ve got is process refund. Right? So in each of these cases, the tools can look very very different, but they’re all the same format, all the same pattern. They all just have the add tool decorator. So let let’s run this. And after that, what we do, and this is our initial code for creating tools. Now what we do to create an agent, we just need two basic things. One is your system prompt. The second is your LLM,
[21:28] your model. In this case, because we’re using native uh bedrock models, hosted models, we don’t really need to specify the model. We’re just using the default model. But like I showed you in the on the strands website, you can establish whichever model you want and you can add your model here. The third thing you want to add apart from this is your tools. So you will call the agent method. Write the tool three tools that we’ve just defined and then create the system prompt which says you are a
[21:58] customer service agent. Um and these are your guidelines. Always verify customer using look up customer before taking action. Use tool data to answer questions. Don’t ask the customer for info you already have. So in the system prompt you tell the agent like you tell the LLM how to use the tools that it’s got access to and what to do with it. So that’s how your LLM and your agent understands what needs to be done with it. So here now when we run this agent
[22:30] we just say hi I’m customer so and so can you check my recent orders and so now it’s saying sure let me pull up um your account and the order history. So it’s invoking tool one. It’s doing the look up on customer. Then it’s calling tool two which is get order history and it’s saying ah okay this is a summary of your recent orders. And then it’s saying hey is there anything else I can help you with? Now this is awesome but how can we figure out what’s actually happening under the hood? Because a lot
[23:00] of times one of the problems we have is my agent is doing things and I have no insight into what it’s doing. Where is my control? How do I get that? Right? So let’s inspect that agent loop. So what we So this is how it works, right? And as we saw in the previous diagram, the user sends in a message, goes to the LLM, the LLM does the tool call, we get a tool result, and finally we get a response. Now we can look at the agent messages agent message. And so this is
[23:30] just code to see what the messages look like. And so this shows us the handoff. So this says the total number of messages for this is what the user is saying. This is what the assistant does. Then this is the tool call one tool call two. Then there’s nothing else that the user has done. And so the assistant says okay here is the response. So this these are the metrics. These are number of tokens that it used. We can use more metrics. You can add more metrics. Do what you will. Additionally uh we just want to do something simple here, right? Because it’s simple walk through. But
[24:01] what we can do is we can also have multi-turn conversations. This is just a single conversation. You can also run your multi-turn conversations where you have an extended chat with your agent. So for that you can also try these right. These are other samples that we’ve given. You’re free to write your own if your internet is working. I hope it is. Is it? Um but also what you can do is we’ve created chat.py under the same module and we’ve got chat.py Pi file for every single one of
[24:32] these modules. So when I click chat.py, this is the exact same underneath underlying code except we’ve enabled it for multi-turn conversation. So you do the same thing enable um you just have to so when you go here what you can do is you can open your terminal and you just have to copy these two lines because we’re already in this specific folder and then you pip install your requirements over here and then you open
[25:04] a thing and then you can chat with it directly if you want to. So then you can say, “Hey, blah, blah, blah.” So you can just type, right? Um, and you can have multi-turn conversations with it. It’s just going to reply and see there we go. So you can continue to have multi-turn conversations with it, the exact same co under underlying code, uh, exact same tools, and it’s just able to talk to you. 60 lines of code, less than 60 lines of code. Uh, so that’s basic agent. Are we good?
[25:35] Okay, cool. Awesome. Second part, how do we make this agent better? What else can we do? This is this is basic stuff, right? Anyone’s who who’s been looking at blogs or just checking online would probably know how to do this. How can we make it better? Let me introduce you to what we call hooks. Now, hooks are amazing because let me first open that. Let me first open that code there. Okay, I’m going to close this. Now hooks are
[26:06] a way by which you can enforce certain programmatic uh commands and functions to take place. So before so what you can do is in this entire process where your from the time your agent is just getting invoked it’s doing its own tool calls and it’s getting responses and sending it out. what you we want to be able to control it, right? Right from the time that the agent is being invoked to the like before the tool is being called or maybe
[26:38] once the tool is being called and then it gets a response. We want to be able to have a lot of control over it. We want to potentially be able to validate who the who’s using it like who which uh who are the customers that are probably talking to this or what type of questions are they answering? Is it even supposed to be be entertaining these types of questions? Do we want to have rate limits on the type of tools that are being called and the number of times these tools are being called? How can we do that? So when you have a hook, you can you can introduce your code at this
[27:09] junction where you can have an assert function or a different type of function that allows it to do to ensure that certain checks go through before it proceeds to your final output. So you can do it before invocation, you can do it after the LLM call, before the tool call and then you can decide whether you want to approve of it or cancel it. And then you can even do it after tool execution, before it sends the response. So you can do it at all of these spaces, but you can also do it at more
[27:40] locations. And um this is just an example. If we go to strands agents, this will show you all the different ways you can enforce hooks. Um so this is this where I am at? No, I keep I’m going to close all of these. Um, okay. So, uh, in hooks, what are we doing here? We’ve got the same data that we’re calling. Let me run this first. Okay. Go to the notebook. >> This is not the notebook. >> No. >> Oh, this is a customer service tools.
[28:10] Okay. Um, yeah. Yeah, I’m on the wrong one. Okay. I’m on the notebook again. We have to install requirements and choose our environment. So how does this work? Now we want to import strands.hooks and we want to import hook provider hook registry and where we want to call these hooks. So in our case we want to do it before
[28:40] invocation and also before tool call. And I’ll tell you what we’re doing. We’re trying to create a rate limiter hook which ensures that for one user request the number of tools that are being invoked is not more than three in case you have um an LLM that’s just going crazy and that’s continuously invoking your tools that’s going to cost you a lot of tokens and you know it’s not working right so you want to create a hard stop rate limiter and say hey even if it’s not working it’s fine stop
[29:10] it at three right so now that’s what we’re doing how can we create that rate limiter over here. So first what we do is we define the rate limiter hook and we want to say okay these are the maximum number of calls we’re creating a default number and then we have to add it to the registry. So over here we add it and say okay be before invocation event and then we want another call back which is before tool call event and a call back means that’s when it would get called that’s because you’re defining it
[29:41] over here. So then we have this counter which that which at before every response like every new time the user is asking sending in a request this gets reset to zero because you don’t want it to continue running that u rate limiter and we define a second one called check second function called check that checks the number that’s basically like a counter it counts the number of times your tools are being invoked so that’s what this does and then This looks at
[30:12] the max calls and then it just calculates that. So we define our rate limiter over here and this is the main function that we’ve been looking at. One extra line that we added is the hooks and we say rate limiter hook max calls equals three. And if we run it, it’s calling these two and it’s saying okay tool call one tool call two. Here’s a summary of your events. This is what’s happened. But let’s actually test it. Let’s try and break it and see if the
[30:43] rate limit is actually working. Right? So here I’m doing max calls equals true. You want to lower the limit to the trigger. So over here it’s calling it so many times, right? And so it’s actually blocked it. So here it’s saying block lookup because it’s exceeded the number of times. So when your agent starts to go haywire and we all worry about oh my god is my agent going to take over everything, right? It won’t because we have something called hooks. Is everyone with me? Are we good? Is
[31:14] anyone able to run it with me? Am I going too fast or are we just watching us? That works. Oh, okay. Good. We have at least a few people. >> I I would like to add something to the hooks. >> Sometimes, you know, hook is better because when you’re using a LLM with some tools, the LLM are probabilistic. >> Yeah. You know they when you put a prom inside your agentic application the prom is like a suggestion you know it’s only about the probability to give you an answer. So when you use a hook you can
[31:45] be more deterministic. So you can put code inside your aent loop so you can put code a python code before or after the invocation. So you can stop uh I don’t know in this example you stop a a lot of more than three tools invocation but for example if you want to restrict a I don’t know some credit cards number something like that you can put a hook a code capable to understand some things
[32:15] so yeah hey you can receive this information so I going to block this with this deterministic uh function so you don’t receive that so the model the model never is going to receive that information. So you block the call so you don’t waste token. So you don’t have to invoke the model again. You don’t you don’t waste tokens because you are stopping that. You send a hook. And if you don’t want to send some type of answer to your customer service, you can stop that answer with
[32:46] after call hook as well. >> Exactly. Thank you. Okay. So you can try it out yourself. And again, if you want to do multi-turn conversations, go to chat.py in the second module with hooks enabled. You can still continue to chat with it. And you can play around, add different hooks at different places, see what works. You can try and block certain customers or block certain types of questions. Thing guard rails, right? So hooks are amazing
[33:17] and we want to have hooks as we’re writing good building good agentic systems. Now, let’s add one more layer of coolness to this project, right? Let’s add skills. Let’s add skills and let’s find a way to steer your agent and your LLM and get them to respond in a fashion that we want it to respond in. And so, steering is I love steering. Steering is awesome. Um, so let’s get to steering. Do I have any questions? Everyone good
[33:47] with the idea of hooks? >> Yes. So the so if we sorry >> oh okay okay okay um so the question that was Oh you have a mic now do you want to >> yes
[34:18] >> okay ask oh this is wrong uh I saw that in the example with the hook, it kept running the agent, but it just blocked the tool call. How do we stop the agent so that it it doesn’t go into infinite loop and keep looping? And >> so, as we’re defining our hooks, we can define the hook in such a way to even end the agent’s turn if we wanted to. For demo purposes, we wanted to show you how it’s working so that we can see it doing the rate limiting and we can see that it’s not running multiple times, right, the calls. So what it’s doing is
[34:49] it’s trying to invoke the tool in this case because we said before tool invocation it just kept attempting to do it and kept stopping and but the LLM still continued to run the loop until the end. But if we want we can create it in such a way that we say okay if I see this just stop the turn and end it at that point. So the we can definitely customize just because we wanted to show you the end to end working. We made it this way. Um thank you for that question. Um, okay. So, skills and steering. Now, now this is a chatbot
[35:22] that’s supposed to be answering customer service questions, but they could be asking a bunch of different questions that the agent may just not have access or the knowledge to answer. So, how do we give it that knowledge? How do we tell it how to answer it? We create what’s called a skills folder, a skills file which contains potentially all of your information on your your your ground truth, right? Your uh single source of truth maybe on what it what actually what steps it needs to take.
[35:54] And we can add this as a markdown file. And this is a way by which so here what it do what it would do is when we add agent skills it would first go look up the skills folder and read all of the skills see which one actually makes sense and then it would use those skills. Um let me get to steering in just a bit but skills is a way by which we can give our let me go to the third one third module.
[36:26] So um I’m I’m just gonna run this first. Perfect. So first thing is when we create skills now we’ve got three types of skills that we’ve created. One is how do you process refund? How do you track orders? And what if people ask some types of account related questions? My password is not working or something a bunch of frequently asked questions. How can we get it to work? Right? So this one is on how to handle account issues.
[36:58] So here we are creating these different skills plugins and then we can directly call it. Um so when I open the skills folder here we can look at sample skills. So this is just a markdown file on skills for account troubleshooting which is giving it context additional context because in your system prompt you don’t want to overflow it with all of the amount of information you have because those are also considered input tokens and those can get wasted
[37:29] unnecessarily needlessly. So when a certain type of question is being asked, we can give it context that is relevant to that specific type of question then it has access to all the information that it needs so that it can do justice and answer the question correctly. So in this case this specific skill talks about how can we do account troubleshooting? What does it require to reset a password? What do you do when the account is locked? And the same thing for like order tracking, right? What do we do? What are the steps that
[37:59] we need to follow? So these are instructions that we give to the agent beforehand and we write this based on what we want the agent to do. And so we create these different skills um files markdown files and when we run it apart from the system prompt what we give it access to is the plug-in. So we’ve now we’re now adding yet another uh parameter here which is called plug-in and this has access to all of the skills
[38:30] plugins and the skills plugin points to the skills folder here. So now it’s going to invoke whichever skills it needs for that specific type of question that’s being asked. And when this runs and we someone says, “I’d like a refund for my wireless headphones,” it’s actually calling the skills as a tool. And then it’s saying, “Okay, I’ve got your account pulled up. Here’s what I found and here’s how it’s doing it.” So, it’s becoming more and more deterministic. It’s got a natural order
[39:03] that it flows and you can invoke the context only at the time that it’s required. And it’s not you’re not lo overflowing your system prompt with a lot of tokens every single time. Now this is skills but how many this is something that I’ve generally faced right with steering. How many times have we struggled as we’re talking to our agents to give us an answer to a question that we ask in a specific format and it always messes up. It seems to get all of the difficult questions
[39:34] right. If I tell it this is so if I ask it okay what is my what is the refund I’m supposed to get it would give us a refund and say okay this is what it is but they also generally tend to talk too much and generate a lot of tokens and they you know just free flowing. So how do we give it how do we get it to respond in the format that we want? How do how can we ensure that it’s giving us like a structured output if that’s what we need or like hey stop using m dashes every single time do we want to keep telling it we want to be able to catch
[40:05] that deterministic the deterministically and ensure that it’s doing it in a deterministic way. So for that we do something called steering which helps the agent which helps the agent steer itself in the direction that we want it to by giving it a buddy agent. So it works, think of it as like pair partnering, like pair programming or pair partnering where as it’s generating an output, the buddy agent looks at what’s being generated and then that
[40:37] buddy agent can then tell it, hey, no, this is not what you’re supposed to do. This is the format that you wanted to do in. So your buddy agent is sort of checking and correcting and course correcting and then the response you want is what is the response that you’re actually happy with. When you’re deploying your code into production there is no room for egger in like format structure. You want it a certain way and steering can help you do that. Now I’m going to do I’m going to do this quickly because I want Ellie to talk about deployment which is how you can
[41:08] actually make sure your agent is helpful and useful. So um quick um quick idea of steering handlers. Now stirring handlers works the same way as hooks. You can um call it you can invoke it at different points. You can invoke it uh before LLM while LM is being invocated before tool call after tool call. very similar to hooks except at that hook point now you’re also adding another agent over
[41:38] there that can do a quick check and that can buddy like sort of buddy work with this and then give it the output once so think of it as another guard rail if you will right so then you can do a tool call and then you can do this and this is a guide that can say oh you know what first look up this before you give me a refund or then you can say revise the tone of this message if it’s sending out a message and then after that it gets sent. So now you have more control over what your agent is generating. And if we
[42:10] go back to steering. Okay. So again what do we want? We want to uh import the steerings uh uh we want to import steerings over here. And from here again the steering handler. And these are all the different places that we’re doing it at. And you can do it in different ways. uh check the the strands agent documentation. It’s the details are going to be in there but also in the workshop mentioned over here you will see all of the details. Now we create a
[42:40] deterministic handler. We tell it we give it rules and we tell it what it’s supposed to do. And this can also be a hardcoded function. This can also be another agent that has an hardcoded function in it that works. We can get it to do you can do like um type enforcement if you want the output to be only of a specific type. You can do different types of enforcements over here. Right? So then you create a a steering agent and then this is all for steering. Right? So now you create a
[43:12] steering agent and you create the guard rail. So here the refund workflow handler has been defined and finally you create the guardrail. So here you’re saying okay don’t overpromise guarantee specific timelines don’t blame the customer acknowledge the customer’s frustration and so this is the tone guardrail handler that we’re creating. So this is the second type of steering agent that we’ve created. Now what we do is in our final code apart from agent skills we just call
[43:44] these two different handlers that we’ve established and these handlers can be established at different points. So we can say steer after model if we wanted to do and we can tell it what to do in this case. But over here we can also tell it we can also do steering data.get we can create a ledger for it and we can choose to enable them at whichever part of the flow the agentic flow we wanted to do. And so at the end all we need to do is give it access to these two
[44:17] sterving handlers. it’s going to be enabled and then when you run it, it’s not just calling the lookup customer and get order history, but it’s also we see that it’s evaluating the agent response. So before you send out the final response to your end user, you can ensure and you can be you can do it with full confidence. you can say with full confidence that your model that
[44:48] your agent is most likely going to be responding in the way that you want to because we’re establishing all of those control features. Um you can try it yourself and then I’m going to quickly give it over to Ellie because she’s going to be talking >> because only have 12 minutes to put this agent in production but I want to I would like to add something to the steering part. you know uh there is a a open source library that is calling agent control that you can add to a stringent is there in the documentation
[45:19] with agent control you can create rules to the steering for example if I have a demo where I this is a travel engine so you can use hooks to block numbers for example it’s one one to booking a room for more than five people you can use a hook a hook to block the room for more than five people. But if you want to steer the agent to block for more for five people, you can create rules. So every time that the agent is going is
[45:50] receiving more than five bookings, he’s going to say if I receive six, I can steer the booking for two rooms. So you can create rules for that using the agent control library. And the rules you can host this rule in a database. So you can create a database for all your rules for steering the agents. So every time that you invoke this agentic application, you can go to the database and see the rules. So what is the good
[46:21] thing for this? So you only have to change the rules in the database. You don’t have to change the code for the agent. So the agent only have to knows they have to know the endpoint for your database. So every time that you have a new rule, you can edit the database and that’s it. And let’s put this agent in production. So here we have the session manager, but I don’t going to show you that session manager is when you want to save the memory using a framework. So
[46:53] but you can do that using n get called memory without the framework and everything is in the in the code and here in the five for deployment we are not going to use a jupy notebook because you can do that for jupy notebook but we are going to use the CLI the terminal. So here in this folder uh lose the folder we are having the same engine. So we have the customer service tools and we having the uh the skills we
[47:23] have everything here. So to put this engine in production you have to go to the workship studio here. This is the thing what we are going to do. We are going to use the AWS CLI through the terminal. We are going to use some one command or two commands in the CLI. We are going to take this agent then we are going to send this agent this agent code to a runtime on AWS and agent core is going to deploy this code inside a container but we are
[47:54] not going to handle that because agent core is going to do that for us and and we are going to have memory too without doing anything. So let’s see let’s follow the steps. So this is the ah something important when you build a gentic application and you want to put that code inside a core runtime the only different that you have to do for your engine is put this deconator the a entry point. So the MPP entry point is is the
[48:24] only different between your engine running in your notebook or your computer uh between production because the MTP entry point is the thing that the runtime when runtime see can see the MTP entry point ah everything behind the MTP entry point is the agent. So every time that you invoke this runtime, this container is going to run that code behind the empty entry point. Okay. So let’s style this.
[48:58] So I go to the here. Sorry, let me open this. This is the library that I need to execute all my CLI codes and mean I hope I have good internet is running. Yeah. So in this environment you are going to able to deploy the agent and everything. But if you are running this locally you
[49:30] are going to be able to test the agent before to putting it in in AWS. And something that you have to do to have the the built-in observability, you need to do something in the console. So let let me show you this. So to go to the console, you open this part AWS console. So it’s going to open the console that is running in this session in this uh in this uh account that you have. So you need to go to a core
[50:01] run not here aen core better aen core so you can see all the service that a core have harness because you can build a hardness with a few lines of code too runtime gateway memory and observability is just right here but you need to select something I don’t remember what is the name but I’m going to show you let me see here here enable no that’s not here configure
[50:31] so you need to go to configure and here you need to enable transaction search so this thing allows you to have the built-in observability inside the runtime if you don’t have that you are not going to see the agentic observability inside your agent because cloudatch is not going to receive the information and another thing that you have to do let Save this is install put inside the requirement the observability
[51:04] library that I have the observability requirements. So for that sorry oh it’s done. So we have this transm requirements because I’m going to use AM core and you need this one the AWS oper telemetry district. So if you are using another framework for example line chain or ci there is a unique library for that uh for that framework but you need to do some modification inside your agentic application for a strand you don’t need
[51:35] to do anything because a strand is built in for AWS so everything is built but the observability works for other frameworks but you need to do some modification everything is in documentation so you can see it so we have the library let’s go to So here I’m already there. So A and C. Great. Oh, so I going to create. No, it’s okay. I I
[52:06] didn’t save it. >> So my name I going to put Ellie because I am Ellie. And for here I don’t going to create a harness. I going to create a agent. But I have my code. You know, if you if you choose agent, it’s going to be a simple agent for you. But I have the code, so I can skip it. And it’s going to create environment everything that I need to put this aent that I already have inside this container. So it’s going to create a folder for me. Here is my folder, the
[52:39] aen core, everything. So you all these steps are here in the workshop. Oh my god. Five minutes. But I going to do it in five minutes. I’m going to put this aent in production. >> That’s all right. >> Yeah. So, a core add to add my aent and what is here. So, well, it’s taking a moment. When I put a is going to add create the the container that I need, but I already have this agent here in my computer
[53:10] because I wanted to show you something. the same engine that Sandy just showed you. This customer engine I have I have the repo here in my computer. So, let me put this bigger. This is the same again the in the five. Yeah, you can use a core dev agent core dev to test the a locally. So you can do this you can’t do this in the virtual studio because virtual studio is a virtual machine that
[53:43] only allows you to run code in this VS code but if you are running this locally in your computer you can have this environment to test the engine. So this is the same agent and you know I have some sessions here too. You can see the amounts of tokens. If you want to explore what’s happening inside your engine and you can do that locally but because I’m using Amazon Metro as a model provider I’m using my AWS credential and to use Amazon a core you
[54:16] need AWS credential if you are running this locally but in the Amazon brow and workshop you don’t need that. So yeah, it’s working. Yeah, it’s the same exactly the same area and I didn’t do anything. So let’s come back to the >> Yeah, I have my everything. >> Yeah. >> So I I I did this. I don’t remember if I did this. >> Nope. So CD >> early. So I going to add my uh code inside this
[54:49] aented application. Let me see inside this container. So agent core what I want I want a agent I going to uh click bring my own code that’s it that’s it and I you can use direct code deploy or you can use container I going to use that and you can bring your own API key to deploy this a using entropy open IO whatever you want but I’m going to use Amazon better I don’t going to do anything here
[55:21] Enter. Enter. That’s it. Now I going to move my code. And to move my code, I have here copy and paste. And okay, now what else? Ah, I need to create this. So let’s see. Copy and paste. One minute. Wait. And I don’t going to do that. So core deploy and one minute to deploy one minute to
[55:55] put this agency in production inside AWS. So it’s running is going to validate it’s going to check my credentials. So if you are familiar with AWS when you build everything inside AWS you need to create the am you need to create policy permissions you need to allows the service to connect with other service you need to do a lot of thing inside core is handle everything for me so you I don’t need to create the policy I don’t need to create permissions I don’t need to create every anything so it’s doing everything for me and you can
[56:27] you can see that ah and because I created that locally it’s creating a cloud formation is a infrastructure as a code using CDK. So you can explore the CDK code. If you are not familiar with CDK, CDK is cloud developer kit. So you can create infrastructure as a code with a l a program lens one that you know for example Python, TypeScript, whatever. So it’s doing that for me. It’s creating it’s creating everything. It’s creating the deployment and everything. And you
[56:57] can do that you can see that in the console. So let’s go to Amazon bedro runtime. Yeah. What? I can’t see anything up. So it’s it’s creating the let me show the cloud formation. Here I going to see my stack. Ah no because it’s a virtual studio account. I’m sorry. You can see that here. But when it start to put this inside the runtime I will see that here.
[57:28] >> There we go. So it’s here and you can test the is is ready. Okay, I can test the end right away. So I can invote this engine here and you know this is super uh terminal everything inside the repo. You can find how to invoke this a using bo tree. So you the only thing that you need is the air and for this agent is working. Okay, I think it’s working. I hope so.
[57:59] >> It is. It’s invoking the agent. >> Yeah. So here you can find how to invoke this agent using the uh SDK. Is there is give me the answer. You can >> it it actually worked. I think is there anything else I can? >> Yeah. So you can invoke this agent using the SD explore. how to involve this engine using the SDK and to see the observability. You can go to the runtime. In here you have the observability
[58:30] dashboard and you can see the session the trace how many runtime that you running how many session do you have each session is a runtime a different container it take a moment you take about one or two minutes to see everything there I’m okay what yeah yeah I’m done that’s it please take a picture for this and share it for the other Friends,
[59:00] here you can find all the information. Everything is here. The the deck, the work studio, some credits if you are lucky because our few about 20 credits for Eds >> and the Feda please. Firestar, we are amazing the internet. Nobody’s not at all [laughter] and all social media and if you have an answer we are on linking, Twitter, Instagram. Please in
[59:31] the QR code is everything that you need to learn more about strands and a core. >> Thank you. >> [music]