Pular para o conteúdo

Pi Durable EXPLICADO: crie agents sempre ativos com modelos locais

Ver no idioma original →

Autoria: Hugging Face · 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: Pi Durable EXPLAINED: Build Always-On Agents with Local Models · Canal: Hugging Face · 29:54 · Assistir no YouTube

Tópicos: Agentes de IA, Aplicações empresariais de IA, Dados, bancos de dados e embeddings, Modelos locais e open source

O vídeo explica como Pi Durable permite criar agents que continuam trabalhando após falhas ou interrupções, salvando o estado e retomando a execução automaticamente. Diferentemente do Pi Coding Agent, Pi Durable não é uma aplicação pronta, mas um harness que serve de building block para desenvolver agents próprios. A apresentação descreve sua posição na arquitetura do ecossistema Pi, as opções de armazenamento e o fluxo para configurar um harness. Por fim, demonstra scripts com um modelo local via llama.cpp, incluindo a retomada de uma conversa interrompida.

  • Pi Durable foi projetado para preservar o estado de tarefas e retomar a execução após falhas ou interrupções.
  • A persistência de checkpoints pode evitar que o usuário precise enviar manualmente uma mensagem para continuar o trabalho.
  • Pi Durable é um harness e building block, não um CLI ou uma aplicação pronta como Pi Coding Agent.
  • Na arquitetura do ecossistema Pi, Pi Durable ocupa o nível do harness e usa Pi AI para integração com modelos.
  • As conversas podem ter configurações próprias, como system prompt, diretório de trabalho e ferramentas.
  • Pi Durable não carrega automaticamente configurações de arquivos .pi; os recursos devem ser configurados explicitamente no código.
  • As opções de armazenamento apresentadas são SQLite, JSONL e memória; a memória é voltada principalmente a experimentos.
  • Um aplicativo pode aguardar a conclusão de tarefas ou transmitir eventos para uma interface interativa.
  • A demonstração usa um modelo servido por llama.cpp e mostra ferramentas para ler, escrever e editar arquivos.
  • O exemplo chat resume retoma uma conversa a partir do estado persistido após reiniciar o processo.
Início Capítulo Resumo
00:00 Apresentação e definição de Pi Durable O vídeo apresenta o objetivo de explicar Pi Durable e define a ferramenta como um harness capaz de sobreviver a falhas e interrupções.
02:14 Retomada de tarefas após falhas Um exemplo de envio de e-mails compara o tratamento manual de uma falha no Pi Coding Agent com a retomada baseada em checkpoints no Pi Durable.
08:07 Onde Pi Durable se encaixa no ecossistema Pi O apresentador esclarece que Pi Durable não é uma aplicação pronta e explica como ele substitui o harness na arquitetura do ecossistema.
13:59 Arquitetura de um aplicativo próprio A explicação mostra como conectar interfaces, conversas, modelos e armazenamento para criar um agent sempre ativo.
19:19 Configuração e demonstração do harness O vídeo percorre as etapas de configuração, apresenta opções de armazenamento e executa um agent minimalista com um modelo local.
23:01 Código, ferramentas e persistência O apresentador detalha a inicialização dos modelos, do registry, do armazenamento e das conversas, além de mostrar a retomada de uma tarefa interrompida.
27:17 Exemplo de retomada e encerramento O script chat resume demonstra a continuação de uma conversa após reiniciar o processo, seguida de um resumo dos exemplos disponíveis.

Um harness de agent projetado para sobreviver a falhas e interrupções de forma confiável. — 02:14

Pi Durable não é uma aplicação como Pi Coding Agent; é melhor entendê-lo como um building block para os seus próprios agents. — 09:09

Quando você está criando um agent que vai trabalhar em segundo plano, com tarefas longas, é aí que você vai querer usar o durable harness. — 13:26

Para aplicações de produção, eu recomendaria escolher SQLite. — 18:13

  • Pi Durable (ferramenta): Harness para criar agents persistentes que podem retomar tarefas após falhas ou interrupções.
  • Pi Coding Agent (ferramenta): Aplicação de agent de programação usada no vídeo para comparar o funcionamento de sessões com o de Pi Durable.
  • Pi harness (ferramenta): Pacote que implementa o loop do agent e coordena sessões e ferramentas no ecossistema Pi.
  • Pi AI (ferramenta): Pacote que integra o ecossistema Pi aos modelos de IA.
  • SQLite (ferramenta): Opção de armazenamento persistente recomendada pelo apresentador para aplicações em produção.
  • JSONL (conceito): Formato de armazenamento também suportado por Pi Durable, distinto dos arquivos de sessão do Pi Coding Agent.
  • llama.cpp (ferramenta): Servidor usado na demonstração para executar um modelo local.
  • Node.js (ferramenta): Ambiente sugerido para a aplicação que importa a biblioteca TypeScript Pi Durable.
  • Hugging Face (empresa): Canal do vídeo, que também é citado como fonte de modelos abertos para aplicações próprias.

00:00 Bom dia, pessoal. Como vão hoje? Hoje vamos dar uma olhada no Pi Durable e em como vocês podem usá-lo para criar suas próprias aplicações de agent sempre ativas, certo? Sei que tudo ficou um pouco caótico recentemente, desde o lançamento, porque não está muito claro como usá-lo e como ele se compara ao Pi Coding Agent, por exemplo. Então, idealmente, este vídeo vai esclarecer tudo, mostrar como vocês podem usá-lo e o que podem construir com ele. Também vou falar um pouco sobre a arquitetura, para que vocês possam criar suas próprias aplicações com modelos open source do Hugging Face. Então, a primeira coisa

00:34 que vamos fazer é dar uma olhada na definição do Pi Durable e no que ele pode fazer. Depois disso, vamos dar uma olhada bem rápida em onde o Pi Durable se encaixa em todo o ecossistema Pi e em como ele se compara ao Pi Coding Agent. Depois, vamos dar uma olhada bem rápida na arquitetura de uma aplicação que usa o Pi Durable, para que vocês tenham uma ideia melhor de como criar seus próprios agents sempre ativos com o Pi Durable, usando qualquer modelo que quiserem, sem ficarem presos, por exemplo, aos modelos da OpenAI com o OpenAI dots ou aos modelos da Grok

01:10 com o Grok Grokbot etc. Assim, vocês podem criar suas próprias aplicações com qualquer modelo que quiserem. E, por fim, vou mostrar um script real que funciona com o Pi Durable e que é um agent de verdade, bem minimalista. É basicamente um script que mostra a API do harness, para que vocês vejam como podem usá-lo para criar suas próprias aplicações, certo? Assim, terão uma ideia clara e uma intuição do que ele realmente faz nos bastidores e de como usa o armazenamento para criar um

01:40 estado persistente para o agent, para que vocês sempre possam retomar de onde pararam. E é isso que vamos fazer hoje. Sem mais delongas, vamos começar. >> [limpa a garganta] >> Certo. Vamos começar pela definição do Pi Durable. Acho que esse é o lugar mais fácil e simples para começar, e vamos falar de um exemplo dele também, para facilitar a visualização do que está acontecendo. A descrição mais simples, ou a definição mais simples em que consigo pensar, é algo assim: podemos chamá-lo de um agent harness projetado para resistir a falhas e interrupções de forma confiável

