Pular para o conteúdo

Dando aos agentes de IA uma memória que aprende — Jake Broekhuizen, LangChain

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: Giving AI Agents Memory That Learns — Jake Broekhuizen, LangChain · Canal: AI Engineer · 16:03 · Assistir no YouTube

Tópicos: Agentes de IA, Avaliação e benchmarks de IA, Engenharia de software com IA, Ferramentas de desenvolvimento com IA

Jake Broekhuizen apresenta uma abordagem para fazer agentes melhorarem ao longo do tempo, convertendo experiências registradas em contexto duradouro para execuções futuras. Ele distingue memória semântica, episódica e procedural, além de memória de curto prazo e de longo prazo, e descreve um ciclo de leitura, execução, filtragem de evidências e atualização da memória. Usando um agente de assistência financeira como exemplo, mostra como identificar desvios de tom e atualizar instruções para orientar interações futuras. Também destaca que a maioria dos registros deve continuar como histórico, que atualizações precisam estar disponíveis para execuções futuras e que mudanças em comportamentos importantes podem exigir revisão humana.

  • Memória é contexto duradouro que o agente pode consultar em execuções futuras; um registro só se torna memória quando uma lição é convertida nesse contexto.
  • A memória semântica abrange o que o agente sabe, a episódica registra o que ele vivenciou e a procedural orienta como deve se comportar.
  • A memória de curto prazo reúne o contexto usado na execução atual; a de longo prazo guarda informações que podem orientar execuções futuras.
  • O ciclo proposto lê contexto duradouro, executa o agente, analisa os registros, filtra o que é sinal útil e atualiza a memória.
  • Nem todo registro deve virar memória: a maior parte deve permanecer como histórico, e parte pode servir a conjuntos de dados para evals offline.
  • Atualizações precisam estar acessíveis às execuções futuras, inclusive em agentes de longa duração que usam cache ou estado de execução.
  • Mudanças em instruções, políticas e diretrizes de tom podem afetar muito o comportamento e, por isso, podem precisar de revisão humana antes de serem aplicadas.
  • LangSmith e o context hub da LangChain são apresentados como uma implementação do ciclo de captura, análise e armazenamento de contexto duradouro.
Início Capítulo Resumo
00:01 Por que agentes precisam de memória Jake apresenta o desafio de fazer agentes melhorarem com a experiência e usa um agente de assistência financeira para ilustrar desvios nas diretrizes de tom.
03:06 O que conta como memória A palestra diferencia registros de execução de contexto duradouro e apresenta as memórias semântica, episódica e procedural.
06:15 Memória de curto e longo prazo Jake explica a distinção entre o contexto da execução atual e a memória duradoura, e propõe um ciclo de leitura, execução e atualização.
09:50 Um ciclo de captura, análise e atualização O palestrante descreve como filtrar evidências e apresenta LangSmith e o context hub como uma implementação desse processo.
12:59 Cuidados ao atualizar a memória A palestra aborda o que deve permanecer como histórico, a disponibilidade das atualizações em execuções futuras e a importância da revisão humana.
15:31 A experiência melhora as próximas execuções Jake retoma a ideia central de que a memória transforma experiência em contexto e aponta para um vídeo com uma implementação prática.

Agentes observáveis mostram o que aconteceu. Agentes adaptáveis conseguem mudar e se orientar nas execuções seguintes. — 04:09

Só se torna memória quando essa lição é convertida em contexto duradouro que o agente pode consultar em execuções futuras. — 04:41

A memória informa a execução. A execução produz evidências. Filtramos essas evidências para obter sinais e usamos esses sinais para atualizar a memória. — 09:50

