Pular para o conteúdo

Harnesses de agentes com memória para combate à lavagem de dinheiro — Nacho Martinez, Oracle

Ver no idioma original →

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: Memory-Aware Agent Harnesses for Anti-Money Laundering — Nacho Martinez, Oracle · Canal: AI Engineer · 51:19 · Assistir no YouTube

Tópicos: Agentes de IA, Cibersegurança e segurança de software, Engenharia de prompts e contexto, RAG, busca e recuperação de informação

Nacho Martinez apresenta os componentes de um agent harness e explica por que a camada de dados — incluindo memória, ferramentas, skills e gerenciamento de contexto — é fundamental para adaptar agentes a tarefas específicas. Usando como exemplo um banco que precisa identificar transações suspeitas, ele descreve como combinar memória de curto e longo prazo, busca vetorial, compactação de contexto e um agent loop configurável. Também compara arquivos e bancos de dados e aborda a recuperação híbrida e o uso de MCP para disponibilizar consultas SQL confiáveis. A sessão termina com a demonstração de um workshop prático de análise de atividades suspeitas.

  • O agent harness reúne os componentes que controlam o uso de ferramentas, a memória e a percepção do agente, permitindo melhorar o desempenho sem alterar o modelo.
  • A camada de dados é uma área importante de personalização, especialmente quando o modelo é fornecido por terceiros.
  • O contexto é limitado e seu aumento pode prejudicar o desempenho; sumarização e compactação ajudam a mantê-lo relevante.
  • A memória pode ser organizada em categorias de curto e longo prazo, incluindo memória episódica, procedural e semântica.
  • A busca vetorial pode selecionar dinamicamente as skills e ferramentas relevantes, evitando carregar todas no contexto.
  • Arquivos e bancos de dados têm usos distintos; bancos de dados oferecem mecanismos de consistência úteis quando há gravações simultâneas.
  • Combinar busca semântica e busca por palavras-chave pode melhorar a recuperação de informações.
  • MCP pode disponibilizar consultas SQL previamente preparadas e validadas, reduzindo erros de consultas geradas dinamicamente.
  • O workshop demonstra um agente que analisa transações suspeitas e encaminha resultados para revisão humana, em vez de tomar medidas drásticas automaticamente.
Início Capítulo Resumo
00:01 Abertura e acesso ao workshop Nacho apresenta a sessão e explica como acessar o repositório e o ambiente no GitHub Codespaces.
02:12 Objetivos da sessão e cenário de AML O palestrante introduz o agent stack e propõe um caso de uso bancário para identificar transações suspeitas.
05:52 Agent stack e tipos de aplicações de IA A apresentação situa a camada de dados e compara chatbots, RAG, workflows com LLM e agentes.
09:01 O que é um agente e o papel do harness Nacho define um agente como um sistema com raciocínio, memória, ferramentas e percepção, e destaca o controle oferecido pelo harness.
13:10 Arquivos, bancos de dados e memória O palestrante discute os limites de gravações concorrentes em arquivos e apresenta categorias de memória para agentes.
17:50 Limites de contexto e agent loop A sessão aborda a perda de desempenho com contextos grandes, a sumarização e compactação, e a montagem dinâmica do contexto.
20:56 Seleção de ferramentas, skills e aprendizado contínuo Nacho explica a recuperação de ferramentas e skills por embeddings, a destilação de skills e as categorias de memória usadas no aprendizado contínuo.
26:10 Hierarquia de instruções e demonstração do sistema O palestrante apresenta a hierarquia de instruções e mostra a interface do agente de monitoramento de transações.
30:22 Workshop prático e perguntas sobre memória A demonstração mostra dados fictícios, decisões do agente e a organização da memória, enquanto Nacho responde a perguntas.
35:02 Skills, custo e montagem do contexto A conversa trata de hubs de skills e ferramentas, cache semântico e estratégias para limitar o conteúdo carregado no contexto.
40:55 Memória de longo prazo e consultas SQL Nacho sugere começar com uma arquitetura simples de memória e explica como MCP pode fornecer consultas SQL validadas.
44:30 Busca híbrida e harnesses personalizados A sessão compara busca por palavras-chave e semântica e recomenda criar harnesses menores, ajustados a problemas específicos.
50:14 Encerramento O palestrante convida os participantes a continuar o workshop e oferece acesso ao ambiente após a sessão.

Não precisamos nos concentrar tanto nos modelos de ponta; podemos usá-los, mas vamos trabalhar no harness. — 04:18

O mesmo modelo de IA de ponta pode ficar melhor ou pior com uma configuração diferente. — 11:07

Quanto menor o context window, melhor o modelo resolverá um problema. — 18:50

Podemos criar harnesses personalizados para problemas específicos. — 48:12

  • agent harness (conceito): Estrutura de componentes e mecanismos que controla como um agente usa ferramentas, memória e contexto.
  • Agent Loop (conceito): Ciclo que reúne contexto, aciona o modelo e coordena as ações do agente.
  • context engineering (conceito): Práticas para selecionar, organizar, resumir e compactar as informações fornecidas ao modelo.
  • memória episódica (conceito): Memória de longo prazo que pode registrar conversas anteriores, eventos, logs de ferramentas e seus resumos.
  • memória procedural (conceito): Memória que reúne procedimentos, como skills e sequências de execução.
  • memória semântica (conceito): Memória de informações persistentes, como preferências e dados de contexto sobre o usuário.
  • busca híbrida (conceito): Combinação de busca semântica baseada em embeddings com busca por palavras-chave para recuperar informações.
  • MCP (ferramenta): Protocolo mencionado como meio de disponibilizar recursos externos, incluindo consultas SQL preparadas, a agentes.
  • Oracle (empresa): Empresa associada ao palestrante e à infraestrutura usada na demonstração do workshop.
  • Nacho Martinez (pessoa): AI developer advocate e cientista de dados que apresenta a sessão sobre agent harnesses.
  • workshopwaitingroom.com (ferramenta): Site usado para conceder acesso ao repositório e ao ambiente do workshop.

00:01 [música] Oi. Oi, pessoal. Obrigado por virem a esta sessão. Esta sessão será sobre agent harnesses. Não temos muito tempo. É uma sessão de apenas uma hora. Então, espero que tenhamos tempo para falar de muitas coisas que interessam a vocês, e a sessão basicamente vai ser…

00:32 …eu falando por uns 10 ou 15 minutos sobre os tópicos que vamos abordar e resolver no workshop. As instruções do workshop estão disponíveis por QR code ou no site. Se não quiserem me ouvir, acharem que sou chato ou algo assim, podem começar o workshop por conta própria enquanto eu falo. Mas, basicamente, é isto que acontece no site. Vocês só precisam se cadastrar com o nome de usuário do GitHub e receberão automaticamente um convite para o repo.

01:03 O workshop está hospedado no Codespaces. Então, é só criar um codespace a partir dali, e vocês receberão automaticamente um convite para acessar o próprio workshop. Depois, basta criar um codespace por lá, abrindo o GitHub Codespaces, e estarão prontos para começar o workshop. Vou mostrar o QR code mais uma vez para quem quiser acessá-lo e vou começar.

01:39 Certo, perfeito. Se tiverem alguma pergunta, meu colega Richmond também está ali. Ele vai passar pelas mesas de todo mundo. Se tiverem alguma pergunta, é só levantar a mão, e ele também pode ajudar. Isso, aí está. E também tem o site: vocês podem acessar workshopwaitingroom.com. Paguei caro demais por esse domínio. Então, usem-no. Certo. Quem sou eu? Meu nome é Nacho…

02:12 Nacho Martinez. Sou defensor de desenvolvedores de IA e cientista de dados de coração. Se quiserem saber algo sobre mim, é só me procurar no YouTube. Tenho podcasts, workshops, de tudo. Não vou falar muito sobre mim. Só uma coisa: lançamos recentemente um curso com Andrew Ang e DeepLearning.AI sobre como criar agentes de IA adaptativos, que é um dos subcomponentes de que vamos falar hoje. E, se vocês…

02:43 …têm particular interesse nas coisas que podem fazer em um modelo para melhorá-lo e adaptá-lo ao longo do tempo, para que ele aprenda com o tempo, deem uma olhada nesse curso. É um curso gratuito de uma hora que vocês podem acessar no Google. Então, por onde vamos passar hoje? Como eu disse, não temos muito tempo. Vou tentar ser rápido. Mas estes são os assuntos de que vamos falar. Primeiro: o que é a pilha de um agent? Quais são os componentes de uma pilha de agent? Quais são os diferentes formatos que uma aplicação de IA…

03:15 …pode assumir? O que é um agente de IA? E o que é o agent harness? Qual é a principal motivação para criar ou trabalhar com agent harnesses, em vez de trabalhar diretamente com agentes de IA ou com um modelo LLM? E também vamos falar de todos os subcomponentes de um agent harness, como, por exemplo, memória, engenharia de contexto, engenharia de memória e todas essas coisas. Como me disseram que haverá muitas pessoas do setor financeiro, como muitas pessoas que trabalham em Wall Street, adaptei este…

03:47 …workshop para se passar em um banco. A ideia é que a premissa principal do workshop seja a seguinte: hoje em dia, ouvimos muito que a OpenAI está lançando 10.000 agentes ou 5.000 agentes para resolver este problema, 10.000 agentes para resolver este problema matemático que levou 100 ou 200 anos para ser resolvido. O problema é que esses agentes são autônomos. Não há nenhum humano no ciclo até que eles cheguem à conclusão ou às respostas, certo? Então, os…

04:18 …próprios agentes não têm capacidade para fazer isso. Por quê? Porque, quero dizer, a context window é limitada. Os componentes de memória não são algo que um modelo de linguagem grande tenha inerentemente. Então, precisamos implementar todas essas coisas nós mesmos para que esses agentes consigam resolver todos esses problemas de forma autônoma por 10 ou 100 horas, certo? A ideia é que muitas pessoas estão se concentrando em: “Certo, temos esses modelos de fronteira”. Mas a minha ideia é que não precisamos nos concentrar tanto nos modelos de fronteira; podemos usá-los…

04:50 …mas vamos trabalhar no harness, que é a parte interessante e que vocês podem personalizar cada vez mais. Nesta aplicação, a ideia é que se trata de um banco de médio porte que, às vezes, tem muitas transações suspeitas, classificadas em cinco tipos diferentes. Por exemplo, se entrar no banco uma transação de um milhão de dólares e, de repente, durante três dias, forem feitos saques de 50 mil dólares em um…