02:14 e confiável. Em outras palavras, se ele estiver fazendo algo e parar no meio da operação, normalmente você vai executá-lo como um daemon em segundo plano, como uma espécie de processo em segundo plano no seu servidor ou na sua máquina. E, se em algum momento o processo falhar ou parar de funcionar, ele vai reiniciar o processo e poderá continuar exatamente de onde parou. E isso será feito com segurança, mesmo que a interrupção aconteça no meio, por exemplo, de um tool call ou de um

02:45 tool call sensível, que é justamente quando isso é mais importante. Deixe-me dar um exemplo para vocês visualizarem isso com um pouco mais de clareza. Suponha que vocês estejam conversando com um agent aqui. Vamos dizer que estejam conversando com um Pi Coding Agent normal, certo? Isso vai ilustrar a diferença entre o Pi Coding e o novo harness Pi Durable que temos aqui. Então, vamos falar do harness Pi Coding normal. Suponha que vocês lhe deram uma tarefa e queriam enviar alguns e-mails a alguns clientes. Então, vocês

03:17 lhe passam uma tarefa. Aqui está o usuário, e ele vai passar uma tarefa. Vocês enviam este prompt e dizem: “Ei, envie meus e-mails.” E o seu robozinho, o seu agent, vai dizer: “Certo, sim”, e vai chamar uma ferramenta. O tool call talvez seja enviar e-mail, certo? Ou ele pode fazer isso por meio do bash ou de outra coisa, mas a ideia aqui é que seu Pi Agent vai chamar uma ferramenta. O que acontece em seguida é que vocês vão receber esse tool call e começar a executá-lo. Suponhamos que vocês

03:49 tenham cinco e-mails para enviar, então ele vai enviar quatro. E, no último e-mail, este aqui, ele falha. Certo, ocorre uma falha aqui. O serviço cai, a aplicação desliga e o sistema precisa iniciá-la de novo. Certo? Então, no seu agent de codificação normal, como aquele a que estão acostumados, isso teria sido salvo da seguinte forma no arquivo JSONL. Então, vocês têm o arquivo JSONL. Este é o arquivo da sessão. Se não conhecem a forma como o PyCodingAgent armazena sessões, podem conferir este outro vídeo, em que explico como os arquivos de sessão realmente

04:22 funcionam e como o PyCodingAgent armazena suas sessões nesses tipos de arquivos, que permitem criar uma estrutura em árvore no sistema de arquivos, na sessão, para ramificar a partir de diferentes partes do arquivo. É muito legal e interessante, aliás. Então, o PyCodingHarness armazenaria isso assim. A tarefa que vocês enviam aqui, enviar e-mails, será uma mensagem do usuário. Deixe-me só mover isso para cá. Será uma mensagem do usuário. O tool call será uma mensagem da AI, ou uma mensagem do assistant, que é, por si só, um tool call. E, como o seu computador começou

04:55 a executar o tool call, ele deveria enviar uma resposta da ferramenta em seguida, porque, nesses tipos de agents, sempre que você envia um tool call, a transcrição espera uma resposta da ferramenta logo depois. Na verdade, se você enviar outro tipo de mensagem depois dessa, o LLM vai falhar. Não vai conseguir responder. Então, >> [fungada] >> as APIs de LLM exigem que você envie uma resposta da ferramenta depois disso. Mas o problema aqui é que não houve resposta da ferramenta, porque o tool call

05:26 nunca terminou. Mas ele fez parte do trabalho. Na verdade, enviou quatro dos e-mails. Só falta enviar um. Então, se você reiniciar seu agent de codificação, ele vai reiniciar com um tool call truncado. Normalmente, o Pi ou outros agents de codificação enviam uma resposta falsa da ferramenta dizendo que houve um erro, para informar ao agent que ocorreu um erro com o tool call. Aí, normalmente, você teria que descobrir o que aconteceu e enviar uma mensagem para continuar. Então, você teria que enviar aqui, como usuário, uma mensagem para continuar. Você teria que reiniciar o agent, enviar uma

05:59 mensagem para continuar e descobrir o que aconteceu nesse meio-tempo. É isso que aconteceria se vocês estivessem usando o agent de codificação. Mas, com o Pi Durable, a diferença é justamente que isso aqui seria tratado automaticamente. Então, com o Pi Durable, a diferença aqui — deixe-me só mudar as cores. Vou dizer que o Durable será azul. Então, Durable. Com o Durable, quando vocês enviam um e-mail, ele é armazenado como uma tarefa no harness, e essa tarefa terá vários checkpoints

06:31 dentro dela. Então, quando o agent responde com um tool call, isso também é armazenado de forma persistente no seu sistema de armazenamento. Normalmente, o Pi Durable vem com armazenamento em um banco de dados SQLite que funciona localmente na sua máquina, ou em uma série de arquivos JSONL, ou também na memória — mas, é claro, isso não é persistente. A memória serve principalmente para experimentação. E o que vai acontecer é que ele vai armazenar checkpoints do que faz. Então, haverá checkpoints dos quatro e-mails que enviou,

07:01 idealmente, se a ferramenta for tratada corretamente. E mesmo que ele não salve checkpoints para cada um dos e-mails, vai salvar checkpoints sobre o fato de que iniciou uma chamada de ferramenta, de que começou algum trabalho, e vai salvar um checkpoint dizendo que… Desculpe, e vai dizer que não concluiu a chamada de ferramenta. E então, o que vai acontecer é que, geralmente, você vai executar isso como um processo no seu servidor ou algo assim, porque, idealmente, você precisa pensar no Durable como um sistema que alimenta assistentes sempre ativos. É principalmente isso que, na minha opinião, vejo o Durable sendo mais útil para.

07:34 E o que vai acontecer é que seu daemon ou sistema vai reiniciar o processo e ler esse estado — as tarefas e todos esses checkpoints — do seu banco de dados SQLite ou dos seus arquivos JSONL, e simplesmente continuar o agent do ponto em que ele parou, sem que você precise tocar em nada para enviar o comando para continuar. Então, essas são as duas principais diferenças. Ele salva checkpoints confiáveis de cada operação e simplesmente continua com o estado que tem nesses checkpoints. Essa é

08:07 essencialmente a principal diferença entre seu agent de programação Pi, seus arquivos JSONL e o Pi Durable. Agora, você talvez esteja se perguntando: “Certo, isso é ótimo. Então quer dizer que agora posso simplesmente abrir minha linha de comando e, em vez de digitar Pi, digitar Pi Durable, e vou ter meu agent de programação Pi que nunca trava?” Não. Não é isso que o Pi Durable é. Deixe-me explicar qual é, de fato, a interface de usuário do Pi Durable.

08:39 Certo. Então, se seu principal ponto de contato com o Pi tem sido o agent de programação Pi, provavelmente você está um pouco perdido sobre o que está acontecendo com o Pi Durable. >> [fungada] >> Talvez tenha ouvido várias pessoas dizerem coisas como: “Ah, o Pi Durable é ótimo. É muito legal que agora você possa simplesmente colocá-lo para trabalhar de forma confiável em tarefas de longa duração e coisas assim.” E talvez esteja se perguntando: “Como devo fazer isso? Existe algum tipo de ferramenta CLI ou algum tipo de agent de programação que roda no Pi Durable ou algo assim?” E [fungada] a resposta é