É mais do que um lugar para armazenar informações. É como a experiência se transforma em contexto. — 15:31

  • Jake Broekhuizen (pessoa): Líder da equipe de labs da LangChain que apresenta uma abordagem de memória para agentes.
  • LangChain (empresa): Empresa em que Jake Broekhuizen lidera a equipe de labs e que desenvolve as ferramentas descritas na palestra.
  • LangSmith (ferramenta): Produto apresentado como uma implementação para capturar trajetórias de agentes e analisar registros em busca de sinais úteis.
  • Context Hub (ferramenta): Repositório de contexto duradouro mencionado como destino de instruções, skills, políticas e regras para execuções futuras.
  • semantic memory (conceito): Categoria de memória que reúne o que o agente sabe, como fatos e preferências.
  • episodic memory (conceito): Categoria de memória que reúne experiências anteriores, padrões aprendidos, interações e exemplos.
  • procedural memory (conceito): Categoria de memória que orienta como o agente deve agir por meio de instruções, skills e regras.
  • working memory (conceito): Memória de curto prazo usada pelo agente durante a execução atual, incluindo resultados de ferramentas e arquivos recuperados.
  • long-term memory (conceito): Contexto duradouro armazenado para orientar execuções futuras do agente.
  • sleep-time compute (conceito): Processo de atualização ou recuperação de memória que pode ocorrer enquanto o agente trabalha ou está inativo.
  • Hermes Agent (modelo): Agente citado como exemplo de sistemas populares que realizam um processo de autoatualização.

00:01 [música] >> Testando. Ótimo. Bom dia a todos. Sei que é o último dia da conferência, então estou muito animado por vocês estarem aqui. Espero conseguir manter vocês envolvidos pelos próximos 15 a 18 minutos, mais ou menos. Meu nome é Jake e lidero a nossa equipe de labs aqui na LangChain. Hoje quero falar com

00:32 vocês sobre um tema sobre o qual tenho conversado bastante com a nossa equipe e com muitas equipes com quem falo, que estão criando agents: como dar memória aos seus agents. Seja você criando um agent de programação, um agent de suporte ou um agent de pesquisa, a maioria das equipes chega à mesma intuição geral: ele deveria melhorar de uma execução para a seguinte. Então, vou dar um exemplo para vocês acompanharem durante o restante desta palestra. Recentemente, a equipe de labs da LangChain tem trabalhado com uma

01:03 empresa do setor de serviços financeiros que está criando um agent para gastos, orçamento e aconselhamento não relacionado a investimentos. Dada a natureza altamente regulamentada do setor de serviços financeiros, é óbvio que vocês imaginariam que ele precisaria seguir diretrizes rígidas de tom. Portanto, a maneira como fala, seu vocabulário e a forma como interage com diferentes usuários são claramente o indicativo de que está seguindo e respeitando o tom correto. Ele deriva a maneira como gera

01:34 esse tom do contexto, das memórias e das referências que tem às regras e políticas. Dá para imaginar que, em certos contextos — e, na verdade, em alguns contextos que vivenciamos —, o tom dele poderia escapar do esperado. Assim, ele deixaria de ser prestativo e oferecer orientação para se tornar incisivo e diretivo, dizendo coisas como: “Pessoas em uma situação parecida com a sua geralmente estabelecem um limite”, e chegaria a dizer: “Bem, na verdade, parece que você precisa cancelar algumas assinaturas e transferir parte do dinheiro para a poupança.” A empresa com que estamos trabalhando

02:05 achou que isso era uma violação de tom, e também houve casos semelhantes. Para corrigir isso, o processo de revisão é manual. É preciso que alguém entenda os traces e identifique onde o tom dele escapou do esperado, faça alterações no contexto ao qual ele precisa recorrer para manter o tom e, depois, garanta também que não haja regressões. Obviamente, isso não escala — ou melhor, é difícil fazer escalar. Portanto, o sistema, ou o sistema ao redor do agent, deveria ser um espaço onde ele pudesse aprender continuamente e se beneficiar

02:35 das interações e experiências que tem. E é sobre essa versão de memória que quero falar hoje. Para chegar lá, quero começar com uma tensão que acho que muitas equipes já enfrentaram. Acho que todos nós aqui hoje estamos nesta conferência porque temos curiosidade e estamos criando agents. Acho que ficamos muito bons em observá-los, mas observá-los e transformar essas observações e experiências dos agents em lições para execuções futuras são coisas claramente muito diferentes. E é aí que a memória