05:21 …caixa eletrônico. Isso é suspeito, certo? Porque por que alguém depositaria um milhão de dólares e depois o distribuiria dessa forma? A ideia é que temos esse banco de médio porte com muitas transações, e elas precisam ser avaliadas de forma mais ou menos autônoma ou, pelo menos, sinalizadas, para que uma pessoa que trabalha no banco passe menos tempo examinando essas coisas. Então…

05:52 Vamos falar um pouco da teoria. O que é a pilha de um agent? Quando falamos de um agente de IA, normalmente estamos falando da camada da aplicação, certo? Daquilo com que interagimos: uma interface, um chatbot, um aplicativo móvel etc. Depois, temos o próprio modelo, que é o núcleo de raciocínio; não temos voz nas decisões tomadas. E também temos a infraestrutura que dá suporte a tudo isso e, depois, a computação.

06:23 Mas hoje vamos nos concentrar na parte dos dados. Os dados são muito importantes porque tudo o que podemos manipular e com que podemos trabalhar está nessa parte. Temos menos controle sobre as outras partes, certo? Especialmente se estivermos usando um modelo de terceiros que não é nosso. Então, hoje vamos nos concentrar na camada de dados, certo? Primeiro, temos o loop do agent, que é, sem dúvida, uma das partes mais importantes de um agente de IA…

06:54 …O loop do agent é responsável, basicamente, por conduzir todo o processo. E ele também pode ser personalizado. Dentro dos dados, você também tem um gateway e o MCP, para conectar a fontes de dados externas de terceiros. Também tem a camada de memória, sobre a qual falaremos mais tarde, e algumas partes de engenharia de contexto que permitem resumir, compactar e reduzir automaticamente a context window de trabalho de um modelo…

07:27 …e, por fim, algumas ferramentas e skills com as quais podemos fazer coisas interessantes e inteligentes, para essencialmente manter a context window limitada. Essa é uma das principais ideias do workshop. Normalmente, as aplicações com que interagimos são uma combinação destes quatro tipos, certo? Chatbots com LLM, que são muito simples. Muitas pessoas simplesmente criam uma aplicação de IA, criam um chatbot para poder conversar com ele. Também há aplicações RAG, que são essencialmente uma espécie de busca vetorial glorificada…

08:00 …E também há workflows conduzidos por LLM e agentes de IA. A propósito, levantem a mão: quem não usa agentes de IA, como o Claude Code etc.? Certo, então Claude Code etc.; todos esses sistemas são uma combinação dos tipos três e quatro, ou seja, uma combinação de workflows conduzidos por LLM, que oferecem automação, e agentes de IA, que oferecem autonomia. É uma combinação…

08:30 …de automação e autonomia, e esses sistemas são chamados de sistemas agênticos. Os melhores sistemas, como Claude Code, Codex, Spy, OpenClaw, Hermes Agent etc., são todos uma combinação desses dois tipos. E algo importante é que a maioria dos engenheiros com quem converso usa esses sistemas todos os dias, certo? Mas paramos por aí, ou muitas pessoas não pensam nesses problemas ao criar suas aplicações de IA. Então, vocês podem ter uma aplicação de IA, mas…

09:01 Então você não consome isso desse jeito. E é nisso que vamos nos concentrar hoje, porque acho que essa é a melhor forma de consumir aplicações de IA: não apenas por meio de chat bots, não apenas por meio de aplicações de RAG, mas também por uma combinação de automação e autonomia. Então, o que é um agente de IA, para aqueles que não sabem? É como uma entidade computacional alimentada por um LLM, com capacidade de raciocínio, um pouco como nós, humanos: temos nosso cérebro, que é

09:32 complementado por um banco de dados para a memória. Também como nosso cérebro, ele é ampliado por ferramentas para realizar ações. O equivalente, para um humano, seria termos nossas extremidades e podermos interagir com o mundo, assim como um agente de IA pode interagir com um sistema operacional por meio das ferramentas que damos a ele, que disponibilizamos para ele. E ele também se baseia em entradas. Por exemplo, seriam como nossos sentidos, para um humano: nossos olhos etc., que nos permitem perceber informações. E o contexto, assim como nossa atenção, também é limitado, como

10:03 os nossos agentes. Não conseguimos assistir a sete filmes ao mesmo tempo; não entenderíamos nenhum deles, não nos concentraríamos em nenhum. Então, a context window dos humanos é semelhante à dos agentes de IA. E tentamos assimilar, ou ter algumas dessas noções mais próximas da experiência humana. E é nisso que vamos trabalhar hoje. Então, a parte do raciocínio é fornecida pelos laboratórios de fronteira, e não temos muito controle sobre

10:35 isso. E também temos as coisas sobre as quais temos um pouco mais de controle: a memória, o uso de ferramentas e a percepção. E esse é o próprio harness. Um harness é, essencialmente, toda a estrutura de suporte necessária para construir esses três componentes: o uso de ferramentas, a memória e a percepção. Não vamos nos concentrar muito no modelo porque, como eu disse, não temos muitas opções sobre o que

11:07 fazer. Então, o harness é, na verdade, um dos tópicos mais interessantes em IA. Acho que hoje é o tópico mais interessante em IA, porque esses harnesses controlam tudo o que o agente de IA pode fazer. Você dá a ele uma configuração diferente e, então, o agente — o mesmo modelo de IA de fronteira, o mesmo LLM que você está usando — fica melhor ou pior. Às vezes, já se comprovou que, simplesmente mudando o harness, o mesmo modelo tem um desempenho melhor ou pior em

11:38 tarefas específicas. Então, é realmente muito importante dar atenção aos harnesses, e pouca gente está fazendo isso. E, como você disse, em um harness há sete ou oito componentes diferentes, se considerarmos também o aprendizado contínuo. Mas há muitas decisões que você precisa tomar, certo? Você tem o modelo, tem o armazenamento — onde colocar os dados —, tem componentes de codificação e recuperação, como: como calcular a distância entre dois vetores para recuperar os dados corretamente?

12:09 O que devo armazenar na minha memória? Devo pensar nela como memória de curto prazo e memória de longo prazo, como os humanos têm? Devo dividi-la em compartimentos diferentes ou em tipos diferentes de memória? Há também a camada semântica, que é uma parte realmente interessante porque, como humanos, estamos aqui e temos um contexto que nunca dissemos uns aos outros, certo? Mas compartilhamos esse contexto. Por exemplo, eu sou palestrante e você está ouvindo; você não está

12:39 cantando agora. Por que você não está cantando? Porque isso não é apropriado para a semântica do contexto em que estamos agora, certo? Então, o próprio modelo também tem acesso à camada semântica, que fala um pouco sobre todas as coisas que não foram ditas ao modelo, mas que são presumidas. Há também o loop do agente, que reúne todas as coisas que fazem o agente funcionar continuamente, de forma automática e autônoma. E essa é uma das partes mais importantes. Também há

13:10 a engenharia de contexto. Vamos nos concentrar em cada uma delas, mas não vou me aprofundar nelas, porque faremos isso no workshop. Só para referência, houve uma grande discussão sobre arquivos versus bancos de dados. Muita gente dizia que precisamos usar arquivos para tudo: basta colocar tudo em um arquivo e, magicamente, um mês depois, o agente fica melhor. Outras pessoas são maximalistas de bancos de dados e querem colocar tudo em um banco de dados.

13:41 Certo? Então, esse dilema continua. E eu diria que… Bem, deixe-me dar um exemplo. Alguém consegue dizer, neste exemplo que vocês veem na tela, qual é a solução alternativa que os agentes usam para resolver esse problema específico que está na tela: vários agentes escrevendo no mesmo arquivo? Como isso funciona hoje em dia nos agentes de IA? Alguma ideia?

14:15 >> Worktrees. Exatamente. Muito bem. Então, worktrees são a solução atual, certo? E isso é uma espécie de solução alternativa, porque os arquivos têm um problema inerente: se várias gravações são feitas no mesmo arquivo, surgem problemas de consistência. Qual gravação veio primeiro? Se alguém estiver lendo, o que faço com essa pessoa que leu o arquivo antes de eu modificá-lo? E assim por diante. Há muitos problemas, certo? Então, para algumas coisas, com certeza vou dizer: arquivos são

14:46 ótimos. Arquivos são ótimos para armazenar muitos dados não estruturados. Por outro lado, bancos de dados também são usados em outros tipos de casos de uso. Mas a minha solução é que, em alguns casos, essas soluções funcionam com arquivos; em outros, funcionam com bancos de dados. Então, precisamos reconsiderar algumas dessas coisas que estão acontecendo, certo? E a solução de worktree, ou a solução alternativa, já tinha sido resolvida pelos bancos de dados há 30

15:16 anos. E estamos tentando reinventar a roda em algumas dessas situações. Na verdade, não precisamos reinventar nada, porque existe uma solução de verdade para isso. Por exemplo, se você tentasse escrever em um arquivo ao mesmo tempo que vários agentes, se tivesse consistência transacional ou consistência ACID — isto é, gravações atômicas, consistentes, isoladas e duráveis — no arquivo, não teria esse problema, certo? Então, arquivos são bons para algumas coisas e

15:46 bancos de dados são bons para outras. Não precisamos escolher apenas um deles, certo? Então, no harness do agente, considerem isso uma reflexão. Outro componente são todos os componentes de memória, certo? Isso abrange toda a mecânica e os sistemas criados em torno de um agente de IA para fazê-lo usar as informações e não apenas usá-las, mas também conseguir

16:16 refiná-las e recuperá-las adequadamente quando chegar a hora, certo? E, como engenheiros, vocês escolhem o que vão considerar na camada de memória do agente. Algumas pessoas preferem memória de curto prazo versus memória de longo prazo. E, neste caso, esta é a parte dois. Temos alguns componentes de memória de curto prazo. Por exemplo, se estivermos conversando com clot ou com codeex, temos memória de curto prazo

16:46 no sentido de que a própria context window é memória de curto prazo. Tudo o que desaparece depois da conversa… desaparece depois da conversa, certo? A maioria das coisas na context window simplesmente some. Então, você inicia outra conversa e tudo começa do zero. Isso é memória de curto prazo. É muito limitada. Não podemos colocar tudo nela. E também temos memória de longo prazo. Dentro da memória de longo prazo, também temos algumas categorias que propomos. Por exemplo, a memória episódica incluiria tudo o que