09:09 na verdade, não. O Pi Durable não é um aplicativo como o agent de programação Pi. O Pi Durable é… Provavelmente é melhor entendê-lo como um bloco de construção para seu próprio assistente de programação ou para os agents que você vai criar. E, idealmente, ele foi feito para alimentar agents de programação que devem ficar sempre ativos. Então, idealmente, algum tipo dessa nova geração de agents, como o novo SciMeta da OpenAI, os bots Grok ou esses agents de programação que vivem em um servidor e que devem

09:41 continuar trabalhando enquanto você faz outras coisas, para que funcionem de forma confiável mesmo quando você não estiver diante do computador. Isso é especialmente útil quando você está criando agents que têm várias entradas ou gateways diferentes. Por exemplo, se você interage com esse tipo de agent pelo Telegram, pelo Slack ou por e-mail, não fica diante do computador o tempo todo para garantir que o agent não trave enquanto executa algo. É aí que o Pi Durable é útil. Ele está aqui para ajudar você a criar esse tipo de

10:15 sistema de forma confiável, certo? E faz isso de uma maneira muito direta. Para explicar onde isso se encaixa na arquitetura geral do Pi, vou fazer uma breve apresentação da arquitetura do agent de programação Pi convencional, certo? Então, você tem seu agent de programação Pi, como este. Você tem o agent de programação Pi, que funciona sobre o Pi harness, certo? São dois pacotes diferentes no projeto Pi. O Pi harness é essencialmente o loop do agent,

10:49 certo? E ele gerencia todas as sessões, o conjunto de ferramentas, como executá-las e todas essas coisas. E então, por cima dele, roda um pacote chamado AI, >> [fungada] >> que é o intermediário entre o Pi e todos os modelos, certo? Então, o agent de programação Pi depende do harness, que é como o loop propriamente dito, e o Pi AI é a integração propriamente dita com todos os modelos. E [fungada] este aqui é o aplicativo.

11:21 Este aqui é onde fica a interface de usuário do terminal. Este aqui é o que define o system prompt. Este aqui é o que define a camada de extensões, etc. Tudo isso fica no Pi coding agent, e esses são os elementos, ou melhor, o aplicativo propriamente dito que você usa e que depende dos outros dois pacotes. Agora, em que nível o Pi Durable se encaixa? O Pi Durable se encaixa como um

11:51 substituto do Pi harness, certo? Então, este aqui é outro harness. E ele também depende do Pi AI, portanto usa a mesma integração com os mesmos modelos de IA e as mesmas chamadas confiáveis aos modelos, com o prompt caching e todas essas coisas que são tratadas com muita precisão e cuidado pelo Pi AI. Mas este é outro pacote raiz, outro dos pacotes centrais que vai alimentar outras coisas. Ele próprio não é o

12:22 próprio aplicativo. Na verdade, uma boa maneira de pensar no que o Durable oferece é que ele oferece uma classe de harness. E essencialmente é só isso. Quer dizer, é claro que há mais coisas, mas essa é uma boa maneira de pensar a respeito. É uma classe de tarefas do harness com uma API muito boa que você pode usar para criar conversas e consultar o harness. Você pode enviar tarefas para esse harness e fazer com que elas sejam executadas de forma confiável, porque este harness vai cuidar delas. Essencialmente, isso é paralelo ou

12:53 uma alternativa ao que você teria se executasse o Pi harness por RPC, por exemplo, ou se importasse o Pi harness pelo seu Pi SDK: você faz a mesma coisa, mas com o Durable harness, certo? Então, neste caso, se você estiver criando um agent de programação ou algo assim, talvez queira usar o Pi harness SDK, o normal. Mas, se estiver criando um agent que vai trabalhar em segundo plano, que terá algumas tarefas de longa duração e, o mais importante, que você não vai

13:26 ficar diante da tela o tempo todo enquanto ele trabalha, é aí que você vai querer usar o Durable harness, certo? Deixe-me explicar um pouco mais sobre como funciona a classe de harness, esta aqui, e sua API, para que você consiga visualizar melhor como criar aplicativos com base no Durable. Certo, então conseguimos entender um pouco melhor a definição do Durable, do Pi Durable, e qual problema ele deve resolver. E também concluímos uma explicação breve de onde o Pi Durable se encaixa na arquitetura de todo o ecossistema Pi, certo? Então, lembre-se: ele se encaixa ali, no nível do Pi harness. Não é um aplicativo, é um bloco de construção. Como você pode usar esse bloco de construção para executar seus próprios aplicativos? Deixe-me dar uma visão geral de alto nível de como seria seu próprio aplicativo. Vamos supor que você queira criar seu próprio assistente sempre ativo, certo? E queira que ele possa ser

13:59 acessado pelo Slack e por e-mail. E ele pode… Claro, isso não serve apenas para assistentes sempre ativos; também pode ser um aplicativo de chat comum, como um agent de programação, o que é totalmente possível, como vou mostrar daqui a pouco. Na verdade, tenho um pequeno script que mostra como o harness convencional funcionaria em um assistente CLI. E o que vai acontecer aqui? Você vai criar algum tipo de interface para todas essas entradas. Idealmente, você vai querer criar sua própria

14:30 interface.

15:01 gateway para lidar com todas essas entradas e enviá-las à sua aplicação. E aqui estará a sua própria aplicação. Idealmente, esta será feita em Node.js, muito provavelmente, porque esta é uma biblioteca TypeScript. E é nela que você vai importar o Pi Durable. É aqui que dá para ver que ele é, na verdade, um bloco de construção. Você precisa construir a aplicação aqui mesmo, que vai lidar com seus usuários. Ela também vai lidar — idealmente, você vai querer

15:33 com as conversas neste nível. Porque, embora o Pi Durable tenha uma API para lidar com as próprias conversas do harness, em primeiro lugar, ela não é uma API CRUD completa e, além disso, não é uma API que ofereça muita flexibilidade. A API também provavelmente vai mudar, porque o Pi Durable ainda está em um estágio muito inicial de desenvolvimento. Mas vamos supor que você tenha isso; então, o Pi Durable vai dar acesso a várias ferramentas diferentes na API dele. Assim, você pode criar várias conversas.

16:07 Então, aqui você tem a conversa A, a conversa B, a conversa C, e isso é ótimo, claro. E uma boa maneira de pensar em cada conversa é como… Você pode pensar em cada conversa como uma sessão do seu Pi Coding Agent. A terminologia pode ser um pouco complicada ou confusa, porque sessão também é um termo usado no Pi Durable para outra coisa. Mas quero que você… Se você está vindo do Pi Coding Agent, eu

16:38 quero que pense na conversa como aquilo que você chamaria de sessão. Neste caso, cada uma delas tem seu próprio system prompt. Cada uma tem seu próprio diretório de trabalho. E cada uma tem suas próprias ferramentas e skills. Então, basicamente, é a mesma coisa que iniciar seu próprio Pi Coding Agent em um novo diretório. E [fungada] esse diretório tem seu próprio diretório .pi, com todas essas coisas. Mas, neste caso, o Pi