03:06 E é aí que a memória entra em cena. Os agents estão produzindo mais sinais e traces do que nunca. Isso obviamente vai aumentar à medida que mais agents forem criados. Isso é ótimo para nós, porque cada execução produz um trace, e esse trace é armazenado em algum lugar. Isso é incrivelmente útil. Significa que podemos entender quais ferramentas foram chamadas, o raciocínio que o agent teve enquanto chegava à sua decisão e os artefatos aos quais recorreu. A observabilidade é, sem dúvida, uma base fundamental para criar agents muito confiáveis.

03:38 muito confiáveis. Mas acho que o verdadeiro desafio surge depois que o trace, o log ou a transcrição do que o agent fez é armazenado. Se o contexto futuro ao qual esse agent recorre nunca mudar, então uma skill ou instrução equivocada fará com que o erro que o agent comete hoje persista nas execuções futuras. O objetivo, ou o sistema pelo qual queremos trabalhar, é fazer com que um trace deixe de ser apenas um log e se torne uma fonte de sinais.

04:09 Memória. Agents observáveis mostram o que aconteceu. Agents adaptáveis conseguem mudar e orientar a si mesmos nas execuções seguintes. Então, mencionei memória. Acho que vai ajudar definir o que quero dizer quando falo em memória. É o contexto duradouro ao qual um agent recorre e que orienta execuções futuras. Um trace, uma transcrição ou um log é uma evidência do que aconteceu. Só se torna memória quando essa lição é convertida em contexto duradouro que o

04:41 agent pode consultar em execuções futuras. Agora, vocês veem seis coisas neste slide atrás de mim: fatos, preferências, padrões, exemplos anteriores, skills e instruções. Acho útil agrupá-las em três categorias distintas, uma taxonomia que tomamos emprestada da ciência cognitiva e que, na verdade, se aplica bastante quando falamos de agents baseados em linguagem. Primeiro, há aquilo que o agent sabe. Isso costuma ser chamado de memória semântica. Inclui coisas como

05:12 fatos e preferências que orientam a maneira como ele responde. Opa. Depois, há aquilo que o agent vivenciou. Essa é a memória episódica. São os padrões que ele aprendeu, as interações passadas e os exemplos. E, por fim, há como o agent deve se comportar. Isso também é conhecido como memória procedural. São as instruções, as skills que provavelmente são familiares a todos vocês e as regras que orientam como ele deve

05:43 se comportar. Na verdade, é na memória procedural que surgem a maioria dos ganhos visíveis. Então, no exemplo de assistência financeira que dei no início, as mudanças de tom que queríamos promover no agent e fazer com que ele seguisse vieram na forma de uma atualização da memória procedural. Não estávamos dando a ele um fato novo nem dizendo para não usar uma palavra inadequada. Estávamos dando a ele uma regra a seguir ao interagir com os usuários. Essa é a memória procedural que orienta o nosso agent.

06:15 Outra distinção que quero fazer — e que considero muito importante ao pensar no paradigma geral de memória de agents — é a separação entre memória de trabalho, ou memória de curto prazo, e memória de longo prazo. A memória de trabalho é aquilo a que o agent recorre durante a execução atual. Isso pode incluir rascunhos intermediários. Pode incluir resultados de ferramentas. Pode incluir os arquivos recuperados como parte da operação. Tudo de que ele precisa para realizar a tarefa atual. A memória de longo prazo é aquilo que existe

06:45 normalmente em alguma estrutura de dados ou em algum armazenamento separado e que contém instruções, skills e coisas às quais ele precisa recorrer em interações futuras e para manter um comportamento contínuo. Diferentes agent harnesses vão usar e inserir a memória de longo prazo de maneiras distintas, seja você criando seu próprio SDK ou usando vários frameworks populares para agents. Alguns a inserem diretamente no prompt. Alguns usam ferramentas para recuperá-la. Alguns a obtêm diretamente de um armazenamento.

07:17 Alguns a carregam por meio de arquivos, e outros alteram o estado em tempo de execução. A implementação pode variar, mas essa distinção é realmente importante. Parte da memória, ou do contexto ao qual um agent recorre, é temporária, enquanto outra parte é duradoura, de longo prazo, e útil para orientar execuções futuras. E acho que essa distinção é muito importante quando pensamos nos traces, logs e artefatos que o agent produz durante a execução. Um trace não é apenas um registro do resultado final. É um registro de como a nossa memória de trabalho