17:18 aconteceu: todos os episódios das nossas conversas, todos os registros de ferramentas, as conversas anteriores, resumos de conversas anteriores que você teve com o agente etc. Tudo isso vai para a categoria de memória episódica de longo prazo. Você também tem procedimentos, ou memória procedural, que inclui coisas como skills e workflows, que são sequências de skills executadas, etc. Tudo isso vai para a memória procedural. E também temos a memória semântica, que inclui tudo aquilo que não foi dito. Como eu disse, o agente se lembra de quem você é, do que são

17:50 suas preferências, qual é seu framework favorito etc. Todas essas coisas vão para a memória semântica. Então, o problema, a principal questão aqui é: por que não podemos colocar tudo na memória de curto prazo? Porque ela é limitada, e não é apenas limitada: quanto maior a matriz de atenção — e a matriz de atenção é essencialmente a context window —, pior é o desempenho. E isso acontece com todos os

18:20 modelos. Muitos estudos mostraram que, se você começa com zero tokens na context window, o problema é resolvido com muito mais precisão do que se você já tiver 256.000 tokens, e o limite agora é de um milhão, certo? Estamos em um milhão por causa do cache KV. Todas essas coisas precisam ser consideradas, e saiba que, mesmo que o limite anunciado seja de 256 mil ou de um milhão, se você continuar, o desempenho fica

18:50 horrível. Então, quanto menor for a context window, melhor ela vai resolver um problema. E isso se aplica a todo tipo de problema que você possa imaginar na humanidade, certo? E há dois tipos de coisas que lidam com isso. Uma é a sumarização de contexto, em que você simplesmente pede: “Ei, gere um resumo, um resumo curto, para mim, com tudo o que foi dito na context window”, e então obtém o resumo e começa a próxima conversa a partir dele. Isso funciona. A outra é a compactação, e

19:22 isso é meio parecido, mas, na compactação, você coloca trechos da conversa no banco de dados ou em um arquivo e, então, atribui um ID a eles. Se o agent de IA precisar deles mais tarde, terá o ID. Ele simplesmente busca usando o ID e um deslocamento, como se estivesse lendo um arquivo, certo? Esses são alguns dos problemas que surgem na engenharia de contexto. E então temos o loop do agent, que é o motorista, ou o carro que conduz todos os componentes sobre os quais falamos. Temos

19:53 uma etapa de montagem do contexto que busca nas skills, nas ferramentas, na conversa anterior, nos arquivos e no banco de dados. Todas essas coisas são inseridas dinamicamente na context window. Depois, ele faz um pouco de raciocínio. Faz uma chamada de API para a OpenAI ou para qualquer modelo com que você esteja falando e decide o que precisa ser feito. E isso acontece automaticamente e indefinidamente, se você quiser. No meu caso, nesse loop do agent que

20:24 preparamos para o workshop, há um limite de paciência, porque não quero ficar sem créditos da OpenAI ou quaisquer outros créditos que eu tenha. Mas, sim, o número máximo de iterações no nosso caso será oito, com no máximo 60 segundos de raciocínio para cada iteração, certo? Mas isso é totalmente configurável. Como eu disse, nós, como engenheiros, temos que definir o que acontece no loop do agent, certo? E também o padrão toolbox, o

20:56 padrão skillbox, que propomos para armazenar ferramentas e skills, que são centenas. Não sei quanto a vocês, mas eu já tenho umas cem skills instaladas. Não vou colocar cem skills ao mesmo tempo na context window, porque cada skill tem de 3.000 a 5.000 tokens. Então, isso ultrapassaria o limite anunciado em pouco tempo. Eu não teria espaço para a conversa propriamente dita com o agent. Então, como resolver isso? Bem, há diferentes maneiras, mas o que propomos é

21:26 vetorizar, criar embeddings vetoriais das ferramentas e das skills. Com esses embeddings vetoriais, quando o loop do agent — deixa eu voltar. Quando o loop do agent quiser recuperar skills ou ferramentas úteis, você fará uma busca de similaridade vetorial nesse repositório de vetores. Vai buscar a skill ou a ferramenta mais relevante para resolver o problema. Você resolve o problema e, depois, a descarrega novamente. E essa é uma das maneiras de manter a context window relevante nesse sentido. E

21:57 sabe, usar skills e ferramentas é um padrão muito, muito comum. Todo mundo usa ferramentas como um comando bash ou um comando para mudar de diretório; tudo isso são ferramentas específicas por meio do bash, certo? Então, usamos ferramentas e skills constantemente. Em alguns casos, elas ocupam mais de 50% da context window. Só quero que vocês tenham em mente o enorme tamanho da context window que, na verdade, é ocupado pelas skills e pelas ferramentas.

22:30 Também temos essa ideia chamada destilação de skills, em que você pega conversas anteriores, execuções e conversas reais que teve com um agent de IA e tenta criar algo significativo a partir disso. Como fazer isso? Bem, há várias maneiras, mas uma das mais fáceis é simplesmente criar um arquivo SKILL.md e colocá-lo no mesmo skillbox onde você guardou tudo antes. E essa é uma das maneiras. Um agent como Hermes, um dos

23:02 inovadores nesse sentido, criava skills particularmente boas para resolver problemas específicos. Digamos que você esteja trabalhando no frontend. Bem, se estiver trabalhando no frontend, talvez queira criar uma skill que tenha funcionado muito bem para você, com todas as suas preferências. “Ei, gosto deste estilo de cores”, etc. E, da próxima vez que trabalhar no frontend, como você criou embeddings vetoriais a partir disso, o agent escolherá automaticamente a skill mais relevante. Então, se você simplesmente disser: “Ei, eu

23:33 gosto deste estilo de cores que usei naquela outra skill”, ele vai saber automaticamente que você está se referindo à nova skill, porque você usou, por exemplo, as palavras “estilo de cores”, certo? A destilação de skills é uma das técnicas que você pode usar para melhorar o aprendizado de um modelo ao longo do tempo. E isso é o mesmo — tem relação com o que eu estava dizendo —: você tem descoberta dinâmica de skills, no sentido de que o loop do agent, ao

24:05 montar ou construir o contexto, buscará as skills e as ferramentas certas quando necessário. E algumas pessoas perguntam: como um modelo congelado pode melhorar? Com “congelado”, quero dizer que não temos controle sobre os modelos de fronteira, certo? Mas temos controle sobre todos os dados, a camada de dados deles, certo? Algumas pessoas dizem: “Vamos modificar os pesos do modelo”; outras dizem: “Vamos criar um modelo de embeddings que funcione melhor para esse problema específico”

24:36 e depois vou me preocupar em recuperar embeddings melhores por lá, etc. Há diferentes maneiras de fazer isso, mas a ideia é que esse é o principal componente do aprendizado contínuo. E o aprendizado contínuo é uma das coisas que você pode fazer para melhorar um modelo. E há três categorias, certo? Você pode trabalhar na memória paramétrica. Ela é chamada paramétrica porque modifica os parâmetros dos pesos da rede neural. Você também tem a memória

25:08 representacional, que é o que trabalha com embeddings etc. E também tem a memória não paramétrica, que é tudo o que discutimos hoje até este ponto. Mas, se você tiver interesse em alguma dessas três, nós nos concentramos na terceira. Você também tem as outras duas, e não vou entrar nelas. Há muitas técnicas, como criar adaptação de baixo rank, fazer fine-tuning de um modelo, criar embeddings etc. E você pode encontrar tudo isso naquele curso

25:39 a que me referi antes, que aborda as três categorias. Então, se tiver interesse, faça esse curso ou converse conosco depois da sessão. Depois da sessão, estaremos no evento pelo restante do evento também, certo? E a última coisa que quero mencionar é que, em tudo o que acontece durante uma chamada à API de chat completions para qualquer modelo da OpenAI ou qualquer outra coisa que você esteja usando, há um aspecto inerente…

26:10 hierarquia de instruções. O que quero dizer com hierarquia de instruções? As coisas fornecidas ao modelo têm pesos diferentes. Por exemplo, com quem interagimos é o usuário, certo? A solicitação. Nesse sentido, essa é a terceira coisa mais importante que podemos passar a um modelo. A mais importante é o system prompt, certo? Todo mundo conhece o conceito de system prompt. E o system prompt é ótimo, mas não pode conter tudo, porque, caso contrário, as coisas não teriam uma

26:41 hierarquia própria. Você precisa, de fato, colocar algumas coisas no system prompt, algumas coisas no prompt do usuário, e todas as ferramentas e skills disponíveis têm essa hierarquia. E isso é bom porque, na verdade, permite que nós — ou o modelo — se concentrem mais em algumas coisas do que em outras. Também vamos abordar isso no workshop. Só para referência, esta é a interface do workshop. Então, se você já estiver executando isso no Codespaces, vai ver que

27:12 você tem isso deployado. Vou mostrar como funciona. Mas, essencialmente, esta é a maneira como imagino que alguém que trabalha com AML, como em um sistema de detecção de fraude em um banco, interaja com um agent autônomo. O agent autônomo roda em segundo plano 24 horas por dia, 7 dias por semana. Não dorme. Não precisa de nenhuma das necessidades humanas que nós temos, certo? Ele está conectado, por meio de um harness, a um banco de dados e tem todas as

27:44 funcionalidades que mencionamos, mas, além disso, toma decisões de forma autônoma para a empresa, mesmo quando estamos offline. Ele não arruína a vida das pessoas simplesmente dizendo: “Ei, esse cara é suspeito. Vamos bloquear o banco inteiro e tudo mais”, porque isso arruinaria a vida da pessoa. Em vez disso, ele toma essas decisões e apenas as registra, para que um humano possa analisá-las depois, mas isso vai economizar muito

28:14 tempo durante o processo de investigação e assim por diante. Então, ao final do workshop, se você concluí-lo, poderá ter um agent conectado a um banco de dados, funcionando como se fosse de qualquer empresa, e realizando análises e tomando decisões de forma autônoma, que depois serão examinadas e consideradas por um humano. Então, esses são todos os componentes do harness sobre os quais falamos

28:45 e, sem mais delongas, vou mostrar o QR code de novo: workshopwaitingroom.com. E, se quiser conferir qualquer um dos outros workshops que temos, basta acessar este repo do GitHub. Estamos fazendo muitos progressos e investindo bastante esforço em tudo o que está lá, desde workshops, sessões e notebooks. Assim, você pode começar a explorar diferentes tópicos, como harnesses de agent etc. Então, dê uma olhada. E deixe-me