17:08 Durable não carrega nada do .pi, na verdade. Então, se você tiver um arquivo agents.md, o Pi Durable não vai executá-lo. Ele executa apenas o que você carregar explicitamente ao inicializar uma conversa no código. E vou mostrar o código daqui a pouco. Na verdade, tenho um script bem legal para mostrar como você pode criar seu próprio agent. Mas, antes disso, vou explicar como funcionaria conceitualmente, para que você não veja um monte de código sem saber o que está acontecendo. E o que vai acontecer aqui é que você terá todas essas conversas e, claro,

17:41 elas estarão vinculadas aos adaptadores de modelos de IA do pacote PiAI. E, muito importante, para que o aspecto durável disso funcione, você precisa de um banco de dados ou algum tipo de armazenamento. Podemos falar um pouco mais sobre o armazenamento depois. Provavelmente é um tópico que exige um pouco mais de aprofundamento. Mas há diferentes maneiras pelas quais o Pi Durable armazena coisas — o estado, ou seja lá o que estiver fazendo na sua aplicação e, claro, as conversas. Atualmente, ele oferece suporte a um armazenamento de

18:13 backend SQLite. Você não precisa criá-lo por conta própria. Basta inicializá-lo no código e ele será criado e gerenciado para você. Também existe o sistema de armazenamento JSONL e o sistema em memória. Este aqui, como o nome sugere, fica na memória e é apagado quando você fecha a aplicação. Então, este serve mesmo só para experimentação. Mas, para aplicações em produção, eu recomendaria escolher SQLite. É o que eu mais gosto de usar nas minhas experimentações. Mas saiba que JSONL também é compatível. Algo

18:46 a ter em mente é que o armazenamento JSONL do Pi Durable não é nem um pouco igual aos arquivos de sessão JSONL do Pi Coding Agent. Na verdade, este aqui usa vários arquivos, para começar. Não é apenas um arquivo por conversa. E tudo isso serve para tornar o conjunto confiável, para que ele possa retomar o trabalho depois de uma possível falha ou de algum outro problema. Então, é isso que acontece na arquitetura da sua aplicação. É assim que você vai importá-lo. Deixe-me mostrar exatamente como o código

19:19 ficaria e como seria cada aspecto desta aplicação, ou desta inicialização da instância do harness durável. Vamos dar uma olhada agora. Certo, agora que entendemos como o Pi Durable funciona, o que ele realmente é, onde ele fica e onde se encaixa em toda a arquitetura do Pi, e como você construiria sua própria aplicação usando esta biblioteca, quero falar um pouco sobre como você pode usá-lo de fato e fazer uma demonstração

19:50 na sua frente. Então, vamos dar uma olhada rápida em um script para mostrar exatamente como ele funciona, e vamos executar um agent bem simples e mínimo no terminal. Mas, antes disso, vou mostrar exatamente as etapas que ele vai seguir, porque não é tão direto quanto simplesmente criar um agent e fazer consultas a ele. O que vai acontecer é o seguinte: primeiro, você vai precisar inicializar sua instância do Pi Durable. Isso vai acontecer em algumas etapas. A primeira etapa será importar ou configurar os modelos, certo? A segunda etapa será importar

20:23 ou abrir o registro, certo? Este vai incluir todas as ferramentas que você vai usar e também as extensões. No Pi Durable e no Pi em geral, há várias extensões já disponíveis, e algumas são integradas. No exemplo que vou mostrar, vou mostrar como usar a extensão de ferramentas do coding agent, que vai adicionar as ferramentas comuns do Pi com as quais você já está familiarizado. Acho que são read, edit, bash e find. Não

20:54 lembro exatamente, mas vamos lá. Vamos dar uma olhada nelas daqui a pouco. E a terceira coisa que vamos fazer é configurar o armazenamento, certo? Para o armazenamento, lembre-se de que temos algumas opções. Você tem SQLite, arquivos JSONL e memória. Neste exemplo, vamos usar SQLite só para mostrar como ficaria, mas, para experimentar, recomendo que você use memória. E, claro, não vou fazer uma apresentação completa de toda a API. Se você for usar isso, use-o com um agent. Não espero que você escreva esse código à mão, claro. A quarta etapa é abrir o harness.

21:28 Depois, vamos precisar criar ou recuperar uma conversa, porque lembre-se de que eu disse que as conversas começam essencialmente como as sessões do Pi Coding Agent normal. E, finalmente, depois disso, vamos enviar nossas consultas. Isso consiste basicamente em fazer uma consulta ao harness e receber uma resposta. Mas, quando você envia algo, isso é armazenado de forma persistente no seu armazenamento. Assim, o harness ou o agent poderá retomar o trabalho e continuar de onde parou se for interrompido

21:59 em algum momento. E algo importante a saber é que, quando você envia uma consulta ou basicamente qualquer alteração ao seu harness, vai aguardar uma resposta, certo? Assim, você poderá aguardar uma resposta e trabalhar em outras coisas de forma assíncrona, ou também poderá transmitir os eventos. Isso depende mesmo do tipo de aplicação que você está construindo. Se você estiver construindo uma aplicação em que envia tarefas, por exemplo, e espera que elas terminem, caso sejam tarefas que levem algumas horas ou talvez até dias, você vai

22:30 provavelmente enviar uma tarefa, esperar que ela seja concluída e então simplesmente receber a resposta quando estiver pronta. E, a propósito, quando você envia uma consulta, recebe um ID de envio, que poderá usar para validar ou verificar o status da tarefa. Se, no entanto, o que você está criando for algo como um aplicativo de chat que precisa ser interativo, você também pode transmitir os eventos, certo? Assim, você poderá transmitir os eventos do seu harness e recebê-los à medida que acontecem. Então, você poderá

23:01 mostrar a conclusão à medida que acontece, mostrar as chamadas de ferramentas e mostrar quaisquer outros eventos que queira exibir na sua interface. Vamos dar uma olhada no código de verdade agora. Certo, vamos analisar o código aqui. Vou mostrar rapidinho. Como eu disse, há basicamente seis etapas para configurar o harness, e é bem simples. Este script aqui — deixa eu mostrar o que ele realmente executa. Estou rodando aqui um servidor llama.cpp com um modelo bem pequeno, só

23:32 para mostrar como isso funciona. Estou rodando o Qwen 3.5 0.8B. O que vai acontecer aqui é que vou executar este script que está aqui ao lado usando llama.cpp. E aqui posso fazer perguntas como: “Olá.” E, claro, como você pode ver, é bem rápido, porque é um modelo minúsculo. E escondi uma frase secreta bem legal aqui no README. É esta aqui. Então, vamos ver se este agent que está rodando no Pi Durable consegue encontrá-la. Vou pedir a ele:

24:03 “Leia o arquivo README e me diga qual é a frase secreta.” E, como você pode ver, ele consegue usar ferramentas. Aqui, usou a ferramenta de leitura e me disse que a frase secreta é esta. A ideia aqui é que você tem um agent funcional. Claro, não é muito simples mostrar em tempo real o que está acontecendo nos bastidores, porque ele está criando os checkpoints, criando o armazenamento persistente com SQLite neste caso, e tudo acontece nos bastidores. É só para mostrar

24:35 que o agent funciona, certo? Agora que você viu que o agent funciona, vamos dar uma olhada no código para que você veja o que está acontecendo nos bastidores. É bem simples. Primeiro, inicializamos os modelos. Neste caso, estou usando um provedor llama, mas também adicionei uma chave da OpenAI aqui. É bem simples. O provedor llama é apenas um adaptador bem simples do Pi. Ele é assim: você cria um provedor pela API de modelos de IA do Pi, preenche os detalhes e pronto.

25:07 Depois disso, como mencionamos, criamos o registro. E o registro, como eu disse antes, é o lugar que vai reunir todas as ferramentas e tudo a que seu agent terá acesso, como as extensões. Neste caso, apenas inicializo o registro. Eu poderia passar o registro assim, completamente vazio, com a configuração padrão pré-construída do Pi. Mas também é possível adicionar as ferramentas de programação existentes que vêm com Pi Durable Tools. É só uma extensão pré-construída que você pode carregar e que vem com as quatro ferramentas

25:41 do Pi. Então, posso perguntar aqui algo como: “Quais ferramentas você tem disponíveis?” Como você pode ver, ele consegue ler, escrever e editar arquivos. Parece ótimo. Agora, a próxima coisa que podemos fazer, depois de criar o registro, é inicializar um harness. Na verdade, primeiro inicializamos o armazenamento. Como você pode ver, inicializamos o armazenamento usando o armazenamento SQLite do Node, que também vem do Pi Durable. Depois disso, inicializamos o harness, que é a classe ou a

26:12 instância que terá esta API, que nos permitirá interagir com as conversas. Aqui, abrimos o harness e passamos o armazenamento, os modelos que inicializamos, o registro e o diretório de trabalho atual. Aqui, a demo é apenas um auxiliar que criei para abstrair algumas coisas e ajudar você a entender o que está acontecendo. Depois disso, diretamente pelo harness, você cria uma conversa, certo? Sem proprietário neste caso específico. Você passa o modelo, o diretório de trabalho atual e, aqui, as instruções,

26:44 que são basicamente como o system prompt. E é só isso. Depois disso, você pode consultar essa conversa diretamente. Pode ir aqui e fazer um envio. Para criar um envio, você usa a mesma instância de conversa que criou. Envia a solicitação com o método submit. Esse método submit retorna um ID de envio, que é retornado aqui. E você pode simplesmente esperar que a tarefa seja concluída e mostrar a resposta. É isso que temos feito aqui ao lado, com o agent de programação que mostrei a você. E esta é basicamente uma demonstração bem rápida

27:17 da API deste harness durável. Como você pode ver, não se trata de um aplicativo completo. É a arquitetura do harness, ou a primitiva durável do harness, que você pode usar nos seus próprios aplicativos. E é bem simples; funciona mais ou menos como um substituto do SDK do Pi, caso você esteja criando um agent durável, como um assistente sempre ativo. O código está na descrição, se você quiser dar uma olhada. E também criei um segundo exemplo, um pouco mais

27:47 complexo, um pouco mais elaborado. Ele se chama chat resume. Você vai vê-lo aqui. Ele faz praticamente a mesma coisa, mas retoma a conversa de onde ela parou depois que você reinicia o programa. Assim, dá para ver o aspecto durável dele. Deixe-me mostrar rapidinho. E você pode executá-lo assim: npm run chat resume. Basicamente, ele só executa este script que está aqui. Como eu disse, faz a mesma coisa: cria o suporte ao chat, cria o armazenamento, cria o registro, adiciona as ferramentas de programação

28:20 e inicializa o harness. Depois, verifica o estado do armazenamento e o estado de persistência do harness, e então continua a partir daquele ponto. Então, deixe-me mostrar como isso funciona. Vou executar npm run chat resume. E, neste caso… Pronto. Eu tinha uma tarefa que não havia sido concluída. Então, vou pedir algo como: “Leia a documentação deste projeto e me diga o que ele faz.” Vou enviar assim. Como você pode ver, ele vai

28:51 pensar um pouco. Provavelmente vai chamar algumas ferramentas, e vou interrompê-lo. Como você pode ver aqui, interrompi o processo e ele parou logo depois de chamar esta ferramenta. Então, vamos ver o que acontece se eu simplesmente executá-lo de novo e retomá-lo com esta instrução aqui. Como você pode ver, ele está lendo do armazenamento — que, neste caso, são os bancos de dados SQLite que mostrei antes — e vai continuar depois desta chamada da ferramenta de leitura. Vamos ver. E pronto. Depois da chamada da ferramenta, ele simplesmente me deu uma resposta curta. É um aplicativo de demonstração técnica local…

29:22 e por aí vai. Então, é basicamente assim que o Pi Durable funciona. Há alguns scripts aqui para ajudar você a entender o que está acontecendo. Tudo isso estará na descrição, então você pode dar uma olhada neste script chat resume, que pode executar com npm, e também no script normal, que é basicamente uma apresentação de alto nível da API do harness. Pronto. Se tiver alguma dúvida, me avise. Espero que tenhamos abordado praticamente tudo sobre o Pi Durable e que agora você entenda um pouco melhor como ele funciona e para que serve.

29:54 Muito obrigado por assistir. Foi um prazer. Deixe um like e inscreva-se no canal. Vejo você no próximo vídeo.

Transcrição original

[00:00] Good morning everyone. How’s it going today? Uh today we’re going to be taking a look at Pi Durable and how you can use it to create your own always-on agent applications, okay? I know that it has been a little bit chaotic recently since the release because it’s not very clear how to use it and how it compares to the Pi Coding Agent, for example. So, ideally this video clears everything up, shows you how you can use it, and what you can build with it. And I’m going to also go a little bit over the architecture of it so that you can build your own applications with open models from Hugging Face. So, the first thing

[00:34] that we’re going to be doing is we’re going to be taking a look at the definition of what Pi Durable is and what it can do. After that, we’re going to be taking a little very quick look at where Pi Durable fits in the entire Pi ecosystem and how it compares to the Pi Coding Agent. After that, we’re going to be taking a very quick look at the architecture of what an application that uses Pi Durable would look like so you can have a better idea of how you can build your own always-on agents with Pi Durable with any model you want so that you’re not tied to models from OpenAI, for example, with OpenAI dots or to models from Grok

[01:10] with Grok Grokbot, etc. That way you can build your own applications with the same with any models that you want. And then finally, I’m going to show you actually a real script that runs with Pi Durable and is an actual very minimalist agent right here. It is basically just a script that shows you the API of the harness so that you can see really how you can use it to create your own applications, okay? So that you have a clear idea and an intuition of what it’s actually doing behind the scenes and how it uses storage to create a persistent