07:47 mudou ao longo da execução. Parte disso deve permanecer como histórico. Outra parte deve se tornar contexto duradouro de longo prazo. E é isso que dá — ah, é isso que proporciona — esse modelo mental muito útil que tenho, ou que eu, a equipe da LangChain e, de modo geral, acho que todos consideramos muito útil para pensar na relação entre memória de trabalho, ou de curto prazo, e memória de longo prazo. É um ciclo de leitura e escrita.

08:18 Então, talvez você já tenha ouvido falar de computação durante o sono ou de dreaming. Esses termos se referem à forma como a memória é atualizada ou como informações são recuperadas da memória de longo prazo para a memória de curto prazo enquanto o agent está trabalhando ou, em alguns casos, enquanto também não está trabalhando. Isso é a computação durante o sono. Se começarmos pelo início de uma execução do agent, ele precisa ler o contexto relevante da memória de longo prazo para a memória de curto prazo. Então, isso inclui qualquer coisa importante para a execução atual que ele tenha. Pode ser…

08:48 skills, pode ser instruções. Provavelmente você já viu divulgação progressiva com agents que buscam as skills relevantes para uma determinada tarefa. Essa é a fase em que as informações passam da memória de longo prazo para a memória de curto prazo. Depois, quando o agent é executado, ele produz um rastro. Essas evidências são muito importantes para nós, porque agora podemos entender como ele recupera o contexto, as chamadas de ferramentas que fez, as decisões que tomou, os subagents ou qualquer coisa que faça parte do trabalho dele. Como mencionei, a maior parte das evidências deve permanecer como histórico. Se transformássemos tudo…

09:19 que veio de… Se transformássemos todas essas evidências em memória de longo prazo, o agent teria dificuldades e ficaria mais difícil para ele raciocinar sobre tarefas futuras. Então, o que eu acho realmente interessante é a etapa de filtragem. Como decidir o que é um sinal útil e o que deve se tornar contexto durável de longo prazo? E como decidir o que deve permanecer como histórico? Depois de tomar essa decisão — e vamos falar disso daqui a pouco —, esse sinal é então gravado de volta no contexto durável de longo prazo. Então, no caso do nosso assistente financeiro…

09:50 isso seria medido, não apontado nem diretivo, para que ele possa atualizar a forma como se comporta em interações futuras. Esse é o ciclo central. A memória informa a execução. A execução gera evidências. Filtramos essas evidências para obter sinais e, então, usamos esses sinais para atualizar a memória. Se você conseguir construir esse ciclo virtuoso, tenderemos a chegar a um ponto em que poderemos criar agents muito confiáveis e poderosos — poderosos mesmo — que simplesmente parecem melhorar com o tempo. E, uma vez que temos esse modelo mental, acho que uma forma ainda mais simples…

10:21 de resumir isso, ou de abstrair os detalhes, é dizer que capturamos o que aconteceu, analisamos o que pode ser importante e, então, atualizamos o contexto para que execuções futuras possam usar essas informações. As implementações de diferentes pessoas que criam diferentes frameworks ainda estão evoluindo, mas essa estrutura de três partes é um ponto de partida muito útil. Uma implementação disso — e não vou afirmar que seja a única —, só para dar uma estrutura concreta…

10:51 ao que estou falando, é a forma como fazemos isso com LangSmith. A etapa de captura, que permite entender e observar a trajetória e as ações do agent, é onde entra nossa observabilidade. Você consegue ver as chamadas de ferramentas. Consegue ver como os agents chamaram subagents. Consegue ver o contexto que foi recuperado. A etapa de análise, no meio, é algo novo que me deixa muito animado. Basicamente, é um processo inteligente que faz a análise e o trabalho em segundo plano para extrair sinais dos rastros com base no que importa…

11:22 para você e, em seguida, promover esse sinal para o armazenamento de memória ou para o ponto de referência que o agent usará em execuções futuras. Esse é o context hub do LangSmith. Imagine, então, que exista um lugar onde essa análise possa ser feita, onde os sinais possam ser extraídos e onde haja um armazenamento remoto que você possa atualizar, para que o agent possa buscar essas informações na próxima execução. É isso que o context hub do LangChain faz. E ele se encaixa perfeitamente no ciclo abstrato: você captura a experiência, extrai o sinal…