29:19 ir ao meu Firefox e mostrar como esse aplicativo funciona. Primeiro, para quem não recebeu um convite: se acessar workshopwaitingroom.com, você receberá, por meio da API do GitHub, um convite para este repositório usando seu usuário. Então, se vier aqui e abrir no GitHub Codespaces, vai ser solicitado que você crie um codespace. E, claro, sou eu que estou pagando, então não se preocupe

29:50 com isso. Só tome cuidado com o hardware que você deploya, porque é caro. Mas a ideia é que você receba um deploy como este, com alguns notebooks. Vou mostrar o próprio workshop e, depois, a ideia é eu me afastar em alguns minutos e então passarmos pelas pessoas que têm perguntas etc. e resolvermos juntos. Mas isso também deploya automaticamente

30:22 este aplicativo, que basicamente acompanha tudo. E, claro, estes são dados falsos. Não se preocupe, não estou expondo ninguém aqui. Ele basicamente apresenta novas transações. Algumas estão em ordem, outras são problemáticas. Então, o agent autônomo, que é um modelo Grok rodando no OCI, toma decisões de forma autônoma. Em alguns casos, diz: “Ei, esta aqui é suspeita, vamos adicioná-la à lista”, e depois você também tem uma maneira de

30:54 visualizar o context window do agent aqui. Você também pode conferir todos os dados que já estão no banco de dados — aqui, todos os clientes etc. — e também ver como o agent analisa tudo isso de forma autônoma e em tempo real, certo? Ele vai percorrer as chamadas de ferramenta que disponibilizamos na nossa caixa de ferramentas.

31:24 É, desculpe, está um pouco pequeno. Então, ele vai examinar as evidências. Vai buscar conhecimento nos espaços de conhecimento que criamos usando vector stores. Vai fazer muitas chamadas de ferramenta. E, por fim, vai percorrer automaticamente toda a atividade — os relatórios de atividades suspeitas. Aqui, temos apenas uma forma sofisticada de visualizar os 30 eventos mais recentes ocorridos no banco. Mas o próprio workshop está neste notebook, o notebook do estudante.

31:57 E o que quero que vocês façam, primeiro, é conferir os diferentes componentes que temos ali, porque estamos implementando-os aqui. Vou passar pela primeira tarefa. Há algumas coisas que vocês precisam fazer no workshop só para confirmar que sabem o que estão fazendo. Então, primeiro, vou mostrar a primeira parte do workshop, certo? Vocês têm este modelo Grok 4.3, que está rodando na Oracle Cloud

32:28 Cloud. E vamos nos conectar ao banco de dados, claro. E depois… Desculpe, deixe-me reiniciar o kernel. Vou executar esta célula. Reiniciar. Mas, sim, avisem se tiverem alguma dúvida ou problema ao entrar no

32:59 codespace. Depois vou me afastar, fazer isso com vocês e responder a qualquer pergunta. Alguma pergunta até agora, por sinal? Certo. Sim. O repo. >> Sim, vocês podem encontrá-lo em workshopwaitingroom.com. Deixe-me colocar o QR code aqui. Se quiserem, podem escanear este QR code.

33:29 Isso vai dar acesso a ele automaticamente, por meio da API do GitHub. Certo. Então, vou reformular a pergunta para quem está no YouTube. Ele está perguntando o que acontece com a memória episódica e todos esses componentes de memória. Isso pode ser confundido com conversas anteriores com um agent? Bem, depende do peso que você atribui a isso. E é por isso que também mencionei a hierarquia de instruções. Talvez você queira incluir isso, se

33:59 for algo muito, muito importante e você realmente quiser buscar informações em um lugar ou em outro. Na verdade, você mesmo pode decidir a arquitetura da sua camada de memória, certo? Por exemplo, em alguns casos em que a memória episódica é muito importante e você realmente quer buscar informações de conversas anteriores, talvez queira vetorizá-las em vez de simplesmente salvá-las como texto bruto. Depende muito do caso de uso. Eu diria que, neste caso, não há conflito

34:30 porque há uma separação clara entre os componentes de memória da arquitetura. Sim. As skills podem ser adicionadas ao system prompt. Normalmente, elas… Ah, desculpe, normalmente têm um peso diferente; sim, na hierarquia de instruções, têm o menor peso entre os quatro, se você pensar nisso dessa forma. Elas ficam geralmente aqui, então eu as vejo como um espaço plug-and-play de onde você pode buscar coisas, e estamos experimentando com

35:02 Isso, na verdade, Richmond e eu queremos criar uma maneira de você se conectar a hubs de skills e hubs de ferramentas externos, internos ou de terceiros. Por exemplo, uma coleção de MCPs que você pode disponibilizar para seu agent pré-computando os embeddings de todos esses itens. Depois de ter esses embeddings pré-computados, você pode simplesmente dizer: “faça buscas vetoriais neste grupo de terceiros de skills ou neste grupo de ferramentas”, em vez de pensar nisso como algo que está sendo

35:33 incluído. E, aliás, isso é claro, incluído em cada solicitação à API de chat completions da OpenAI ou de qualquer outro modelo. Isso é anexado ao final e, normalmente, representa uns 80% do total; uns 80% de toda a solicitação são ferramentas e skills. Mas o que acontece, ou por que você não é cobrado umas cinco vezes mais do que paga agora, é que a OpenAI e todos esses sistemas têm um cache semântico. E eles colocam… se 80% de

36:07 isso for igual ao da solicitação anterior, não recalculam; simplesmente recorrem ao cache semântico. Isso permite a você — e permite a todos nós — consumir os modelos dos Frontier Labs de maneira econômica. E, claro, ainda é muito caro. Mas quero que entendam que seria quatro ou cinco vezes mais caro se não tivéssemos esse cache semântico, que simplesmente inclui as ferramentas e essas skills. Porque, na resposta, lembrem-se de que, quando

36:39 vocês estão interagindo com um modelo de IA de ponta, essencialmente fazem tudo por meio de uma solicitação HTTP. E tudo isso, por exemplo, seriam 10 mil ou 5 mil tokens como system prompt: “Você é um assistente de IA e precisa me ajudar a resolver isto e aquilo”. Depois, você tem as instruções específicas do aplicativo para o desenvolvedor, a consulta do usuário — que é o que digitamos no chat e é insignificante, talvez 100 ou mil tokens — e, então, as saídas das ferramentas

37:09 e os documentos recuperados, que representam 80% da solicitação, algo entre 35 mil e 100 mil tokens já em cada solicitação. Isso responde à sua pergunta? >> Só mais uma. >> Sim. >> Certo. A pergunta dele era: como vocês gerenciam o orçamento? E, já que há tantos itens nos padrões de skillbox e toolbox, como fazem isso funcionar, essencialmente? Temos uma separação clara. A context window é algo que consideramos — ou pensem nela como uma matriz n-dimensional que começa

37:42 em zero, mas nunca é zero; fica mais perto de 10 mil. Eu estava lendo um artigo que comparava a eficiência de cada harness em relação ao quanto cada um colocava no primeiro system prompt e na primeira solicitação à API de completions, no início. O Pi, vocês conhecem o Pi, o harness, é o harness mais minimalista e eficiente, porque inclui cerca de 6 mil tokens no início de cada solicitação. Mas, se você olhar para outros harnesses, eles têm mais, uns 30 ou 40 mil tokens. Como nós…

38:16 Temos uma separação clara na context window? Simplesmente deixamos tudo acontecer ao redor do agent loop, certo? Então, deixa eu ir até o agent loop para mostrar uma coisa. O agent loop controla tudo a que se conecta, certo? Então, aqui, por exemplo, está o agent loop. [fungada] Ah, estou no fim. Esperem. Só para referência, o agent loop.

38:53 Então, aqui, certo, a montagem do contexto: quando você está trabalhando com isso, essencialmente vai montar… e vocês podem acompanhar isso no notebook. Vou explicar o notebook, mas a montagem do contexto é uma parte em que, primeiro, definimos um número máximo de ferramentas ou skills para recuperar. Acho que o número padrão é três. Então, sempre que chega uma nova solicitação, ela determina — e isso é feito

39:24 pelo próprio modelo — o que precisa ser feito. Depois, tenta montar o contexto com os itens necessários para executar a tarefa, certo? E um desses itens é recuperar as três ferramentas mais relevantes e as três skills mais relevantes. Não estamos usando um reranker. Mas o que vocês também poderiam fazer é, no fim da busca por similaridade, incluir um modelo de embedding e um reranker, que vão pegar esses três e

39:54 indicar qual deles é o mais importante. E vocês poderiam refinar melhor o resultado, porque talvez não queiram carregar um total de três skills para cada tarefa. Talvez seja possível resolver a tarefa com apenas uma, certo? Então, a ideia é que vocês possam usar a estratégia que quiserem; basta manter-se fiéis a ela e ser consistentes até o fim. A ideia, neste caso, neste workshop em particular, é que fazemos um certo número de buscas vetoriais

40:25 em um vector store que contém as ferramentas e em outro vector store que contém as skills, com k igual a três. Depois, entre as três, vocês podem recuperar a mais relevante com um reranker. Em seguida, o agent vai despachar as ferramentas, claro, e montar uma context window, mas isso é inteiramente uma decisão e uma responsabilidade do agent loop. Isso. Certo. Então, qual é a maneira mais importante ou interessante de vocês interagirem com a camada de memória de…

40:55 >> Quer dizer, a eficiência vem simplesmente do número de entidades que vocês criam, certo? Então, minha primeira recomendação seria manter as coisas simples. Não criem abstrações nem componentes demais na camada de memória. Por exemplo, experimentem primeiro apenas com memória de curto prazo e memória de longo prazo, mantendo só duas estruturas, certo? Se vocês acharem — ou se tiverem um agent que considere que algo que estava na memória de curto prazo

41:26 ou na context window vale a pena manter, vocês promovem isso para a memória de longo prazo e simplesmente colocam em algum lugar como texto bruto. Essa é a coisa mais fácil que vocês podem fazer, certo? Depois que estiver em texto em algum componente ou objeto de memória de longo prazo, vocês podem vetorizá-lo e deixar que o agent loop o explore de alguma forma. Por exemplo, aqui vocês teriam apenas mais uma coisinha entre observar e

41:58 raciocinar, que permite ao agent recuperar memórias, ou algo assim. Podem chamar isso de “recuperar memória de longo prazo”. Isso vai fazer com que ele reflita antes de resolver o problema mais uma vez. Então, ele vai até o vector store, ou o que quer que vocês usem como memória de longo prazo — o episódio que registraram numa conversa anterior — e, a partir daí, vocês podem permitir que ele veja: “Certo, vou buscar isso, caso considere que