[01:40] state for your agent so that you can always pick up where it where it left off. And there you go, that’s what we’re going to be doing today. Without any further ado, let’s get right into it. >> [clears throat] >> Okay. So, let’s start off with the definition of Pi Durable. I think that’s the easiest and the simplest place to start, and we’re going to talk about an example of it. Also, to make it easier to visualize what’s going on. The simplest term or the simplest definition that I can think of is something like this. We can call it an agent harness that is designed to survive just crashes

[02:14] and interruptions reliably. In other words, if it is doing something and it stops in the middle of the operation, you usually will run this as a daemon in the background like some sort of like a background process in your server or in your machine. And if at some point the process crashes or it breaks, it will spring the process back on, and it will be able to continue exactly at the point where it left off. And this is going to be done safely even if the interruption happened in the middle of, for example, a tool call or a

[02:45] sensitive tool call, especially that’s in when this is the most important. And let me give you an example for you to actually visualize this a little a little bit more clearly. So, let’s suppose that you have right here, you’re talking to an agent. So, let’s call let’s say that you’re talking to regular PyCoding agent, okay? And this will illustrate the difference between PyCoding and the PyDurable new harness that we have right here. So, let’s talk about the regular PyCoding harness. Let’s suppose that you handed a task and you wanted to send a few emails to some of your clients. And so, you

[03:17] send it a task. Here is going to be my user, and it’s going to send it a task. And you send this prompt and you say, “Hey, send my emails.” And your little robot, your little agent, what it’s going to do is it’s going to say, “Okay, so yes, it’s going to call a tool.” And the tool call is going to be maybe send email, okay? Or it may do this via bash or something else, but the idea right here is that your PyAgent’s going to call a tool. What happens next is that it’s going to I mean, you’re going to receive that tool call and you’re going to start executing that tool call. And let’s suppose that you

[03:49] have five emails to send, so it’s going to send four emails. And then on the last email, this one right here, it crashes. Okay, so there is a crash right here. And the service is down, the application shuts down, and the system has to bring it back on. Okay? So, in your regular coding agent, like what you’re used to, this would have been saved the following way in your JSONL file, okay? So, you have your JSONL file. So, this is your session file. In case you’re not familiar with how PyCodingAgent stores sessions, feel free to take a look at this other video where I explain how session files actually

[04:22] work and how PyCodingAgent stores its sessions in these kind of files that actually allow you to create a tree structure in your file system, in your session, so you can branch off of different parts of your file. It’s very fun, very interesting, by the way. So, your PyCodingHarness would store this like this. So, your task right here that you send, send emails, will be user message. Let me just move this right here. It’s going to be user message. Your tool call is going to be an AI message or your assistant message, which is in itself a tool call. And since it’s your your computer started

[04:55] working on the tool call, it was supposed to send a tool response afterwards because in these kinds of agents, whenever you send a whenever you receive a tool a tool call, the transcript expects a tool response right after that. Actually, if you send a different kind of message after that one, the LLM’s going to crash. It’s not going to be able to to respond to you. So, >> [snorts] >> the LLM APIs necessarily require you to send a tool response after this. But, the problem right here is that there was no tool response because the tool call

[05:26] never ended. But, it did do some work. It actually sent four of the emails. It’s only one that is not sent. So, if you restart your coding agent, it will restart a truncated tool call. Usually, Py or other coding agents send a fake tool response saying that there was an error to tell your agent that there was an error with the tool call, and then you you would usually have to figure it out from here, and you would have to send continue message. So, you would have to send right here, as a user you would have to send a continue. So, you would have to restart the agent, send a

[05:59] continue message, and figure out what happened in the meantime. That’s what would happen if you were using the coding agent. But, with I mean, the difference right here with PyDurable, precisely, is that this right here would be handled automatically. So, with PyDurable the difference right here, let me just change colors. So, I’m going to say on durable it’s going to be blue. So, durable. So, with durable, when you send send an email, it is stored as a task in your harness, and that task is going to have multiple checkpoints

[06:31] inside of it. So, when your tool when your agent responds with a tool call, that is going to be also stored persistently in your storage system. So, usually PyDurable comes with storage either in a SQLite database that runs locally in your machine, or in a series of JSON L files, or also in memory, but that of course is not persistent. Memory is mostly for experimentation. And what’s going to happen is that it’s going to store checkpoints of what it does. So, it’s going to have checkpoints of this four emails that it sent,

[07:01] ideally if the tool is handled correctly. And even if it doesn’t save checkpoints for each one of the emails, it’s going to save checkpoints about the fact that it started a tool call, that it started some work, and it’s going to save a checkpoint, and that Sorry, and and it’s going to say that it didn’t finish the the tool call. And then, what’s going to happen is that usually you will be running this as a process in your server or something like that, because ideally you would have to think about durable as a system that powers always-on assistants. That is mostly, in my mind, what I see durable most mostly

[07:34] being useful for. And what’s going to happen is that it’s going to your daemon or your system is going to restart the process, and it’s going to read this state, so the tasks and all of these checkpoints from your SQL i database or from your JSONL files, and it’s going to just continue the agent from the point where it left off without you having to tap to send continue. So, those are the two main differences. It saves reliable checkpoints of each operation, and it just continues with the state that it has in those checkpoints. That is

[08:07] essentially the main difference between your pie coding agent and your JSONLs and your durable pie. Now, you may be wondering, “Okay, that is great. So, does that mean that now I can just run open my command line and instead of typing pie, I can type pie durable, and I will have my pie coding agent that never breaks down?” Nope. That is not what pie durable is. Let me explain to you what actually is the user interface of pie durable.

[08:39] All right. So, if your main point of contact with pie has been through the pie coding agent, you probably are a little bit lost about what is going on with pie durable. >> [snorts] >> You may have heard a bunch of people say things like, “Oh, pie durable is great. It’s pretty cool that you can now just have it work on long-running tasks reliably and things like that.” And you may be wondering, “How am I supposed to do that? Is there some sort of a CLI tool or some sort of a coding agent that runs on pie durable or something like that?” And [snorts] the answer is

[09:09] actually no. Pie durable is not an application like pie coding agent. Pie durable is It’s probably a better way to look at it as a building block for your own coding assistant or your own agents that you’re going to be building. And ideally, it is meant to power coding. It is meant to power agents that are supposed to be always on. So, ideally, some sort of this new generation of agents, such as OpenAI’s new SciMeta or Grok bots or of of this coding of these agents that live in a server and that are supposed to

[09:41] continue working while you’re doing other things so that they work reliably even when you’re not in front of the computer. And this is especially useful when you’re building agents that have a bunch of different inputs or different gateways. So, for example, if your interaction with this kind of agents is via Telegram or via Slack or via email, you’re not in front of the computer the time to make sure that the agent doesn’t break while it is running something. That is where Pi Durable is useful. It is here to help you build those kind of

[10:15] systems reliably, okay? And it does that in a very straightforward way. Let’s talk in order to cover the like where this fits in the whole architecture of Pi, I’m going to just very briefly go over the architecture of the regular Pi coding agent, okay? So, when you have your Pi coding agent like this. So, you have your Pi coding agent and it relies on top of the Pi harness, okay? Which are two different packages in the Pi project. So, the Pi harness is essentially the agent loop,