11:53 e, então, armazena esse contexto durável para execuções futuras. Para detalhar um pouco mais e também enquadrar isso no contexto do assistente financeiro de que falei no início, bem como na forma como construímos esse ciclo: quando o agent é executado, seu contexto é carregado do context hub. Isso pode incluir instruções, skills, arquivos Markdown relevantes, políticas e regras. Quando ele funciona — ou quando o invocamos —, é produzido um rastro que…

12:26 nos mostra as chamadas de ferramentas que falharam, as correções dos usuários ou, neste caso, sinaliza quando nosso tom se desviou do que queríamos. O Engine então procura padrões e identifica quais arquivos Markdown estáticos de skills, armazenados no context hub, precisam ser alterados ou promovidos, e faz essa alteração. Na próxima execução do agent, conseguimos entender e observar que o tom dele muda quando interage com os usuários.

12:59 Então, algumas coisas em que eu e minha equipe pensamos atualmente — ou estamos sempre pensando — ao projetar memória, e que idealmente também devem orientar a forma como você projeta e cria algumas dessas abstrações, são que os agents produzem muita coisa. Chamamos isso de resíduos ou, de certa forma, de feedback. Nem tudo deve se tornar uma atualização de memória. Na verdade, os detalhes fazem toda a diferença na hora de decidir o que deve se tornar uma, como discutimos ao longo desta apresentação. O importante é entender e decidir o que importa para você. Sabe, a maior parte dos dados dos rastros…

13:30 na verdade, deve permanecer como histórico consultável. Algumas partes podem se tornar conjuntos de dados para evals offline e coisas do tipo. Apenas uma pequena parte disso — ou um subconjunto — deve acabar alterando a memória do agent. A segunda questão é uma espécie de armadilha em que caí muitas vezes, e acho que é uma linha tênue: tentar criar um sistema otimizado, mas que também tenha um armazenamento de memória ou atualizações disponíveis no caminho crítico. E o que descobri foi…

14:00 Isso é especialmente relevante para agents que executam tarefas em segundo plano por longos períodos, certo? Imagine que você tenha um agent que funciona por períodos prolongados e faça algumas atualizações de memória no início da operação dele. Mas, por causa do estado em tempo de execução e da forma como ele acessa a memória, ele talvez não acesse essas atualizações, ou elas talvez não estejam disponíveis para execuções futuras. Então, é muito importante entender o que pode ou não ser armazenado em cache, para garantir que as atualizações de memória estejam disponíveis em execuções futuras. Fiquei batendo a cabeça na parede por um tempo, tentando entender por que meu comportamento não estava…

14:31 mudando. Eu precisava reconhecer e levar em conta esse segundo princípio. E também o terceiro. Acho que open core, o Hermes agent e muitos agents que estão se tornando populares e fazem esse processo de autoatualização levantam uma consideração muito importante: o que você permite que seja atualizado automaticamente e o que exige revisão humana? Se estamos falando de memória procedural, com instruções, políticas e diretrizes de tom, elas provavelmente vão…

15:01 determinar cerca de 75% do comportamento do meu agent. Então, provavelmente deveria haver algum nível de participação humana e interação humana nesse processo. Você deve ter um lugar onde possa apresentar as alterações feitas nas partes procedurais da memória do agent, antes de efetivamente confirmá-las e colocá-las no caminho de atualização a quente do agent. Proteger comportamentos importantes com a… acho que esse é outro terceiro nível muito importante, que considero essencial. Então, vou voltar a essa…

15:31 ideia inicial: a próxima execução deve ser melhor. A memória nos permite fazer isso. A palavra memória é usada o tempo todo. Acho que, no contexto de criar agents, trabalhar com harnesses e fornecer contexto ao agent, a memória realmente nos dá a capacidade de fazer isso. E é mais do que apenas um lugar para armazenar informações. É a forma como a experiência se transforma em contexto. E é esse contexto que dá às próximas execuções a oportunidade de melhorar. Se você tiver curiosidade sobre uma implementação concreta disso, aliás, essa…

