Usando Jev no seu agent harness
Autoria: Sam Witteveen · 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: Using Jev In Your Agent Harness · Canal: Sam Witteveen · 20:21 · Assistir no YouTube
Tópicos: Agentes de IA, Engenharia de prompts e contexto, Modelos de IA, RAG, busca e recuperação de informação
O vídeo explica como Jev e outros decision models podem melhorar um agent harness ao lidar com decisões rápidas, como selecionar ferramentas, verificar riscos e avaliar resultados. O apresentador descreve seis usos principais e quatro pontos do loop em que esses modelos podem ser integrados, além de alertar sobre situações em que um LLM continua sendo mais adequado. Nas demonstrações, mostra a seleção progressiva de skills por categoria e o reranking de resultados de RAG. A proposta é reduzir custos e latência sem substituir o LLM em tarefas que exigem texto ou raciocínio complexo.
Pontos-chave
Seção intitulada “Pontos-chave”- Muitas chamadas em um agent harness servem para tomar decisões, não para gerar texto; decision models podem responder a essas decisões com rapidez e probabilidades.
- Jev pode ser usado para roteamento de modelos, verificação de risco antes de executar ferramentas, seleção de tools e skills, ranking de resultados, triagem e filtragem em tempo real.
- O modelo pode ser integrado antes da construção do prompt, antes da chamada ao modelo, antes da execução de uma ferramenta e depois que um resultado retorna.
- A divulgação progressiva de skills pode ser feita em duas etapas: escolher uma categoria e, depois, selecionar a skill apropriada.
- Para RAG, um decision model pode pontuar passagens recuperadas e selecionar as mais relevantes para enviar ao LLM.
- Decision models são mais adequados a decisões claras e rápidas; tarefas que exigem texto, raciocínio em várias etapas ou síntese continuam sendo trabalho de LLMs.
- Entradas muito longas, perguntas compostas, prompt injection, critérios vagos e o envio de dados a uma API hospedada são limitações a considerar.
- O apresentador recomenda definir critérios explícitos e avaliar as mudanças com benchmarks.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:00 | Decisões dentro do agent harness | O apresentador explica por que muitas etapas de um agent são decisões e como decision models podem reduzir o custo e a latência dessas chamadas. |
| 04:17 | Usos e pontos de integração | São apresentados seis usos de Jev e quatro momentos do loop em que um decision model pode ser conectado. |
| 09:06 | Limitações e cuidados | O vídeo aborda tarefas inadequadas para decision models, entradas longas, perguntas compostas, prompt injection e privacidade. |
| 12:13 | Demonstração: seleção progressiva de skills | Jev classifica uma tarefa por categoria e escolhe uma skill, evitando carregar todas as skills no prompt. |
| 16:02 | Demonstração: reranking para RAG | O modelo pontua passagens recuperadas e seleciona as mais relevantes para encaminhar ao LLM. |
| 18:45 | Recursos e conclusão | O apresentador indica materiais sobre Jev e incentiva experimentar decision models em harnesses personalizados. |
Citações
Seção intitulada “Citações”Jev é como um if inteligente. — 03:13
Se um grupo de pessoas inteligentes puder responder à pergunta em poucos segundos, provavelmente é o tipo de pergunta para um decision model. — 06:58
Monte um estado com o que o loop já tem, faça suas perguntas e leia as probabilidades e respostas que voltarem. — 08:01
Você precisa definir as instruções e os critérios por conta própria. — 11:12
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- Jev (modelo): Decision model apresentado como uma forma rápida de responder a perguntas estruturadas sobre um estado e retornar respostas tipadas com probabilidades.
- OpenJevs (modelo): Versões abertas de decision models mencionadas como alternativas que podem ser executadas localmente.
- agent harness (conceito): Estrutura que coordena o loop do agent, as chamadas ao LLM, as ferramentas e o processamento dos resultados.
- decision model (conceito): Modelo voltado a decisões estruturadas, como escolher uma opção, atribuir uma pontuação ou responder sim ou não.
- RAG (conceito): Abordagem que recupera informações e pode usar reranking para selecionar passagens relevantes antes de enviá-las ao LLM.
- skill (conceito): Instrução ou capacidade que pode ser carregada sob demanda no contexto do agent.
- TypeSafe (empresa): Organização cujas orientações e modelos Jev são citados no vídeo.
- LangChain (ferramenta): Framework mencionado como compatível com a integração de decision models por middleware.
- OpenRouter (ferramenta): Serviço indicado pelo apresentador para acessar Jev e consultar materiais sobre o modelo.
- Pydantic (ferramenta): Projeto citado por oferecer uma integração de um modelo TypeSafe ao loop de agents.
- BM25 (conceito): Método de recuperação mencionado como alternativa a um embedding model para obter passagens que podem ser reordenadas.
- Sam Witteveen (pessoa): Apresentador do vídeo e autor das demonstrações de uso de Jev em um agent harness.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:00 Certo, a maioria das chamadas de modelo em um agent harness não está realmente escrevendo nada. Elas estão tomando decisões. Decisões como: qual ferramenta devo usar aqui? Qual skill devo carregar? Este comando é seguro para executar? E até decisões para coisas como RAG, em que se pergunta qual destes 20 resultados de busca realmente responde à pergunta. E, até pouco tempo atrás, todo mundo abordava essas decisões praticamente da mesma maneira. Usavam uma chamada completa de LLM para obter a resposta.
00:32 Então, neste vídeo, quero mostrar como você pode usar Jev e os outros modelos de decisão open source para realmente melhorar um agent harness por dentro. Vou falar sobre algumas coisas que você pode fazer com ele. Vou mostrar alguns exemplos legais com os quais tenho trabalhado: divulgação progressiva em muitas skills e reclassificação de resultados de RAG. Mas também vou falar sobre alguns princípios gerais e, talvez mais importante, sobre os casos de uso em que você não vai querer usar um modelo como esse. Certo, vamos começar pelo loop que todo agent executa.
01:02 Uma solicitação chega e vai para um LLM. Junto com isso, você basicamente tem algum tipo de registro de ferramentas, um system prompt, talvez um conjunto de skills, algumas diretrizes sobre como o agent vai funcionar etc. E o LLM decide imediatamente que ação deve tomar, se precisa usar uma ferramenta. E, se precisar, ele escreve uma chamada de função, fornecendo o nome da ferramenta e os argumentos como JSON. Seu scaffolding, seu agent harness, então executa esse código como uma função. Ele obtém os resultados e os acrescenta à conversa, e o
01:34 conjunto todo volta para o LLM. E o processo se repete até que, por fim, o LLM decida que terminou e escreva a resposta final. Ao longo desse caminho, provavelmente vai usar muitas ferramentas. Basicamente, vai obter informações para expandir seu contexto. E vai tomar muitas decisões ao longo do percurso. Agora, se você observar essas etapas do LLM para ver o que realmente está acontecendo em cada uma, todo aquele processo de ele se perguntar qual ferramenta deve usar, se é seguro executá-la e, muitas vezes, por tomar essas decisões sozinho, ele nunca realmente
02:06 para para fazer algum tipo de etapa de verificação ou de segurança, para perguntar: isto é seguro para executar? E, para a maioria dos agents, se não houver algum tipo de etapa de reflexão, eles nunca chegam nem a se perguntar: “Este resultado é bom o bastante ou devo dar outra volta e tentar de novo?” Cada uma dessas coisas é uma decisão clara para a qual você pode usar um modelo de decisão como Jev ou um dos OpenJevs para realmente melhorar a qualidade do agent harness. Além disso, muitas vezes as decisões que o LLM está de fato
02:39 tomando envolvem apenas um pequeno conjunto de opções. Vou para este nó ou para aquele? Qual skill parece ser a melhor para usar nesta situação? De qual skill peço mais informações nesta situação? E, a cada vez, você paga por uma chamada completa a um LLM grande. Isso custa dinheiro pelos tokens, mas, muitas vezes, custa ainda mais tempo, porque você precisa esperar a execução dessas etapas. É por isso que, muitas vezes, quando as pessoas criam agents personalizados, elas não incluem nem de perto tantas etapas de verificação quanto deveriam
03:13 simplesmente porque isso deixaria tudo muito mais lento. Então, se você assistiu a algum dos meus outros vídeos sobre Jev, sabe que falei basicamente do conceito de Jev como uma instrução if inteligente. Você fornece um estado, que é simplesmente aquilo que está avaliando, e depois fornece um conjunto de perguntas tipadas sobre esse estado. Ele retorna respostas tipadas com probabilidades. Sem texto algum. choice escolhe uma opção de uma lista. Score avalia o estado em uma escala que você define.
03:44 Um booleano é um sim ou não, ou verdadeiro ou falso, retornado como uma probabilidade. E o legal é que você não fica limitado a uma pergunta de cada vez. Pode fazer muitas perguntas sobre um mesmo estado em uma única chamada e receber as respostas em paralelo. E isso quase não altera o tempo de resposta. Então, se está pensando em como melhorar seu agent harness, uma das principais coisas que pode fazer é observar esse loop, cheio de instruções if disfarçadas de ferramentas de função ou de solicitações ao modelo
04:17 para retornar respostas estruturadas em JSON. E você pode converter esse tipo de chamada em algo muito mais rápido, como um modelo de decisão. Certo, então onde isso realmente se encaixa no seu agent harness? Eu diria que há seis áreas principais que você deve considerar. A primeira é o roteamento de modelos. Fiz um vídeo inteiro sobre como você pode fazer isso. Veja só: chega uma solicitação e Jev decide se ela vai para um modelo barato e rápido ou para um modelo caro que fará um raciocínio muito melhor, e assim por diante. Se ainda não assistiu ao vídeo que fiz sobre isso, pode ver todo o processo de raciocínio
04:48 para montar tudo isso. O segundo uso é o controle de risco. Antes de uma chamada de ferramenta ser executada, Jev pode verificar se ela vai fazer algo destrutivo, como excluir um banco de dados ou apagar uma pasta, ou se o que vai fazer é algo inofensivo. Sabemos que muitos agents de programação já têm esse tipo de verificação há algum tempo, mas, em geral, ela fica oculta no harness. E, quando você a usava, basicamente pagava por uma chamada completa de ferramenta, de acordo com a quantidade de tokens utilizada. Então, você pode configurar seu harness para que, quando determinadas ferramentas forem chamadas,
05:22 talvez uma ferramenta bash, você examine quais argumentos serão passados e os envie para Jev, perguntando basicamente: “Ei, isso vai ser malicioso ou inofensivo?” Muito rapidamente, você tem uma verificação de segurança que pode levar milissegundos. E, claro, com os modelos de decisão open source, ela também pode ser executada totalmente localmente. Em terceiro lugar, temos a seleção de ferramentas e skills. Em geral, o que as pessoas faziam era inserir todo o registro de ferramentas que pretendiam usar no system prompt, o que podia consumir milhares de tokens.
05:53 A ideia das skills reduziu bastante isso usando divulgação progressiva. Essa é uma das principais coisas que vou mostrar um pouco nas demonstrações: você pode ter muitas skills, categorizá-las, fazer o modelo de decisão escolher de que categoria vai precisar e, então, carregar apenas as skills apropriadas no system prompt naquele momento. Em quarto lugar, temos coisas como classificação e avaliação. Essa é outra coisa que quero demonstrar aqui. Acho que a ideia de atribuir pontuações a trechos recuperados e avaliar respostas com base em uma rubrica
06:25 pode trazer um enorme benefício para tudo o que você faz com RAG ou para qualquer situação em que esteja inserindo contexto na context window. Em quinto lugar, temos coisas como triagem. Isso inclui tudo, como tickets de suporte e problemas de e-mail. Uma única chamada aqui pode fornecer uma probabilidade adequada de urgência para algo e começar a ajudar a atribuir uma probabilidade real de prioridade. E isso pode ser muito útil também para decidir quando fazer o modelo voltar ao humano, em situações com human in the loop. E o sexto uso, sobre o qual não vou falar muito aqui, é a ideia de
06:58 filtragem em tempo real. Isso pode ser muito útil sempre que você estiver lidando com APIs, solicitações de polling ou qualquer situação em que seja bom filtrar o que retorna antes de inserir isso na context window. Então, a regra prática que uso para tudo isso vem da própria Typesafe. Se um grupo de pessoas inteligentes pudesse responder à pergunta em apenas alguns segundos, então provavelmente é o tipo de pergunta para a qual você deveria usar um modelo de decisão. Se elas precisarem se afastar para elaborar uma resposta e depois escrever algo complicado
07:30 responder, é quando você deve continuar usando os LLMs. Daqui a pouco, vou analisar os casos de uso em que você não deveria usar esses decision models de jeito nenhum. Então, como você conecta isso de fato? Se voltarmos àquele loop que vimos, há quatro pontos em que podemos inserir uma decisão. E, na verdade, eles serão os mesmos em qualquer framework, seja usando LangChain, ADK ou apenas código Python personalizado para escrever seu próprio loop. Você pode agir antes de o prompt ser montado e decidir quais skills ou ferramentas carregar.
08:01 Antes da chamada ao modelo, decida qual modelo específico você vai chamar. Antes de uma ferramenta ser executada, decida se é seguro; depois que um resultado voltar, decida se ele é bom o suficiente para usar ou se você deve voltar e passar pelo loop novamente. Então, cada ponto de integração aqui é o mesmo pequeno trecho de código. Monte um estado com o que o loop já tem, faça suas perguntas, leia as probabilidades e as respostas que voltarem e, então, ramifique ou tome sua decisão sobre o caminho a seguir com base nelas.
08:32 Agora, há também um segundo padrão que você pode usar, em que Jev é quem toma as decisões no loop, e o LLM é o fallback. Assim, Jev escolhe a ferramenta ou a resposta e só encaminha para o LLM quando não tem certeza ou quando é preciso escrever um texto. Esse padrão pode reduzir ainda mais as chamadas ao LLM, mas certamente exige uma mudança muito maior no seu agent. Até agora, descobri que ele simplesmente não parece funcionar tão bem quando há muito mais coisas complicadas acontecendo. De qualquer forma, você não precisa de um framework para nenhum desses padrões. Dito isso, o primeiro padrão que mencionei aqui já foi disponibilizado pelo LangChain como middleware. E o Pydantic
09:06 disponibilizou sua própria versão, transformando o modelo TypeSafe em algo que você pode simplesmente conectar e usar no loop do agent. Certo, antes de mostrar as demonstrações, vou explicar rapidamente onde acho que isso não se encaixa. Claramente, em qualquer situação em que você precise receber um texto. Em qualquer situação que exija algum tipo de raciocínio em várias etapas e em qualquer situação em que você precise conectar várias coisas para gerar uma resposta. Tudo isso ainda é trabalho para um LLM. E, em muitos aspectos, boa parte dessas tarefas com várias etapas ainda será o tipo de coisa para a qual você vai usar o LLM e depois
09:37 fazer seu harness processar isso e continuar enviando de volta para o LLM grande. A segunda coisa que você deve considerar aqui é o tamanho. Se o seu estado estiver ficando grande demais e você estiver tentando passar 100.000 tokens para obter algum tipo de resposta daquele context window, Jev não será uma boa opção. A documentação da TypeSafe diz que a precisão cai bastante com entradas longas. E, em geral, parece que isso se aplica tanto ao usar o decision model Jev da TypeSafe quanto ao usar um dos decision models open source.
10:09 Além disso, outra coisa, obviamente, é que o próprio Jev não usa imagens. Alguns dos modelos open source, por outro lado, usam imagens — e muito bem. Então, no momento, isso é definitivamente uma vantagem dos decision models open source em relação aos modelos proprietários. Certo, outra coisa que não funciona bem são as perguntas compostas. Os decision models muitas vezes não lidam muito bem com perguntas compostas. Se você tem uma pergunta de sim ou não, tudo bem. Mas, se há algo que exige responder a várias perguntas, muitas vezes o LLM vai se sair melhor nesse tipo de tarefa.
10:41 Outra coisa com que você deve ter cuidado é que, embora os decision models possam ser muito bons em detectar pontos fracos, é preciso ter cautela ao confiar neles o tempo todo. No momento, parece que muitos desses modelos podem sofrer prompt injection, com instruções que acabam desviando os resultados. Muitas vezes, a maneira de contornar isso é fazer primeiro uma pergunta para saber se há algum prompt injection no conteúdo, antes de passar a pergunta que você realmente queria fazer. Outra coisa que percebo é que você precisa pensar de verdade sobre
11:12 os critérios para tomar as decisões. Se houver pontos de decisão muito claros, nos quais você faz as mesmas perguntas, você consegue controlar muito bem os critérios em situações assim. Se você estiver fazendo uma pergunta vaga sobre a saída do LLM e não tiver critérios claros, eu não necessariamente confiaria no LLM para formulá-los de um jeito que melhore muito o sistema como um todo. Você deve definir as instruções e os critérios por conta própria
11:42 e depois fazer benchmark de todas as mudanças que implementar ao longo do tempo. E, claro, por último, se você estiver executando seu agent localmente, mas usando Jev na nuvem, precisa considerar o fato de que se trata de uma API hospedada e perguntar se realmente confia nela para cada estado que enviar à nuvem. Tudo bem que isso saia da sua máquina? E acho que é aqui que os decision models open source têm avançado bastante. Então, vamos às demonstrações e ver alguns exemplos de como você poderia fazer isso para algumas dessas tarefas principais e alguns dos desafios
12:13 que talvez encontre pelo caminho. Certo. Nesta demonstração, criei uma interface só para facilitar a visualização do que está acontecendo. Mas este é exatamente o tipo de decisão que acontece no seu agent. Se tivermos um conjunto de skills, cada vez mais pessoas estão começando a usar grandes quantidades de arquivos de skills. E lembre-se de que o mais legal das skills é que elas permitem a divulgação progressiva. A ideia aqui é que, se este for o arquivo da skill — e ele pode ser bem mais longo —, ao percorrê-lo, você só fornece isso ao modelo depois que ele
12:48 decidir que, certo, precisa basicamente usar uma skill de programação para escrever testes. Aí, você realmente forneceria isso no context window. O que fazemos de diferente aqui é que, em vez de fornecer 50 skills de uma vez, vemos que, para cada uma dessas 10 categorias diferentes, temos cinco skills. E, se injetarmos isso no system prompt toda vez que chamarmos o LLM, vamos consumir muitos tokens.
13:18 Então, a ideia é que o que injetamos no LLM são apenas as categorias de skills. E o próprio modelo Jev basicamente recebe a tarefa que temos. Em seguida, decide de qual categoria escolher; depois, recebe a lista de skills dessa categoria e escolhe a mais adequada para fazer isso. Então, vamos ver. Se a tarefa for basicamente alguém dizer que outra pessoa recebeu um e-mail fingindo
13:49 ser nosso CEO e pedindo cartões-presente: isso é um ataque hacker? Você pode ver que estou executando isso com um dos modelos Jev maiores, mas, na verdade, dá para testar com muitos modelos Jev diferentes. Se eu executar e encaminhar isso, você verá que primeiro ele decide que a categoria é segurança e acesso. Então, ele fez essa escolha. Basicamente, retornou isto. E, nessa categoria, há várias opções. Podemos ver que ele decidiu investigar um alerta de segurança.
14:23 E, de fato, a descrição dessa skill é fazer a triagem de um login suspeito, de uma denúncia de phishing ou de um alerta de segurança. Você pode ver que, neste caso, o que fizemos foi uma espécie de classificador em cascata: primeiro, usamos um classificador para identificar a categoria e, depois, usamos um segundo para identificar a skill, neste caso. Como estamos executando isso localmente, foi super-rápido. Certo. Você pode ver que, se eu fizer uma pergunta mais geral aqui, há algumas coisas que podemos fazer.
14:54 Vamos encaminhar isso. Como esperado, neste caso, basicamente está dizendo: “Pesquise na web, verifique os fatos de uma afirmação.” Certo? Provavelmente também poderia ter optado por “pesquise na web”, embora eu ache que… isso faz mais sentido, na verdade, porque está apresentando um fato e perguntando se ele é verdadeiro. A partir daí, poderíamos carregar o arquivo da skill ou usar qualquer tipo de API, etc., que quiséssemos. Certo, mais um exemplo aqui. Você pode ver: “Faça uma narração curta desta descrição do produto para um vídeo de lançamento.” Agora ele está decidindo que isso está relacionado a imagens, áudio e vídeo, e que precisa
15:28 ter uma skill de conversão de texto em fala. Essa é uma forma de usar Jev para fazer uma divulgação progressiva das skills, especialmente se você tiver muitas skills. Ao classificá-las primeiro em categorias e depois determinar qual skill está sendo escolhida, você consegue obter um resultado muito rápido. Em seguida, a própria skill pode ser enviada ao LLM para descobrir quaisquer argumentos que precisem ser incluídos nela, esse tipo de coisa. Isso nos ajuda a reduzir o gasto de tokens, mas também a acelerar as coisas. Outro
16:02 exemplo que você pode usar na mesma linha é fazer etapas de verificação das respostas recebidas de APIs, basicamente para que o sistema decida se o que voltou da API está realmente bom e pode ser aceito diretamente. Ou se você precisa alterar os argumentos enviados à API, ou se precisa chamá-la novamente porque recebeu um determinado tipo de erro, etc. A próxima demonstração combina isso com RAG. Um dos padrões de RAG que funciona muito bem é buscar uma grande quantidade de informações e depois reclassificá-las.
16:35 Em geral, há maneiras de fazer isso usando um modelo reclassificador separado, e esse padrão pode funcionar muito bem. O único desafio é que, em certos projetos, simplesmente não dá para fazer isso por causa do tempo. Também pode não dar para fazer isso porque você vai precisar de mais modelos; e, principalmente, se já estiver usando um modelo de embedding por meio de uma API, provavelmente não vai querer fazer muitas chamadas à API para reclassificação e coisas desse tipo. A ideia aqui é que podemos fazer uma pergunta. Ele vai buscar muitas passagens diferentes e, em seguida, vai enviá-las para
17:08 o próprio modelo Jev, que pode decidir: “Certo, estas são as cinco principais passagens que vou enviar ao LLM completo.” Há diferentes maneiras de fazer isso. Você poderia, basicamente, usar uma abordagem de sim ou não. Poderia usar algum tipo de pontuação. Ou, se realmente quisesse escolher apenas uma, poderia simplesmente oferecer uma opção para ver o que vai ser selecionado. Para mim, ao testar isso, a opção de pontuação parece funcionar muito bem. Então, basicamente, obtemos uma pontuação. A pergunta aqui é: “Por que minhas solicitações de webhook estão falhando com um erro?”
17:40 E então podemos ver que, como esperado, estamos recebendo de volta “verificação de assinaturas de webhooks”. Em segundo lugar, “corpos brutos de webhooks”. Em terceiro, “proxies”. Em quarto, “segredos de assinatura de webhooks”. E você pode ver que agora temos os cinco itens que podemos enviar de volta. Isso é algo que você poderia até usar sem um modelo de embedding, se estiver usando apenas algo como BM25 para obter diferentes seções. Você pode ter um pouco do melhor dos dois mundos fazendo uma busca ampla que retorna 25 passagens diferentes e, em seguida, usando
18:13 o modelo Jev — neste caso, novamente, usando um dos modelos locais open source — para selecionar as cinco principais, que você então envia ao seu LLM. Você pode ver que, se eu testar com outro modelo, ele consegue percorrer o conteúdo, obter partes diferentes do contexto, selecionar o que é mais relevante e, então, passar isso adiante. Esses trechos de texto são certamente maiores do que os que eu tinha com as skills, então talvez isso não seja tão rápido quanto o sistema em cascata que usamos no exemplo anterior.
18:45 Mas, fundamentalmente, a ideia ainda é a mesma: usar pontuação e classificação, com base no conhecimento de mundo presente naquele decision model específico, para ajudar a tomar decisões simples, mas úteis. Certo, para encerrar, você pode ver que há muitas aplicações para o próprio modelo Jev ou para as várias versões open source dele na criação de qualquer tipo de harness personalizado. Se tiver interesse, recomendo que explore mais essas possibilidades e leia alguns dos tutoriais do Jev.
19:17 A OpenRouter tem um aqui. E, quando uso o modelo Jev, faço isso pela OpenRouter. Então, para quem está perguntando: se você não foi incluído na lista de permissões da API TypeSafe no site deles, qualquer pessoa pode usar esta versão da OpenRouter. Outro recurso útil que vale a pena conferir é um bom artigo da LangChain sobre como usar Jev com LangChain, com diferentes aplicações e coisas do tipo. Eles até criaram um middleware para isso. Mas, de modo geral, eu diria: experimente. Se você estiver criando qualquer tipo de harness personalizado ou fazendo qualquer tipo de modificação em um
19:50 harness, vale muito a pena considerar incluir isso no seu pipeline, para tomar essas decisões de forma muito rápida e barata e, assim, melhorar os resultados gerais do seu harness. Enfim, como sempre, contem nos comentários o que vocês já experimentaram. Tenho certeza de que há muitos exemplos que não incluí neste vídeo. Então, se vocês tiverem casos de uso interessantes, compartilhem, porque seria muito interessante conferir e ver que outras ideias interessantes as pessoas têm para usar esse tipo de coisa. E, como sempre, se acharam o vídeo útil, cliquem em curtir e inscrevam-se, e
20:21 converso com vocês no próximo vídeo. Até mais.
Transcrição original
[00:00] Okay, so most of the model calls in an agent harness aren’t actually writing anything. They’re making decisions. They’re making decisions like which tool should I use here? What skill should I load? Is this command safe to run? and even decisions for things like RAG, where it’s asking which of these 20 search results actually answers the question. And up until recently, everybody has approached those decisions pretty much in the same way. They’ve used a full LLM call to get the answer back.
[00:32] So in this video, I want to show how you could use Jev and the other open decision models to actually improve an agent harness from the inside. I’m gonna talk about some of the things that you can actually do with it. I’ll show you a couple of cool examples that I’ve been playing with for doing progressive disclosure on lots of skills and for doing re-ranking of RAG results. But I’ll also talk about some general principles And perhaps more importantly, what are the use cases that you don’t want to use a model like this? Alright, so let’s start with the loop that every agent runs.
[01:02] A request comes in and it goes to an LLM. Along with that, you basically have some kind of tool registry going in there, a system prompt, perhaps a set of skills some guidelines of how the agent’s gonna work, et cetera. And the LLM decides straight away what action should it take, whether it needs to use a tool. and if it does, it writes out a function call, giving us the tool name plus the arguments as JSON. Your scaffolding, your agent harness then runs that code as a function. it gets the results and it appends that to the conversation, and the
[01:34] whole thing goes back to the LLM. And then round and round this goes until eventually your LLM’s decided it’s done and it writes its final answer. Along that road, it’s probably gonna use many tools. It’s basically gonna get information to expand its context. And it’s gonna make a lot of decisions along the way. Now, if you look at those LLM steps to see what’s actually going on at each step, the whole sort of thing of asking itself which tool it should use? Is it safe to actually run that? And often because it’s making those decisions itself, it never really
[02:06] stops to ask any sort of verification step or any kind of safety step in there to ask, is this safe to run? And for most agents, if they don’t have any sort of reflective step in there, they’re really never even asking themselves, “Is this result good enough, or should I go around again and try again?” Each of those things are clear decisions that you can use a decision model like Jev or one of the OpenJevs to actually improve the quality of the agent harness. On top of that, a lot of the times the decisions that the LLM is actually
[02:39] making are just a small set of options. Do I go to this node next or this node? Which skill looks like the best one to use in this situation? Which skill do I ask for more information in this situation? And each time you’re paying for a full call to a large LLM there. And that’s costing you both in money for tokens, but often even more, it’s costing you in time of you actually having to go through and do these things. And that’s why a lot of the time when people are building custom agents, they often don’t put anywhere near as many verification steps in there
[03:13] as they should, simply because that’s just gonna slow everything down. So if you’ve watched any of my other Jev videos, you know that I’ve basically talked about the whole concept of Jev as being like a smart if statement. You give it a state which is just the thing that you’re evaluating, and then you give it a set of typed questions about that state, and it gives you back typed answers with probabilities. No text at all. choice will pick one option from a list. Score rates the state on a scale that you define.
[03:44] A noul is a yes or no or a true or false that’s returned back as a probability and the cool thing is you’re not limited to one question at a time. You can ask many questions about the one state all in a single call and get answers back in parallel. and it almost doesn’t change the response time at all. So if you’re looking at how to improve your agent harness, one of the key things you can do is look at that loop of where it’s full of a bunch of if statements that are dressed up as function tools or dressed up as asking the model
[04:17] for structured JSON responses back. And you can convert those kind of calls to something that’s much quicker, like a decision model. All right, so where does this actually belong in your agent harness? I would say that there’s six main places that you want to be thinking about here. So the first one is model routing. I did a whole video about how you can, look at this. You’ve got a request coming in. Jev decides whether it goes to a cheap, fast model or expensive model that’s gonna do much better reasoning, et cetera If you haven’t watched the video that I made about that, you can see the whole thinking process
[04:48] for actually putting that together. The second use is risk gating. So before a tool call actually runs, Jev can actually check whether it’s gonna be something destructive like deleting a database or wiping a folder or whether what it’s actually gonna be doing is quite benign. Now we know that a lot of the coding agents have had this kind of check for a while, but it’s been hidden generally in their harness. And when you were using it, you were basically paying for a full tool call with the amount of tokens that it actually gets used there. So being able to configure your harness so that when certain tools get called,
[05:22] perhaps like a bash tool, you actually look at what the arguments are going to be going into that, and you send that to Jev to basically ask it, “Hey, is this going to be malicious or benign?” Very quickly, you’ve got a safety check that can take milliseconds. and of course, with the open decision models, that can be running fully locally as well. third up you’ve got tool and skill selection so generally what people have done is they inject their entire tool registry that they’re gonna be using into the system prompt and that can chew up thousands of different tokens.
[05:53] So the whole idea of skills has reduced that a lot by using progressive disclosure. This is one of the key things that I’m gonna show you in the demos a bit, that you can actually have lots of skills going on, categorize them, have your decision model decide which kind of category it’s gonna need, and then just load the appropriate skills into a system prompt at that point Fourth up, you’ve got things like ranking and judging. So this is another one that I want to sort of demo here. I think the whole idea of scoring retrieved chunks and grading on answers against a rubric.
[06:25] This can be a huge win for anything that you’re doing with RAG or anything you’re doing where you’re injecting context into the context window. Fifth up, we’ve got things like triage. So this is all your things like support tickets, email issues, and one call here can give a proper probability of how urgent something is and start to help giving things an actual probability of priority here. and this one can be really useful for when to basically get the model to go back to the human for things like human in the loop as well. And the sixth use that I’m not gonna go into too much here is the whole
[06:58] idea of just real-time filtering. This can be really useful for any time you’re basically Dealing with APIs, polling requests, anything where it’s good to just filter what comes back from that before you inject that into the context window. So the rule of thumb that I use for all of these actually comes from Typesafe themselves. If a panel of smart people could answer the question in just a few seconds, then it’s the kind of question that you probably should be using a decision model for. If they need to go away and formulate an answer and then write a complicated
[07:30] answer back, that’s when you should be sticking with the LLMs. in a little bit I’ll actually go through the use cases of where you shouldn’t be using these decision models at all. So how do you actually wire this in? So if we go back to that loop that we had there, there are four places to hook a decision in. And really they’re going to be the same in any framework, whether you’re talking about LangChain, whether you’re talking about ADK, whether you’re just using custom Python code to write your own loop here. You’ve got before the prompt is built, so decide which skills or tools to load.
[08:01] Before the model call, decide which actual model you’re gonna call. Before a tool runs, decide whether it’s safe, and then after a result comes back, decide whether it’s good enough to use or whether you should go back and actually go through the loop again. So each hook here is the same small piece of code. Build a state from what the loop already has, ask your questions, and then read the probabilities and answers that come back, and then branch or make your decision for the path going forward based on those.
[08:32] Now there’s also a second pattern that you can use where Jev is the loop’s decider and the LLM is the fallback. So Jev picks the tool or the answer and only hands it to the LLM when it’s unsure or when something needs text to be written Now this pattern can actually cut more LLM calls, but it’s definitely a much bigger change to your agent And so far I’ve found with this one, it just doesn’t seem to work as well when you’ve got a lot more sort of complicated things going on in there Anyway, for either of these patterns, you don’t need a framework That said, the first pattern that I talked about here, LangChain has already shipped that as middleware And Pydantic
[09:06] has shipped their own version by making the TypeSafe model something that you can just plug in and use in the agent loop. All right, so before I show you the demos, let me just go through quickly where I think this doesn’t fit. Clearly anything where you need text back. Anything that needs any sort of multi-step reasoning and anything where you’re gonna need to connect several things together to generate an answer out. All of those are still an LLM’s job And in many ways, a lot of that multi-hop stuff is still gonna be the stuff that you’re gonna use the LLM for and then
[09:37] have your harness process that and keep passing it back to the large LLM. the second thing you want to think about here is size. So if your state is just getting too big, and that you’re trying to pass in 100,000 tokens to get some kind of response back from that context window, then Jev is not gonna be a good fit here. Typesafe’s own docs say the accuracy drops a lot on long inputs. And so it generally seems to fit whether you’re using the type safe Jev decision model or one of the open decision models.
[10:09] On top of that, another thing obviously is that Jev itself doesn’t use images. Now, some of the open models actually do use images and use images really well. So at the moment, that’s definitely a win for the open decision models over the proprietary models. Alright, another thing that doesn’t work well are compound questions So compound questions are often something that the decision models don’t handle that well. If you’ve got a yes, no question, okay, that’s fine. But if you’ve got something that requires multiple questions in there to be answered, then often the LLM is gonna do better for that kind of thing.
[10:41] Another thing you want to be wary about in here is while the decision models can be really good at spotting sort of weak spots, you want to be careful about how you always rely on them. It does seem currently that a lot of these models can be prompt injected to basically have instructions that actually move the results out of that. So often the way to get around that is to basically have a question first that asks, are there any prompt injections in here? Before you actually pass it on to the real question that you wanted to actually ask. The other thing I find too is that you really want to think about
[11:12] criteria for making the decisions. So if you’ve got, very clear decision spots where you’re asking the same questions, you can control the actual criteria, very well in situations like that. If you’re just asking some vague question about the output from the LLM and you haven’t got a nice, clear criteria in there I wouldn’t necessarily be trusting the LLM to write that in a way that’s gonna make the whole system a lot better. You kind of want to define the instructions and the criteria yourself
[11:42] and then benchmark any changes that you make to that over time. And then of course, lastly, if you’re actually running, your agent locally but then you’re using Jev in the cloud, you’ve got to think about the whole fact that it’s a hosted API and do you really trust it for every state that you’re gonna send to the cloud? is it okay that that leaves your machine? And I think this is where the open decision models have really come along so far now So let’s jump into the demos and actually look at some examples of how you could do this for a couple of these key tasks And some of the challenges
[12:13] that you might face along the way alright. So in the demo here, I’ve basically made a UI just so you can see what’s going on a lot easier. But these are exactly the kind of decisions that are going on, in your agent. So if we’ve got a bunch of skills, more and more now people are starting to use large amounts of skills files. and remember the whole thing that’s really cool about skills, is that you’ve got progressive disclosure in there. So the idea here is that if this is the actual skill file, and it might actually be a lot longer, going through this, you only give the model this after it’s
[12:48] decided that, okay, it needs to basically use a coding write tests skill for this. Then you would actually go and give it this in the context window. So the different thing that we’re doing here is that rather than just give it 50 skills, in one shot, We can see for each of these 10 different categories, we’ve got five different skills, in here And if we’re injecting that in the system prompt for every time we call the LLM, that’s gonna burn a lot of tokens.
[13:18] So the idea is that the thing that we inject into the, LLM is just the categories of skills. And then the Jev model itself will basically take the task that we’ve got. It will then decide which category, to pick from, Then it will be given the list of skills for that category, and it will then choose the most appropriate one to actually do this So let’s look at this. So if the task is basically someone saying someone got an email pretending
[13:49] to be our CEO asking for gift cards, is this a hacking attack? And you can see I’m running this through one of the bigger Jev models in here, but actually you can try it out on a lot of the different, Jev models. You can see if I run this and route it, it goes through and it basically first decides that the category here is security and access. So It’s done that as a choice. It’s basically returned this back. and then in this category, it has, a bunch of these in here. and we can see it decided investigate a security alert, in here
[14:23] And sure enough, the description for that is triage a suspicious login, phishing report, or security, alert in there So you can see in this case, what we’ve actually done is a sort of cascade classifier where we’ve done one sort of classifier first to basically pick out, the class of the category, and then we’ve done a second one to actually pick out the skill, in this case. Because we’re running this locally, it’s done it super quick, going through this. Alright. You can see that if I give it a sort of general question here, we’ve got, certain things that we can actually do.
[14:54] Let’s route it through. Sure enough, in this case, it’s basically saying, “ Do web research, fact check a claim.” Right? it probably could’ve, also gone for, search the web, although I guess… this does actually make more sense in that It’s actually stating a fact and then asking if it’s true here. And from there we could load the skill file or use any sort of API, et cetera, that we actually wanted to there All right, one more in here you can see, okay, make me a short voiceover of this product description for a launch video. now it’s deciding that, okay, that relates to images, audio and video, And it needs
[15:28] to be a text-to-speech skill in there. So this is a way of using Jev for sort of progressive disclosure, with skills, especially if you’ve got lots of skills. By classifying them first into categories and then putting them into, actually which skill is being chosen, you’re able to get a very fast result here, And then the skill itself can actually be sent to the large language model to work out any arguments that need to go into that skill, those kinds of things but this is able to help us reduce on token spend, but also just speed things up like this Another
[16:02] one that you can use in the same sort of vein of this is doing sort of verification steps of things that come back from APIs to basically have the whole thing make a decision of whether whatever’s coming back from the API is really good and can just go through, straight through, as a result, whether you need to change the arguments that you gave to the API Or whether you just need to call it again because you got a certain type of error, et cetera the next demo is combining this with RAG. so one of the patterns in RAG that works really well is go and get a lot of information and then re-rank that information.
[16:35] And generally there are ways to do that where you’ve got a separate re-ranker model, and that can work really nice as a pattern. The only challenge is that For certain projects, you just can’t do that because of time. You can’t do that because you’re gonna need more models and especially if you’re already using an embedding model on an API, you probably don’t wanna have lots of calls, to the API for re-ranking, for that kind of thing. so the idea here is that we can ask it a question. it will then go off, get a lot of different passages, then give those to
[17:08] the actual Jev model, which can decide, okay, these are the top five passages that I’m gonna send to the full size LLM. And there are different ways you could do this. You could basically do it on a sort of yes/no thing. you could do it via sort of, scoring kind of things. or if you really wanted to just sort of pick one, you could actually just have a choice of one to see, okay, what’s actually gonna go through in there? Now for me playing around with this, I find the scoring one seems to work quite nicely here. We then basically get a score. So in our question here is why are my webhook requests failing with an error?
[17:40] And then we can see, sure enough, we’re getting back webhooks verifying signatures. second up, webhooks raw bodies. third up was proxies. Fourth up was webhooks signing secrets. And you can see that we’ve got the five things now that we can basically send back. And this is something that you could even use if you weren’t using an embedding model, If you’re just using something like BM25 to basically get, different sections out you can kind of get a bit of the best of both worlds by having a sort of a broad sweep that gets you, 25 different passages back and then using
[18:13] the Jev model, again, in this case using one of the open local ones here, to actually go through and pick out the top five that you then send to your LLM. You can see if I try it with one of the other ones, that it’s then able to basically go through, get out, different parts of the context, pick out stuff that’s most relevant, and then pass that through. Now, These are certainly larger chunks of text than what I had with the skills before, so it’s perhaps not quite as fast as the cascading system that we had for the last one.
[18:45] but it’s still fundamentally the same idea of where you’re doing scoring and classification using the world knowledge that’s in that particular decision model to help it make simple but useful decisions for you. All right, so just to finish up, you can see that there are lots of uses of where you can use either the Jev model itself or the many open versions of this in building any sort of custom harness I recommend if you’re interested to basically think of these things more, come through and read some of the Jev, tutorials.
[19:17] this, OpenRouter has got one up here. And when I’m actually using the Jev model, I’m going through OpenRouter. So for those of you who are asking, if you haven’t been whitelisted for the actual TypeSafe API, on their site, Anyone can just come and use the OpenRouter one here. another useful resource that’s worth checking out is LangChain has got a nice article about using Jev, in LangChain, about different uses and stuff like that. they’ve actually made some middleware for doing this. but overall I would say just try it out. If you’re doing any sort of custom harness or any sort of, modifications to a
[19:50] harness, it’s definitely worth it looking at putting this in your pipeline to be able to get these really fast and really cheap decisions made for improving the results that your harness gets overall. Anyway, as always, let me know in the comments what you’ve tried out. I’m sure there are plenty of examples that I haven’t put into this video. so if you’ve got some interesting use cases, please share them ’cause that would be really interesting to check out and see, What other interesting ideas people have got for how to actually use this kind of thing And as always, if you found the video useful, please click like and subscribe, and
[20:21] I will talk to you in the next video. Bye for now