42:28 seja interessante”, ou se a similaridade vetorial — isto é, se a distância entre o vetor da consulta e o que tenho na memória de longo prazo for relevante o bastante e pequena o bastante —, então vou incluir isso na context window. Se for grande demais ou não for relevante o bastante, simplesmente vou descartar. Então, seria uma abstração diferente, adicional, entre as partes de observação e raciocínio. Há maneiras de fazer isso. Não estamos usando MCPs aqui, mas um dos benefícios

42:59 de usar MCPs seria resolver… Eu diria que MCP não é tão relevante neste caso, mas depende do que vocês têm no banco de dados. Por exemplo, se vocês têm um banco de dados e estão interagindo com ele, como estamos fazendo aqui, usar um MCP é interessante. Mas um dos principais problemas que gosto de apontar às pessoas é: o que um MCP resolve, especialmente em bancos de dados? É que sou da área de bancos de dados, porque trabalho na Oracle. Então, uma das coisas que vocês podem

43:29 resolver é permitir que agents de IA façam consultas SQL sem alucinar nem tentar criar uma nova consulta SQL toda vez. Esse é um dos maiores problemas que os agents de IA têm com SQL. Existem uns 15 mecanismos de SQL, como Postgres, Oracle Database, VSQL; há muitos tipos diferentes de consultas que funcionam com SQL, mas eles têm dicas específicas ou sutilezas na consulta que fazem com que ela

43:59 não funcionar bem. Certo? Então, o principal problema que o MCP resolve nesse caso seria: tudo bem, vou pré-criar algumas consultas SQL e depois deixar os agents acessarem essas consultas. Assim, sabemos que elas funcionam, em vez de deixar um agent tentar criar uma consulta SQL dinamicamente toda vez, certo? Isso. Boa pergunta. Deixe-me dar um exemplo. Então, o mais importante seria a rapidez e o significado das

44:30 frases e do que a própria skill significa. Em vez de ter isso como texto — se você armazenasse isso apenas como texto em um arquivo SQL, ou melhor, em um arquivo no sistema de arquivos, no sistema operacional —, haveria muitas maneiras de um agent fazer correspondência por expressão regular. Por exemplo, toda a busca seria basicamente uma busca por palavras-chave ou uma busca por palavras, baseada

45:01 nessa skill, o que não tem problema. Mas, quanto maior ela fica, menos… mais difícil fica para um agent. Primeiro, a correspondência por expressão regular, como GP, é ineficiente para arquivos enormes e, às vezes, se o sistema de arquivos cresce e cresce linearmente, o desempenho da correspondência por expressão regular diminui exponencialmente. Bem, não exponencialmente, quadraticamente, digamos, apenas quadraticamente. Mas esse é um dos problemas: isso não escala

45:34 bem conforme aumenta o tamanho dos arquivos. Outra coisa é que, se você pré-computar os embeddings de uma skill, também estará capturando o significado nesses embeddings, o significado oculto que nós, humanos, não conseguimos compreender. Em vez de apenas descrevê-lo em texto, que é fácil para nós ler, também há uma pré-computação de, no mínimo, 384 até mais de 1.000 dimensões. E esse embedding realmente vai conter relações entre cada um

46:07 dos tokens na matriz de embeddings, tornando-os muito mais fáceis de descobrir, por exemplo, por meio de busca semântica. E é isso que leva você a tentar a busca híbrida, que é uma combinação de buscas semânticas — que usam embeddings — com busca por palavras-chave. Isso se chama RRF, um tipo de recuperação híbrida. Ela funciona muito melhor porque, essencialmente, combina as duas. E isso… Posso mostrar o exemplo na oficina, porque criei esta visualização que explica exatamente o que quero dizer com busca híbrida, certo? Você vê… Sim, então, dependendo… Essencialmente, este é um gráfico que combina a capacidade de busca da busca por palavras-chave com a da busca semântica, e essa lacuna que você vê no meio representa tudo o que, ao fazer uma busca híbrida, será mais

46:38 relevante do que qualquer resultado das outras duas. Então, em resumo, quanto mais você puder usar dois tipos diferentes de busca, melhor. Cada um tem suas vantagens, mas, se você combinar os dois, vai fazer um pouco mais de computação, mas a qualidade da recuperação será melhor ao longo do tempo. Estou pensando na maioria dessas coisas do ponto de vista de um agent de IA. Não espero que ninguém nesta

47:10 sala comece a criar seus próprios harnesses personalizados, porque já temos ótimas soluções no mercado, certo? Temos o Claude Code, temos o Codex. Cada um tem suas preferências. A propósito, quem gosta do Pi? Levantem a mão. Menos gente do que eu esperava, mas tudo bem. Então, estou pensando nisso do ponto de vista de um agent de IA. O que quero que vocês entendam é que podem criar harnesses personalizados para

47:40 problemas específicos. E criar harnesses personalizados não precisa ser tão sofisticado quanto criar um novo Claude Code e fazer todo o seu trabalho nesse harness personalizado. Em vez disso, vamos simplificar os problemas que vocês estão tentando resolver e, então, criar harnesses personalizados que se conectem a eles. Neste caso, penso que, se você é consultor, é o caso de uso ideal para você, ou o usuário ideal para esta oficina, porque poderia criar um

48:12 harness personalizado que funcione bem para um agent financeiro e tenha tudo de que ele precisa para um caso de uso financeiro. Mas, se você tiver outro tipo de cliente, com outros tipos de dados ou de restrições — se quiser resolver o próximo problema de Navier-Stokes ou algo assim —, esses problemas têm restrições diferentes. Por exemplo, os problemas da OpenAI, os problemas matemáticos, precisam de compactação automática ilimitada ou de sumarização automática do contexto, porque esses agents não têm nenhum

48:43 humano no loop. Então, tudo o que envolve a resolução desses problemas precisa incluir, por padrão, a sumarização automática do contexto. Também precisa ter paciência infinita ou quase infinita. Neste caso, o loop do agent é simplificado para, no máximo, oito etapas. Todas essas considerações dependem do problema. Sim, eu começaria do zero, porque assim você consegue remover 90% de

49:14 tudo de que não precisa. Então, sim, definitivamente… Quer dizer, tudo é construído em torno da API de chat completions, e tanto a Anthropic quanto a OpenAI criaram seus próprios padrões para se defender disso, mas tudo gira em torno dessa API. Se você pensar na forma de se comunicar com um modelo apenas como um plugin adicional para o harness, fica muito mais claro que, quanto menor for tudo, melhor será no final. Isso responde à pergunta?

49:44 Certo. Então, vamos fazer o seguinte. Comecem com a base de código, com um codespace. Configurem esse notebook vocês mesmos e depois vamos… Vou dar uma volta e, se alguém tiver alguma pergunta, podemos conversar de um jeito menos… intenso, porque sinto que estou sendo observado, e vocês provavelmente não sentem pressão. Então vou pressionar vocês saindo daqui. E, se vocês… Sim, vamos continuar. Quer dizer, não

50:14 temos muito tempo. Meu Deus. O tempo voou. Mas, sim. Obrigado. Obrigado pelos aplausos. Obrigado. Obrigado. [aplausos] Achei que tinham passado uns 15 ou 20 minutos, mas passou uma hora. Então, uma coisa: configurei tudo para que vocês possam criar o codespace no hotel, em casa. Vocês podem… Eu

50:46 vou pagar do meu próprio bolso. Então podem usar esta oficina e brincar com ela como quiserem, e eu vou pagar. Não se preocupem. Se quiserem conversar sobre algum conceito de agent harness, venham ao estande da Oracle. Estaremos aqui até quarta-feira à noite. Obrigado por virem à sessão. Certo. [aplausos]

51:19 Vou pagar por isso do meu bolso. Então vocês podem usar este workshop e brincar com ele como quiserem, e eu vou pagar por isso. Não se preocupem. Se quiserem conversar sobre algum conceito de agent harness, é só aparecer no estande da Oracle. Estaremos aqui até quarta-feira à noite. E obrigado por virem à sessão. É. Certo. [aplausos]

Transcrição original

[00:01] [music] Hi. Hi everyone. Uh thank you for coming to this session. Uh we’re it’s going to be a session about agent harnesses. We don’t have a lot of time. It’s only one hour session. So um hopefully we have time to talk about a lot of things that that you guys are interested in and the the session essentially is going to be

[00:32] uh like me talking like 10 15 minutes about the topics that we’re going to talk about and solve in the workshop. You have the workshop instructions in a QR code or in a website and if you don’t want to listen to me, you think I’m boring or something, you can start uh on your own on the workshop as I’m speaking. But essentially this is this is what’s uh happening on the website. You just um sign up with your GitHub handle and then you will automatically receive an invitation to the repository.

[01:03] The workshop is hosted on code spaces. So you can just like create a code space out of that uh and you will receive an invitation automatically to get access to the workshop itself and you just have to create a a code face over there uh opening GitHub code spaces and you’re good to go and and and begin with the workshop. Uh so I’ll just put the QR code uh one more time for those of you who were uh who who want to take that and I’ll I’ll get started.

[01:39] Okay, perfect. Uh, if you have any questions, also my colleague Richmond is over there. He’s going to go through um, you know, everyone’s uh, table. If you have any questions, just raise your hand and he can help out as well. Yeah, there you go. Also, the website, I mean, you can go to the website workshopwaiting room.com. I paid too much money for that domain. So, uh, use it. Okay. So, who am I? My name is Nacho

[02:12] Nacho Martinez. I am an AI developer advocate and a data scientist by heart. And if you’re interested in anything about me, just find me on YouTube. I have podcasts, I have workshops, I have everything. Not going to go too much into myself. Um just one thing though uh we re recently released a course with Andrew Ang and deep learning AI about uh building adaptive AI agents which is one of the subcomponents that we’re going to talk about today. And you know if you’re

[02:43] particularly interested in the things that you can do on a model to make it better and adapt over time, learn over time, just check out that course. is a free course uh a 1hour course that you can check out on on Google. So what are we going to go uh through today? Like I said, we don’t have a lot of time. So I’m going to try to be quick. Um but these are the things that we’re going to talk about. First of all, what is the agent stack? Uh what are the components of an agent stack? What are the different shapes that an AI

[03:15] application can take? What an AI agent is? And what is the agent harness? what is the main motivation of building or working around agent harnesses rather than working with AI agents or with an LLM model directly and you know all the subcomponents of an agent harness like for instance memory context engineering memory engineering and all these things. So because they told me that there’s going to be a lot of people from uh financial uh like a lot of people that work in Wall Street uh I adapted this