16:03 O código QR leva a um vídeo em que explico como construí um agent que faz exatamente o que acabei de descrever. Espero que isso ajude a tornar a ideia mais concreta e a ligar alguns desses pontos. E, se quiser conversar mais sobre isso, venha falar comigo. Estamos no estande Eugene 19. Eu adoraria

Transcrição original

[00:01] [music] >> Testing. Awesome. Good morning everybody. Uh I know it’s the last day of the conference, so super excited to have you here. Hopefully hopefully I can keep you engaged for the next uh 15 to 18 minutes or so. My name’s Jake and I lead our labs team here at LangChain. And today I want to talk to

[00:32] you about a topic that I have uh been speaking a lot about with with our team and and with a lot of teams that I speak with who are building agents, and that’s how to give your agents memory. Whether you’re building a coding agent, a support agent, a uh a research agent, most teams arrive at the general same instinct that it should get better from one run to the next. So, let me give you an example to hold onto for the rest of this talk today. Recently my my the the labs team at LangChain have been working with a

[01:03] company in the financial services sector who’s building a uh spending, budgeting, and non-investment advice agent. Given the highly regulated nature of the financial services sector, obviously you would imagine that it would need to follow some strict tone guidelines. And so, the way that it speaks and and the and its vocabulary and the way that it interacts with different users is obviously the the tell on whether or not it’s following and abiding by the correct tone. It will derive the way that it generates

[01:34] this tone from the context and from the memories and from the references that it has to its rules and policies. And you can imagine in some contexts, and actually in some contexts that we experience, its tone would slip. And so, it would move from being advisory and helpful to actually pointed and directive, saying things like users in your similar situation would generally set a cap and it would actually say, “Oh, well, actually it looks like you need to cancel some subscriptions and move some money into savings.” The company that we’re working

[02:05] with thought that this is a violation of tone and there were similar instances of this, too. And so, to correct that, the review process is manual. You have to have someone understand the traces and understand where its tone slipped, make those changes to the context that it needs to reference when it’s giving its tone, and then make sure that there are no regressions, as well. Obviously, that that doesn’t scale, or rather it’s challenging to scale. And so, the system should be or or the system around the agent should be a place where it can continuously learn and benefit

[02:35] from its interactions and its experiences. And that’s the version of memory that I want to talk about today. To get there, I want to start with a tension that I think a lot of teams have run into. I think all of us here today, the reason why we’re at this conference is we’re curious, we’re building agents. I think we’ve gotten very good at observing them, but observing them and then turning those observations and those agent experiences into lessons for future runs are obviously very different things. And so, that’s where memory

[03:06] And so, that’s where memory comes into play. Agents are producing more signal and more traces than ever before. And this is going to be something that’s obviously that will obviously increase as more agents are built. That’s fantastic for us because every run produces a trace and that trace is stored somewhere. That’s incredibly useful. It means that we can understand the tools that were called, the reasoning that the agent made as it was on its way to making its decision, the artifacts that it referenced. Observability is obviously a critical foundation for building very reliable

[03:38] very reliable agents. But I think the challenge really is after the trace is stored or after the log or after the transcript of what the agent did is stored. If the future context that that agent references never changes, then a misguided skill or instruction will mean that the agent The mistake that the agent makes today will still persist in future runs. The goal or the system that we want to work towards is where a trace stops just being a log and becomes a source of signal.

[04:09] Memory. Agents that are observable tell you what happened. Agents that are adaptive are able to change are able to change and guide themselves on the following runs. So, I’ve mentioned memory. I think it will really help to sort of define what I mean when I say memory. It’s the durable context that an agent references that will guide future runs. A trace, a transcript, or a log is evidence of what happened. It only becomes memory when that lesson is converted into durable context the

[04:41] agent can reference on future runs. Now, you’ll see six things on this slide behind me. Facts, preferences, patterns, previous examples, skills, and instructions. I think that it’s helpful to group them into three distinct buckets, a taxonomy that we borrow from cognitive science, and actually that applies a lot when we’re talking about agents that are language-based. First, there’s what the agent knows. This is often referred to as semantic memory. This includes things like the

