Deixe seu agent fazer a própria engenharia de harness (veja como)
Autoria: Cole Medin · 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: Let Your AI Agent Do ITS OWN Harness Engineering (Here’s How) · Canal: Cole Medin · 16:00 · Assistir no YouTube
Tópicos: Agentes de IA, Automação de tarefas e workflows, Engenharia de software com IA
O vídeo mostra como aplicar práticas de engenharia de harness de coding agents a agents de produção, usando regras, skills e workflows em arquivos Markdown. São apresentados dois ciclos de melhoria: registrar lições a partir de incertezas e correções humanas, e analisar traces de produção para propor mudanças nas instruções. Em uma demonstração de help desk, o agent aprende com uma correção e usa essa lição para responder a um caso semelhante. As melhorias continuam sob aprovação humana, com histórico de alterações e possibilidade de reversão.
Pontos-chave
Seção intitulada “Pontos-chave”- Práticas de engenharia de harness usadas em coding agents também podem tornar mais confiáveis os agents de produção.
- Regras, instruções, skills, memórias e guardrails podem ser organizados em arquivos Markdown e conectados pela plataforma.
- O primeiro ciclo de melhoria registra incertezas, encaminha casos à equipe humana e transforma correções em memórias reutilizáveis.
- Memórias por usuário são mantidas separadas das lições compartilhadas, e a recuperação evita inserir todo o conhecimento no contexto a cada conversa.
- O segundo ciclo analisa traces e falhas de produção para sugerir alterações nas instruções e no harness.
- As sugestões de alteração devem ser revisadas e aprovadas por uma pessoa antes de chegar ao agent de produção.
- O histórico de versões permite examinar commits, promover versões e reverter mudanças.
- Na demonstração, o agent passou de 4 respostas corretas em 14 para 13 em 14 após o processo de aprendizagem.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:00 | Engenharia de harness para agents de produção | O vídeo apresenta a ideia de transferir práticas de coding agents para agents de automação e negócios. |
| 03:34 | Definição do agent com arquivos Markdown | Cole Medin mostra como regras, skills, guardrails e ferramentas são reunidos com uma definição de código enxuta. |
| 05:40 | Primeiro ciclo: memórias e correções humanas | O agent reconhece incertezas, encaminha casos à equipe e registra as respostas corrigidas como lições. |
| 07:43 | Demonstração do help desk | Uma correção sobre o workflow Arcan é salva e ajuda o agent a responder com confiança a uma situação semelhante. |
| 11:50 | Segundo ciclo: melhorar instruções com traces | O LangSmith engine analisa falhas e traces para propor mudanças que uma pessoa pode revisar e aprovar. |
| 14:25 | Versões, resultados e controle humano | O vídeo mostra o histórico de alterações, a possibilidade de reversão e a melhora de 4 para 13 respostas corretas em 14. |
Citações
Seção intitulada “Citações”acompanhar todos os erros que seu agent comete em produção — 00:30
Então, vou dar a resposta certa desta vez. — 06:10
Ainda precisamos estar no ciclo, aprovando as mudanças. — 13:22
Engenharia de harness não é um trabalho de uma só vez. — 15:28
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- Harness Engineering (conceito): Processo iterativo de melhorar as regras, os workflows e outros componentes ao redor do modelo com base em erros e dados de uso.
- LangChain (empresa): Empresa cuja plataforma é usada na demonstração para construir e gerenciar agents de produção.
- LangSmith (ferramenta): Plataforma usada para acompanhar traces e métricas e apoiar a análise de falhas e as melhorias do harness.
- Managed Deep Agents (ferramenta): Plataforma gerenciada apresentada para definir, empacotar e implantar agents com regras, skills e outros componentes.
- Context Hub (conceito): Repositório de memórias e lições que o agent pode recuperar quando situações relevantes voltam a ocorrer.
- human-in-the-loop (conceito): Abordagem em que uma pessoa analisa incertezas e aprova mudanças propostas antes que sejam aplicadas.
- Cole Medin (pessoa): Criador do vídeo que apresenta a demonstração de engenharia de harness para agents de produção.
- Arcan (ferramenta): Workflow mencionado na demonstração, usado como exemplo em dúvidas de suporte sobre execuções e commits.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:00 Então, este ano, no meu canal do YouTube, tenho me concentrado principalmente em agents de IA para programação. Mas o que muita gente não percebe, talvez até você, é que muitas dessas estratégias para tornar nossos agents de programação mais confiáveis com o tempo também se aplicam muito bem a outros tipos de agents de IA que colocamos em produção para automação e casos de uso empresariais. E uma dessas grandes ideias é a engenharia de harness: melhorar, com o tempo, tudo o que envolve o modelo, como as regras e os workflows. Agora, sobre
00:30 como fazer o agent melhorar com o tempo: o que quero dizer especificamente aqui com engenharia de harness é acompanhar todos os erros que seu agent comete em produção e, depois, voltar a eles para conversar com o agent e descobrir o que devemos melhorar nas regras e skills para que esses erros não aconteçam de novo. Ensino isso o tempo todo com engenharia de harness para agents de programação e, na verdade, é a mesma coisa com seus agents em produção. E o interessante é que isso se aplica ainda melhor do que você imaginaria, porque hoje em dia a maioria dos agents de produção é construída exatamente
01:01 como os agents de programação: gerenciamos todo o harness com bastante Markdown. Isso mantém tudo muito flexível. O jeito, digamos, antigo de fazer as coisas com agents envolvia muito mais código diretamente na infraestrutura, como criar nossas funções em Python e TypeScript para as ferramentas, por exemplo. Mas agora temos nossas skills em Markdown, nossas regras globais, como as instruções em um arquivo MD, e nossas memórias. Isso deve parecer bem familiar. É uma configuração de harness muito parecida com a de um agent de programação. E essa correspondência funciona tão bem que todos os componentes da engenharia de agents no nosso harness têm uma
01:31 correspondência direta com os agents em produção. Por exemplo, temos nossas regras, que, para um agent tradicional, são exatamente a mesma coisa que um system prompt. Temos nossos subagents, que correspondem aos workflows multiagente, em que fazemos qualquer tipo de delegação. Temos ferramentas MCP para nossas conexões. As skills são nossos workflows, substituindo muitas das ferramentas tradicionais. E temos hooks para nossas proteções. Se você quiser monitorar ou bloquear ações em cada chamada de ferramenta, ou no início ou no fim das conversas, temos nossas proteções para isso. Então, hoje, não vou apenas
02:02 mostrar um exemplo de como montar esse harness, mas também como melhorá-lo com o tempo usando nossos dois ciclos principais. Temos a memória principal do agent e também o aprimoramento retroativo, examinando os traces enquanto monitoramos o agent em produção, conversando com usuários reais. Essa é a maior mina de ouro de informações que não podemos ignorar. A maioria das pessoas ignora. Então vamos falar de tudo isso, mas também quero mostrar, em alto nível, como construir um agent que adota o harness de um agent de programação. Porque, ao criar nossos documentos Markdown para nossas skills, regras
02:33 e todo o resto, precisamos de algum tipo de sistema que realmente reúna tudo e conecte os componentes quando colocamos o agent em produção. Para essa plataforma, você pode criá-la por conta própria, se quiser gerenciar seu próprio deploy e os pipelines de engenharia de harness. Não há problema nenhum. Mas, muitas vezes, é mais prático usar uma plataforma que faça esse gerenciamento por você. Por isso, em todas estas demonstrações, vou usar os deep agents gerenciados da LangChain, que configuram tudo isso para nós no LangSmith. Já vi isso funcionar repetidas vezes em produção. E, à medida que avançarmos, você verá como isso é bastante universal. Todas as
03:04 estratégias se aplicam, não importa como você esteja criando esses agents. E um agradecimento rápido à LangChain por trabalhar comigo neste vídeo. Já estava na hora de colaborar com eles, porque uso o tempo todo as plataformas deles, como os deep agents gerenciados. E, para relembrar rapidinho, este foi um dos primeiros vídeos que publiquei no meu canal do YouTube, há mais de dois anos, quando comecei a criar conteúdo. Eu estava criando agents de IA, programando-os à mão com a LangChain como framework. Por isso, ela sempre teve um lugar especial no meu coração. Continuo usando a LangChain porque ela sempre
03:34 esteve na vanguarda, especialmente agora, com os deep agents gerenciados, que ajudam você a colocar seus agents em produção no estilo dos agents de programação. Outra coisa que eles oferecem são traces e métricas, que nos ajudam a investigar a engenharia de harness e descobrir onde nosso agent está errando, além de até sugerir mudanças que podemos aplicar automaticamente. Também vamos falar disso quando chegarmos aos diferentes ciclos de aprimoramento do nosso harness. Certo, legal. Quero mostrar rapidinho como é criar esse tipo de agent agora com os deep agents gerenciados da LangChain. Depois, vamos falar dos ciclos de aprendizado e também vou
04:05 fazer uma demonstração ao vivo. Então, como eu estava dizendo antes, quando costumávamos criar nossos agents, um ou dois anos atrás, havia muito trabalho de infraestrutura no código. Quer dizer, precisávamos escrever muito código para configurar nossas proteções e ferramentas, integrar nosso system prompt e tudo mais. Mas agora dê uma olhada neste arquivo agent.py. Ele tem 30 linhas de código. É tudo o que precisamos para definir nosso agent, e isso inclui proteções, subagents, todas as ferramentas que temos, as skills e as instruções, porque agora tudo isso é definido simplesmente como documentos Markdown
04:37 . Então, uma parte da definição do agent é escrita no código. Ainda há um pouco de trabalho de infraestrutura, mas, na maior parte, funciona como os agents de programação, em que os componentes são carregados automaticamente. Temos nosso arquivo instructions.md. Basta ele estar na raiz da pasta do agent, como nosso claw.md ou agent.md no caso de um agent de programação, para que seja carregado automaticamente. Temos nossas skills na pasta skills, assim como temos nossa pasta .claw ou .codex, seja lá qual for. E, quando empacotamos tudo isso para executá-lo localmente em desenvolvimento ou colocá-lo em produção,
05:08 a LangChain cuida de conectar tudo nos bastidores. Assim, é muito fácil criar e gerenciar nossos agents, e tudo é bastante flexível. Então, se não estivermos satisfeitos com o desempenho do agent, basta alterar esses documentos Markdown, exatamente como fazemos com a evolução do sistema, como chamo esse processo para nossos agents de programação. Também há muito mais acontecendo nos bastidores com evals e aprendizados, melhorando nosso harness com o tempo. Vamos falar disso agora. E também vou fazer uma demonstração ao vivo do primeiro ciclo, que é a memória do agent. Então, não importa qual agent você tenha colocado em produção, você vai precisar de um
05:40 sistema como este. A LangChain faz isso muito bem. Há bastante inspiração que podemos tirar dessa configuração, e vou mostrar isso também na demonstração ao vivo. Basicamente, só precisamos de uma maneira para que nosso agent aprenda lições enquanto está em produção. E isso significa encaminhar algumas coisas para uma pessoa. Assim, quando alguém conversa com nosso agent e ele está com dificuldades, queremos que consiga perceber isso e encaminhe a incerteza. Por isso, temos algum tipo de caixa de entrada para gerenciar as diferentes questões sobre as quais o agent está incerto. Damos a resposta correta e garantimos que o agent registre
06:10 isso como uma lição. Então, temos algum tipo de central de contexto, como a LangChain a chama, onde armazenamos essas memórias. O agent sempre pode recuperá-las depois e reconhecer algo como: “Ah, sim, já lidei com essa situação antes. Foi assim que a equipe humana me corrigiu. Então, desta vez, vou dar a resposta certa.” Isso é muito importante porque, principalmente quando estamos colocando nosso agent pela primeira vez diante de usuários reais, não conhecemos bem as lacunas de conhecimento e de processo dele. E os LLMs, sim, alucinam, mas fazem um trabalho surpreendentemente bom ao sinalizar incertezas. Então
06:40 podemos corrigir essas coisas e acumular essas lições ao longo do tempo. E, claro, temos aqui uma estratégia eficiente de recuperação. Então, não é como se estivéssemos simplesmente despejando todas essas lições no contexto, como fazemos com nossas instruções principais. Claro que podemos usar essas lições para melhorar nossas instruções. Vamos falar disso no segundo ciclo. Mas, aqui, o foco é construir uma base de conhecimento sobre como lidamos com as principais situações envolvendo clientes e usuários, porque, em geral, há muitas semelhanças entre as formas como as pessoas usam nosso agent. E essa base de conhecimento que começamos a construir no que
07:10 a LangChain chama de context hub ajuda bastante. E, à medida que o agent melhora, também há cada vez menos casos que são encaminhados ao longo do tempo. Então, isso não vai se tornar um enorme fardo para as pessoas que gerenciam os agents. Aqui temos o pacote de produção do meu agent no managed deep agents. Dentro da pasta memory, há algumas coisas. Primeiro, temos todos os casos: situações em que o agent não tinha certeza e encaminhou o caso para mim na caixa de entrada da equipe, que vou mostrar daqui a pouco. Eu faço a correção, e então ele vai se lembrar dessas coisas tanto por usuário quanto
07:43 vai construir esse tipo de agents.md interno, com as regras principais aprendidas com as lições que ensinei por meio dos casos encaminhados. Certo, agora vou mostrar isso em ação. Este é um painel personalizado que criei com uma versão de demonstração de um agent real em que estou trabalhando: o balcão de ajuda para membros do Dynamis. Isso aqui é uma prova. Tenho executado e testado isso antes de gravar este vídeo, e conseguimos melhorar o agent de forma bastante autônoma ao longo do tempo. Vou mostrar apenas um exemplo. Mantive o conjunto de dados simples. Mantive tudo simples aqui só para a
08:14 demonstração. Tenho aqui um balcão de ajuda no qual simulei diferentes membros da comunidade fazendo perguntas sobre Arcan, o conteúdo do meu curso e outras coisas. Esta é a Nina. Vou fingir que sou a Nina e fazer uma pergunta ao meu agent de suporte: “Oi, Amina, fiz commit de uma correção no comando plan.md localmente e executei o workflow do Arcan, mas a execução usou o texto antigo do comando. Sei que isso parece estranhamente específico, mas esta é uma pergunta real que recebi sobre Arcan algumas semanas atrás.” Na verdade, tudo o que testei aqui se baseia em perguntas reais que recebi. E
08:45 o agent do balcão de ajuda vai responder daqui a pouco, mas, como vocês vão ver, ele não vai ter certeza da resposta. Como vocês viram, demorou um pouco para começar a pensar porque precisei compilar o agent localmente, mas, depois disso, levou apenas cerca de 10 segundos para fazer tudo, incluindo pesquisar as memórias dessa pessoa específica, carregar a skill de diagnóstico da configuração e também atualizar as memórias dessa pessoa. Temos memórias individuais de usuário, que também vou mostrar melhor daqui a pouco. Mas aqui está a coisa mais importante. O balcão de ajuda disse: “Ainda não tenho informações suficientes
09:17 para afirmar isso com certeza.” Mesmo assim, ele vai tentar ajudar. Não queremos que o agent simplesmente pare e espere totalmente por uma pessoa, mas ele sinalizou a incerteza. Agora, olhem a caixa de entrada da minha equipe. Antes desta conversa, havia quatro itens. Agora subiu para cinco porque algo acabou de ser encaminhado para mim. Aqui está a pergunta da pessoa. E aqui está a resposta do balcão de ajuda. Então, preciso confirmar a correção. Posso corrigir o agent aqui ou dizer que ele acertou. De qualquer forma, ele vai atualizar suas
09:47 memórias. Vai aprender uma lição para ter certeza da resposta da próxima vez. Neste caso, já sei a solução. O Arcan cria as árvores de trabalho a partir de origin main. Então, a solução é executar git push e rodar de novo. Vou enviar isso ao agent como a correção confirmada. Agora ele vai aprender uma lição com isso. Volto quando estiver pronto. E pronto: apenas 10 segundos depois, temos a confirmação de que há uma nova memória compartilhada. Aprendemos uma lição. Como mostrei antes, ele atualizou o arquivo principal agents.md na pasta memory e também a memória privada da Nina.
10:18 Esta é a parte importante, porque, daqui para a frente, se outra pessoa tiver um problema parecido, ele vai ter muito mais confiança nas respostas. Vou mostrar isso também. Voltando aos meus chats, agora vou fingir que sou outra pessoa. Sou o Omar. “Minha execução do Arkon terminou com sucesso e abriu um PR, mas faltam três commits que fiz hoje de manhã no diff. Isso é um bug ou o quê?” Não é exatamente o mesmo problema da Nina, mas é parecido o bastante para que ele consiga aprender com aquela lição. Também quero mostrar algo que não seja tão forçado, em que o problema seja literalmente igual, só para mostrar
10:48 que o agent consegue extrapolar com base nas memórias. E aí está. Desta vez, ele não disse que estava em dúvida. Disse que provavelmente não era um bug. “É assim que o Arkan funciona”, certo? Esta é a lição que acabamos de ensinar a ele, e isso permitiu que desse uma resposta bem fundamentada. Se eu acessar a aba de memória, conectada diretamente à LangChain, posso abrir a pasta cases aqui e, de fato, temos uma nova memória. “O Arcan cria a árvore de trabalho da execução; então, o membro fez git push da correção e depois executou novamente o workflow run do Arcan.” Pronto. É exatamente a mesma coisa que estamos vendo aqui em cases, dentro do
11:19 managed deep agents. E, se acessarmos o context hub, também podemos ver as memórias por usuário. Estas, por exemplo, são apenas as memórias da Nina. Também temos essa separação garantida pelas proteções no agent, então as memórias de cada usuário nunca se misturam. E os usuários não conseguem ver as memórias de outros usuários. Legal. A última coisa que quero mostrar agora é o segundo ciclo. Falamos bastante sobre a memória. Ela é uma parte importante do nosso context hub, mas não é realmente a parte principal do nosso harness. As lições de cada caso
11:50 são um bom recurso para o agent consultar quando precisa, mas temos o harness de nível mais alto, que consiste nos nossos workflows e instruções principais. Queremos atualizar tudo isso ao longo do tempo, à medida que aprendemos com nossas lições e com os outros traces que temos dos dados de produção. É isso que quero mostrar agora. Esta é a outra parte do managed deep agents. Este é o mecanismo. Ele usa o LangSmith nos bastidores para todos os dados de traces e, depois, usa o mecanismo para coletá-los e começar a sugerir como podemos melhorar
12:20 nosso agent com base nas falhas que estamos vendo com dados reais. Este é um exemplo real de uma falha que veio das minhas execuções em produção. A descrição no topo é bem detalhada. Se eu quiser, posso ver as evidências com o trace do LangSmith. Posso abrir a conversa exata e ver o que o modelo estava fazendo quando esse problema aconteceu. E minha parte favorita está embaixo, onde temos a correção proposta. Tudo isso é executado nos bastidores pelo LangSmith engine. Ele propõe: “Veja o que devemos alterar em instructions.md.”
12:51 Isso é como a evolução do sistema com nossos agents de programação, em que ele examina o harness inteiro: nossas regras, proteções, instruções e tudo mais. Ele tenta descobrir: “O que devemos ajustar para esse tipo de problema não acontecer de novo?” Aqui está a correção proposta. Ela é concisa, o que é bom, porque também não quero simplesmente inchar minhas regras enfiando um monte de contexto novo aqui. Depois, posso clicar em aplicar, e isso será aplicado imediatamente ao meu agent de produção. Então, aprovo as mudanças e deixo que ele se corrija em tempo real, mas apenas com base nas correções que eu
13:22 estou supervisionando, certo? Não quero muito que meu agent se aprimore de forma autônoma, porque aí perco o controle do meu agent e não sei muito bem que rumo ele está tomando. Esse é realmente o grande tema de tudo isso. Queremos sempre que o agent identifique e aplique correções automaticamente, mas ainda precisamos participar do processo e aprovar as coisas. Então, se formos à seção de contexto, todas as memórias que temos criado para o nosso agent, para cada pessoa, e as principais lições que estamos aprendendo: sempre participamos de cada uma delas. E, ao acessar nossas skills e instruções, tudo o que mudamos aqui, mais uma vez, é aprovado por nós antes que qualquer coisa
13:54 seja alterada. Assim como quando trabalhamos com nossos coding agents, geralmente criamos pull requests para atualizar nossas regras ou skills. Estamos fazendo algo do mesmo tipo aqui, mas diretamente no LangSmith, usando managed deep agents como nossa plataforma. Portanto, não importa como você decida fazer esse tipo de engenharia de harness para seus agents em produção, você precisa de uma plataforma com os dados de traces e um dashboard para aprovar as coisas enquanto seu agent trabalha e identifica o que precisa ser feito. E, dando continuidade à analogia com os pull requests de um coding agent, temos literalmente os commits aqui no
14:25 managed deep agents. Assim, posso analisar cada um deles e ver exatamente como estão as diferentes partes do meu harness. Posso promover diferentes versões e reverter as alterações, se precisar. Então, também não é o fim do mundo se deixarmos nosso agent pior ao aplicar as correções que ele propõe. Temos controle total do nosso sistema aqui. Também é incrivelmente fácil fazer deploy disso em qualquer lugar. Por exemplo, até fiz deploy no meu ambiente do Slack, então posso conversar com o managed deep agent diretamente aqui. É claro que já trabalhei com conjuntos de dados muito maiores, mas, para esta demonstração, eu tinha um conjunto de
14:56 14 perguntas. O agent inicial que criei, com a primeira versão das regras, das skills e de todo o resto, acertou apenas quatro das 14 perguntas. Mas, depois de passar pelo processo de aprendizado e aplicar lições, usando os traces do LangSmith com o engine para aplicar as melhorias sugeridas, cheguei a 13 acertos em 14 perguntas. Então, os LLMs nem sempre serão perfeitos. Não vão acertar 100% das vezes. Mas dá para chegar bem perto, e usamos os dois ciclos para isso. Então, é assim que você deixa seu agent fazer a própria engenharia de harness, enquanto continua participando do processo e aprovando tudo. E
15:28 espero que este vídeo tenha mostrado o poder dos managed deep agents do LangChain, mas também, de forma geral, as ideias de alto nível sobre como queremos desenvolver nossos agents para deploy em produção. Estamos aproveitando todas essas ideias dos coding agents, ou seja, o que faz com que funcionem tão bem. E a maior lição aqui é que a engenharia de harness não é um trabalho que se faz uma única vez, e é nisso que os managed deep agents ajudam. Eles dão ao seu agent um harness personalizado, no qual você pode usar qualquer modelo, e depois acrescentam o engine do LangSmith, para que você possa usar o LangSmith para continuar aprimorando seu harness. Tudo isso mantendo o controle total. Então, vou
16:00 deixar um link na descrição para você experimentar o LangSmith. Você ganha US$ 50 em créditos se usar o código Cole M. E agradeço à LangChain por trabalhar comigo neste projeto. Se você gostou deste vídeo e quer ver mais conteúdo sobre engenharia agêntica e engenharia de harness, eu agradeceria muito se deixasse um like e se inscrevesse no canal. E, com isso, nos vemos no próximo vídeo.
Transcrição original
[00:00] So, on my YouTube channel this year, I’ve mostly been focusing on AI agents for coding. But, what a lot of people don’t realize, maybe even including yourself, is that a lot of these strategies that go into making our coding agents more reliable over time, also translate over very well to other kinds of AI agents that we deploy to production for automation and business use cases. And one of those big ideas is harness engineering, making everything around the model, like the rules and the workflows, better over time. Now, of
[00:30] course, you wire agent to get better over time. But, what I’m referring to specifically here with harness engineering is tracking all the mistakes that your agent is making in production, and then going back retroactively, having that conversation with your agent to figure out what should we make better in your rules and skills so these mistakes don’t happen again. I teach that all the time with harness engineering for coding agents, and really it’s the same thing with your production agents. And the thing is this translates even better than you would think because these days production agents for the most part are built just
[01:01] like coding agents, where we manage the entire harness with a lot of markdown. And this keeps things very flexible. The quote-unquote old way of doing things with agents was a lot more of the plumbing directly in the code, like creating our Python and TypeScript functions for our tools, for example. But, now we have our skills as markdown, our global rules, like our instructions on MD, our memories. This should look very familiar. It’s a very similar sort of harness setup to a coding agent. And this translation works so well that all the components of agentic engineering in our harness, they really have a
[01:31] one-to-one mapping with our agents in production. Like we have our rules, which for a traditional agent is the exact same thing as a system prompt. We have our sub-agents, that’s the same thing as multi-agent workflows where we’re doing any kind of delegation. We have MCP tools for our connections. Skills are our workflows, replacing a lot of our traditional tools. And then we have hooks for our guardrails. If you want to monitor or block things for each tool call or the start or end of conversations, we have our guardrails for that. And so today, I’m not only
[02:02] going to show you an example of building out this harness, but also improving it over time with our two core loops. We have the main memory of the agent, and then also improving it retroactively by looking at the traces as we are monitoring the agent in production talking to real users. That is the biggest goldmine of information that we can’t ignore. Most people do. And so we’ll get into all of this, but also I just want to show you at a high level how do we build an agent that takes on the coding agent harness. Because the thing is, as we create our markdown documents for our skills and our rules
[02:33] and everything, we need some kind of system that actually bundles it and connects it together when we deploy the agent to production. Now, for this platform, you can build it yourself if you want to manage your own deployment and harness engineering pipelines. That’s totally fine. But a lot of the time it’s more practical to use a platform that manages this for you. And so that’s why for all these demos, I’m going to be using LangChain’s managed deep agents, which sets up all this for us in the LangSmith. I’ve seen this work time and time again in production. And as we go through everything, you’ll see how this is very universal. All the
[03:04] strategies apply no matter how you’re building these agents. And for a quick shoutout, thanks to LangChain for working with me on this video. It is about time that I’ve collaborated with them because I’m using their platforms like managed deep agents all of the time. And for a super quick throwback here, this is one of the very first videos I put on my YouTube channel over two years ago when I first started my content. I was building AI agents coding them by hand with LangChain as my framework. And so it’s always had a special place in my heart. I continue to use them because LangChain has always
[03:34] stayed on the cutting edge, especially now with managed deep agents helping you deploy your agents in the sort of coding agent fashion. And then the other thing that they have is the tracing and metrics to help us really get into the harness engineering figuring out where our agent is going wrong, and even giving us suggestions that we can automatically apply. So we’ll talk about this once we get into the different improvement loops for our harness as well. Okay, cool. So I want to quickly show you what it looks like to build these kinds of agents now with LangChain’s managed deep agents, and then we’ll get into the learning loops, and I’ll even
[04:05] give you a live demo. So, kind of like what I was saying earlier, back when we used to build our agents a year or two ago, it was a lot of that plumbing in the code. I mean, we had to write so much code to build out our guardrails and our tools and hook in our system prompt and everything. But now take a look at this agent.py file. It is 30 lines of code. That is all it takes to create the definition for our agent, and this includes guardrails, sub-agents, all the tools that we have, the skills and the instructions, because all this is simply defined as markdown documents
[04:37] now. So, with some of the agent definition here, we are writing into code. There’s a little bit of that plumbing still, but for the most part it works like coding agents, where things are picked up automatically. So, we have our instructions.md. As long as it’s at the root of the agent folder, kind of like our claw.md or agent.md with the coding agent, then it’s going to be picked up automatically. We have our skills in the skills folder, just like we have our, you know, dot claw or dot codex folder, whatever it is. And so, all these things when we package it up together to run it in development locally or deploy to production,
[05:08] LangChain handles stitching everything together behind the scenes. So, it’s very easy for us to build and manage our agents, and it’s all very flexible. So, if we’re not happy with how the agent is performing, then we simply just change these markdown documents exactly like we do for the system evolution, as I call it, for our coding agents. There’s also a lot more behind the scenes with the evals and learnings, making our harness better over time. So, let’s get into that now. And I’ll even give you a live demo here with the first loop, which is the memory for the agent. So, no matter the agent you have deployed to production, you’re going to want a
[05:40] system like this. LangChain does it really well. There’s a lot of inspiration we can take from this setup, and I’ll show you with the live demo as well. We essentially just need a way for our agent to learn the lessons as it’s running in production. And that does mean escalating some things to a human. So, whenever someone is talking to our agent and our agent is struggling, we want it to be able to recognize that and escalate the uncertainty. And so, we have some kind of inbox where we’re managing the different things the agent is uncertain with. We give it the right answer and we make sure the agent writes
[06:10] that down as a lesson. So we have some kind of context hub as LangChain calls it where we’re storing these memories. It can always retrieve that later so it can recognize like, “Oh yeah, this situation I handled before. This is how the human team corrected me. So I’m going to give the right answer this time.” And this is so important because especially when we’re first deploying our agent out to real users, we don’t really know the gaps in its knowledge and process. And so LLMs, yes, they hallucinate, but they do a surprisingly good job at surfacing uncertainties. So
[06:40] we can correct these things and have these lessons build up over time. And of course, we have an efficient retrieval strategy here. So it’s not like we’re just dumping in all these lessons into context like our main instructions. Now of course, we can use these lessons to improve our instructions. We’ll get into that with the second loop. But right here, it’s all about building up a knowledge base of how we’re handling the key situations with customers and users because generally there’s a lot of commonalities between how people are using our agent. And so this knowledge base that we start to build up in what
[07:10] LangChain calls the context hub helps significantly. And as the agent gets better and better, there’s also just less that is escalated over time. So it’s not like this continues to become a huge burden for the humans managing the agents. So here we have the production bundle for my agent here in managed deep agents. And so within the memory folder, there’s a couple of things that we have here. First of all, we have all of the cases, things where the agent was uncertain and it escalated to me in the team inbox that I’ll show you in a little bit. And so I make that correction and then it’s going to remember those things both per user and
[07:43] it’s going to build up this sort of internal agents.md, the core rules that are all learned from the lessons that I’ve taught it with the escalations. All right, so let me show you this in action now. So this is a custom dashboard I built with a demo version of a real agent that I’m working on, the Dynamis member help desk. And so this here is proof. I’ve been running this and testing it before I made this video that we We able to improve the agent pretty autonomously over time. I’m just going to give you one example of this here. So, I kept the data set simple. I kept everything simple here just for the
[08:14] demo. And so, I have a help desk here where I’ve mocked different members of the community asking different questions about Arcan, my course content, whatever it is. And so, this is Nina. I’m going to act like I am a Nina here with the question to my support agent. So, “Hi Amina, I committed a fix my plan.md command locally and I ran the Arcan workflow, but the run used my old command text. I know that seems oddly specific, but this is a real question that I received about Arcan a couple of weeks ago.” And so, all the things here that I’ve tested with is actually based on real questions that I’ve gotten. And
[08:45] so, the help desk agent is going to answer in a second here, but as you’ll see, it isn’t going to be confident in its answer. So, as you saw, it took a little bit to start thinking just cuz I had to compile the agent locally, but it only took about 10 seconds for it to do everything after, including searching the memories for this specific person, loading the skill for the diagnose setup, and then also updating the memories for this person. So, we have individual user memories that I’ll show you more in a little bit as well. But, here’s the most important thing. The help desk said, “I don’t have enough
[09:17] yet to say for sure.” So, it’s still going to try to help. We don’t want the agent to just block and wait for a human entirely, but it surfaced the uncertainty. And then take a look at my team inbox now. It was four right before I had this conversation. Now it’s moved up to five because there’s something that was just escalated to me. So, here’s the question from the person. And then here’s the answer from the help desk. And then I have to confirm the fix. And so, I can either correct the agent here or say that it did it right. Either way, it’s going to update its
[09:47] memories. It’s going to learn a lesson so it’s confident the next time. So, for this case, I have the solution already. Arcan creates the work trees from origin main. So, the solution is to run get push and rerun. So, I’m going to send this into the agent, host the confirmed fix. And so, now it’s going to learn a lesson from that. So, I’ll come back once we have it. And boom, just 10 seconds later, we have the confirmation that we have a new shared memory. We have learned a lesson. So, it updated that core agents.md file in the memory folder like I showed you earlier, and then also the private memory for Nina.
[10:18] This is the important one though, because now going forward, if someone else has a similar issue, it’s going to be a lot more confident in its answers. So, let me show you that, too. So, back over in my chats here, I’m going to act as a different person now. So, I’m Omar. My Arkon run finished green and open a PR, but the diff is missing three commits I made this morning. Is this a bug or what? And for this, it’s not quite the same as Nina’s problem, but it is similar enough where it’s going to be able to learn from that lesson. So, I also want to show you something that’s not so cheesy where it’s like literally the same exact problem, just to show
[10:48] that the agent is able to extrapolate based on memories. And so, there we go. This time it didn’t say it was uncertain. It said likely not a bug. Here’s exactly how Arkon works, right? This is the lesson that we just taught it, and that let it to giving a very solid answer now. If I go into the memory tab that’s hooked directly into LangChain, I can take a look at that cases folder right here, and sure enough, we’ve got our new memory. Arkon builds the run work tree, so the members fix was get pushed and then rerun Arkon workflow run. There we go. This is the exact same thing that we’re looking at here within the cases, right within
[11:19] managed deep agents. And then also, if we go into the context hub, we can see the per user memories as well. Like these are the memories for just Nina. And so, we also have that separation that’s guaranteed with the guardrails in the agent, so we have per user memories that never have any overlap. And it’s not like users can view other users’ memories. Cool. So, the last thing I want to show you now is the second loop. We’ve talked a lot about the memory. And this is an important part to our context hub, but it really isn’t the main part of our harness. The per case lessons,
[11:50] it’s a good resource for the agent to search through when it needs, but we have the higher level harness, which is our core workflows and instructions. And we want to update these over time as we are learning from our lessons and the other traces that we have with our production data. And so, that’s what I want to show you now. This is the other part of managed deep agents. This is the engine. Using LangSmith under the hood for all the trace data, but then using the engine to collect that and start to make suggestions for how we can improve
[12:20] our agent based on the failures that we’re seeing with real data. So, this is a real example of the failure that came from my production runs. And so, we have the description at the top here getting quite detailed. If I’m interested, we have the evidence with the LangSmith trace. I can go into the exact conversation and see what the model was doing when this issue happened. And then my favorite part is at the bottom we have the proposed fix. All of this running behind the scenes with LangSmith engine. And so, it proposes, “Here’s what we should change to the instructions.md.”
[12:51] This is just like system evolution with our coding agents where it’s surveying the entire harness, our rules and guardrails and instructions and everything. It’s figuring out, “What should we adjust so this kind of issue doesn’t happen again?” So, here is our proposed fix. It’s nice and concise cuz I also don’t want to just like bloat my rules by shoving a bunch of new context here. And then I can click apply and it’ll immediately apply this to my production agent. So, I’m approving things and having it fix itself in real time, but only based on the fixes that I
[13:22] am overseeing, right? I don’t really want my agent to autonomously improve itself because then I lose control of my agent and I don’t really know the direction it’s heading. That’s really the big theme with everything here. We always want the agent to be surfacing and applying fixes automatically, but we still need to be in a loop approving things. So, if we go to the context sub, all of the memories that we’ve been creating for our agent for individuals, the main lessons that we’re learning, we’re always a part of every single one of these. And going into our skills and instructions, everything that we change here, again, we approve before anything
[13:54] is changed. Just like when we’re working with our coding agents, generally we’ll create pull requests to update our rules or our skills. We’re doing the same kind of thing here, but just directly in LangSmith with managed deep agents as our platform to do so. And so, no matter how you end up doing this sort of harness engineering for your production agents, you need a platform where you have the trace data and you have the dashboard for you to approve things as your agent is working and surfacing thing. And continuing with that pull requests for a coding agent analogy, we literally have the commits right here in
[14:25] managed deep agents. And so, I can go through each one of these and see what exactly the different parts of my harness look like here. I can promote different versions, roll things back if I need. So, it’s also not the end of the world if we make our agent worse by applying the fixes that it’s proposing. We have full control of our system here. It’s also incredibly easy to deploy this anywhere. Like I’ve even deployed it to my Slack environment, so I can talk to the managed deep agent right here. Now, of course, I have worked with much larger data sets before, but for just for this demonstration, I had a set of
[14:56] 14 questions where the initial agent that I created with the first version of rules and skills and everything, it only got four out of the 14 questions right. But, after I went through the learning process of applying lessons, using the LangSmith traces with the engine to apply its suggested improvements, I got to 13 out of 14 right. So, LLMs aren’t always going to be perfect. It’s not going to be 100% of the time. You can get really close though, and we’re using both of these loops to get there. So, that is how you let your agent do its own harness engineering with you still in the loop approving everything. And
[15:28] so, I hope this video showed you the power of LangChain’s managed deep agents, but just also generally the high-level ideas here for how we want to engineer our agents that we’re deploying to production. Just taking all these ideas from coding agents, so what makes them work so well. And the biggest lesson here is harness engineering is not a one-time job, and that’s what managed deep agents helps with. It’s giving your agent a bespoke harness where you can use any model, and then layering on top the LangSmith engine, so you can use LangSmith to keep improving your harness. All the while, you maintaining full control. And so, I’ll
[16:00] have a link in the description to try out LangSmith. You get $50 in credits if you use the code Cole M. And thanks to LangChain for working with me on this. And so, if you appreciate this video, you’re looking forward to more things on agentic engineering and harness engineering, I would really appreciate a like and a subscribe. And with that, I will see you in the next video.