[10:49] okay? And it handles all that sessions and the fact that the tools are together and how to run the tools and all of these things. And then on this one right here runs on top of a package called AI, >> [snorts] >> which this one right here is the intermediary with Pi and all of the models, okay? So, Pi coding agent relies on the harness, which is kind of like the actual loop that is going on, and Pi AI is the actual integration with all of the models. And [snorts] this one right here is the one that is the application.

[11:21] This one right here is where you have the terminal user interface. This one right here is the one that defines the system prompt. This one right here is that define one that defines the extension layer, etc. All of these things are in the PyCodingAgent and these are the tools or kind of the actual application that you use that relies on these other two packages. Now, on which level does PyDurable fit in? PyDurable actually fits in as a

[11:51] replacement to Py’s to PyHarness, okay? So, this one right here is another harness right here. And this one right here also relies on PyAI, so it uses the same integration with the same AI models and the same reliable model calls with the prompt caching and all of those things that are dealt very accurately and very nicely with PyAI, but this one is another root or another one of the core packages that is going to power other things. This one itself is not the

[12:22] application itself. Actually, what Durable actually ships, the good way to look at it, is that it ships a harness class. And that’s essentially all there is. I mean, of course, there are more things, but that is a nice way to think of it. It’s a harness task class with a very nice API that you can use to create conversations and that you can use to query it and then you can send tasks to this harness and have those tasks run reliably because this harness right here is going to take care of them. That is essentially a parallel or

[12:53] an alternative to what you would have if you were running the PyHarness through RPC, for example, or if you were importing the PyHarness through your the PySDK, you’re doing the same thing but with the Durable Harness, okay? And if So, in this case, if you’re building a coding agent or something like that, you may want to use the PyHarness SDK, the normal one, but if you’re using if you’re creating an agent that is going to be creating that is going to be working in the back in the background, that is going to have some long running tasks and most importantly, one that you’re not

[13:26] going to be in front of the screen all the time that it is working, this when you’re going to want to use durable harness, okay? Let me tell you a little bit more about how the harness class, this one right here, the API, actually works so that you can visualize a little bit better how you can build applications on top of durable. Okay, so we have successfully understood a little bit better about what the definition of durable is, of Pi Durable, and what it is supposed what problem it is supposed to solve. And we have also finished a little bit like a quick

[13:59] explanation of where Pi Durable fits in the full Pi ecosystem architecture, right? So, remember, it fits right there at the Pi harness level. It’s not an application, it’s a building block. So, how can you use this building block to run your own applications? And let me give give you a very high-level overview of what your own application would look like. So, let’s suppose that you want to create your own always-on assistant, okay? And you want it to be able to be

[14:30] reached via Slack, via email, and it can Of course, this is not only for always-on assistants, it can always also be a regular [snorts] chat application, like a coding agent, that is completely possible, as I’m going to show you in a moment. Actually, I have a quick little script that shows you how the regular harness would work in a CLI assistant. And what’s going to happen right here? You’re going to build some sort of like the interface to all of these inputs. Ideally, you want to create your own

[15:01] gateway to handle all of these inputs and sell them to your application. And here’s going to be your own application. And this one, ideally, is going to be in Node.js, most likely, because this is a TypeScript library. And into this one, you’re going to import Pi Durable. And that’s here is where you see that it is actually a building block. You have to build the application right here that is going to handle your users. It’s going to handle Also, ideally, you want

[15:33] to handle the conversations at this level. Because even though Pi Durable does have an API to handle its own conversations of the harness, it is not a complete crowd API, first of all, and also it is not an API that allows you a lot of flexibility. And also the API is likely to change because the the Pi Durable is very early in development. But, let’s suppose that you have this, and then Pi Durable will then give you access to a bunch of different tools in its API. So, you can create multiple conversations.

[16:07] So, here you have conversation A, conversation B, conversation C, and that is great, of course. And each conversation, a good way to think about them, is as You can think about them as each conversation as a session in what is your Pi Coding Agent. The terminology can be a little bit complicated or a little bit confusing because session is also a term that is used in Pi Durable for something else. But, I want you to If you’re coming from Pi Coding Agent, I

[16:38] want you to think of conversation as what you would call a session in the sense that this one right here, each one right here has its own system prompt. Each one has its own working directory. And each one has its own tools and skills. So, essentially, it’s basically the same thing as if you had started your own Pi Coding Agent in a new directory. And [snorts] that directory has its own .pi directory which with all of these things. But, in this case, Pi

[17:08] Durable does not load any of the things from .pi, actually. So, if you have an agents.md file, Pi Durable is not going to run it. It just runs whatever you load explicitly when you initialize a conversation in the code. And I’m going to show you the code in just a moment. I actually have a nice little script to show you how you can create your own agent. But before that, I’m going to show you how how it would work conceptually so that you don’t see a bunch of code and know don’t know what is going on. And what’s going to happen right here is that you have all of these conversations and you have, of course,

[17:41] these ones linked to the AI model adapters from the PiAI package. And very importantly, in order for the durable aspect of this to work, you need a database or some sort of storage. And storage, we can talk a little little bit more about it later. Probably it’s a little bit more of a more in-depth topic. But there are different ways in which Pi Durable stores things, stores the state or what of whatever it’s doing in your application and, of course, its conversations. So, currently it supports a SQLite

[18:13] back-end storage. You don’t have to create this by your yourself. Just initialize it in the code and it will be created, handled for you. And there is also the JSONL storage system and there is also the memory in-memory system. So, this one right here, as its name suggests, it lives in memory and it’s erased after you close the application. So, this one right here is really just for experimentation. But for actual production applications, I would actually recommend that you choose SQLite. That’s the one that I like the most in my experimentations. But do know that JSONL is also supported. Something

[18:46] to keep in mind is that the JSONL storage of Pi Durable is not at all the same thing as the JSONL session files in High Coding Agent. This actually This one right here is multiple files, first of all. It’s not just one file per conversation. And all of this is intended at making the whole thing reliable so that it picks up after potential crash or something happens. So, that’s what’s going on in the architecture of your application. That’s how you’re going to be importing it. Let me show you exactly what the code would

[19:19] look like and what every aspect of this application or this initialization of the durable harness instance would look like. Let’s take a look at it right now. Okay, so now that we have understood how Pi Durable works, what it actually is and where it stays, where it lands in the entire architecture of Pi, and how you would build your own application using this this library, uh I want to talk a little bit about how you can actually use it and demo it in

[19:50] front of you. So, we’re going to take a look at a very quick script right now to show you exactly how it works and we’re going to run a very simple minimal agent in the terminal. But, before doing that, I’m going to show you exactly the steps that that is going to follow because it’s not as straightforward as just creating an agent and just querying it. So, what’s going to happen is, first of all, you’re going to have to initialize your Pi Durable instance. And it’s going to happen in a few steps. The first step is going to be to import or configure the models, okay? The second step is going to be to import

[20:23] or open your registry, okay? And this one right here is going to include all the tools that you’re going to be using and the extensions as well. So, in Pi Durable and and in Pi in general, you have a bunch of extensions that are already available and some are built in. In the example that I’m going to show you, I’m going to show you how to use the coding decoding agent tools extension and that is going to add the regular tools that you are already familiar with that come from Pi. These are read, edit, bash, and find, I