[03:47] workshop to be around a bank right so the idea is that the main premise of the workshop is this we are hearing lots of the uh nowadays like open AAI is launching 10,000 agents or 5,000 agents to solve this problem 10,000 agents to solve this mathematical problem that was solved like in a 100 years 200 years. The thing is that these agents are autonomous. They don’t have any human in the loop until they arrive to uh to the conclusion or the answers, right? So the

[04:18] agents themselves don’t have the capacity to do this. Why? Because I mean the context window is limited. The memory components are something that a large language model doesn’t have inherently. So all these things we need to implement ourselves to make these agents able to solve all these problems for 10 hours 100 hours autonomously right. So the idea is that a lot of people are making focus on okay we have these frontier models but my idea is that okay we don’t need to focus so much on the frontier models we can use them

[04:50] but let’s work on the harness which is the interesting part and the things that you can actually customize uh more and more. So on this application, the idea is that it’s a medium-sized bank that has lots of uh you know suspicious transactions uh sometimes and they are categorized into five different types. So for example, if you get like a million dollar transaction that’s coming into your bank and automatically and magically uh for three days you’re making like $50,000 withdrawals on an

[05:21] ATM. That’s suspicious, right? because why would you like put $1 million in and then just like distribute uh like that. So the idea is that we have this medium by uh medium-sized bank that has lots of transactions and these transactions they need to be kind of autonomously decided or at least flagged so that a human that actually works in the bank needs to spend less time actually looking at these things you know. So

[05:52] let’s go to the theory a little bit. What is the agent stack? Right? When we talk with an AI agent, we typically are talking with the application layer, right? Uh what we interact with either an an interface, a chatbot, an a mobile application etc. Then we have the model itself which is the reasoning core the the you know we don’t get any say in what the decisions are. Uh and then we have also the infrastructure that supports it all and then the compute.

[06:23] But what we are going to focus about today is the data part of it. And the data is very important because everything that we can manipulate and work around is on this part. The other parts we get less control over them, right? Especially if we’re using like a third party uh model that isn’t ours. So the data layer is what we focus about uh today, right? First of all, we have the agent loop and this is arguably one of the most important parts of an AI

[06:54] agent. Uh the agent loop is in charge of essentially driving the whole thing. Uh and it’s customizable as well. And inside the data, you also have like a gateway and MCP so that you can connect it to third party external data sources. You also have the memory layer which we will talk about later and essentially also some context engineering uh parts of it that let you automatically summarize and compact and shrink the working context window of a model

[07:27] and finally also some tools and skills uh which we can do some interesting and intelligent stuff so that we can essentially keep the context window limited. This is one of the main ideas of the workshop. Now, typically the applications that we interact with, they are either a combination of these four, right? LLM chatbots which are very easy. Lots of people just create an AI application, create a chatbot so that you can talk with it. You also have rag applications which is essentially like a glorified uh

[08:00] vector search. And then you also have LLM driven workflows and AI agents. And typically what most of us use uh by the way raise of hands who doesn’t use AI agents like cloud code etc of course uh so cloud codec etc all these systems are a combination of three and four which is um you know a combination of LLM driven workflows that provide automation and AI agents that provide autonomy. So it’s a combination

[08:30] of automation and autonomy and these are called agentic systems. The better systems like cloud code, codeex, spy, uh open claw, hermes agent etc. they are all a combination of these two types and most of the engineers that I talk to and this is important is that we use these systems every day, right? But we stop or a lot of people not a lot of people think about these problems when building their AI applications. So you might have an AI application but

[09:01] then you don’t consume it like this. And this is something that we’re going to focus on today because I think this is the better way of consuming um AI applications not only through chat bots, not only through rag applications but also through a combination of automation and autonomy. So what is an AI agent for those of you uh who don’t know? It’s a like a computational entity that is powered by an LLM by reasoning kind of like us humans we have our brain it’s

[09:32] augmented by a database for memory also like our brain it’s extended through tools for actions so the equivalent of a human would be like we have our extremities and we can interact with the world just like an AI agent can interact with an operating system through the tools that we give it they provide it and it’s also grounded in inputs. So for for instance it would be like our senses for a human our eyes etc that let us perceive information and the context like our attention is also limited like

[10:03] our agents we can’t watch seven movies at the same time like we will not understand any of the movies we will not focus on any of them so the context window for humans is similar to AI agents and kind of we try to assimilate or you know have some of these notions be closer to our human experience. experience and this is something that we’ll we’ll work on today. So the reasoning part of it uh is provided by the frontier labs and we don’t get a lot of control over

[10:35] that and then we also have the things that we do have a little bit more control over which are the memory the tool uses and the perception right and this is the the harness itself. A harness is essentially all the scaffolding that you need to do to build uh these three components which is the the tool use the memory and the perception and we’re not going to focus too much on the model because like I said we don’t have a lot of possibilities on what to

[11:07] do right so the harness is actually one of the most interesting topics in AI I think is the most interesting topic in AI nowadays because these harnesses actually control everything that the AI agent can do. You give it a different configuration then the agent the same LLM frontier AI model that you’re consuming becomes better or worse. Sometimes you know it’s been proven that by just changing the harness the same model performs better or worse for

[11:38] specific tasks. So it’s really really important to make focus on the harnesses and not a lot of people are doing this and like you said in a harness there are you know seven different or eight different components if you consider continue learning as well but there are lots of decisions that you need to make right you have the model you have the storage like where do you put the data uh you have some encoding and retrieval components like how do I make the distance between two vectors to actually retrieve the data properly

[12:09] uh what do I store in my memory? Do I think of it as short-term memory plus long-term memory kind of like humans have? Do I think of it in different uh compartments or different types of memory? uh also the semantic layer which is a part that’s really um interesting because as humans we are here and we have some context that we have never said to each other right but we are sharing this for instance I’m a speaker and you are listening you are not

[12:39] singing right now why are you not singing because it’s not appropriate in the semantics of the context that we are at right now right so the model itself also has access to the semantic layer which talks a little bit about all the things that haven’t been set to the model but they are assumed. Also the agent loop which is like all the things that drive and automatically and autonomously make the agent work all over uh again and this uh is like one of the most important parts and also

[13:10] context engineering and we’ll focus on each of them but I will not go d uh I will not deep dive into them because we’ll actually do that in the workshop. So just for reference um there was this big discussion around files versus databases like lot of people were saying we need to use files for everything like you just put everything into a file and then like magically one month later the agent becomes better. Some other people are database maximalists and they want to put everything into a database.

[13:41] Right? So this dilemma is still going on and I would say that um well let let me give you an example like can can anyone tell me in this example that you see on the screen can anyone tell me what is the workaround that agents use to solve uh this specific problem that you’re seeing on screen multiple agents writing to the same file. How does that work nowadays in AI agents? Any ideas?

[14:15] >> Work trees. Exactly. Good. So, work trees is the current solution, right? And this is a a thing or a workaround because files have an inherent problem in themselves, which is that they they like if multiple writes are coming into the same file, then you have problems with consistency like which right came first? If someone is reading, what do I do with this person that read the file before I modified it, etc. lots of problems, right? So for some things I will definitely tell you like files are

[14:46] great. Files are great at storing lots of unstructured data. Database on the other hand is also used for some other types of use cases. But my solution is that for some cases some of these uh solutions work with files, for some other cases they work with databases. So we actually um need to reconsider some of these things that are going on, right? Um, and the work tree uh solution or the workaround has been already solved by databases 30

[15:16] years ago. And we’re trying to reinvent the wheel with some of this. And we don’t actually need to reinvent anything because there is an actual solution to this. For example, if you’re trying to write to a file um at the same time multiple agents, if you had transactional consistency or acid consistency like atomic consistent isolated and durable um rights into the file, you would not get this issue. Right? So files are good for some things and

[15:46] databases are good for for other things. We don’t have to go into only one of them, right? So in the agent harness just consider this as an as a thought. Uh another component is the all the memory components right and this comprises all the mechanics and the the systems that are created around an AI agent to make it use the information um and not only use this information but also be able to

[16:16] refine it and recall it appropriately when it’s time right and agent memory you as the engineers you get to choose like what are the things in your agent memory layer that you’re going to consider. Some people like the short-term versus long-term memory. And in this case, this is part two. We have some short-term memory components. For example, if we are talking with clot or with codeex, we have short-term memory

[16:46] in the sense that the context window itself is short-term memory. Anything that disappears after the conver like it disappears after the conversation, right? most things uh in the context window just vanish. Then you launch another conversation and it starts from zero. That’s short-term memory. It’s very limited. We cannot put everything into it. And then we also have long-term memory. And inside the long-term memory, we also have some categories that we propose. Uh, for example, episodic memory would be all the things that

[17:18] happened, all the episodes of our conversations, all the tool logs, the previous conversations, um, summaries of previous conversations that you’ve had with the agent, etc. They all go into this episodic long-term memory category. You also have procedures or procedural memory, which are all the things like skills, workflows, which are like a sequence of skills that are being run etc. All of those go into procedural memory. And also we have semantic memory which is all the unset like I said the agent remembers who you are what are

[17:50] your preferences what’s your you know favorite framework etc all these things go into semantic memory so the problem the main issue here why cannot we put everything into the short-term memory because it’s limited and it’s not only limited but actually the bigger the attention matrix is and the attention matrix is essentially the the context window. The bigger it is, the worse it performs. And this happens for every

[18:20] model. There are lots of studies that have shown that if you start at zero tokens on the context window, the problem is being solved much more accurately than if you have 256,000 tokens already and the limit is a million right now. We’re at a million because of the KV cache. All these things need to be considered and just know that even if the advertised limit stops at uh 256k or 1 million if you keep going the like the performance goes

[18:50] horribly. So the smaller the context window is the better it will solve a problem. And this applies for every type of problem that you can think of uh in humanity right and there are two types of things that tackle this. One is context summarization which you just ask it hey just generate a summary a short summary for me with this uh with all the things that have been said in the context window and then you get the summary and then you start off from the summary the next conversation that is fine. Uh, another one is compaction and

[19:22] that’s kind of similar, but in compaction you’re just like putting chunks of the conversation into the database or into a file and then you just put it with an ID and if the AI agent needs it later, it has the ID. It just pulls from the ID with an offset kind of like reading from a file, right? Some of the these are some of the problems that happen in context uh context engineering. And then we have the agent loop which is the driver or the the car that that drives all the components that we have talked about. We

