O ser humano é uma API assíncrona — Melanie Warrick, Temporal
Autoria: AI Engineer · Assistir no YouTube
Vídeo de autoria do canal indicado, não da IANIA; todos os direitos pertencem ao criador. Transcrição, resumo e tradução gerados automaticamente; o conteúdo no idioma original é preservado na versão em idioma original.
Idioma original: inglês
Vídeo original: The Human Is an Async API — Melanie Warrick, Temporal · Canal: AI Engineer · 18:54 · Assistir no YouTube
Tópicos: Agentes de IA, Infraestrutura e hardware de IA, Saúde e ciência
Melanie Warrick apresenta uma demonstração de entrega de sorvetes para explicar como Temporal ajuda a coordenar agentes e manter o estado de sistemas distribuídos. A palestra propõe tratar a interação humana como uma API assíncrona, usando condições de espera e sinais para receber respostas sem bloquear o restante do sistema. Uma demonstração mostra que eventos podem ser registrados enquanto um serviço está offline e processados quando ele volta, sem perder o estado do workflow. A decisão de envolver uma pessoa deve considerar o custo de um erro e o risco de fadiga causada por alertas.
Pontos-chave
Seção intitulada “Pontos-chave”- A demonstração coordena agentes de frota, clientes e despacho para realizar entregas.
- Temporal oferece primitivas para acompanhar o estado e padronizar o tratamento de falhas em sistemas distribuídos.
- Workers executam código, workflows acompanham etapas e activities tratam interações externas, como chamadas a modelos e ferramentas.
- Uma condição de espera pausa uma etapa enquanto o sistema continua executando outras tarefas.
- Um sinal permite enviar a resposta humana a um workflow em execução ou pausado.
- Respostas humanas podem levar minutos, dias ou mais; por isso, a interação não deve depender de uma chamada bloqueante.
- Se o serviço ficar offline, eventos podem ser enfileirados e o workflow pode retomar do estado registrado quando o serviço voltar.
- O envolvimento humano deve ser avaliado caso a caso, considerando o custo de errar e a fadiga causada por alertas.
- Temporal pode ser integrado a diferentes frameworks, incluindo Google ADK, LangChain e LangGraph.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:13 | Demonstração de entrega de sorvetes | Agentes coordenam pedidos e entregas, enquanto Temporal acompanha o estado e permite processar uma alteração com aprovação humana. |
| 03:20 | Agentes, harness e durabilidade | A palestrante relaciona os ciclos dos agentes à necessidade de manter o estado e lidar com falhas em produção. |
| 06:58 | O ser humano como API assíncrona | Condições de espera e sinais permitem receber informações humanas sem bloquear o sistema nem perder o progresso após uma falha. |
| 10:05 | Primitivas e integração com frameworks | A palestra detalha a integração de Temporal com Google ADK e LangChain por meio de workflows, activities, condições de espera e sinais. |
| 13:08 | Aprovação humana e recuperação após falhas | Uma encomenda de alto valor exige aprovação humana, e a demonstração mostra que o sistema pode registrar a resposta enquanto está offline e retomá-la depois. |
| 16:20 | Quando envolver uma pessoa | A decisão deve equilibrar o custo de um erro, a confiabilidade probabilística dos modelos e a fadiga causada por alertas. |
| 18:23 | Recursos e encerramento | A palestrante indica recursos e demonstrações disponíveis no GitHub e convida o público a conversar sobre seus projetos com agentes. |
Citações
Seção intitulada “Citações”O ser humano é uma API assíncrona. — 07:30
O que você quer são duas primitivas centrais: uma condição de espera e um sinal. — 08:01
Humanos provavelmente vão levar vários minutos, talvez dias, talvez semanas ou mais. — 14:44
O principal a considerar é o custo de estar errado. — 16:51
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- Temporal (empresa): Empresa e plataforma apresentadas na palestra para gerenciar estado e execução durável em sistemas distribuídos.
- Melanie Warrick (pessoa): Palestrante que apresenta a demonstração e explica o uso de Temporal com agentes.
- durable execution (conceito): Abordagem que permite preservar o estado e retomar a execução de um sistema após falhas ou interrupções.
- worker (conceito): Primitiva de Temporal responsável por executar código.
- workflow (conceito): Primitiva de Temporal que registra e acompanha as etapas de um processo.
- activity (conceito): Primitiva usada para operações externas, como chamadas a modelos e ferramentas.
- wait condition (conceito): Condição que pausa uma parte do workflow enquanto aguarda um evento ou uma resposta.
- signal (conceito): Mecanismo para enviar informações a um workflow e permitir que ele continue.
- Google ADK (ferramenta): Framework do Google usado na demonstração para orquestrar agentes.
- LangChain (ferramenta): Framework usado no exemplo de integração para construir fluxos com agentes.
- LangGraph (ferramenta): Framework usado para executar o agente de despacho na demonstração.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:13 Certo. Bem, estou aqui hoje para falar com vocês sobre esta demonstração, e já saí dos limites que me disseram para não ultrapassar. Enfim, estou aqui hoje para falar com vocês sobre uma demonstração de entrega de sorvete que preparei e, no fim das contas, estou aqui para falar com vocês sobre Temporal. Então, vocês vão me ouvir apresentar a empresa em que trabalho e, mais especificamente, falar sobre esta entrega de sorvete que está acontecendo agora, como vocês podem ver online. Então, o que está acontecendo? Bem, este é o Ziggy. Ziggy’s é o nosso mascote. Eu adoro o Ziggy. E o Ziggy tem uma sorveteria
00:43 — na verdade, não, mas vamos dizer que tem — lá no Ferry Building. No momento, está trabalhando duro, entregando todo tipo de sorvete. Agora, o que está acontecendo nesta tela é que temos vários agents coordenando a entrega para o serviço de sorvetes do Ziggy. Temos um agent de frota, um agent de atendimento ao cliente e um agent de despacho, todos trabalhando em coordenação para garantir que o sorvete chegue aonde precisa. Nesta demonstração específica, o que estou mostrando aqui é que temos o 80K integrado com
01:16 Temporal. Então, 80K é uma solução que o Google oferece para ajudar a orquestrar agents ou vários agents e, neste caso, ajuda especificamente a coordenar as atividades relacionadas a esses agents. E Temporal está integrado a ele. Nossa integração permite acompanhar o estado do que está acontecendo nesse tipo de entrega. Então, Temporal ajuda a acompanhar e gerenciar o estado, e oferecemos uma interface que permite ver o que está acontecendo
01:47 naquela tela. É isso que vocês estão vendo aqui. E essa interface mostra o histórico de eventos. Este é o workflow pai de todas as atividades que estão acontecendo agora na operação de entregas do Ziggy. E, nesse contexto, às vezes precisamos incluir um humano no loop quando temos vários agents. Então, digamos que um cliente fez um pedido e disse: “Ei, acho que mudei de ideia sobre esse pedido. Vou enviar uma alteração.” E, claro, quando você envia essa alteração,
02:18 ela pode — dependendo de como você montar o sistema — acabar fazendo o sistema parar de funcionar. Mas, longe de nós deixar o sistema parar de funcionar quando alguém envia uma alteração. Neste caso, temos um pedido que está pausando o motorista A. Então, o motorista A está esperando essa atualização chegar. O sistema continua funcionando enquanto essa alteração específica pausa apenas uma parte do sistema.
02:48 Essa alteração veio de um humano. E outro humano precisa decidir se quer aceitá-la. Então, essa pessoa aprova, e vocês vão ver que, como mencionei, o resto do sistema continuou funcionando: os pedidos continuaram chegando e sendo preparados. Mas, quanto a essa questão específica da alteração do pedido, a atualização está sendo processada e deve ser aplicada daqui a pouco. Suspeito que a internet esteja interferindo. Vocês podem ver que ela é processada, a
03:20 atualização é lida, e agora o pedido segue para o próximo destino, que é o Oracle Park. E lá vai o pequeno A, entregando o pedido para vocês. Pronto. Isso é execução durável com Temporal e 80K integrados. Certo. Estou aqui para falar sobre “O humano é uma API assíncrona”. Vamos começar. Primeiro, temos ouvido falar de loops agênticos, certo? Você pode raciocinar, agir e observar. Essa é a ideia geral de que todos têm falado quando falam sobre desenvolver esses agents e fazer com que funcionem com o máximo possível de autonomia. Existe esse tipo de loop que estamos analisando, certo? Já ouvimos outros termos para isso: pensar, agir, perceber. E essa é a essência. Pode ser um loop for, pode ser um loop while. Durante a maior parte deste ano, temos ouvido as pessoas falar sobre o harness e sobre o que o harness deve ser para nos ajudar a colocar esses agents em produção. Então, não vou
03:50 ficar aqui dizendo que sou especialista em harness. Vou contar, com base em tudo que pesquisei, o que entendo até agora e tentar oferecer pelo menos um mapa geral, sabendo que há muito debate sobre o assunto. Ouvi dizer que talvez o modelo faça parte do harness — ou talvez não. Acho que há debates sobre se o modelo está incluído, se as ferramentas estão incluídas, se a memória está incluída, assim como os guardrails e a segurança. Mas, no fim das contas, trata-se de dar estrutura a esses agents para que funcionem de maneira razoável quando forem colocados
04:22 em produção. E a durabilidade deveria fazer parte desse quadro. O sistema que mostrei — a demonstração que acabei de mostrar — é assim. Ele tem esses loops. Temos um loop para o agent de frota, um loop para o agent de atendimento ao cliente e um loop para o agent de despacho. O agent de frota e o agent de atendimento ao cliente fazem pesquisas. Um pesquisa sobre os motoristas de fato, usando ferramentas como Google Maps. O outro pesquisa os pedidos, usando ferramentas como Google Search. Enquanto isso, o agent de despacho
04:53 recebe essas informações e toma decisões com base nelas. Certo. Então, é ótimo que essas atividades estejam acontecendo nesses três loops e que o humano possa fornecer informações como parte dessa estrutura. Mas o importante é que precisamos de alguma durabilidade nesse sistema para garantir que continue funcionando e não saia do ar. É aí que Temporal entra. Temporal ajuda a padronizar o tratamento de falhas e o gerenciamento de estado no seu sistema.
05:24 Em qualquer sistema, em qualquer sistema distribuído, especialmente em sistemas com agents, vamos ajudar você a padronizar isso. Somos software e também um serviço. O próprio software cria muitos recursos básicos que você pode usar imediatamente e aplicar à sua base de código. Temos versões em várias linguagens, então você pode usar isso com Python, TypeScript ou Rust. Mas, no fim das contas, oferecemos alguns recursos básicos padronizados para você aplicar ao seu código e garantir que seu sistema mantenha o estado.
05:55 Os três principais recursos básicos de que costumamos falar são o worker, o workflow e a activity. O worker é quem executa o código. O workflow é onde você pode acompanhar as etapas do seu sistema. Por exemplo, um framework 80K seria executado dentro de um workflow. Seu agent poderia ser executado dentro de um workflow, porque é um loop, certo? Já a activity abrange tudo que se integra ou interage com sistemas externos. Então, se você tem um loop, qualquer chamada a um modelo ou qualquer
06:26 chamada de ferramenta seria configurada como uma activity. Esses são os recursos básicos. Você estrutura seu código com nossos recursos básicos para acompanhar o estado do seu sistema. Somos gratuitos e open source naquele endereço do GitHub. Você paga se quiser que gerenciemos o estado com nosso serviço. Caso contrário, pode hospedar o sistema por conta própria. Vamos voltar ao humano no loop. O que eu queria realmente transmitir a vocês com esta palestra é o seguinte:
06:58 o humano — reconheço que não somos ferramentas, mas somos uma ferramenta para o agent. E talvez você pense: “Certo, vamos chamar o humano ou fazer com que o humano entre e nos dê alguma informação para passar para esse loop.” Se você simplesmente escrever isso como uma função que diz “chame o humano” ou “permita que o humano forneça uma entrada”, isso pode se tornar uma chamada bloqueante. E a informação pode se perder se o serviço sair do ar. O sistema pode perder o contexto do que estava acontecendo com aquele humano
07:30 o humano, é verdade, sabe, não somos ferramentas, mas somos uma ferramenta para o agent. E você pode pensar: “Certo, bem, vamos chamar o humano ou fazer o humano entrar e nos dar algum tipo de informação para passar para esse loop. Se você escrever isso diretamente como uma função, dizendo para chamar o humano ou permitir que o humano forneça uma entrada, isso pode se tornar uma chamada bloqueante. E isso pode se perder se o seu serviço cair. Talvez ele perca o fio do que estava acontecendo com aquele humano
08:01 engajamento. O que você quer é que essas duas primitivas centrais sejam aplicadas ao seu código e aos seus agents. Você quer uma condição de espera e um sinal. Você se permite isolar um evento, aplicar uma condição de espera e armazená-lo nesse workflow, nessa camada de durabilidade, para que, se algo falhar no sistema, quando ele voltar, saiba de onde parou.
08:31 E você pode enviar um sinal a qualquer momento, mas o sistema inteiro pode continuar funcionando sem que você necessariamente fique bloqueado naquela chamada específica ao humano. O código é bastante simples em termos das primitivas. E, claro, sei que isto é Python, mas a situação é a mesma. Você vai aplicar uma condição de espera e um sinal. Basicamente, você não mantém uma thread ocupada, e isso vai sobreviver a qualquer tipo de falha. Tem todo tipo de primitivas integradas,
09:02 como timeouts, por exemplo. Se você está esperando uma resposta de um humano e quer garantir que a espera dure só até certo ponto, pode aplicar timeouts e outros tipos de primitivas. E isso pode escalar. Você pode ter milhões de workflows parados, e tudo pode continuar funcionando. Então, o que eu quero mostrar — na verdade, vou mostrar mais código, mas vou iniciar a próxima demonstração para que ela já esteja rodando. E vou contar a todos vocês, caso ainda não tenham percebido: meus olhos estão machucados. >> [risos] >> Às vezes, estou apertando os olhos e também
09:34 percebendo que preciso de apoio adicional aqui, para o qual não me preparei, mas tudo bem, porque posso me adaptar. Certo, vamos iniciar este outro exemplo e, depois, vou contar um pouco mais sobre o código que está aqui. Vamos conferir se está rodando. Estou reiniciando meu exemplo e, claro, não vai ser tão fácil quanto eu gostaria. Além disso, todos estão me ouvindo bem? Acho que sim. Ótimo. É uma condição interessante para
10:05 trabalhar neste espaço com os ruídos ao nosso redor. Certo, acho que está rodando. Certo, vamos falar um pouco mais sobre o código. Já falei sobre nossas primitivas de activity, workflow e worker. No caso da activity, especificamente para ADK, temos a classe temporal model, que você envolve em torno do modelo e depois passa para o ADK poder configurar esse agent. É bem
10:36 simples. Você aplica esse temporal model, aplica nossa activity para envolver suas ferramentas e executa seu agent. Você executa seu agent como faria em qualquer configuração de ADK. E também configura um worker e passa o plugin do Google ADK. Assim, você configura seu worker, workflow e activity. De maneira semelhante, você tem sua condição de espera, que usa esse async io quando usa uma espera
11:06 para dizer: para esse workflow específico, quero que você o pause e não execute nenhum outro código, mas pode continuar executando as corrotinas nesse workflow ou em quaisquer outros workflows do sistema. Enquanto isso, workflow.signal poderá receber qualquer tipo de entrada e inseri-la em um workflow em execução. E o workflow será removido da memória ou do sistema e colocado em estado de espera, caso não esteja executando nada naquele momento.
11:36 Então, mostrei a interação de humano para agent. O que quero mostrar é como fica quando o agent entra em cena e precisa que o humano se envolva. É bem parecido. Você vai usar — já vou adiantar — um workflow, uma condição de espera e um sinal. Neste exemplo, vou usar LangChain e também 80K, porque a realidade é que, com Temporal, podemos trabalhar com vários frameworks. Não somos vinculados a frameworks. Trabalhamos com uma variedade de ferramentas.
12:06 Então, no LangChain, eles constroem graphs para montar a configuração com vários agents. E, nessa integração, a forma como trabalhamos é passando-nos para cada nó do seu graph. Assim, você configura a aparência dos metadados. Se fizer qualquer tipo de chamada a um modelo, como invocar o modelo, isso será configurado como uma activity. Se fizer qualquer outro tipo de chamada a uma ferramenta, ela também será configurada como uma activity. Mas, se for uma etapa do processo, ela será configurada como um workflow. Isso é determinismo e não determinismo
12:38 no contexto dos workflows: eles são determinísticos, enquanto as activities são não determinísticas. E, claro, você passa o plugin do LangChain para o worker. Especificamente no LangChain, usamos o interrupt para chamar a partir do nó deles. Isso faz parte do LangChain e, para ser justa, o LangChain é mais do que um framework, mas, neste caso, estou usando-o como framework. Você usa o interrupt para chamar e, em seguida, o que vai fazer é usar essa condição de espera no
13:08 rastreamento do loop para esse sinal de interrupt, a fim de pausar o workflow. E o sinal vai capturar o que quer que o humano responda à pergunta feita. Certo, vamos ver como fica. Vou abrir minha demonstração e mostrar enquanto ela está rodando. Este é o projeto que preparei. Tenho os agents de cliente e de frota rodando no 80K. Tenho o agent de despacho rodando no LangGraph. E o Temporal está entrelaçado por todo o sistema.
13:40 Então, é assim que funciona. Agora, vamos ver se consigo mostrar. Neste caso, vou inserir um pedido de alto valor. É um pedido que provavelmente vai exigir o envolvimento de um humano. O workflow do sistema inteiro mostra que todos esses agents estão fazendo seu trabalho. Eles continuam avaliando os pedidos. Configurei isso de modo que tenho workflows filhos separados para cada pedido, por framework. Então, aquele
14:12 pedido especial teve sua própria avaliação. Aqui vemos que os agents de cliente e de frota fizeram o trabalho deles. Fizeram a avaliação e chegaram a um resultado. E enviaram isso ao agent de despacho. O agent de despacho disse: “Ah, certo, preciso… Ah, bom, olha só. >> [risos] >> Preciso envolver um humano nisso. Então, vou entrar em estado de pausa enquanto espero a resposta do humano.” E sabemos que os humanos não vão
14:44 responder em 200 milissegundos. Se você responde, ótimo. Talvez haja algumas pessoas por aí que respondam. Mas, provavelmente, os humanos vão levar vários minutos, talvez dias, talvez semanas ou até mais. E você pode fazer isso porque está apenas pausando aquele evento específico. E, como podem ver, os carrinhos continuam andando. Agora, vou tentar mostrar o que acontece se eu colocar esse serviço offline. Então, vamos aumentar a imagem para que todos possam ver. E
15:19 encerrar o worker. Beleza. Isso deixa o serviço offline. Dá para ver que está desconectado. Não reparem enquanto faço isso de um jeito bem peculiar. Certo. Se eu disser “aprovar” enquanto está offline, o que aconteceu é que, como mencionei, isso está acontecendo fora do seu serviço. Está no próprio armazenamento de dados. Então, ainda podemos acompanhar esse evento e colocá-lo na fila. E, quando eu o iniciar de novo,
15:50 sim, eu sei. Deixei tudo muito bem organizado aqui para vocês. Mas vou iniciá-lo de novo e vamos ver se funciona. Vamos lá. E voltou a ficar online. Vocês vão notar que o agent de despacho… O que está acontecendo é que o log de eventos está sendo reproduzido. Ele não está sendo refeito, só reproduzido até o ponto em que parou, para saber: “Este é meu estado atual. E esta é agora a próxima etapa desse estado.” E isso foi colocado na fila para que essa etapa saiba que a pessoa aprovou
16:20 isso, e esse pedido foi atribuído e já foi entregue, na verdade. Então, pronto. Isso é durabilidade no seu sistema. Seu sistema pode ficar indisponível e se recuperar. E pode ter todas essas outras primitivas que vão ajudar você a gerenciar um estado complexo, porque esse tipo de sistema distribuído é complexo. Certo. Mais algumas coisas que quero mencionar. Quando o ser humano deve participar do processo? Essa é a pergunta de verdade. É difícil. Vou dizer o seguinte: a principal coisa que você
16:51 precisa levar em consideração é que o custo de estar errado é alto. Certo, isso depende de cada caso, e sabemos que estamos tentando chegar ao máximo de autonomia possível. Também sabemos que esses modelos são probabilísticos e é difícil torná-los confiáveis. Por isso há toda essa movimentação interessante em torno de harnesses. Poderia entrar em outra conversa inteira sobre isso, se vocês quiserem, em outra ocasião. Mas, no fim das contas, você quer avaliar o custo de estar errado. Quanto isso vale para você? Especialmente do ponto de vista da segurança. E sabemos que, do outro lado dessa questão, a fadiga de alertas é real. Muitos de nós estamos vendo isso: você começa a dizer sim, sim, sim, sim, sim toda vez que ele faz uma pergunta. Então, você está tentando equilibrar essas duas coisas. E estamos tentando melhorar os modelos para que você possa confiar neles e lidar com essa fadiga de alertas, mas eles ainda são modelos probabilísticos. Então, quando eles devem participar do processo? Quando o ser humano deve participar do processo? É isso que você precisa avaliar para os problemas que está tentando resolver. Mas, no fim das contas, o que vocês viram ali, o exemplo que dei, seja o ser humano iniciando ou o computador iniciando
17:21 isso, você viu que estamos usando duas primitivas principais: você aplica uma condição de espera para pausar esse workflow e um sinal do ser humano para continuar o trabalho e dizer: “Aqui está o resultado. Agora continue.” E, quer você tenha realmente pausado e colocado isso offline, quer tenha trazido de volta para online. E mostrei que podemos usar vários frameworks. Certo, se tiverem alguma pergunta, vou ficar por aqui mais alguns
17:52 minutos. Se quiserem, tenho aqui um código QR que leva a alguns recursos sobre Temporal, assim como a algumas demonstrações que fiz, incluindo esta. Ela está no GitHub. Os slides em si serão publicados mais tarde, porque, claro, no meu estilo habitual, fiquei ajustando-os até agora. Então, vou publicá-los e adicionar os links ao repo do GitHub. Mas, sim, se tiverem perguntas, podem entrar em contato. E, sabe, divirtam-se criando seus agent clips. Também estou curiosa para saber que problemas vocês estão resolvendo com agents e como estão criando-os de forma autônoma
18:23 atualmente. Então, fiquem à vontade para me encontrar. Obrigada. >> Uhu!
18:54 atualmente, de forma autônoma. Então, fique à vontade para me procurar. E obrigada. >> Uhu!
Transcrição original
[00:13] All right. Well, I’m here to talk to you today about this demo and I’ve already stepped outside the box they told me not to step outside of. Anyways, I’m here to talk to you today about an ice cream delivery demo that I’ve got for you and ultimately I’m here to talk to you about Temporal. So, you’re going to hear me pitching about the company that I work for and specifically in a way that will be about this ice cream delivery that’s happening as you can see online right now. So, what’s happening? Well, this is Ziggy. Ziggy’s Ziggy’s is our mascot. I love Ziggy. And Ziggy has an ice cream
[00:43] store, not really, but let’s say he does down in the Ferry Building. Currently working hard delivering all kinds of ice cream. Now, what’s happening on this screen is that um we have multiple agents that are currently coordinating the delivery that’s happening for deliver for Ziggy’s ice cream service. We have a fleet agent and a customer agent and a dispatch agent all working in coordination to make sure that the ice cream goes where it needs to go. In this specific demo, what I’ve got up here is showing you we have 80K integrated with
[01:16] Temporal. So, 80K is a um solution that Google’s providing to help you orchestrate agents or multiple agents um and in this case it’s specifically helping to coordinate the activities in relation to these agents. And Temporal is baked into it. We are integrated into it so that we can help track the state of what’s happening with this kind of delivery. So, Temporal actually helps you track your state and manage that state and we provide a UI that allows you to see what’s going
[01:47] on on that screen. So, this is what you’re seeing over here. And in that UI it’s showing you the event history. There’s this this is the parent workflow for all the activities that are happening for Ziggy right now in its delivery suite. And in this world, sometimes what we’ll have in multiple agents is we need to have human in the loop. So, let’s say a customer made an order and the customer said, “Hey, I think I changed my mind about that order. So, I’m going to submit a change.” And of course, when you do submit that change,
[02:18] it will not it if you depending on how you build it out, it could actually break your system. But, heaven forbid you have it break your system when somebody has a change to submit. In this case, we have an order and this order is currently pausing driver A. And so, driver A is waiting for that update to come through. The system is running while this one specific change is only pausing one part of your system.
[02:48] That one change coming from a human. And another human needs to make a call and whether or not they want to accept that. So, they say approve, and you’ll watch that as I mentioned, the rest of the system kept running, orders were coming in, they’re being filled, but in this specific question that came up about changing that order, the update is getting processed and should go through in a second. I suspect internet is part of it. You can see it does get processed, the
[03:20] update is read, and that order will now move on to its next location, which is to the Oracle Park. And there goes little A delivering the order for you. So, there you go. That is durable execution with Temporal and 80K integrated. All right. I’m here to talk to you about the human is an async API. Let’s go into First off, we’ve been hearing about agentic loops, right? You can reason, act, and observe. That is our whole
[03:50] thing that everybody’s been talking about when they’re talking about building out these agents and these agents running as autonomously as we possibly can. Um there’s this kind of loop that we’re looking at, right? We’ve heard other words for this where we’re thinking, we’re acting, we’re perceiving. Um and that’s that’s the essence of it. It can be a for loop, it can be a while loop. Most of this year we’ve been hearing people tell us about the harness and what the harness is supposed to be to help us get those agents into production. So, the harness I’m not
[04:22] going to sit here and tell you I I am the expert on the harness. Um I’m going to tell you from everything I’ve researched, I’m trying to give you at least a map to a degree of what I understand so far with the understanding that there’s a lot of debate about this. I’ve heard that the harness is possibly the model is is part of all of this or it’s not. I think there’s there’s debates around whether the model’s in it, whether tools are in it, memory’s in it, uh guardrails, security, but ultimately it’s all about getting these agents with structure so that they can work reasonably well when they’re put
[04:53] out into production. And part of that picture should be durability. The system that I showed you, the demo that I just showed you, this is what it is. It’s got these loops. We’ve got a loop for the fleet agent, we got a loop for the customer agent, we got a loop for the dispatch agent. The fleet and the customer are doing research. One’s doing it on the actual drivers using thing tools like Google Maps. Um the other one is doing research on the orders like Google with tools like Google Search. While the dispatch
[05:24] agent is taking that input and making decisions with it. All right. So, that’s great that these activities are happening with these three loops and we’ve got the human potentially providing input in part of this structure. But what’s important is that we need to have some durability in that system to make sure that it stays up and running and doesn’t fall over. And that’s where Temporal comes in. So, Temporal is helping you to standardize your fai- failure handling and your state management in your system.
[05:55] Any system, any distributed system, especially any systems with agents, we are going to help you standardize that. We’re software and we’re also a service. The software itself is creating a lot of primitives that you can just use out of the box and basically apply to your code base. We come in all kinds of flavors of code, uh so you can use this in Python or TypeScript or Rust, um but ultimately we’re giving you some standard primitives to apply to your code to be able to make sure your your state your your system is stateful.
[06:26] So, the three main primitives we tend to talk about are the worker, the workflow, and the activity. The worker is really running that code. The workflow is where you’re going to be able to uh keep track of the steps in your system. And so, this is where like an 80K framework would be running inside a workflow. Uh your agent could work run inside of a workflow cuz it’s a loop, right? Whereas the activity is all the stuff that’s integrating or interacting with stuff externally. So, if you’ve got a loop, uh any kind of model call or any
[06:58] kind of tool call, those would be set up as activities. So, these are the primitives. So, you structure your code with our primitives to be able to track the state of your system. And we’re free and open source at that GitHub URL. Um you pay us if you you have us manage your state with our service. Otherwise, you can host it self-host it on your own system. Let’s get back to human in the loop. Why uh what I wanted to really get across to you about this whole talk. So,
[07:30] the human, granted, you know, we’re not tools, but we are a tool to the agent. Um and you might think, “Okay, well, we’re going to call the human or we’re going to have the human come in and give us uh some kind of information to pass into this loop. If you write it just straight out as a function to say call the human or let the human have a an input, it can become a blocking call. And it can get lost if your service went down. It might lose track of what was going on with that human’s
[08:01] engagement. What you want is these two core primitives to be applied to your your code and your agents. You want a wait condition and a signal. You’re allowing yourself to isolate an event, apply a wait condition, store that in that workflow, in that durability layer, so that if anything fell over in the system, when that system came back up, it would know where it left off.
[08:31] And you could send a signal at any point, but the whole system could keep running without you necessarily being blocked on that one call to the human. The code pretty much is is is fairly simple in terms of the primitives. And granted, I know this is Python, but it’s the same situation. You’re going to apply a wait condition and you’re going to apply a signal. You basically you’re not holding a thread, you’re not it’s going to survive any kind of crashes. It’s got all kinds of built-in
[09:02] primitives like timeouts, for example. If you’re waiting on a human to respond and you want to make sure that it only waits for so long, you can apply timeouts and other types of primitives. Um and this can scale. You can have millions of workflows out there parked, and it can keep running. So, what I want to show you actually I’m going to show you some more code, but I’m going to kick off the next demo so that it’s up and running. And I’ll share with all of you, if you haven’t already figured this out, uh my eyes are injured. >> [laughter] >> I am squinting at times and also
[09:34] realizing that I need additional in support here that I did not prepare for, but that’s okay cuz I can adapt. All right, so let’s get this other example up and running and then I’m going to tell you a little bit more about the code that’s up here. Let’s make sure that’s running. I’m resetting my example and of course it’s not going to be as easy peasy as I’d like. Also, is everybody hearing me okay? Think so. Great. It’s an interesting condition to be
[10:05] working in this space with the noises around us. All right, I think it’s up and running. All right, so let’s talk a little bit more about the code. Now, I already told you about our primitives of activity workflow and worker. And so with the activity, you are basically for ADK in particular, we have we have the temporal model class that you will wrap around the model and then you’ll pass it in for ADK to be able to set up that actual agent. It’s pretty
[10:36] simple. You apply this temporal model, you apply our activity tool to wrap around your tools and you you run your agent. You run your agent like you would with any kind of ADK setup that you’re going to do. And you also set up a worker and you pass in the Google ADK plugin. So that’s setting up your worker workflow and activity. And then similarly, you have your wait condition and the wait condition is using this async io when it uses a wait
[11:06] to say like for that specific workflow, I want you to pause it, don’t run any other code, but you can keep running the co-routines on that workflow or any other workflows in the system. Meanwhile, that workflow.signal, it will be able to take any kind of input and inject it into a running workflow. And the workflow will be taken off of your memory or taken off of your system and put in in parked if it’s not running anything at that point.
[11:36] So, I showed you human to agent. What I want to show you is what does it look like when the agent comes in and needs the human to be involved? It’s pretty similar. You’re using I’m just going to go ahead and tell you right now, you’re going to use a workflow you’re going to use a wait condition and a signal. I’m going to use LangChain in this example and also 80K because the reality is with Temporal we can work with multiple frameworks. We are framework agnostic. We work across a variety of different tools. Um
[12:06] so, in terms of LangChain they build out graphs and to build out the multiple agent setup. And in this integration the way we work, you’re passing us into each node for your graph. So, you’re setting up with the metadata looks like. And if you’re making any kind of model call like an invoke the model, that would be set up as an activity. If you’re making any type of other tool call, it would also be set up as an activity. But if it’s a step, a step in that process, then that’s set up as a workflow. This is determinism and non-determinism
[12:38] in terms of workflows are deterministic, activities are non-deterministic. And then of course, you pass in for the worker the plugin for the LangChain. In terms of LangChain in particular, we use the interrupt to call out from their node. So, this is part of LangChain and also to be fair, LangChain is more than a framework, but in this case I’m using it as a framework. But you use interrupt to call out and then what you’re going to do next is use that wait condition in
[13:08] the loop tracking for that interrupt signal to pause that workflow. And then the signal will capture whatever the human human responds with to the question that’s been asked. Okay, let’s see what that looks like. I’m going to bring up my demo and show you as they’re running. This is the design that I’ve got. I’ve got the customer and the fleet agents running on 80K. I’ve got the dispatch agent running on LangGraph. And Temporal is interwoven throughout.
[13:40] So, that’s how that’s working. Now, let’s see if I can show you. In this case, I’m going to drop a high-value order. This is an order that will most likely want a human involved. The workflow for the whole system is showing that all these agents are doing their job. They’re continuing to keep assessing orders. And the way I’ve got this set up is I have workflows uh child workflows that are split off for each order per framework. So, that
[14:12] special order actually had its own assessment done. And here we see that the customer and the fleet agents did their work. They did their assessment. They came back with a result. And they sent that off to the dispatch agent. The dispatch agent said, “Hey, okay, I need Oh, well, there you go. >> [laughter] >> I need to get uh a human involved in this. So, I’m going to go into a pause state while I’m waiting for the human to respond.” And we know that humans are not going to
[14:44] respond in 200 milliseconds. If you are, that’s great. Maybe there’s a there’s probably a couple people out there who are. But humans are most likely going to take several minutes, maybe days, maybe weeks, maybe longer. And you can you can because this is just pausing that one specific event. And as you can see, the little cars are continuing to keep going. So, now what I’m going to try to do is show you what happens if I was to take this service offline. So, let’s make it bigger for all of us. And
[15:19] kill worker. Cool. So, that takes it offline. You can see it’s disconnected. Don’t mind me as I do this in a very interesting way. All right. If I say approve while it’s offline, so what’s happened is as I mentioned, this is stuff that’s happening off of your service. It’s over on its own data store. So, we can still keep track of that event and queue it. And then when I bring it back up,
[15:50] yeah, I know. I have this really well organized here here for y’all. But, I’m going to I’m going to bring it back up and then we’re going to see if it works. Let’s see. Make it. And it’s back online. And you’ll notice that the dispatch agent will What’s happening is that your event log is getting replayed. It’s not redone. It’s just replayed up until the point at which it last left off, so it knows, here’s my current state. And this is now the next step in that state. And it’s been queued up to then have that step know that it that the person approved
[16:20] it, and that order got assigned, and it’s already been delivered, actually. So, there you go. That is durability in your system. Your system can come down, and it can recover. And it can have all these other primitives that will help you manage a complex state because these kinds of distributed systems are complex. All right. Last couple things I want to mention. When should the human be in the loop? This is the real question. It’s a hard one. I will say this. The big thing you
[16:51] want to take into consideration is the cost of being wrong is high. Okay, it’s a case-by-case basis, and we know we’re trying to get to autonomy as much as we possibly can. We also know these models are probabilistic, and they are hard to get to a place to be reliable. That’s why we got all this stuff happening around harnesses that are interesting. I could go into a whole ’nother conversation about that if y’all want it at a later date. But, ultimately, you want to assess the cost of being wrong. What is that worth to you? And especially in a security standpoint. And we know like on the other side of this picture, alert fatigue is real. Like a
[17:21] lot of us are seeing, you know, you just start saying yes, yes, yes, yes, yes every time it asks you questions. So, you’re trying to balance between those two. And we’re trying to get the models better so that you can trust them, so that you can address that alert fatigue, but they’re still probabilistic models. So, when should they be in the When should the human be in the loop? That’s the thing you’ve got to evaluate for the problems that you’re solving. At the end of the day though, what you saw there, what I gave you as an example, whether it’s the human initiating it or the computer initiating
[17:52] it, um you were seeing that we are using two main primitives in terms of you’re applying a weight condition to pause that workflow, and a signal from the human to be able to continue the work and say, “Here’s the result. Now keep moving forward.” And And whether you’ve actually paused it and taken it offline or you brought it back online. And I’ve shown you that we can use multiple frameworks. All right, if you have any questions, I’m going to stick around for a few more
[18:23] minutes. Um if you I’ve got up here a QR code that will take you to some resources about Temporal, as well as some of the demos that I’ve done, this demo included. This is up on GitHub. Uh the slides itself will be up later cuz of course in true form I’ve been tweaking them up until now. So, I’ll be posting those up and linking them to the GitHub repo. But yeah, if you have questions, please reach out. Um and you know, have fun building your agent clips. I’m also curious to hear what your what problems you’re solving with agents and how you’re building them
[18:54] autonomously currently. So, feel free to find me. And thank you. >> Woo!