[20:54] think. Don’t remember exactly, but there you go. We’re going to take a look at them in just a moment. And then the third thing that we’re going to do is we’re going to set up the storage, okay? For the storage, remember that we have a few few options. You have SQLite, you have JSONL files, and then you have memory. In this example, we’re going to be using SQLite just to show you how it would look, but for experimentation, I recommend that you use memory. And of course, I’m not going to give you an entire tour of the entire API. If you’re going to be using this, do use it with an agent. Don’t expect you to be coding this by hand, of course. The fourth part is to actually open the the harness.

[21:28] Then, we’re going to have to create or retrieve a conversation cuz remember that I told you that conversation starts essentially kind of like what sessions would be in the regular PyCoding agent. And finally, after that, we’re going to submit our queries. And this is essentially just querying the harness and getting a response. But when you submit something, it is going to be stored persistently in your storage, and that way the harness or the agent’s going to be able to take over that and continue the work if it gets interrupted

[21:59] at some point. And something important to know when you submit a query or basically any change to your harness, you’re going to await a response, okay? So, here you’re going to be able to await a response because that way you can work on other things asynchronously, or you can also stream the events. And that really depends on the kind of application that you’re building. If If you’re building an application where you submit jobs, for example, and you wait for them to finish, if they are jobs that are going to take a few hours or maybe even days, you’re going to

[22:30] probably submit a task, wait for it to complete, and then just get the response once it’s done. And by the way, when you submit a query, you do get a submission ID in return, which is the one that you’re going to be able to use in order to validate or check the status of your task. If, however, what you’re building is something like a chat application that has to be interactive, you’re also able to stream the events, okay? So, you’re going to be able to stream the events from your harness and get them as they happen. So, you’re going to be able

[23:01] to show the completion as it happens, show the tool calls, and show whatever other events you want to show in your interface. Let’s take a look at the actual code right now. Okay, so let’s go over the code right here. Going to show you real quick. As I told you, there are basically six steps in the whole thing in order to set up the harness, and it’s very straightforward. This script right here, let me just show you what it actually runs. I am running here a llama.cpp server with a very small model really

[23:32] just to show you how this work. I’m running quant 3.5.0.8b. And what’s going to happen right here is I’m just going to run this script that I have right here on the side and run it with llama.cpp. And here I can just ask questions like, “Hello.” And of course, as you can see, it’s pretty fast because it’s a super tiny model. And I have hidden a nice secret phrase right here in the readme. This one It’s this one. So, let’s see if this agent that is running on Drupal can actually find it. So, I’m going to ask it,

[24:03] “Read the readme file and tell me the secret phrase.” And as you can see, it can use tool tools. Here it used to read, and it told me the secret phrase is this. And the idea right here is that you have a working agent. Of course, I’m not It’s not super straightforward to show you what’s actually going on behind the scenes in real time because it is creating the checkpoints, it is creating the persistent storage with SQLite in this case, and everything is happening behind the scenes. It’s just to show you

[24:35] that the agent works, okay? Now that you see that the agent works, let’s actually take a look at the code so that you see what’s going on behind the scenes. So, very straightforward. First, we just initialize the models. In this case, I’m using a llama provider, but I also added just an OpenAI key right here. And it’s very straightforward. The llama provider is just a very straightforward adapter from Pi. It looks like this. You create a provider from the Pi AI models API and you complete the details and you have it complete.

[25:07] And after that, we as we mentioned, we create the registry. And the registry as I told you before is this place that is going to encapsulate all the tools and everything that your agent’s going to have access to such as the extensions. In this case, I just initialize the registry. I could just pass in the registry like this completely empty with the regular pre-built Pi setup. But you can also add the existing coding tools that come from Pi durable tools. It’s just a pre-built extension that you can load and it comes with the four tools

[25:41] from Pi. So I can just ask it right here something like, what tools do you have available? As you can see right here, it can read, write, and edit files. Sounds pretty good. Now, next thing that we can do is after your registry is created, we’re going to initialize a harness. Well, first we’re initializing the storage actually. So as you can see, we initialize the storage using node SQLite storage, also comes from Pi Arendelle. And after that, we just initialize the harness, which is the class or the

[26:12] instance that is going to have this API that is going to allow us to interact with the conversations. Here, the harness, we open it, we pass in the storage, the models that we initialize, the registry, and the current working directory. Here, the demo is really just a helper that I created to abstract some stuff away just so you understand what’s going on. And then after that, directly from the harness, you create a conversation, right? Ownership, just owner list for this one in particular. You pass in the model, the current working directory, and here you pass in the instructions,

[26:44] which are basically like the system prompt. And that’s all. Basically, after that, you can just query that conversation directly. You can go right here, just a submission. In order to create a submission, you take the same conversation instance that you created. You send the submission with the submit method. And that submit method returns a submission ID that is returned right here. And you can basically just wait for that to complete and show the answer. And that’s what we have been doing on the side right here with the coding agent that I showed you. And this is basically just a very quick

[27:17] demo of the API of this durable harness. As you can see, this is not a complete application. It is the harness architecture or the harness durable primitive that you can use in your own applications. And it is actually very straightforward and it works kind of like replacement to the Pi SDK. If what you’re building is a durable agent such as an always-on assistant. So, the code for this right here is in the description if you want to take a look at it. And I actually created a second example that is a little bit more

[27:47] complex, a little bit more complicated. It’s called chat resume. You will see it right here. It does pretty much the same thing, but it resumes the conversation after you restart it from the point where it left off. So, you can actually see the durable aspect of it. Let me show that to you real quick. And you can run it like this with npm run chat resume. It essentially just runs this script that I have right here. As I told you, does the same thing, creates the chat support, creates the storage, creates the registry, adds the coding

[28:20] tools, initializes the harness, but then after that just checks that checks the state of the storage and like the persistence state of the harness, and then continues from that point. So, let me show you how that would work. So, I’m going to say npm run chat resume. And in this case There you go. So, I actually had a task that had not completed. So, I’m going to ask it something like read the documentation of this project and tell me what it does. So, I’m going to send it like that. As you can see, it’s going

[28:51] to think a little bit. It’s going to probably call a few tools and I’m going to stop it. As you can see right here, I stopped it and it stopped right after calling this tool. So, let me see what happens if I just rerun this and resume it with this instruction right here. As you can see, it’s reading from the storage that in this case it’s the SQLite databases I showed you before and it’s going to continue after this read tool call. Let’s see. And there you go. After the tool call, it just sent me the short answer. It’s a local technical

[29:22] demo app, blah blah blah. So, there you go. That is essentially how I durable. You have a couple of scripts right here to help you understand what’s actually going on. All of this is going to be in the description so you can take a look at this chat resume script right here that you can just run with NPM and also the regular one which is basically just a very high-level showcase of the harness API. So, there you go. Please let me know if you have any questions. I hope that we have covered pretty much everything related to PyJaRable and you understand a little bit better now how it works and what it is useful for.

[29:54] Thanks a lot for watching. It has been a pleasure. Please do leave a like and subscribe and I’ll see you in the next one.