[19:53] have a context assembly part that pulls from the skills pulls from the tools pulls from the previous conversation from the files from the database. All of these things just brings in uh brings into the context window dynamically. Then it does some reasoning. it makes an API call to open AAI or whichever model you’re talking to and decides on what needs to be done and this happens you know automatically and infinitely if you want in my case in this agent loop that

[20:24] that uh we prepared for the workshop it has a maximum patience because I don’t want to run out of openi credits or any any credits that I that I have but uh yeah the the maximum number of iterations in our case will be eight and a maximum of 60 seconds of reasoning for each one of the iterations, right? Um, but this is completely configurable. Like I said, as engineers, we have to say in what goes on into the agent loop, right? And also the toolbox pattern, the

[20:56] skillbox pattern, what we propose for this for storing tools and skills, which are hundreds. I don’t know about you, but I have like a hundred skills already installed. I’m not putting a 100 skills at the same time into the context window because each skill is like 3,000 5,000 uh tokens. So that would automatically like go over the advertise limit in no time. I I would have no space for my actual conversation with the agent. So how do you fix that? Well, there are different ways, but what we propose is

[21:26] that you vectorize, you create vector embeddings out of the tools and out of the skills. And through those vector embeddings, once the agent loop, let me go back. Once the agent loop wants to retrieve some useful skills or tools, you’re going to do vector similarity search against this vector store that you have. You’re going to pull the most relevant skill or tool to solve it. You solve the problem and then you offload it again. And that’s one of the ways in which you uh keep the context window relevant in this in this sense. And you

[21:57] know using skills and using tools is a very very uh common pattern like everyone’s using tools like a bash command or a change directory all these are specific tools through bash right so we’re using tools and skills constantly this is for some cases more than 50% of the context window that’s being used right so I just want you to be mindful of the vast amount of context window size that is actually being kept by the skills and by the tools.

[22:30] Um we also have this idea called uh skill distillation where you take previous conversations, runs and you know actual like conversations that you’ve had with an AI agent and then you try to create something meaningful out of that. How do you do that? Well, you can do it in several ways, but one of the easiest ways that you can do it is just like create a skill MD and put it into the same skill box that you had everything before. And this is one of the ways like a Hermes agent, one of the

[23:02] innovators in this sense was creating skills that are particularly good to solve specific specific problems. Let’s say that you’re working on a front end. Well, if you’re working on front end, you might want to create a skill that has worked very well for you with all your preferences. Hey, I like this coloring style, etc. And the next time you work on the front end, since you have created vector embeddings out of this, you can just like the agent will automatically choose the more relevant skill. So if you just mention, hey, I

[23:33] like this coloring style that I had in this other skill, it’s automatically going to know that you’re referring to the new skill because you use the word uh coloring style for for instance, right? So skill like skill distillation is one of the techniques that that you can use to improve the the learning the learning of a model over time. And it’s the same uh this is uh related to what I what I was saying is that you have dynamic skill discovery in the sense that the agent loop when

[24:05] assembling or building the context will pull the right skills and the right tools when it needs and you know some people ask uh like how does a frozen model get better and what I mean by frozen is that we we don’t get any control over the frontier models right uh but we do get control over all the data the data layer of it right and some people say hey let’s modify the weights of the model some other people say let’s create an embedding model that works better for this specific problem

[24:36] and then I’ll worry about you know just retrieving the better embeddings there uh etc so there are different ways to do that but the idea is that this is the main component of continual learning and continual learning is one part of of of the things that you can do to make a mo model better. And there are three categories, right? You either work on the parametric memory. It’s called parametric because it modifies the parameters of the weights of the neural network. You also have representational

[25:08] memory which is what it works with embeddings etc. And you also have nonparametric memory which is everything that we have spoken about today until this point. But um if you’re interested in any of these three, we have focused on the third one. You also have the other two and I will not go into the uh into those two. There are lots of techniques like um you know creating low rank adaptation uh fine-tuning a model uh creating embeddings etc. And all these things you can find in that course

[25:39] that I I was referring to before which focuses on the three categories. So if you’re interested just take out uh take that course if uh or chat chat with us after after the session. So after the session, we’ll be in the event for the for the rest of the event too, right? And last thing I want to mention is that all of the things that happen during a chat completions API call to any uh OpenAI model or anything that you’re using is that there is an inherent uh

[26:10] instruction hierarchy. What do I mean by instruction hierarchy? There is a different weight on the things that are given to the model. For instance, what we use to interact with is the user, right? The request. In this sense, this is the third most important thing that we can pass to a model. The most important one is the system prompt, right? Everyone knows about this the system prompt concept. Um, and the system prompt is fine, but it cannot hold everything because otherwise things would not have a

[26:41] hierarchy in itself. uh you need to actually put some of the things in the system prompt, some of the things in the user prompt and all the tools and the skills that the things that are made available, they have this hierarchy. And this is good because it it’s it actually um lets us or lets the model focus more on some things than others and we’ll also go through that in the workshop. So just for reference uh this is the the UI of the workshop. So if you’re running it in code spaces already, you’ll see that

[27:12] you have uh this deployed. I will go through through it uh with you. But this is essentially the way in which I envision someone that works in AML like um a fraud detection system in a in a bank interacts with an an autonomous agent. The autonomous agent is running in the background 24/7. It doesn’t sleep. It doesn’t need any of the humanly uh necessities that we have, right? It’s connected through a harness to the to a database and it has all the

[27:44] functionalities that we have mentioned but on top of that uh it’s autonomously making decisions for the company even when you know we’re offline. It’s not ruining people’s lives by just like saying, “Hey, this this guy is suspicious. Let’s just like block the whole bank and everything, you know, because I would ruin ruin the person’s life, but rather it’s making these decisions and just like printing them so that a human can actually inspect them later on, but it’s going to save a lot

[28:14] of time during the, you know, the discovery process, etc. So by the end of the uh of the workshop, if you complete it, uh you’re going to be able to have an agent that connects to a database that is actually working as if it was uh any any company and it’s going to do autonomous analysis and decision making that then a human is going to take and interact with. So these are all the the components that we have talked about

[28:45] about the harness and without further ado I will uh put the QR code just again or workshopwaiting room.com um and if you want to check out any of the other workshops that we have uh you can just check out this GitHub repo we’re making a lot of uh progress and effort into all the things that go in there everything from workshops sessions uh notebooks So you can get started on different topics like agent harnesses etc. So just check it out. Uh and let me

[29:19] let me go to my Firefox and show you how this application works. So, first of all, let me just uh for those of you who didn’t receive an invitation, if you go to workshop waiting room.com, you will get an invitation via the GitHub API with your uh user to this repository. So, if you just go here and then open on GitHub code spaces, it’s going to ask you uh to create a code space. And of course, I’m paying for it, so don’t worry about

[29:50] that. uh just be careful with um with the hardware that you deploy because it’s expensive. But uh the idea is that you will get a a deployment like this with a couple of notebooks and I’ll show you the workshop itself and then my idea is for me to step down in a couple minutes and then we’ll go through the you know people who have questions etc and then we’ll solve it together. But it’s automat automatically also deploys

[30:22] this application which essentially is tracking all the things and this is of course uh fake data. Don’t worry I’m not exposing anyone here but it’s essentially coming up with new transactions. Some of them are fine some of them are uh problematic. So the autonomous agent which is a grog model running on OCI it’s essentially making autonomous decisions and some of them it’s saying hey this one is suspicious let’s add it to the list and then afterwards uh you also get like a way to

[30:54] visualize the context window of the agent here um you can also check out all the data that’s already in the database uh here uh like all the customers etc and also an autonomous way in which the agent is actually going to make an analysis of all this um of of all this in real time, right? So, it’s going to run through the tool calls that we give uh that we have available in our tool um in our toolbox.

[31:24] Uh yeah, it’s sorry, it’s a little small. Um you know, so it’s going to go through the evidence. It’s going to search for knowledge in the knowledge spaces that we created through vector stores. It’s going to make a lot of tool calls. And finally, it’s going to essentially go through the whole activity uh suspicious activity reports automatically. And here is just a fancy way of visualizing the 30 most recent um events that happen in the bank. But the workshop itself is this notebook, the notebook student.

[31:57] And what I want you to do is first of all just check out the different components that we have there because we are implementing them uh here. And I’m going to go through the first uh the first to-do. There are a couple of things that you need to do on the workshop just to confirm that that you know uh what you’re doing. So first of all, let me just go ahead and show you uh the first part of the workshop, right? Uh you have this rock model 4.3 uh which is running on on cloud Oracle

[32:28] cloud and let’s uh connect to the database of course. And after sorry, let me restart the kernel. Let me run this cell. Restart. But yeah, uh let let us know if you have any questions or issues uh when getting

[32:59] into the code space and then I’ll step down and and do this with you and answer any questions. Any questions by the way so far? Okay. Yes. Uh the the repo. >> Yes, you can find it on workshopwingroom.com. And let me just put the QR code here. Uh this QR code if you want to uh scan it.

[33:29] And this will automatically give you access to to it via GitHub API. Okay. So let me re uh reframe the question for the people who are on YouTube. Um so he’s asking about what happens with the episodic memory and all these memory components. Does it get it confused with previous conversations with a with an agent? Well, it depends on how much uh weight you give it. And this is why I was mentioning the instruction hierarchy as well. You might want to put this if

[33:59] it’s a really really important thing and you actually wanted to pull from some place or the other place. Uh you can actually decide your memory layer architecture yourself, right? So you might want to for instance in some cases where the episodic memory is really important and you actually want to pull from previous conversations you might actually want to vectorize that rather than just save it as raw text right depends a lot on the on the use case. I would say in this case it doesn’t uh it doesn’t there is no confliction there

[34:30] because we have a clear separation on the memory uh components of the architecture. Yes. So the the skills can be added to to the system prompt. uh they typically um oh sorry they typically have a different uh yeah in the instruction hierarchy they have the least weight out of the four uh if you were to think about it it um it’s typically here so it has the least weight I would think of it as a plugandplay place in which you can pull things and we are experimenting with

[35:02] this uh actually Richmond and I because we actually want to create a way in which you can plug into external internal or third party skill hubs and tool hubs for instance a collection of MCPS that you can give your agent availability by precomputing the embeddings of all of these things and once you have these precomputed embeddings you can just like say hey do vector searches against this third party uh group of skills or group of tools but rather than thinking of it as being