[05:12] facts and the preferences that guide the way that it responds. Oops. Then there’s the Then there’s what the agent has experienced. This is the episodic memory. This is the learned patterns that it’s seen, past interactions, and examples. And finally, there’s how the agent should behave. This is also known as procedural memory. And that’s the instructions, the skills that you’re all probably very familiar with, and the rules that guide how it should

[05:43] how it should behave. Procedural memory is where actually most of the visible gains come from. So, in that financial assistance that I the example that I gave at the beginning, tone changes that we wanted to to promote to the agent and and make it follow came in the form of updating its procedural memory. We weren’t giving it a new fact or we weren’t telling it not to use a bad word. We were giving it a rule to follow as it engages with its users. That’s the procedural memory that guides our agent.

[06:15] Another distinction that that I want to make and I think this is very important when thinking about the general agent agent memory paradigm is the separation between working memory or short-term memory and long-term memory. Working memory is what the agent is referencing in its current run. So, these might be things like intermediate scratch pads. It might be tool results. It might be the files retrieved as part of its operation. Everything that it needs to do to perform its current job. Long-term memory is what exists

[06:45] typically in some data structure or some store somewhere else that has instructions and skills and things that it needs to reference as part of future turns and and continuous behavior. Different agent harnesses will leverage and inject long-term memory in different ways, whether you’re building your own SDK or or using a variety of different popular agent frameworks. Some inject it directly into the prompt. Some will use tools to retrieve that. Some will Some will pull it directly from a store.

[07:17] Some load it through files or some change the run time state. The The implementation can vary, but the distinction is really important. Some of the memory or some of the context that an agent references is temporary while some of it is durable and long-term and is useful to guide future runs. And I think that distinction is really important when we think about traces and logs and artifacts that the agent produces as it runs. A trace isn’t just a record of the final output. It’s a record of how our working

[07:47] memory changed over the course of the run. Some part of that should stay as history. Some part of that should become durable long-term context. And so that’s what gives Oh, that’s what lends itself to this really helpful mental model that I have or that I and and the team at LangChain and generally I think is is a very useful way to sort of think about the relationship between working or short-term memory and long-term memory. It’s a read-write cycle.

[08:18] And so you might have heard of sleep-time compute or dreaming. Those terms refer to the way that memory is updated or pulled from long-term into short-term whilst the agent is doing work or actually in some cases whilst the agent is also not doing work. That’s the sleep-time compute. If we start somewhere at the beginning of an agent run, it needs to read relevant context from long-term memory into its short-term memory. So this is anything This is anything important for the current run that it has It might be

[08:48] skills, it might be instructions. You’ve probably seen progressive disclosure with agents that actually pull in the relevant skills for a certain task. That’s that phase moving from long-term memory into short-term memory. Then when the agent runs, it produces a trace. This evidence is really important to us because now we can understand how it retrieves context, the the tool calls that it made or the decisions or the sub-agents or anything that’s part of its working job. As I mentioned, most evidence should stay as history. If we turned everything

[09:19] that was from a If we turned all of that evidence into long-term memory, then it would make the agent struggle and it would make it harder to reason over future tasks. And so what I think is really interesting is the filter step. How do you decide How do you decide what is useful signal and what should become durable long-term context and how do you decide what should stay as history. Once you’ve made that decision and we’ll get into that in a moment. Once you’ve made that decision, that is that signal is then written back into durable long-term context. So, in the case of our financial

[09:50] assistant, that was be measured and not pointed or not directive, so that it can update the way that it behaves on future turns. And that’s the core loop. Memory informs the run. The run makes the evidence. We filter that evidence to make signal, and then we use that signal to update memory. If you can build that flywheel, then we trend towards a place where we can build very reliable and very powerful powerful agents that just feel like they get better with time. And so, once we have that mental model, I think, you know, an even more simple

[10:21] way to break this down or to to abstract this away is is capturing what happened, analyzing what might matter, and then updating the context so that future runs can use this. The implementations around how different how how different people building different frameworks are still evolving, but this three-part shape is a really useful starting point. One implementation of this, and I won’t I won’t claim it’s the only implementation, but just as just a kind of like put some concrete structure to