[35:33] included and by the way this is of course included in every open AAI or every chat completions API request that you’re making to open AAI or any other model. This is attached at the bottom and this typically is like 80% of it like 80% of the whole request is uh is is tools and skills. But what what happens or like why don’t you get charged like five times more than what you’re charged now is because uh OpenAI and all these systems they have a semantic cache and they put uh if 80% of

[36:07] it was the same as the previous request it doesn’t recomputee it just goes into the semantic cache and this allows you and this allows all of us to have um an a way in which to consume the Frontier Labs models in an economical way and of course it’s still very expensive. But what I want you to understand is that it would be four or five times more expensive if we didn’t have this semantic cache that just um puts the tools and these skills into it. Because in the response like remember that when

[36:39] you’re interact with interacting with a frontier AI model, you’re essentially making the whole thing through an HTTP request and everything like this would be for example 10K or 5K as a system prompt. you’re an AI assistant and then you need to help me solve this this and that. You have the developer like the specific app instructions, the user query which is what we type in the chat which is negligible like 100 tokens thousand tokens maybe and then the tool

[37:09] outputs and the the retrieve docs which is 80% of the request like 35 to 100,000 tokens is already this in every request. Does that answer your question? >> One last. >> Yes. >> Okay. So his question was like how do you manage the budget and since there are so many things in the skillbox and the toolbox patterns like how do you essentially make this work right um we have a clear separation the context window we think of it as or think of it as an n-dimensional matrix that starts

[37:42] at zero but it’s never zero it’s closer to like 10,000 I was reading a paper that was comparing the efficiency of each harness on how much they put into the first system prompt and the first uh completions API request at the beginning. Pi, you know, Pi, the harness, that’s the most minimalistic and the most efficient uh harness because it includes about 6,000 tokens at the beginning on every request. But if you go to other harnesses, they have more like 30 40,000 tokens. Um how do we

[38:16] we have a clear separation the context window? we just let the everything goes around the agent loop, right? So, let me go to the agent loop to show you uh one thing. The agent loop will control everything that it connects to, right? Um so here, for example, the agent loop. [snorts] Oh, I’m at the bottom. Hold on. Uh just as a reference um the agent loop.

[38:53] So here right uh the context assembly when you’re working with it uh you will essentially build and you can go through this in the in the notebook. explain the notebook but um the context assembly is one part that first of all we have a maximum number of defined uh tools or skills to retrieve I think the defi the default number is three uh so every time a new request is coming it’s determining and this is done

[39:24] by the model itself it’s determining what is the thing to do then it’s going to as try to assemble the context with the things that it needs to perform Right? And one of these things is retrieving the three most relevant tools, the three most relevant skills. And we are not using a reranker. But what you could also do is like at the at the end of uh the similarity search, you can also put an embedding model plus a reranker that will take those three and

[39:54] tell you out of these three, this is the most important one out of the three. And you could actually have a better refinement out of that because you you might not want to have a total of three skills loaded for every task. The task might be solvable by only one. Right? So the idea is that you can put uh whichever strategy you want just uh stick with it and uh stay consistent with it until the end. Uh so the idea in this case in the particular workshop is that we have a total number of uh vector

[40:25] searches that we’re doing against one vector store which holds the tools another vector store that holds the skills k equals three and then out of the three you can retrieve the most relevant one with a reranker and then it’s going to dispatch the tools of course and build a context window but this is entirely the decision and the job of the agent loop. Yep. Okay. So what is the most uh important or interesting way in which you you can

[40:55] interact with the memory layer of >> I mean the efficiency comes just from the number of entities that you create right so my first recommendation would be just like keep it simple uh so don’t create too many abstractions or too many components of the memory layer so for instance try to experiment first of all with only short-term memory and long-term memory and just have two structures Right? If you think or if you have an agent that considers that something that was in the short-term

[41:26] memory or in the context window is kept is is worth keeping, you promote it to the long-term memory and you just put it somewhere as raw text. That’s the easiest thing that you can do, right? Once you have it in text somewhere else in a long-term memory component or object, then you can take that vectorize it and then let it be explored by the agent loop in some way. So for instance, here you would just have like an extra thingy in the middle of observing and

[41:58] reasoning that lets the agent recall memories or something. You can call it like recall recall long-term memory. And this is going to make it uh be introspective before solving the problem once more. Uh, so it’s going to go to your vector store or whatever you have this long-term memory uh, episode that you recorded in a previous conversation and from that you can let it see okay I’m going to let it pull from it if it

[42:28] considers it to be interesting or if the vector similar like if the distance between the vector of the query and what I have in my long-term memory is relevant enough and the distance is small enough then I will consider it into the context window if it’s too big or it’s not relevant enough then I will just discard it so it will be like a different an additional abstraction between the observing and the reasoning part there are ways we are not doing MCPS right here but one of the benefits

[42:59] of of using MCPS would be to solve um I would say that MCP is not really that that relevant in this case um but it depends on what you have in the database so for example If you have a database, you’re interacting with a database like we are doing right here. Having an MCP is interesting, but one of the main problems that I like to say to people like what does an MCP solve, especially in the database, because I’m a database guy because I work in Oracle. Um, so one of the things that you can

[43:29] solve is letting AI agents make SQL queries, but by not hallucinating or trying to come up with a new SQL query every time. This is one of the bigger problems that that AI agents have with SQL. SQL has like 15 times like 15 engines like posgres, you have Oracle database, you have VSQL, you have like lots of different queries that work on SQL, but they have specific hints or subtleties in the query that makes it

[43:59] not not work well. Right? So the main problem that MCP solves in this case would be okay, I’m going to pre-create some SQL queries and then let the agents access those. So those queries are proven to work um rather than having an agent try to come up with a SQL query dynamically every time, right? Yep. Good question. Uh let me give you an example. So the most important thing would be the rapidness and that the meaning of the

[44:30] sentences and what the skill means itself. Uh rather than having it as text and if you were to store this just as text in a SQL file it would be able sorry in a in a file in the file system right in the operating system then you would have uh lots of ways in which an agent can do regular expression matching. So for instance, all the search would basically be either keyword search or like word search based uh into

[45:01] that skill which is fine. Um but the bigger that gets the less in like the the harder it gets for an agent. First of all, regular expression matching like GP is inefficient for huge files and sometimes if uh like the the file system grows and grows linearly, the performance of the regular expression matching decreases exponentially. Well, not exponentially, quadratically, let’s say just quadratically. But this is one of the problems um that it doesn’t scale as

[45:34] well as the size of the files. Uh, another one would be that if you premp compute the embeddings of a skill, you’re actually also capturing the meaning in these embeddings, the hidden meaning that we as humans don’t cannot comprehend. But rather than just describing it in text, which is fine for us to read, uh, it also has a premputation of 384 minimum to a,000 plus dimensions. And this embedding will actually hold uh things between each one

[46:07] of the tokens in the in the in the embedding matrix to be much more discoverable for instance by semantic search. And then this is what leads you to try hybrid search which is a combination of semantic searchs uh which is embeddings plus keyword search and and this is called RRF uh which is a type of hybrid retrieval. it performs much better because it will essentially just have both of them. Uh and it will essentially and this is uh we can I I

[46:38] can show you uh the example in the in the workshop because I I created this visual visualization here that explains exactly what I mean with hybrid search, right? Uh you see yeah so depending on the on the this essentially is a plot that uh combines the search capability of keyword search plus semantic search and this gap that you see at the middle is anything that’s that’s plotted here when doing hybrid search it will be more

[47:10] relevant than any of the other two. So uh as a summary uh the more like the more you can have two different types of of search. Each one has its advantages but if you combine them both you will uh effectively do a little bit more compute but then the quality of the retrieval will be better over time. Um these are like most of these I’m thinking of it from the AI agent perspective. So I’m not expecting anyone uh from this uh

[47:40] room to just like start building their own custom harnesses because we already have great uh solutions in the in the market right we have cloud code we have codeex each one has their own um preference by the way a show of hands for who likes pi okay less than I expected by but uh good so um I would say that I’m thinking of it as from the AI agent perspective. This what I want you to understand is that you can build custom harnesses for

[48:12] specific problems. And building custom harnesses doesn’t to be doesn’t have to be as sophisticated as creating the new clo the new clo code and then you’re running all of your work in that custom harness. Rather, let’s simplify the problems that you’re trying to solve and then build custom harnesses that attach on to onto that. So in this case I’m thinking of um you know if you’re a consultant you are my perfect uh use case or my perfect user for this workshop because you could be creating a

[48:43] custom harness that is working fine for a financial agent and has all the things that it needs to a financial uh use case. But then if you have another type of customer or with different types of data or with different types of constraints if you want to solve the next navir stocks problem or something uh you know those have different constraints for for instance the open AI problems the mathematical problems they need an infinite an automatic compaction or automatic context summarization because these agents don’t have any

[49:14] human in the loop in the middle. So the like everything that goes around solving these problems have to have by default automatic uh automatic context uh summarization. It also has to have infinite patience or near infinite patience. In this case this agent loop is simplified to only eight steps maximum. All these considerations right depends on the on the problem. Yeah, I would start from scratch because that way you can you get to uh strip 90% of

[49:44] what you don’t need. Um so I would definitely yeah I mean everything is built around the chat completions API and both Anthropic and OpenAI have created their own standards to fight off against this but everything goes around that API. So if you just think of uh the way to communicate with a model just as an additional plugin to the to the harness, it becomes much clearer that the smaller the everything is, the better it is at the end. Does that answer the question?

[50:14] All right. So let’s do uh this. You guys uh start with the code base um with a code space. just set that uh notebook uh by yourselves and then we’re gonna go I’m gonna go through and do a round and if anyone has any questions we can chat in a less uh aggressive way because I feel observed and you probably feel no pressure. So I’m going to put the pressure on you by stepping off and if you Yeah, let’s uh keep going. I mean we

[50:46] don’t have a lot of time. Oh my god. Um I time flew. Um but yeah. Yeah. Thank you. Thank you for the clap. Um thank you. Thank you. [applause] Uh so I thought like 15 minutes or 20 minutes went by, but one hour went by. So uh one thing uh so I’m going to leave I set this up so that you can create the code space in the hotel at home. You can I

[51:19] will pay for it myself. So you can, you know, use this workshop and and play with it as as you wish and I will pay for it. So don’t worry about it. Just um if you want to chat about some of the agent harness concept, just come to the Oracle booth. We’re going to be here until Wednesday evening. And thank you for coming to the to the session. Yeah. Okay. [applause]