[10:51] what I’m talking about is the way that we do this with LangSmith. The capture step, to be able to understand and see the trajectory and the things that the agent did, is where our observability comes in. You’re able to see the tool calls. You’re you’re able to see the way that the agents called sub-agents. You’re you’re able to see the context that was retrieved. The analyze step in the middle is something new that I’m really excited about, but basically, it is that intelligent process that’s doing the background analysis and doing the background work to extract signal from traces based on the things that matter

[11:22] to you, and then promoting that signal to the memory store or the point of reference that the agent will use for future runs, and that is LangSmith’s context hub. So, you can imagine now if there is a place where this analysis can be done, signal can be in track extracted, a remote store where you can now go and update what’s in that so that the agent can pull that down the next time it runs. That is what LangChain’s context hub does. And the abstract loop it maps cleanly. You capture the experience, you extract the signal,

[11:53] and then you store that durable context for future runs. To kind of put that in some more detail and and also to frame it in the in the the context of the financial assistant that I was speaking about at the beginning and and sort of the way that we we built this loop. When that agent runs, its context is loaded from the context hub and so that might include its instructions, its skills, relevant markdown files that matter to it, policies, and rules. When it functions or when we invoke that agent, then the a trace is produced that

[12:26] shows us the the uh failed tool calls or user corrections or in this case it flagged where our tone strayed from what we wanted it to be. Engine then looks for patterns and then identifies where different static skill markdown files that are based in context hub need to be changed or promoted, and it’ll make that change. And then the next time our agent runs, we’re able to actually go and and understand and see that its tone changes when it interacts with engages with users.

[12:59] So, some things that I and my team have currently uh or kind of always think about when when designing memory and and this should also as well ideally guide the the way that you design and build some of these abstractions is that agents produce so much we call it exhaust or we call it kind of like feedback. Not everything should become a memory update. And actually the devil is in the details around what should become one as as we’ve sort of discussed over the course of this presentation. It’s understanding and deciding what matters to you. You know, most trace

[13:30] data actually should stay as history as referencable history. Some some might become data sets to do offline evaluations and things like that. A small a small segment of that or or subset should end up becoming what changes your agent’s memory. Now, this second one is sort of like a gotcha that I I ran into a lot and I think that you sort of tread the fine line of trying to build a system that’s optimized, but then also one that has a memory store or updates available to it in the hot path. And what I found was

[14:00] uh for particularly for long-running background agents, right? Imagine if you have an agent that’s running over long time horizons and you make some memory updates in the beginning of its operation, but because of the run time state and because of the way that it’s accessing memory, you don’t actually access that or that’s not available to it for future runs. And so, you know, understanding what you can cache, what you can’t cache to be able to make sure that memory updates are available for future runs, very important uh and sort of I was I was banging my head on a wall for a while while while I was trying to sort of understand why my behavior wasn’t

[14:31] changing and I needed to recognize and think about that second principle. And then the third one as well. I think that uh open core and uh you know, Hermes agent and and a lot of agents that are uh becoming widely popular that sort of do this self-update process, right? I think that it’s another really important consideration of like what do you make self-updateable as opposed to what do you make something that needs human review? And so, if we’re talking about procedural memory with instructions and policies and tone guidelines, those are probably going to

[15:01] drive about 75% of the behavior of my agent. And so, that actually probably should have some level of human in the loop and human interaction. You should have somewhere to surface it. The changes that you make to the parts of the agent’s memory that are procedural before actually committing those and and putting those in the in the in the agent’s sort of like hot reload path. So, protecting important behavior with the is, I guess, another really important third third kind of like level to this that I find really important. So, I’m going to come back to this

[15:31] initial refrain. The next run should be better. Memory allows us to do this. The word memory is thrown around a lot. I think in the context of building agents and working with harnesses and working with like providing context to your agent, memory really does give us the ability to do this. And it’s more than just a place to store information. It’s how experience becomes context. And then that context is how our next runs get the chance to improve. If you’re curious about an actual implementation of this, by the way, that

[16:03] QR code has a video of me walking through how I built an agent that does exactly what I’ve just described. Uh hopefully that’ll kind of like make it tangible and and will sort of connect some of those dots. Uh and if you want to have any further discussions about this, please come and see me. We’re at booth Eugene 19. Uh I’d love to