Pular para o conteúdo

De vibe coding à produção: como avaliar e lançar agentes de IA que funcionam — 101, com Laurie Voss, Arize AI

Ver no idioma original →

Autoria: AI Engineer · Assistir no YouTube

Vídeo de autoria do canal indicado, não da IANIA; todos os direitos pertencem ao criador. Transcrição, resumo e tradução gerados automaticamente; o conteúdo no idioma original é preservado na versão em idioma original.

Idioma original: inglês

Vídeo original: From Vibes to Production: Evaluating and Shipping AI Agents That Work 101 — Laurie Voss, Arize AI · Canal: AI Engineer · 1:51:24 · Assistir no YouTube

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

Laurie Voss apresenta um fluxo prático para avaliar agentes de IA e prepará-los para produção, usando Arize AX e um agente financeiro de exemplo. Ela explica como instrumentar aplicações, analisar traces e combinar code evals, avaliações com LLM como juiz e revisão humana. A oficina também aborda como validar os próprios juízes, transformar falhas em conjuntos de dados e comparar mudanças com experimentos. Por fim, mostra como fechar o ciclo em produção com avaliações online, monitoramento e agentes de programação que ajudam a corrigir problemas.

  • Traces mostram o que aconteceu em cada etapa do agente; evals medem se o resultado foi bom.
  • Leia traces reais e defina critérios de sucesso antes de criar evaluators.
  • Combine code evals determinísticos, LLM as a judge e avaliação humana, cada qual para os casos em que é mais apropriado.
  • Avalie resultados e estados finais, não uma sequência rígida de passos que o agente deveria seguir.
  • Escreva rubricas específicas, com critérios observáveis, exemplos e opções de resposta simples.
  • Valide os juízes comparando suas avaliações com rótulos humanos em um conjunto de dados de referência.
  • Use conjuntos de dados e experimentos para comparar mudanças com os mesmos exemplos e evaluators.
  • Em produção, avaliações online e monitores ajudam a detectar falhas e transformá-las em novos testes de regressão.
  • Priorize a qualidade dos dados e as melhorias de prompt antes de ajustar hiperparâmetros.
Início Capítulo Resumo
00:12 Objetivos da oficina e preparação Laurie Voss apresenta o conteúdo, as ferramentas necessárias e a conta Arize AX usada durante a oficina.
07:12 Fundamentos de traces e evals A palestrante compara evals a testes de IA e traces a logs que registram as etapas de execução.
14:27 Por que agentes são mais difíceis de avaliar Agentes introduzem decisões, chamadas de ferramentas, possíveis loops e falhas em cascata que precisam ser avaliadas.
20:40 Instrumentação com Arize AX A demonstração configura OpenTelemetry e OpenInference para enviar traces da aplicação à plataforma.
28:11 Construção e execução do agente financeiro A oficina cria um agente simples que pesquisa informações financeiras e escreve relatórios sobre ações.
36:28 Conjunto de testes e análise de traces Voss apresenta consultas variadas, examina falhas reais e explica como categorizar suas causas.
49:07 Primeiro code eval A palestrante cria uma verificação determinística para conferir se o relatório menciona o ticker solicitado.
58:01 Evals prontos e escolha do critério adequado A demonstração compara avaliações de correção e faithfulness e mostra por que o contexto determina qual usar.
1:06:17 Criação de uma rubrica personalizada Voss explica como elaborar critérios específicos e observáveis, delimitando os dados e incluindo exemplos.
1:17:40 Antipadrões e validação dos juízes A oficina aborda rubricas frágeis, evaluators que tentam medir tudo e a comparação dos juízes com rótulos humanos.
1:30:23 Conjuntos de dados e melhoria do agente Falhas são reunidas em um conjunto de dados e usadas para orientar mudanças de prompt e experimentos.
1:39:12 Iteração, amostras e desenvolvimento orientado por evals A palestrante discute o ciclo de experimentação, o tamanho das amostras e a escrita de evals antes de implementar funcionalidades.
1:42:17 Evals online e monitoramento em produção A demonstração mostra avaliações em traces de produção, amostragem de tráfego e o ciclo de monitoramento e correção.
1:45:59 Agentes de programação e fechamento do ciclo Voss explica como fornecer traces e requisitos a um agente de programação e encerra com recomendações para começar.

Evals são testes para IA, e traces são logs para IA. — 07:45

Você define o que quer, constrói, mede o quanto funciona, lança, monitora em produção e itera com base no que observa. — 20:40

Leia suas traces antes de escrever evals. — 39:06

O valor real está no ciclo, não na pontuação em si. — 1:39:12

Não espere que a excelência aconteça: você pode chegar a ela de forma sistemática, especificando, medindo e melhorando. — 1:50:07

  • Laurie Voss (pessoa): Palestrante que conduz a oficina sobre avaliação e implantação de agentes de IA.
  • Arize AI (empresa): Empresa apresentada como provedora da plataforma Arize AX e do projeto open source Phoenix.
  • Arize AX (ferramenta): Plataforma de observabilidade e avaliação usada para coletar traces, executar evals e monitorar aplicações de IA.
  • Phoenix (ferramenta): Projeto open source da Arize AI com ideias centrais compartilhadas com a plataforma Arize AX.
  • Claude Agent SDK (ferramenta): SDK da Anthropic usado na oficina para criar o agente financeiro de exemplo.
  • Claude Code (ferramenta): Agente de programação usado para propor melhorias na aplicação a partir das explicações das avaliações.
  • Anthropic (empresa): Empresa cujos modelos e ferramentas são usados na demonstração.
  • OpenTelemetry (conceito): Padrão de observabilidade usado para instrumentar a aplicação e transmitir traces.
  • OpenInference (conceito): Camada que acrescenta atributos específicos de LLM, como prompts, respostas e contagem de tokens, aos dados de observabilidade.
  • traces (conceito): Registros estruturados das etapas de execução de um agente, incluindo chamadas a LLMs e ferramentas.
  • spans (conceito): Unidades que representam etapas individuais de uma execução e compõem a estrutura de uma trace.
  • code evals (conceito): Avaliações determinísticas, geralmente escritas em código, para verificar condições objetivas de uma resposta.
  • LLM as a judge (conceito): Uso de um LLM para avaliar respostas segundo critérios definidos em uma rubrica.
  • faithfulness (conceito): Avaliação que verifica se a resposta permanece fundamentada no material de origem fornecido.
  • metaavaliação (conceito): Processo de verificar a qualidade de um evaluator comparando suas avaliações com julgamentos humanos.
  • conjunto de dados de referência (conceito): Coleção de exemplos rotulados por pessoas, usada para medir e calibrar evaluators.
  • experimentos (conceito): Execuções controladas sobre os mesmos exemplos e avaliações para comparar mudanças no agente.

00:12 Olá, pessoal. Tenho uma sala lotada para um workshop de duas horas, o que é incrível. Boas-vindas ao AI Engineer. Sei que ninguém deu as boas-vindas oficialmente, mas sejam bem-vindos ao AI Engineer. Este local é incrível. Este público é realmente surpreendente, e tenho muito conteúdo para vocês hoje. Meu nome é Lori Voss. Sou diretora de relações com desenvolvedores na Arize AI. Alguns de vocês talvez se lembrem de mim da época em que fui cofundadora da npm Inc. Então talvez

00:45 se lembrem de mim dos tempos de JavaScript. Mas, hoje em dia, falo sobre IA, como testá-la e como fazê-la funcionar. Então, o que vamos abordar hoje? Temos bastante tempo juntos. Vamos cobrir muito conteúdo, e vou começar pelos fundamentos. É por isso que esta sessão se chama 101. Vamos começar falando sobre o que são evals, por que você precisa deles e por que os agents tornam a avaliação mais difícil do que em aplicações simples de LLM. Depois, vamos configurar o rastreamento no Arize AX,

01:17 que é como capturamos os dados brutos necessários para executar evals. Vamos criar um agent de IA simples com o Claude Agent SDK. Vamos executá-lo e examinar os rastros que ele produz. Quem já criou um agent? Levantem a mão. Certo, ótimo. Não vou gastar tempo nenhum explicando como o agent funciona, porque presumo que todo mundo saiba como um agent funciona e que vocês estão aqui para aprender a avaliá-los. Depois que tivermos alguns dados, vamos fazer algo que muitos tutoriais deixam de lado:

01:48 vamos realmente examinar os dados. Vamos ler nossos rastros. Vamos categorizar o que deu errado. E vamos descobrir o que medir antes de escrever um único eval. Depois, vamos escrever três tipos de evals. Há evals de código, que são verificações determinísticas simples, muito parecidas com testes unitários. Em seguida, vamos usar evals de LLM integrados, como o de fidelidade, em que um segundo LLM julga a saída do primeiro. E vamos criar um eval personalizado

02:19 com LLM as a judge do zero. Também vamos testar se nossos avaliadores estão julgando corretamente, um processo chamado meta-avaliação. Depois, vamos concluir com conjuntos de dados e experimentos, que são como iterar no agent e medir de fato se ele está melhorando. Isso inclui usar o Claude Code para melhorar automaticamente nosso app em resposta ao feedback dos nossos evals. Então, antes de mais nada, peguem seu notebook. Cometi um erro antes e

02:51 não configurei as permissões corretamente. Então, se vocês escanearam o código antes e não funcionou, agora funciona. Peguem este notebook e façam uma cópia para vocês. É nele que vamos trabalhar o dia todo. Vou esperar vocês fazerem isso, porque, caso contrário, vou ter que ficar voltando para este slide. Certo, a maioria já terminou. Não, não, ainda estou vendo gente tirando fotos. Certo, beleza.

03:22 Também vamos precisar de uma certa infraestrutura de IA. Hoje vou usar a Anthropic e o Claude Code. O Arize AX funciona com a OpenAI e com todos os outros provedores de laboratório, mas eu precisava escolher um para fazer um workshop sobre isso. Então, escolhi o Claude. Este notebook vai exigir que vocês tenham uma chave de API da Anthropic, que podem obter em console.anthropic.com. Se não tiverem, mas forem muito espertos, podem trocar rapidamente para a OpenAI. Também vão precisar de uma conta da Arize. Acessem

03:53 arize.com e iniciem um teste gratuito. Depois disso, vocês vão precisar de um Arize Space ID e de uma chave de API da Arize, que podem obter na página de configurações. Meu adorável assistente, Dat, está aqui. Ele está ali no canto. Se tiverem algum problema para obter as chaves de API ou algo do tipo, chamem-no, e ele virá correndo ajudá-los a resolver, o que é muito gentil da parte dele. Obrigada, Dat.

04:24 Sim. Quem já tinha tudo isso? Alguém já tem uma conta do Arize AX? [risos] Certo, vou deixar vocês cuidarem disso por enquanto. Vou dar um tempo para configurarem. Para fazer isso, acessem arize.com

04:57 e cliquem em… Opa, fui parar na documentação, porque estou sempre nela. Acessem arize.com. Obrigada. Cliquem no grande botão rosa “Get started” e depois façam o cadastro por aqui. Não se cadastrem por engano no Phoenix. Phoenix é nosso querido projeto open source, que também tem um serviço hospedado. Às vezes, quando vocês pesquisam Arize no Google, acabam sendo direcionados ao Phoenix. Não se cadastrem no Phoenix. Hoje vocês vão usar o AX.

05:34 Certo. Enquanto vocês se cadastram, vou falar um pouco mais sobre o que é o AX. É uma plataforma de observabilidade e avaliações. Ela captura rastros da sua aplicação de IA, armazena e executa seus evals e monitora seu app em produção, alertando você quando algo dá errado. Por padrão, nós hospedamos a plataforma para vocês. É por isso que estamos usando-a hoje: vocês não precisam executar nenhum software para fazê-la funcionar. Então, não há infraestrutura para gerenciar. Mas, se vocês trabalham em uma empresa que é muito rigorosa com os dados

06:04 e pensa: “Não, precisamos executar isso nós mesmos”, podem fazer isso, sem problema. E, como eu disse, se vocês já usaram o Arize Phoenix, nossa ferramenta open source, muita coisa vai parecer familiar. Eles compartilham as mesmas ideias fundamentais. Uma foi criada para ser acessível como open source, e a outra foi criada para empresas, com produção, equipes e coisas do tipo. Como está indo o cadastro para obter as chaves?

06:35 >> O Wi-Fi é péssimo. >> O Wi-Fi é péssimo. Era de se esperar, não é? Certo. Alguém está precisando muito de ajuda agora? >> Certo.

07:12 Certo. Bem, o conselho é usar o celular como ponto de acesso. Peço desculpas pelo Wi-Fi. Estou muito preocupada com meu workshop das 14h, em que tenho um repo do Git que sei que tem 200 megabytes, e fico pensando: “Não, ninguém vai conseguir baixar o repo porque ele é grande demais.” >> Sim, comecem a clonar esse repo agora. Enfim, vamos falar sobre esses fundamentos. Há bastante teoria neste workshop, o que dá tempo para vocês se atualizarem. Aqui está o modelo mental: evals são testes para IA, e rastros são

07:45 logs para IA. Não sei bem por que precisamos inventar dois nomes completamente novos para essas coisas. Vocês escrevem testes para o código. Dada esta entrada, espero esta saída. Evals fazem a mesma coisa, mas para saídas de IA, que nunca são exatamente iguais duas vezes. Assim como os logs registram o que o servidor fez durante a execução, os rastros registram o que a IA fez. Cada chamada de agent, cada tool call, cada invocação de LLM, com as entradas e saídas em cada etapa. Os blocos básicos de um rastro são

08:17 chamados spans. Nesta pequena captura de tela, vocês podem ver um rastro no Arize AX. Ele é formado por vários spans. Tem uma estrutura em árvore. Cada span representa uma etapa da execução. Uma chamada de LLM é um span. Uma chamada de ferramenta é um span. E uma rodada completa do agent é um span que contém outros spans. Cada span registra sua entrada, sua saída, o tempo, a contagem de tokens e vários metadados. Tudo de que vocês precisam para entender o que aconteceu naquela etapa. Os rastros mostram o que aconteceu. Os evals dizem se foi bom. Esse é o modelo para

08:49 modelo mental para hoje. Isso não é ciência de foguetes. Mas deixa eu falar sobre por que precisamos de evals. E isso é o problema das impressões. Em geral, as funcionalidades de IA são lançadas assim: você cria uma funcionalidade de IA, executa algumas consultas e pergunta: “Isso parece certo?” “Sim, parece bom.” E aí você lança. De longe, esse é o método mais popular de lançar aplicações de IA hoje. O problema é que, depois, ela falha com entradas que você não testou. E o fato é que provavelmente parece boa nas suas consultas de teste, mas o problema é que você a executou três vezes. Três vezes não é uma suíte de testes. A solução habitual para software instável são os testes unitários, mas eles não funcionam aqui porque a saída é não determinística. O mesmo prompt produz textos diferentes a cada execução. Então, duas respostas diferentes podem estar ambas corretas. Por isso, não existe uma string esperada com a qual você possa comparar. Assim, as equipes recorrem à revisão humana. Observam a execução. Parece tudo certo, então lançam. Isso não escala. Não detecta regressões. E, o mais importante,

09:20 não é executado na CI. Aqui estão algumas coisas que você não consegue fazer sem evals. Se você alterar o system prompt para corrigir um problema de tom, o tom vai melhorar. Mas agora seu bot está alucinando funcionalidades do produto. Sem uma eval, você não percebe isso até que um usuário relate o problema. Com uma eval de fidelidade, você teria percebido o aumento antes do lançamento. E todo prompt pode afetar todos os tipos de entrada que os usuários enviam. Então, você pode estar mudando o prompt por um motivo e causar um efeito completamente inesperado

09:51 em uma parte totalmente diferente da sua aplicação, porque o prompt é apenas um bloco enorme de texto que você envia à sua IA. Você não consegue testar manualmente todas as combinações. Então, sem evals, você fica jogando whack-a-mole: corrige um problema e quebra alguma outra coisa em outro lugar. Em vez disso, evals dão a você um número que pode acompanhar, comparar e usar para agir. Também não dá para trocar de modelo sem evals. Isso importa cada vez mais porque essa área avança muito rápido. Novos modelos são lançados a cada poucos meses. Sem evals,

10:21 trocar de modelo significa semanas de testes manuais. É melhor? É pior? Alguma coisa mudou? Alguma coisa quebrou? Você não sabe. Com evals, você executa a suíte. Compara as pontuações e fica sabendo em poucas horas. Essa é a diferença entre voar às cegas e voar por instrumentos. E isso não é teórico. Equipes reais, como Dcript, Bolt e o próprio Claude Code da Anthropic, seguem o mesmo caminho: lançam com base em impressões, descobrem que impressões não escalam e, então, criam evals. E esse é o mesmo caminho

10:51 que vamos seguir no workshop de hoje. Como mencionei antes, existem dois tipos gerais de evals. Evals de código são funções determinísticas. Elas são executadas em milissegundos, não custam nada e dão uma resposta imediata e inequívoca, como: a saída pode ser analisada como JSON? A saída tem menos de 500 tokens? Ela mencionou aquilo que eu perguntei? A grande vantagem das evals de código é que são rápidas, baratas e totalmente reproduzíveis. Elas recebem a mesma entrada e dão a mesma resposta todas as vezes. Isso as torna muito

11:23 parecidas com os testes unitários tradicionais. A desvantagem é que, assim como os testes unitários tradicionais, elas podem ser frágeis. Temos algumas estratégias que ajudam a evitar isso, e vou abordá-las mais tarde. Isso porque duas respostas perfeitamente corretas podem ser formuladas de maneiras completamente diferentes, e você precisa ajustar suas expectativas em relação aos testes unitários para lidar com isso. O segundo tipo de eval é uma eval com LLM as a judge. Elas usam um segundo LLM para avaliar suas saídas com base em uma rubrica. Rubrica é outra palavra que inventamos e que significa simplesmente regras. É

11:53 o conjunto de regras que você coloca no seu prompt sobre o que é considerado bom. Evals com LLM são muito mais flexíveis. Elas conseguem lidar com os tipos de perguntas que as evals de código não conseguem responder. Esta resposta é factualmente correta? Ela se manteve fiel ao material de origem? O tom está adequado? Em um contexto de atendimento ao cliente, o ponto forte dos LLM judges é que eles entendem o significado, não apenas as strings presentes na saída. Mas os LLM judges têm desvantagens. O ponto fraco é que custam dinheiro para executar

12:25 e também são não determinísticos. Então, podem errar, o que significa que você precisa calibrá-los com base no julgamento humano, e vamos fazer isso mais tarde hoje. Há também um terceiro tipo de eval: a avaliação humana. Um especialista no domínio pode ler sua saída e avaliá-la. Esse é o padrão-ouro de qualidade. Mas é lento e caro, e as pessoas se cansam, por isso não podemos fazer isso o tempo todo. Curiosidade nada divertida: anotadores humanos deixam passar até 50% dos

12:56 defeitos por causa do cansaço. Então, eles também não são perfeitos. Quando você cria um LLM as a judge e pensa: “Bem, ele nem sempre detecta meus erros”, lembre-se de que, se uma pessoa estivesse avaliando, ela também nem sempre detectaria seus erros. Mas essas abordagens são complementares. A maioria das aplicações reais vai usar uma combinação de evals de código, LLM as a judge e avaliação humana. Então, quando usar cada uma? Use evals de código quando a resposta for determinística: validação de formato, limites de tamanho,

13:26 frases proibidas e campos obrigatórios. Use LLM judges quando precisar de compreensão semântica. Uma eval de correção pergunta se a resposta está correta. Uma eval de fidelidade pergunta: ela se manteve fiel aos documentos de origem sem alucinar? E você deve manter pessoas no processo para analisar modos de falha que ainda não encontrou e verificar se seus LLM judges estão realmente avaliando corretamente. LLM judges podem errar. Compará-los com o julgamento humano é como você sabe se pode ou não confiar neles.

13:56 Tudo isso vale para qualquer aplicação que use LLMs. Mas os agents tornam as coisas ainda mais difíceis em alguns aspectos que vale a pena destacar. Você pode pensar nisso como uma escala de complexidade. Uma chamada única a um LLM é relativamente simples. Você recebe uma entrada e uma saída. Quando falamos de um agent, ele faz uma série de chamadas a ferramentas e uma série de decisões. Isso significa que, a cada etapa da cadeia, aumentam as chances de ele cometer um erro e, portanto, também aumentam as chances de sair dos trilhos. Então, é preciso

14:27 avaliar também as etapas intermediárias. Você precisa verificar se o agent está usando a ferramenta certa. Ele passou os argumentos corretos? Soube quando parar? Ficar preso em loops é um modo de falha real para agents. E sistemas multiagent, se você estiver criando um, acrescentam mais um nível de complexidade. Eles acrescentam transferências de tarefa. Um agent decide passar o trabalho para outro. O agent de triagem encaminhou corretamente? O agent especialista lidou bem com a transferência? Cada camada acrescenta novas formas de as coisas darem errado. E

15:01 o não determinismo significa que você precisa de mais evals, porque os erros podem se propagar. Veja como é um exemplo de falha em cascata. Se você fizer uma consulta sobre Tesla, referindo-se à fabricante de carros, seu agent pesquisa na web, encontra um monte de informações sobre um inventor do século XVIII e as repassa ao agent, que escreve um relatório muito bem formatado sobre um inventor do século XVIII e o envia ao seu chefe. Nada do que ele fez estava errado. Você mandou pesquisar Tesla na web. Ele pesquisou

15:31 Tesla na web. Encontrou informações sobre Tesla e escreveu um relatório sobre Tesla. Onde foi que deu errado? Isso é pior do que uma falha óbvia, porque, para perceber, você precisa ler suas entradas e saídas. Não havia como um teste unitário detectar isso. Mas os agents também podem fazer o contrário. Eles podem acertar de uma forma que seus testes não esperavam e, por isso, receber uma avaliação errada. Isso aconteceu com a Anthropic quando executaram um benchmark chamado Tao Squared Bench, que simula interações de várias rodadas entre clientes e atendimento

16:02 ao cliente

16:33 tarefas. Eles pediram ao agent que reservasse voos e que fizesse algo que achavam impossível: remarcar um voo da classe econômica. Mas as políticas que forneceram ao agent permitiam que ele primeiro fizesse um upgrade do voo para a primeira classe. Voos de primeira classe podem ser remarcados, ao contrário dos voos da classe econômica. Então, o agent encontrou uma maneira de remarcar um voo da classe econômica e falhou no teste porque ele

17:03 não deveria conseguir fazer isso, mas conseguiu. Este é um exemplo de como a flexibilidade dos agents e as soluções que eles encontram, nas quais você não tinha pensado, precisam ser levadas em conta nos seus testes. Há uma diferença entre estar certo de forma criativa e estar errado, e vamos voltar a isso quando falarmos sobre como avaliar seus agents mais adiante — ou melhor, como avaliar seus evals. Há também uma segunda maneira de categorizar seu eval em duas categorias: evals de capacidade e evals de regressão. Um eval de capacidade

17:35 pergunta: meu agent consegue fazer isso? Espera-se que os evals de capacidade falhem na maioria das vezes. Espera-se que seu agent obtenha uma pontuação muito baixa neles, porque eles representam uma subida a ser vencida. Eles dão ao seu agent algo em que tentar melhorar. Depois que você vence essa subida, seu eval de capacidade se transforma em um eval de regressão. Um eval de regressão é um eval que você espera que seu agent passe completamente ou quase completamente, todas as vezes. Então, à medida que seu agent amadurece, você vai aplicando evals de capacidade, um após o outro, e transformando-os lentamente em uma suíte de evals de regressão que você executa o tempo todo para garantir

18:05 que o comportamento anterior não tenha regredido. Este é o aspecto do resultado de um eval. Cada eval produz uma pontuação e um rótulo. Neste caso, é uma pontuação numérica, muitas vezes simplesmente zero ou um. Pontuações binárias são muito fáceis para os LLMs. [fungada] Também há um rótulo legível por humanos, como correto ou incorreto, válido ou inválido. Os LLMs

18:35 como judge acrescentam uma terceira coisa: a explicação. Evals de código produzem explicações porque são apenas código. Mas um LLM como judge não diz apenas que algo está incorreto: ele diz por que decidiu que algo está correto. Isso é extremamente valioso, porque, se você trabalha em um mundo de coding agents, pode pegar várias explicações de vários evals e passá-las de volta ao seu coding agent, dizendo: “Aqui estão todos os motivos pelos quais você errou no último teste. O que

19:05 você poderia fazer para melhorar nisso?” E seu coding agent simplesmente vai dizer: “Ótimo, obrigado pelo feedback”, melhorar sua aplicação e ficar melhor nisso da próxima vez. É isso que vou mostrar na oficina de hoje: como transformar um eval que falhou em uma melhoria do prompt. Esta é uma explicação real de um judge. Neste exemplo, é um agent de planejamento de viagens e você está executando um eval de correção. O judge não diz apenas “incorreto”. Ele explica exatamente o que está faltando. Você pediu um voo econômico. Ele não apresentou uma discriminação dos custos. Ele diz que o agent forneceu informações sobre o destino e recomendações, mas o usuário perguntou sobre viagens econômicas e não havia estimativas de custo.

19:36 Essa explicação torna o eval acionável, porque agora você tem uma falha concreta. Você sabe o que corrigir no prompt. É a explicação que transforma evals em uma ferramenta útil de depuração, e não apenas em um placar. E, se você vir a mesma explicação em 50 traces diferentes, saberá que tem um problema sistemático, não um caso extremo isolado; isso faz dele a primeira coisa que você deve corrigir. Então, você precisa

20:07 pegar as explicações dos seus evals, categorizá-las por tipos de falha e contar cada categoria. Isso se chama codificação. Mais uma vez, podemos inventar palavras a partir do vocabulário de ML. Mas categorizar coisas é conhecido como codificação. E, claro, cada explicação está em linguagem natural. Então é difícil fazer essa codificação, a menos que você use mais um LLM para fazer a categorização. Vamos ver como isso funciona mais para o fim de hoje. E, como eu

20:40 disse, você pode entregar um monte dessas explicações a um coding agent e deixar que ele corrija o aplicativo para você. Este é o ciclo completo que vamos construir hoje. Vamos instrumentar, registrar traces, executar evals e iterar. Cada etapa alimenta a seguinte. Você define o que quer, constrói, mede o desempenho, faz o deploy, monitora em produção e itera com base no que observa. Todo produto de software tradicional passa por um ciclo como esse. Mas, no caso da IA, é na etapa de medição que a maioria das equipes falha, e os evals são a forma de medir.

21:12 Os evals são o tecido conjuntivo de todo esse ciclo de vida. Então, vamos começar a construir. A primeira etapa é configurar o tracing com o Arize AX. Antes de executar evals, precisamos de dados para usá-los. E não dá para avaliar aquilo que não se consegue observar. Por isso, a observação vem primeiro. Então, espero que você já tenha conseguido se conectar ao Wi-Fi e esteja com nosso notebook aberto, executando, para garantir

21:43 que está tudo certo. Vamos à nossa primeira célula de código, onde instalo nossas dependências. O Claude Agent SDK é autoexplicativo: é o SDK do Claude Agent. O pacote de instrumentação OpenInference para o Claude Agent SDK é o pacote de instrumentação automática do Claude Agent SDK. É assim que ele sabe capturar traces dos agents do Claude sem que você precise alterar o código da aplicação. Como mencionei antes, você também pode usar o OpenAI ou algum framework.

22:15 Temos pacotes para todos eles também. Basta substituí-los. Arize e Arize Otel são os pacotes que enviam seus traces ao AX e permitem que você os consulte. Há também um pacote Phoenix que usamos como pacote utilitário. Não se preocupe com ele. O pacote anthropic permite usar o Claude tanto para executar nosso agent quanto para avaliar a saída dele mais adiante. Então, execute esta célula se ainda não

22:45 tiver feito isso. Enquanto a instalação é feita, vou falar sobre o que vamos construir. Se você ainda não usou o Claude Agent SDK, ele é o framework da Anthropic para construir agents — a resposta da Anthropic ao LangChain e a ferramentas desse tipo. Ele pode usar ferramentas, pesquisar na web e manter o contexto da conversa entre turnos. O OpenAI tem seu próprio SDK de agents e, claro, há frameworks completos para agents, como CrewAI, LangChain e Mastra. O AX é compatível com todos eles. Então, não importa em qual framework você construiu seu agent,

23:17 ele já está instrumentado; basta ativar o registro em log e todos os seus traces aparecerão. Espero que a instalação já tenha terminado — estou sendo otimista com o tempo. Em seguida, configure suas chaves. Neste caso, copiei minhas chaves do Colab. Se você estiver se sentindo ousado, pode simplesmente colá-las diretamente na célula. Há três coisas aqui, como eu disse

23:48 antes: você precisa de uma chave de API da Anthropic, que será usada nas chamadas ao LLM do nosso agent e também pelo judge mais adiante. Você precisa de uma chave de API do Arize, que pode obter nas configurações e que autentica seu tráfego no serviço AX. E precisa de um ID de espaço do Arize, que informa ao AX em qual espaço de trabalho colocar todos os seus dados. Se suas chaves não estiverem funcionando, o culpado mais comum é um erro de cópia e colagem. E, claro, ele ainda está por aí para ajudar se suas chaves não estiverem funcionando. Ele já foi descrito como um buraco de segurança ambulante.

24:18 Então, ele com certeza vai lhe dar uma chave se você não conseguir descobrir como fazer suas chaves funcionarem. Agora vamos rolar até a seção de registro. Vou aumentar a fonte aqui. Mais uma vez. >> O QR code, aumente mais uma vez. Claro. Provavelmente.

24:56 >> Desculpe. >> É, não coloquei minhas chaves no Colab. Então, o recurso de secrets do Colab as recupera. Certo, vou voltar para onde eu estava. Espero conseguir fazer isso. Certo. Então,

25:29 instalamos as dependências, falamos sobre o SDK, falamos sobre os secrets. [suspira] E agora chegamos ao registro. Aqui está a mágica. Qualquer pessoa que trabalhe na Arize vai dizer que você só precisa adicionar duas linhas de código à sua aplicação para instrumentar sua chamada. E estas são as duas linhas de código. O que estamos fazendo aqui é passar nosso ID do espaço da Arize, nossa chave de API e um nome para associar a todos os traces. A função de registro está configurando o OpenTelemetry.

25:59 O OpenTelemetry é o padrão da indústria para observabilidade de aplicações. E ele tem uma camada chamada OpenInference, que adiciona atributos específicos de LLM. Coisas como o texto do prompt, o texto da resposta, a contagem de tokens, qual modelo foi chamado e quais ferramentas foram invocadas. Apontamos para o AX e damos um nome ao projeto; é assim que seus traces são agrupados na interface. Neste caso, também passamos batch=false porque, quando você executa em um notebook, quer enviar sua telemetria assim que ela acontece, em vez de agrupar os dados,

26:31 como o sistema faz por eficiência em produção. Aquela linha no fim, claude agent SDK instrument, diz ao SDK do Claude para enviar um span ao AX toda vez que faz uma chamada de LLM ou invoca uma ferramenta. E agora a instrumentação está feita. Isso funciona com tão pouco código porque o OpenTelemetry é um padrão aberto que quase todo mundo usa. Então, os autores do SDK do Claude, os autores do SDK da OpenAI, os autores do LangChain, todos já escreveram o código dentro dos seus

27:01 SDKs que chama o OpenInference e envia os dados de volta. Então, tudo o que você precisa fazer é dizer: “Ei, sou um coletor de OpenInference. Estou aqui. Envie os dados para mim.” Mais um detalhe da configuração: a chamada de registro envia dados para o AX, e o cliente da Arize lê os dados do AX. Vamos usá-lo para trazer nossos spans de volta para o notebook. É disso que trata esta linha. Então, confira se você colocou as mesmas chaves ali ou se as copiou para lá.

27:40 >> Ah, você precisa fazer uma cópia do notebook pelo menu Arquivo para poder editá-lo. Legal. Certo. Então, se você executou essas células, estamos prontos para construir. Antes de construir, vale a pena saber que tudo o que vamos fazer manualmente hoje também pode ser feito pelo seu agente de programação. Estamos fazendo manualmente para

28:11 que você entenda os fundamentos do que está fazendo e não chegue ao sucesso só na base do vibe coding. Mas publicamos um conjunto de skills chamado Arize skills, que sabe fazer tudo isso por você no nível de skill. Então, você pode instalar suas Arize skills e executar evals, criar conjuntos de dados e instrumentar sua aplicação desde o início. Todas usam os padrões recomendados pela AX, e você as instala uma vez com um único comando npx. Elas funcionam no Claude Code, no Cursor, no Codex e em dezenas de outros agentes de programação.

28:43 Então, hoje vamos fazer as coisas manualmente, mas, em produção, num ambiente real, usamos nossas próprias skills todos os dias para fazer isso. Agora, vamos construir nossos agentes. Quando perguntei se todo mundo já tinha construído um agente, todos levantaram a mão. Então, não vou passar muito tempo explicando como este agente funciona. Vou presumir que você já tem um agente em algum lugar e está tentando instrumentá-lo e fazê-lo funcionar para você. O agente fictício que estou usando hoje é um chatbot de análise financeira

29:13 que usa o SDK de agentes do Claude. Você fornece um ticker de ação e uma área de interesse, e ele pesquisa na web as informações mais recentes sobre aquela ação. Pesquisa dados financeiros atuais e reais e escreve um relatório para você. É um caso de uso real em torno do qual startups inteiras são construídas. Embora a minha versão do agente seja extremamente simples. Vou presumir que você já construiu um agente. Nosso agente funciona em duas etapas. Primeiro, há uma etapa de pesquisa que usa ferramentas para pesquisar na web e reunir dados. Depois,

29:43 há uma etapa de redação que compila a pesquisa em um relatório legível. Vou explicar isso para vocês. Aqui estão meu prompt de pesquisa e meu prompt de redação. Eles são propositalmente muito simples. Vão causar erros mais tarde, e vamos usar nossas evals para depurá-los. Depois, configuro as opções do meu agente do Claude. Estou usando o Claude Haiku como modelo do agente porque o Haiku é capaz, mas comete erros, e queremos alguns erros para poder corrigi-los. Além disso, é

30:14 rápido e barato, então não vou gastar muito do seu dinheiro enquanto fazemos isso. O modo de permissões controla o que o agente pode fazer de forma autônoma. Há uma armadilha escondida nas escolhas específicas que fiz e nas ferramentas permitidas específicas que estou dando a este agente agora, como vamos descobrir mais tarde. Agora, vamos ver nossas duas etapas. A primeira etapa é a pesquisa. Há uma

30:45 [fungada] porção de código padrão aqui que não vou explicar; ela serve apenas para mostrar a saída, para que possamos ver o que o agente está fazendo enquanto trabalha. A segunda etapa é escrever o relatório, novamente com um monte de código padrão. Os prompts são fundamentais. É aqui que quero que vocês comecem a fazer suas próprias alterações no próprio notebook. No início, dei a ele prompts extremamente básicos. Se vocês conseguirem pensar, assim, de cabeça, em um prompt melhor que

31:15 resolva esse problema melhor do que os prompts que incluí, o que seria melhor do que o que escrevi para fazer a pesquisa? O que seria melhor do que o que escrevi para redigir o relatório? Se vocês acertarem de primeira, terão menos trabalho mais tarde. Uma das coisas que fazemos aqui é envolver tudo em um span do OpenTelemetry. Isso porque, se eu não fizer isso, o Claude envia as duas etapas como dois spans separados, e queremos que elas sejam agrupadas na interface.

31:47 Então, envolvi as duas etapas juntas em um span para que apareçam como uma única execução do agente. Isso só nos poupa algum tempo mais tarde. Queria deixar claro por que estou usando esse trecho de código. Agora podemos executar nossos agentes. Executei o meu agente com antecedência porque queria saber exatamente o que ele faria. Mas agora é hora de iniciar o seu próprio agente. Pedi a ele que analisasse

32:17 a Tesla, especificamente seu desempenho financeiro e suas perspectivas de crescimento. Podem executar esta célula. Vai levar um ou dois minutos porque o agente vai realmente pesquisar na web. E o LLM vai fazer várias rodadas de raciocínio. O agente recebe nosso prompt de pesquisa. Decide que precisa pesquisar na web, o que é um tool call. Lê os resultados da pesquisa. Decide se já tem informações suficientes e talvez pesquise de novo. Essa é a parte agentic. Você não disse: faça uma pesquisa na web, pegue as informações da pesquisa e escreva um relatório sobre elas. O agente está decidindo se esta pesquisa na web

32:49 informações suficientes? E, se não, vou escrever que vou fazer mais pesquisas na web. Ele fará um número indeterminado de pesquisas na web para obter informações suficientes, até decidir o que significa “suficiente”. E então escreverá o relatório. Esse caminho de execução é não determinístico por definição, e esse é o ponto principal a entender aqui. Se você executar isso de novo com a mesma entrada, seu agent poderá pesquisar coisas diferentes. Poderá encontrar resultados diferentes. Poderá escrever um relatório diferente. E os dois relatórios podem ser bons. Ou um pode ser bom e o outro, ruim. E é exatamente por isso que precisamos de evals. Não podemos

33:21 prever a saída apenas com base na entrada. E cada uma dessas decisões está sendo registrada como um trace. Vou abrir as últimas 12 horas ou, acho que, as últimas 24 horas. Legal. Este é um conjunto de traces. Você vai entender o que tudo isso significa mais adiante, mas aqui dá para ver o caso da Tesla que executei antes. É assim que fica quando eu percorro o processo. Dá para ver cada turno. Está chamando uma skill. Está fazendo uma pesquisa com uma ferramenta

33:52 Está fazendo uma pesquisa na web. Dá para ver cada coisa que ele faz. Dá para ver que executou quatro pesquisas na web antes de finalmente decidir que já tinha informações suficientes. Depois, fez a segunda chamada na etapa e escreveu o relatório. Uma das coisas que ele faz — e que veremos mais adiante — é algo ligado à pegadinha nas ferramentas que forneci. Aqui está esta etapa inesperada que apareceu enquanto preparávamos a demonstração. Ele tentou escrever o relatório. Eu pedi que escrevesse um relatório. Ele

34:23 tentou salvar o relatório em disco como um arquivo Markdown. Ele está sendo executado em um notebook do Colab. Portanto, não há sistema de arquivos onde ele possa gravar. Então, a etapa de gravação falharia. E é para isso que você precisa de evals. Você precisa de evals para detectar quando seu agent está fazendo algo útil, mas incorreto. Isso falha silenciosamente. Ele ainda fornece uma saída, mas realiza essa etapa extra e desnecessária de tentar gravar em disco sem que você saiba que isso aconteceu.

34:54 Voltando ao Colab, este é um relatório bem bom. É uma tabela de desempenho financeiro com números reais, fatores de crescimento, fatores de risco, preços-alvo de analistas e uma conclusão. Não está ruim para uma primeira tentativa, mas não está ruim apenas como uma impressão. E estamos aqui para substituir impressões por números de verdade. Como eu disse, dá para ver tudo isso nos traces.

35:25 Não precisamos fazer nada para obter todas essas informações. Não precisamos instrumentar cada linha para capturar a chamada ao LLM, a chamada à ferramenta e todas essas coisas. Tudo isso já vem integrado ao cloud agent SDK, assim como está integrado ao SDK da OpenAI. E cada linha desta tabela é um span. Os traces revelam cada decisão tomada pelo agent. Sem eles, tudo o que você vê é que dei um prompt e recebi um relatório. Com os traces, você vê cada etapa. Se clicar em qualquer span, como eu disse, verá exatamente o que o modelo recebeu como entrada e exatamente o que

35:56 retornou. E é isso que observabilidade significa na prática. Não apenas se funcionou, mas como funcionou e exatamente onde deu errado. Quando executarmos nossa avaliação daqui a alguns minutos, vamos extrair a entrada e os atributos de saída desses spans e fornecê-los aos nossos avaliadores. A entrada será a entrada do avaliador. A saída será o que será avaliado. Agora precisamos gerar alguns dados de

36:28 teste para executar evals significativos. Precisamos de mais do que o único trace que você gerou até agora. Precisamos de um conjunto de dados. No notebook, há 12 consultas de teste que abrangem diferentes tickers e tipos de análise. Você deve iniciá-las agora. Elas levam de 5 a 10 minutos para serem executadas, supondo que você tenha Wi-Fi e que tudo esteja funcionando. Vou mostrar como elas são. E opa, são estas aqui.

37:01 O ponto principal aqui é a diversidade. Dei a ele várias consultas óbvias que devem funcionar. Também incluí alguns casos extremos. Por exemplo, uma consulta com dois tickers, Apple e Microsoft, pedindo uma comparação. Em teoria, ele poderia fazer isso. Também usei os mesmos tickers várias vezes em alguns casos para podermos observar a saída não determinística ao pedir tendências e perspectivas de lucratividade da Amazon, em comparação com desempenho e lucratividade da Amazon AWS.

37:33 Tickers diferentes, perguntas diferentes e diferentes níveis de complexidade são importantes para gerar dados de teste que cubram o conjunto de coisas que os usuários realmente perguntarão. Embora, alerta de spoiler, na realidade, seus usuários vão perguntar coisas muito estranhas que você não conseguirá prever de antemão, e esse é outro motivo pelo qual evals são importantes. A consulta sobre a Rivian, RIVN, pergunta sobre uma empresa com muito menos dados públicos do que

38:03 Apple ou Microsoft, e a consulta sobre o rendimento de dividendos da Coca-Cola é um tipo de análise bem diferente de uma consulta sobre uma ação de crescimento. Mais uma vez, o importante é a diversidade. A diversidade do seu conjunto de teste é o que permite detectar aquilo em que seu agent não será bom. Enquanto as suas consultas estão sendo executadas, as minhas já terminaram, então posso mostrar todos os meus dados. Estes são todos os meus spans de todas aquelas execuções. Dá para ver que, na

38:36 parte de baixo, há 13: a execução inicial da Tesla e as 12 consultas de teste. Cada uma é uma execução completa do analista financeiro cloud. Agora temos os dados, mas, antes de escrever evals, precisamos realmente examinar os dados. Isso é análise de erros. E toda essa etapa se resume a uma instrução: leia seus traces antes de escrever evals. Antes de escrever um único avaliador, comece pelos seus dados. Leia uma dúzia ou mais dos seus

39:06 traces do início ao fim. Esta é a prática mais importante de todo este workshop. Concentre-se nos casos em que algo deu errado. Qual foi a entrada? Qual foi a saída? O que, especificamente, está quebrado? Isso parece extremamente antiquado. Basta ler a entrada. Mas é uma das atividades de maior valor no desenvolvimento de agents. A Anthropic, por exemplo, investiu em ferramentas específicas para visualizar transcrições de evals, e a equipe passa bastante tempo todos os dias simplesmente examinando essas transcrições. Um trace mostra se o agent

39:36 cometeu um erro de verdade ou se seus avaliadores rejeitaram uma solução válida. Se você automatizar antes de entender suas falhas, vai criar um eval que mede aquilo que é fácil de medir, em vez do que realmente importa. Você precisa primeiro definir os requisitos para poder categorizar as falhas. Precisa saber como é o sucesso. Não pode dizer que algo não funciona se não definiu o que significa funcionar. Para o nosso analista financeiro, como seria um bom relatório? Ele deve mencionar

40:08 o ticker correto. Deve incluir dados financeiros recentes, reais e úteis, além de recomendações acionáveis. Deve distinguir a análise prospectiva do resumo histórico. Esses são nossos critérios de sucesso e parecem óbvios quando os escrevemos, mas muitas equipes nunca fazem isso. Elas lançam um agent e depois reagem às reclamações, em vez de definir o padrão de antemão. Registrar os requisitos transforma uma insatisfação vaga em critérios específicos e testáveis, e esses critérios são o que se transformam em evals.

40:40 Mas há algo importante a observar sobre a definição de sucesso: não é algo que os engenheiros possam fazer sozinhos. A definição do que é bom geralmente depende do conhecimento do domínio, e esse conhecimento está nas pessoas que sua empresa muitas vezes, de forma até ridícula, chama de não técnicas. Portanto, seus product managers, sua equipe de QA e sua equipe de suporte são as pessoas que sabem qual é realmente a definição de bom. Elas sabem como serão as falhas. São essas pessoas que devem ajudar você a escrever seus evals. A OpenAI publicou…

41:11 muito bem. Eles disseram que habilidades de gestão de pessoas são habilidades de IA. Então, metas claras, feedback direto, saber qual é sua proposta de valor: essas habilidades importam mais do que nunca quando o sistema é probabilístico. E essa é uma das coisas em torno das quais o AX foi construído. Qualquer pessoa da sua equipe pode ler os traces, adicionar anotações e contribuir para seus critérios. Esta não é uma área voltada apenas à engenharia. Espera-se que outros membros da sua equipe também estejam aqui. Uma observação rápida sobre onde obter esses dados de teste. Temos esses traces porque nós mesmos já executamos o agent, mas

41:43 e se você estiver criando algo novo e ainda não tiver tráfego real? Você pode fazer o que acabamos de fazer: usar dados sintéticos. Você pode pedir a um LLM que gere consultas variadas para as categorias esperadas. Então, “pesquise o desempenho financeiro da Tesla” é uma formulação. “O que está acontecendo com as ações da Tesla?” é outra consulta que pergunta a mesma coisa. “Ei, vale a pena comprar Tesla agora?” é uma terceira forma de expressar a mesma consulta. Todas têm a mesma intenção, mas parecem bem diferentes. Então, varie a formulação, a complexidade e o nível de especificidade.

42:14 Um especialista no domínio deve revisar seu conjunto de consultas, porque consultas geradas por LLM tendem a se concentrar em formulações óbvias e não captam as coisas estranhas que usuários reais escrevem. Você também precisa incluir casos extremos nos seus dados de teste. Por exemplo, códigos de ações inexistentes, perguntas com várias partes e tentativas de jailbreak. Talvez esses casos representem 1% do seu tráfego, mas são justamente o 1% que acaba, sabe, virando um desastre de relações públicas na imprensa. Seus dados de teste devem se parecer com os dados de produção, não com o que você gostaria que os dados de produção fossem. Então, dados sintéticos

42:45 podem ajudar você a começar, mas, assim que tiver dados de produção, eles devem ser os dados usados nos testes. Então, vamos examinar nossos traces. Como eu disse, os primeiros 13 traces são os 13 primeiros que escrevi. A maioria gerou relatórios estruturados e longos em linha. Tesla, Apple, Nvidia, coisas assim. De 3 mil a 7 mil caracteres de relatório ali mesmo na saída do trace, com resumos executivos, tabelas de avaliação e recomendações explícitas de compra ou manutenção.

43:16 À primeira vista, a maioria parece estar certa, mas, como eu disse, três dos 13 estavam fazendo algo estranho: a saída do relatório era bem mais curta, porque dizia apenas: “Ah, salvei isso em um arquivo para você”. E a saída foi gravada em um arquivo. Então, em vez de apresentar o relatório completo, ela traz um resumo do relatório, e o corpo do relatório foi gravado em um disco inexistente. É isso que a eval foi criada para encontrar. O

43:50 agent decidiu gravar um arquivo sem permissão. A gravação falhou silenciosamente, e ele nos disse que o relatório tinha sido salvo. Esse é o tipo de padrão que você só vê se realmente lê o trace. Então, acredito que esta seja uma das três fontes. Não, essa tinha funcionado. Ah, não, o Wi-Fi. Aqui vamos nós.

44:24 Então, este mostra outro tipo de falha: ele simplesmente ficou preso em um loop para sempre. Estava tentando encontrar informações sobre quem mesmo? Microsoft. E fez uma série interminável de pesquisas na web, levando uma eternidade. Foi isso que ele tentou gravar em um arquivo. E foi isso que realmente escreveu na saída. Aqui, pronto. “O relatório foi salvo como Microsoft cloud segment financial report.mmd.” Este relatório é inútil porque faz referência a um relatório que não existe.

44:58 Também há um exemplo de algo que está errado, mas é apresentado com confiança. Se formos ao relatório da Rivian, cujo código é RIBN… onde foi parar? Aqui está. A Rivian tem o mesmo problema que o relatório da Microsoft, mas, até dentro do relatório completo que ele tentou gravar em um arquivo, há um monte de informações apresentadas com muita confiança sobre [limpa a garganta] uma empresa privada, que não há como verificar. Isso pode ser alucinação ou não, mas não fizemos

45:29 nada para verificar se esse relatório está realmente fundamentado na realidade. Então, vamos fazer uma eval sobre isso mais tarde. Há uma forma estruturada de fazer essa leitura que, como mencionei antes, é chamada de codificação. Há a codificação aberta e a codificação axial, e elas vêm da pesquisa qualitativa. Codificação aberta significa ler cada trace e anotar o que você vê. Por exemplo: recomendação vaga, número inventado, referência ao código de ação errado. Você não está tentando organizar tudo. Como programador, é

46:00 muito tentador tentar definir categorias de antemão e dizer: “Ah, isso é uma falha de recuperação ou algo assim”. Não faça isso durante a codificação aberta. Apenas descreva qual foi o problema da forma mais natural possível. E depois, quando encontrar a falha — desculpe —, você deve fazer a codificação axial. A codificação axial é quando você olha para todos os códigos abertos que reuniu e então faz a categorização. Você diz: “Certo, agora há cinco coisas que

46:31 parecem semelhantes. Vou dar a todas uma única categoria e transformá-las em categorias”. A segunda etapa, a etapa de codificação axial, é estrutural. E, como eu disse, a tendência, a tentação, é ir direto para a codificação axial, mas você deve resistir a isso. Quando encontrar uma falha, pergunte por que ela aconteceu. A resposta errada é um sintoma. O agent obteve resultados de pesquisa ruins? Isso é uma falha de recuperação. Ele obteve os dados certos, mas chegou à conclusão errada? Então

47:03 isso é um erro de raciocínio. Inventou um preço de ação? Isso é claramente uma alucinação. Respondeu fora do seu domínio? Isso é uma violação de escopo. Fez algo que você não disse que deveria ser capaz de fazer? Cada causa raiz, cada código axial, aponta para uma correção diferente. Se você não souber qual é a decisão certa, se não souber a causa, não poderá escolher a correção adequada. Depois de categorizar — como fiz aqui —, você pode resumir tudo em

47:35 uma tabela. Então, hora da confissão: na verdade, não li todos esses traces nem os codifiquei. Apenas atribuí códigos axiais aleatórios a eles. Mas o resultado é esta tabela de frequência das causas raiz, com itens como “parece bom”, “possível alucinação”, “lacuna de raciocínio”, “dados não verificáveis” e “recomendação ausente”. É tentador olhar para o item mais frequente, a possível alucinação, e decidir que é o mais importante a corrigir. Mas, na realidade, você

48:05 vai querer equilibrar frequência e gravidade. Então, se uma vez em cada cem, em vez de gerar um relatório financeiro, o sistema der instruções ao usuário sobre como fabricar uma bomba, você corrige esse problema primeiro, porque é a falha potencialmente mais grave. Portanto, você precisa multiplicar a gravidade pela frequência para decidir quais problemas corrigir primeiro. E é por isso que você analisa os dados antes de escrever suas evals.

48:36 Mais um conceito antes de começarmos com isso: o modelo do queijo suíço, que é um conceito da engenharia de segurança. Imagine cada camada de defesa como uma fatia de queijo suíço. Cada fatia tem buracos, lacunas por onde os problemas podem passar. Mas, se você empilhar fatias suficientes, os buracos não ficam alinhados. Assim, o que passa por uma camada é detectado pela próxima. Sua eval de código detecta problemas de formato, mas não percebe problemas semânticos. Seu LLM judge detecta lacunas de raciocínio, mas não percebe alucinações sutis. E a revisão humana detecta as coisas sutis, mas não consegue

49:07 escalar para todos os traces. Nenhuma eval desse conjunto detecta tudo, e é a combinação delas que oferece cobertura. Então, empilhe as fatias de queijo. Agora que sabemos o que está errado, vamos automatizar as verificações. O próximo passo são as evals de código. Não há configuração de modelo nem chamadas de API, apenas Python. Vamos escrever a eval útil mais simples que consigo imaginar. Nosso agent deve analisar um código específico de ação. O que vou

49:38 o que fazer é escrever um avaliador de código que verifica se esse ticker realmente apareceu no relatório. Esse é um teste em que minhas demos iniciais falharam várias vezes. Um LLM as a judge seria exagero para isso. Você está procurando uma string específica. Ela está em algum lugar do relatório. Não precisa de um LLM para avaliar se você mencionou ou não o ticker. Então, há duas maneiras de fazer isso. Há duas maneiras de fazer tudo no AX: uma é programaticamente e a outra é pela interface. No notebook, você pode ver

50:10 a maneira programática. O que vou mostrar na tela é como fazer isso pela interface. Então, esse botão grande no canto superior direito é o que você quer. Você quer adicionar um avaliador. Neste caso, já adicionei meu avaliador de menção, mas você vai querer adicionar um avaliador, que abrirá esta tela. Aqui você verá basicamente um pouco de Python. No notebook, forneci o Python que você pode usar para

50:43 fazer sua versão programática ou sua versão na interface. Esta é uma função Python muito simples que retorna um resultado de avaliação que se parece exatamente com aqueles resultados de avaliação que mostrei antes. Ela tem um rótulo e uma pontuação. Então, depois de escrever o que seu avaliador de código faz, você terá

51:15 parâmetros para o seu avaliador de código. Neste caso, chamei-os de query e report. E você precisará dizer ao AX quais variáveis do seu trace correspondem a essas variáveis. Há uma interface extremamente divertida, a interface de trace único, em que você examina um único trace e pode simplesmente clicar no item específico da sua saída que quer usar como variável. Aí, você diz: certo, aquele deve ser a query e aquele deve ser o report. Então, eles são mapeados.

51:47 Você também deve alterar seu avaliador para funcionar em um trace, em vez de em um span. É isso que disponibiliza aquela interface. Depois de fazer isso, você precisa salvar seu avaliador de código no nosso hub de avaliadores. Em seguida, clique em salvar para salvar a avaliação.

52:17 Supondo que você tenha feito isso. >> Sim. >> Claro. Ele pediu mais detalhes sobre como funcionam os avaliadores de código. Os avaliadores de código são funções completamente determinísticas. Você simplesmente recebe uma entrada e uma saída e pergunta se essa saída foi boa segundo alguma definição de bom. Neste código, estou usando Python muito, muito simples. Estou

52:47 simplesmente dizendo: procure todas as palavras em letras maiúsculas. Remova as que são siglas óbvias que eu já conheço e verifique se alguma das palavras restantes é a sigla, ou seja, o ticker que estou procurando. É só isso que ele faz. Muitos avaliadores de código são ainda mais curtos do que isso. São coisas como: esta saída tem 500 caracteres ou menos? Esta saída é um JSON analisável? Você está fazendo algo muito simples, muito determinístico, para

53:19 ter essa primeira linha de defesa no seu modelo de queijo suíço. Então, já falei sobre como adicionar coisas. No notebook, você pode executar a avaliação programaticamente. Estas são as instruções para fazer isso pela interface, caso você as tenha seguido. A alternativa é fazer isso no código, onde você pode executá-lo diretamente, o que é mais fácil se estiver acompanhando em um

53:50 notebook. Um avaliador de código retorna um rótulo e uma pontuação. Como eu disse, não precisa de LLM. Não há chamada de API. É instantâneo. E, se você está se perguntando por que estamos envolvendo isso em supressão de tracing, é porque a avaliação em si é uma chamada ao SDK do agent, que seria armazenada como traces, e eu não queria traces do meu tracing acontecendo, porque isso fica metademais. Então, mandei suprimir o tracing durante a execução de uma avaliação.

54:21 Se você olhar para esta execução programática, verá que 12 passaram e uma falhou. Faltava um ticker para a Amazon. O trace específico que deu errado foi quando perguntei — vocês vão notar que eu disse antes que fiz duas consultas sobre a Amazon. Em uma, perguntei sobre a lucratividade dela; na outra, perguntei sobre a lucratividade da AWS. Se vocês abrirem os traces — posso tentar fazer isso agora — verão que o

54:54 relatório sobre a AWS escreveu um relatório inteiramente sobre a AWS, apenas sobre a divisão AWS da Amazon, em vez de sobre toda a Amazon. Então, não mencionou o ticker da Amazon de jeito nenhum. Falou apenas sobre a AWS. É uma falha bem sutil, porque ele fez um monte de pesquisa. Descobriu várias coisas sobre o que estava acontecendo na Amazon. Só não pensou no que estava acontecendo com a Amazon como empresa. Pensou apenas na AWS, porque acrescentei aquele prompt extra, dizendo que também queria saber sobre a lucratividade da AWS.

55:24 Então, olhando para esses resultados no AX, eles aparecem como anotações ao lado dos nossos traces. Você pode abrir qualquer um desses traces e verá as avaliações. Já executei muito mais avaliações do que vocês até agora, mas dá para ver que minha avaliação de menção ao ticker foi executada com o span. Ela foi executada no nível do span. Foi aprovada e recebeu uma pontuação de um.

55:57 O notebook tem uma pequena função auxiliar chamada log_eval_to_ax, que faz esse trabalho para você. Ela pega os spans que executou offline e os testes que executou offline e os envia de volta ao AX para você. Então, agora toda pontuação — toda avaliação — tem uma avaliação de menção ao ticker que você pode consultar e usar como filtro para encontrar as que falharam. Por que isso importa? Porque é sua primeira linha de defesa. Se o agent analista financeiro escrever um

56:28 relatório lindo sobre a Microsoft quando o usuário perguntou sobre a Tesla — algo que realmente aconteceu comigo enquanto eu desenvolvia isso —, não importa o quanto a resposta do seu agent seja eloquente, porque ela está errada. Você pode detectar isso com cinco linhas de Python. A verificação do ticker detecta falhas bem básicas, mas faz isso a um custo muito baixo. É por isso que ela é importante. Avaliadores de código não são apenas exemplos de brinquedo. Muitas vezes, você vai querer saber se sua saída é JSON ou

56:59 se tem um determinado comprimento, ou vai querer evitar frases proibidas como “como um modelo de linguagem de IA”. E essas são verificações essenciais para produção. Uma avaliação de código não precisa ser uma simples operação com strings. Avaliador de código significa que a lógica de avaliação é determinística, mas pode fazer coisas complexas. Pode consultar um banco de dados para você. Pode chamar uma API e obter o preço real da ação para garantir que não alucinou um preço. Qualquer coisa cuja avaliação sempre dê a mesma resposta para a mesma entrada pode ser um avaliador de código. Um princípio importante é avaliar o que

57:31 o agent produziu, e não o caminho que percorreu. Mencionei isso antes. É comum ter o impulso de verificar se o agent seguiu uma sequência específica de etapas. Ele chamou esta ferramenta primeiro e depois aquela, nessa ordem? Na prática, profissionais descobriram que isso é rígido demais. Os agents encontram regularmente abordagens válidas que o designer da avaliação não previu. Então, se você avalia o caminho, penaliza a criatividade. Em vez disso, avalie o que

58:01 o agent produziu. A saída tinha as informações certas? O estado final correspondeu ao que você queria? Nossa verificação do ticker não se importa com a forma como o agent encontrou os dados. Ela só verifica se o ticker está na saída. Esse é o nível certo de abstração para a maioria dos avaliadores de código. Agora vamos às avaliações integradas: avaliações com LLM. É aqui que as coisas começam a ficar mais interessantes. O código pode verificar se o ticker aparece, mas não pode verificar se a análise é boa. Os dados financeiros estão corretos? O relatório está completo? As recomendações

58:31 bem fundamentado? Essas são perguntas semânticas e, para perguntas semânticas, você precisa de um avaliador. Todo LLM as a judge tem três partes. Tem um modelo avaliador, que é o LLM que faz a avaliação para você. Tem um template de prompt que, como mencionei, também é chamado de rubrica. É o conjunto de critérios e regras que o avaliador aplica para definir o que é bom. E tem os dados, que são os exemplos avaliados. A AX mantém essas três coisas separadas, o que significa que você pode combiná-las como quiser. Pode testar os mesmos critérios com diferentes modelos avaliadores. O mesmo

59:02 modelo avaliador com diferentes critérios. Ele é modular por natureza. A boa notícia é que a AX vem com várias avaliações integradas, então você não precisa escrever as suas. Há diversos tipos de avaliações que costumam se aplicar à maioria das aplicações de IA. Então, já escrevemos os prompts para elas, e você não precisa escrevê-los por conta própria. A avaliação de correção, por exemplo, verifica se uma resposta está factualmente correta. A avaliação de fidelidade verifica se a resposta se mantém fundamentada no material de origem. E

59:34 há avaliações para a seleção de ferramentas. O agent escolheu a ferramenta certa? E para a invocação de ferramentas. Ele passou os argumentos certos para essa ferramenta? Coisas como relevância de documentos, detecção de recusas e muitos outros aspectos que você gostaria de verificar em uma aplicação com agents já vêm prontos. Então, a primeira avaliação que vamos executar é uma avaliação de correção. E, adiantando o resultado, ela não vai funcionar.

1:00:04 É muito fácil configurá-la. Damos a ela um LLM. Neste caso, escolhi o LLM da Anthropic, Sonnet 4.6, porque ele é melhor que Haiku, que é o modelo que está fazendo o trabalho. Muitas vezes, você vai querer escolher um modelo maior e mais lento para ser o avaliador. Depois, passei a avaliação de correção ao LLM e a executei aqui.

1:00:35 Como eu disse, depois de executarmos a avaliação com evaluate data frame, também ativamos a supressão do rastreamento aqui, para que nossa avaliação não envie um monte de rastros extras para a AX. Isso nos dá esta saída, que consiste em várias linhas de avaliação. Elas não são muito fáceis de ler. Por isso você precisa da AX para analisá-las. O avaliador lê a entrada e a saída de cada span e as classifica de acordo com a rubrica.

1:01:07 E podemos ver que todas as pontuações são zero. Se eu rolar para o lado, o status é concluído, o nome é correção, a pontuação é zero. Isso acontece porque a avaliação de correção julga com base na definição de correção e verdade do LLM. Ou seja, ela depende dos dados de treinamento do LLM. Neste agent, estamos fazendo muitas buscas na web em tempo real

1:01:38 para obter preços atuais de ações e informações financeiras atualizadas. Isso significa que o agent fala sobre acontecimentos de 2026, mas o LLM que faz a avaliação só tem informações até janeiro. Então, se você ler as explicações da nossa avaliação de correção na AX, pode rolar até as avaliações, abrir a avaliação de correção e ver que ela está incorreta. Vou poupar você da leitura de uma coluna muito densa. O que ela está fazendo é reclamar que há várias coisas que vêm

1:02:08 do futuro e que ela não teria como saber. Portanto, nossa avaliação de correção falhou completamente aqui. Não era isso que queríamos. Em vez disso, vamos usar uma avaliação de fidelidade. A fidelidade é uma avaliação melhor para nosso caso de uso porque o avaliador tem acesso ao contexto. Na avaliação de fidelidade, você fornece ao LLM as a judge as informações nas quais a resposta se baseia e pergunta: com base nas mesmas informações que o agent coletou, ele fez um bom trabalho ao escrever o relatório?

1:02:40 Assim, os dois ficam em condições iguais. Ambos têm a mesma quantidade de informações, e seu agent avaliador, lento e complexo, pode julgar se o agent executor, rápido e ágil, fez um bom trabalho. Vamos analisar as células de fidelidade. Como tudo o mais, essas avaliações podem ser feitas tanto online quanto offline. Então, há um avaliador de fidelidade integrado

1:03:12 que não está nesta visualização. Há um avaliador de fidelidade integrado que você pode abrir e fornecer a entrada, a saída e o contexto. Você também pode fazer isso em código. E, se estiver usando skills, provavelmente é isso que vai acontecer. Suas skills vão dizer: “Ah, não vou usar a interface; vou usar o código.” É por isso que estou mostrando isso aqui. A primeira coisa que fazemos é extrair o contexto de pesquisa dos rastros. Como você deve se lembrar, fazemos um processo em duas etapas

1:03:42 Então, pego a saída da primeira etapa, em que a pesquisa é feita, e a anexo a todos os meus spans como contexto para o avaliador trabalhar. Depois, executo o avaliador de fidelidade. Aqui você pode ver os spans com contexto. São os mesmos spans que acabei de extrair da AX. Anexei todo o meu contexto no nível da coluna. Depois, chamei evaluate dataf frame com esses spans

1:04:14 e passei a avaliação de fidelidade, que instanciei aqui, assim como instanciei a avaliação de correção. Isso nos dá dados muito mais interessantes. O resultado mostra sete casos sem fidelidade e seis com fidelidade. Então, segundo o Sonnet, aproximadamente metade das vezes meu relatório bem simples alucina. Ele inventa coisas que não estavam nos dados de origem.

1:04:45 E essa é uma avaliação útil. É uma avaliação em que falhamos metade das vezes. É uma avaliação de capacidade que nos permite avançar, modificar nosso prompt e melhorar a capacidade de escrever um relatório fundamentado. É exatamente o tipo de avaliação que você quer. Então, são duas avaliações integradas e dois sinais bem diferentes. E há uma lição muito importante aqui: a avaliação de correção nos deu zero de 13, enquanto a avaliação de fidelidade indicou que os relatórios não estão fundamentados nas fontes em aproximadamente metade das vezes. A diferença não é que

1:05:16 uma avaliação seja melhor que a outra. A diferença está no caso de uso. Há muitos casos de uso em que a avaliação de correção que mostrei antes funciona muito bem. Só não funciona neste caso específico, em que estávamos fazendo pesquisa ao vivo, em tempo real. Então, é importante saber qual pergunta você está realmente fazendo. As avaliações integradas são um ponto de partida. Elas dão um sinal imediato sem que você precise fazer engenharia de prompt. Mas, mesmo com uma boa avaliação integrada, como a de fidelidade, há várias

1:05:47 coisas que ela não consegue verificar. Nosso analista financeiro deve produzir recomendações práticas. Não deve apenas resumir os dados. Ou seja, não basta fornecer um relatório financeiro: é preciso dizer o que fazer com ele. Devo comprar, vender ou manter? Nenhum template integrado verifica isso. A AX não cobre todos os casos de uso. Então, você precisa criar uma avaliação específica que verifique se as recomendações são práticas. Precisa criar uma avaliação personalizada para o seu domínio.

1:06:17 Se estiver criando avaliações de verdade, com certeza vai precisar escrever uma avaliação personalizada com uma definição de qualidade que nós não previmos. Isso nos leva à próxima etapa: escrever uma rubrica de avaliação personalizada. É aqui que você torna a avaliação realmente específica para sua aplicação. E escrever uma boa avaliação é complicado. Então, vou dedicar um pouco de tempo a falar sobre o que torna uma rubrica de avaliação boa. Recomendamos quatro partes para uma rubrica personalizada. A primeira é definir o papel do avaliador. Você deve explicitar

1:06:47 critérios claros de aprovação e reprovação. Deve marcar os dados com tags XML. E deve definir as opções de saída fora do próprio prompt. Vou acrescentar mais uma coisa, que é um tanto controversa entre os profissionais da área: costumo incluir exemplos de saídas boas e ruins. Alguns profissionais acreditam que incluir exemplos fará sua avaliação sofrer overfitting. Mas vamos passar por todos esses pontos. A primeira parte é definir o papel. Você vai notar

1:07:20 Esse clichê, que a esta altura já está desgastado, é: “você é um avaliador especialista em análise financeira”. Essa não é a parte importante. Os testes mostram que isso faz uma diferença muito pequena para determinar se o seu eval funciona ou não. O importante é dar a ele o contexto do que está analisando. Você está analisando um relatório financeiro, e o que espero é uma análise financeira. Esses são os elementos importantes de contexto que você está fornecendo ao LLM. Você também está dizendo que o que quer é algo que possa ser colocado em prática. Então

1:07:51 isso nos leva à parte dois. É aqui que a maioria das pessoas investe pouco. Não diga “uma resposta boa”, porque isso é uma aspiração, não um critério. “Uma resposta boa é útil e precisa” parece acrescentar mais detalhes, mas você continua sendo igualmente vago, porque “útil” e “precisa” não significam nada para o LLM. Em vez disso, você deve listar exatamente o que torna um relatório útil para orientar ações. Portanto, liste exatamente o que o torna útil para orientar ações e o que não o torna. Cada critério deve ser específico e observável. Algo que, se você fosse um

1:08:23 ser humano analisando esse relatório, conseguiria identificar se está presente ou não e responder sim ou não. Então: contém recomendações específicas. Isso é algo para o qual você definitivamente consegue responder sim ou não. Inclui uma análise voltada para o futuro, não apenas dados históricos. Essa é uma distinção clara para a qual você consegue responder sim ou não. E o importante aqui é que cada um desses critérios corresponde a algo que vimos na nossa análise. Quando estávamos lendo os relatórios, vimos — observamos isso de fato ao ler nossos traces, ou pelo menos quando

1:08:53 li nossos traces — que essas são maneiras específicas pelas quais esses relatórios estão dando errado. Isso não é coincidência. Sua análise de erros é o que indica quais critérios você deve escrever. Você não os tira do nada, porque não vai conseguir pensar neles. Você obtém esses dados lendo seus traces e pensando: “Ah, ele não fez isso. Minha codificação axial mostrou que ele comete este erro específico.” Portanto, critérios específicos produzem avaliações consistentes, enquanto critérios vagos produzem resultados aleatórios. A terceira coisa que você deve fazer na sua

1:09:23 rubrica é rotular os dados com tags XML, especialmente se estiver usando Anthropic. A Anthropic adora XML e acha muito fácil entendê-lo. Sua rubrica tem variáveis: a entrada e a saída. Você quer garantir que ela consiga distinguir suas instruções da entrada e da saída, e as tags XML são uma excelente maneira de fazer isso. Então, coloque uma tag de consulta do usuário em volta da entrada e uma tag de relatório financeiro em volta da saída. Limites claros reduzem a chance de o judge confundir a pergunta com a resposta. Isso é especialmente importante se você estiver

1:09:54 incluindo exemplos: rotule-os com tags XML, porque, caso contrário, ele vai pensar: “Ah, é exatamente isso que devo escrever” e simplesmente devolver o exemplo. Isso nos leva aos exemplos. Essa é a parte que muita gente pula. Na minha opinião, é a parte que mais melhora a qualidade. LLMs são razoáveis em seguir instruções. Estão ficando cada vez melhores nisso. Mas aquilo em que são realmente bons é copiar um exemplo que você já forneceu e substituir as coisas relevantes para a

1:10:25 situação atual. Então, se você der a ele um exemplo exatamente do tipo de relatório que procura, ele vai seguir esse formato à risca. Dependendo do seu domínio, isso pode ou não ser uma boa ideia. Se o seu exemplo for rígido demais, o LLM sempre produzirá o mesmo relatório, e você terá reduzido o espaço para a criatividade. Por outro lado, se ele estiver sendo muito não determinístico e o seu relatório estiver ficando absurdo, dar um exemplo vai ancorá-lo exatamente no que você espera.

1:10:55 Veja como é, no modelo, um exemplo útil para orientar ações. Ele tem tudo: crescimento percentual da receita, uma relação P/L. Identifica um risco concreto, com um número que o sustenta, e apresenta uma recomendação específica. É isso que significa ser útil para orientar ações. Aqui está um resultado que não é útil para orientar ações. Ele não está errado. Tudo o que diz está correto, mas não diz nada útil. Não apresenta nenhum dado específico nem nenhum risco específico. Apenas diz que os investidores devem considerar vários fatores. Isso não é uma recomendação. Então, agora o judge tem uma referência concreta do que você realmente quer dizer com os rótulos que está usando.

1:11:27 Isso pode melhorar muito a consistência, especialmente nos casos limítrofes em que, de outra forma, o relatório ficaria em algum ponto intermediário. E esta é uma parte importante. Ao escrever essa rubrica, é muito tentador dizer: “E agora, escreva a palavra ‘correto’ ou ‘incorreto’”, porque era isso que você queria obter. Você não precisa mais fazer isso. Na verdade, por baixo dos panos, o que acontece é que nós

1:11:57 demos ao LLM uma ferramenta que diz: “Chame esta ferramenta quando terminar”, e ele a chama com “correto” ou “incorreto” quando termina. Portanto, você não precisa dizer a ele qual deve ser a saída. Na verdade, pedir que ele produza uma string específica como saída tem mais chances de confundi-lo e fazer seu eval falhar. Então, basta definir as opções na interface ou, ao criar isso por meio de código, definir as opções e deixar o LLM fazer o trabalho dele. Ao definir essas opções, é

1:12:27 melhor mantê-las simples. Uma opção binária é o ideal: dois rótulos claros. Escalas numéricas, como uma escala de 1 a 5, são tentadoras, mas os LLMs não são bons nisso. Qual é a diferença entre um três e um quatro? Você teria que escrever um monte de regras para o LLM saber. Ele não sabe isso automaticamente. Já se você der a ele as opções “aprovado” e “reprovado”, ele será bem bom em decidir o que é aprovado e o que é reprovado. Se você realmente precisar de mais categorias, pode incluir um resultado parcial. Pode dizer que uma pontuação de 0,5

1:12:59 significa que ele fez um trabalho meia-boca. Mas, por padrão, opte por zero ou um. Mais uma dica prática: use chain of thought para judges. Peça ao judge que raciocine antes de dar a pontuação e que explique primeiro seu raciocínio. Isso melhora a precisão de forma mensurável. Quando o judge precisa explicar por que algo é útil para orientar ações ou não, ou por que está correto ou não, ele comete menos erros do que quando simplesmente escolhe um rótulo sem pensar primeiro. Essa

1:13:30 explicação também é muito útil para você. Mas também ajuda o judge a pensar melhor. É só uma daquelas coisas estranhas sobre LLMs. Então, se você está acompanhando e programando, agora é hora de encontrar seu modelo de utilidade para orientar ações. Ele contém todos os exemplos e todas as instruções de que acabei de falar. Você consegue fazer melhor do que eu? Consegue chegar a um eval perfeito com uma única tentativa, modificando este modelo de eval?

1:14:01 Como acontece com tudo no AX, você também pode fazer isso pela interface. Você pode criar um avaliador online e um novo LLM as a judge. Neste caso, eu já criei o meu avaliador de utilidade para orientar ações, que tem exatamente o mesmo texto que acabei de mostrar no notebook. Como antes, tive que escolher um escopo de trace. E, como é um LLM as a judge, tive que configurar um modelo. Desculpe, eu

1:14:31 tive que configurar um LLM para ele usar na interface. Isso significa que você precisa fornecer sua chave da Anthropic novamente. Escolhi minhas entradas e saídas usando o método de trace único. Depois, salvei. Uma das coisas que você pode fazer com evals online é configurá-los para serem executados continuamente em novos traces recebidos. Isso é algo que você quase certamente fará em produção. E, se seus evals forem caros ou você tiver muito tráfego, não vai querer executá-los em todo o tráfego. Você pode configurá-los para serem executados em uma determinada proporção

1:15:05 apenas uma porcentagem. Essa é a taxa de amostragem. Então você pode dizer: sabe, observe apenas 1% do meu tráfego, e isso ainda vai fornecer uma grande quantidade de dados de eval sem estourar seu orçamento. Voltando à versão em código, conectá-la é como conectar a outra ação, os outros avaliadores que criamos. Criamos um avaliador de classificação. Demos a ele o nome actionability. Demos a ele um LLM. Demos a ele o template que acabei de mostrar

1:15:37 e demos a ele aquelas opções. Estamos fazendo programaticamente o que faríamos na interface, onde dissemos que as opções são correta ou incorreta, acionável ou não acionável, com pontuação de um ou zero. E então executamos evaluate data frame. Isso nos fornece os dados que eu estava pulando, porque já tinha executado antes. Então, você pode ver actionability, acionável. Se olharmos a aba de avaliações, podemos

1:16:08 rolar para baixo até actionability e temos uma explicação muito boa do motivo pelo qual o relatório é acionável ou não. Muitos dos nossos relatórios receberam a pontuação de acionáveis, mas vários não, o que é ótimo, porque significa que, de novo, temos uma eval de capacidade e um caminho a percorrer. Então, no notebook, é aqui que você registra seus resultados de volta no AX, ou, se executou isso online na interface, seus evals e os resultados dos evals já estão lá, como você viu.

1:16:38 Então, agora você pode ver no AX que cada trecho tem várias pontuações de eval. Tem mention sticker, correção, fidelidade e actionability. E você pode filtrar e selecionar resultados específicos de eval. Por exemplo,

1:17:10 eval.actionability.label é igual a not actionable. Isso encontra o conjunto de falhas. Esse é o conjunto em que você pensa: “Certo, minha eval diz que meu código deu errado aqui”. Posso transformar isso em um conjunto de dados e começar a executar novos prompts com ele. Posso fazer experimentos com ele, como veremos.

1:17:40 Antes de continuar, quero destacar alguns erros comuns que transformam evals de uma ferramenta útil em ruído. O primeiro é tratar seus prompts de eval como código. E digo isso literalmente. Eles são muito sensíveis à formulação. Pequenas mudanças no prompt de eval podem levar a mudanças drásticas nos resultados da eval. Então, você deve versioná-los. Deve testá-los com exemplos cuja resposta correta você conhece. Se o avaliador — o LLM como avaliador — discordar dos rótulos humanos em 40% dos exemplos, então sua eval

1:18:12 provavelmente está errada. Não é que seus resultados estejam errados. É que você escreveu a eval incorretamente. O AX tem um ambiente de testes de prompt, onde você pode iterar sobre critérios sem tocar no código, e isso é muito útil para esse tipo de iteração da sua eval. O segundo erro é o avaliador-deus. É tentador criar um avaliador gigante que verifica tudo de uma vez. Ele procura precisão, tom, completude, conformidade com políticas e formatação em um único prompt. Não faça isso, porque calibrá-lo é um pesadelo. Quando

1:18:45 seu avaliador-deus diz “falha”, qual dessas cinco dimensões falhou? Você não sabe. Então, de repente, pensa: “Ah, vou pedir para ele gerar rótulos”. E aí pensa: “Ah, ele está gerando 15 rótulos diferentes”. De repente, fica complicado demais. Você não consegue entender, avaliar nem pontuar com ele. É muito, muito mais simples e fácil dividir isso em um avaliador por dimensão. Já fiz isso hoje. Tenho uma verificação de ticker. Tenho fidelidade. Tenho actionability. Três evals focadas e separadas. E cada uma informa algo específico. A

1:19:17 combinação fornece uma visão mais rica do que qualquer eval isolada poderia oferecer. Se você se pegar escrevendo critérios que listam seis coisas diferentes que a resposta deveria fazer, pare. Isso são seis avaliadores, não um. O terceiro ponto é conhecer seus limites de segurança e suas métricas norteadoras. Algumas evals são limites de segurança. Elas impedem o lançamento. Se um agent alucinar o preço de uma ação, isso é uma falha grave. Não faça o deploy. Outras são métricas norteadoras. São aspiracionais. Então, recomendar sempre investimentos complementares é algo desejável neste caso. Não é

1:19:48 um fator decisivo. Então, saiba qual é qual entre suas evals. Isso muda a forma como você age com base nos resultados e, mais adiante, muda como configura os monitores de produção. Uma regressão em um limite de segurança deve acionar um alerta para alguém no meio da noite. Uma queda em uma métrica norteadora é algo que você analisa em um relatório semanal. Isso nos leva à próxima seção: podemos confiar em nossos avaliadores? Essa é uma pergunta que temos contornado. Já a mencionei algumas vezes. É hora de avaliar seu avaliador. Criamos um avaliador LLM e ele nos disse que

1:20:18 alguns relatórios não são acionáveis. Mas podemos confiar nele? Como sabemos que o avaliador está correto? O principal modelo mental aqui é que seu avaliador é um classificador. Então, você pode tratá-lo como um classificador. Ele recebe uma entrada — neste caso, um relatório financeiro — e faz uma previsão: acionável ou não acionável. Essa previsão pode estar certa ou errada. Portanto, como acontece com qualquer classificador, você pode medir seu desempenho comparando as previsões com a verdade de referência. Neste caso, o julgamento de uma pessoa. Você pode corrigir a lição de casa do avaliador.

1:20:51 O problema de aplicar julgamento é que dá muito trabalho. Você precisa ler de fato cada resultado. Precisa pensar cuidadosamente e atribuir um rótulo. O AX faz o que pode para ajudar, permitindo definir anotações e vinculá-las a trechos diretamente na interface. Então, deixe-me mostrar como isso funciona. Ao visualizar um trecho, você pode clicar em “Anotar trecho” e adicionar ou remover configurações de anotação. Neste caso, já criei uma chamada human actionable. E você pode marcar esse trecho como

1:21:22 acionável ou não acionável. Depois, basta usar estas pequenas setas para percorrer todos os seus rastros e marcá-los como acionáveis ou não acionáveis, o que eu, convenientemente, já fiz. Esse é o tipo de trabalho que você pode delegar a um membro da equipe sem conhecimento técnico. É por isso que a interface é assim. A pessoa pode simplesmente clicar, ler o relatório e marcar uma caixa. Não precisa escrever código. Não precisa saber nada além de sua experiência no domínio para decidir se esse relatório deve ser considerado acionável ou não acionável.

1:21:52 O que estamos fazendo aqui ao adicionar anotações humanas é construir um conjunto de dados de referência. Construir conjuntos de dados de referência é extremamente útil, porque é assim que você mede se o avaliador está realmente cumprindo sua função. A forma de fazer isso é a mesma usada pelo LLM. Defina critérios concretos e siga-os. Então, não diga que algo foi bom ou ruim. Seja específico, da mesma forma que você pediu ao LLM para ser específico. Você falhou nesta coisa específica. Você pediu que esta coisa estivesse presente, mas ela não estava. E elimine a possibilidade de fazer isso de qualquer jeito quando se cansar de rotular.

1:22:24 Como eu disse, rotular consome muito tempo, então já fiz isso. Depois de rotular alguns trechos na interface, posso exportá-los novamente para o notebook. Uma coisa boa do AX é que as anotações humanas que adicionei manualmente voltam como colunas na exportação. Então, filtramos para obter apenas as linhas que rotulei aqui. E agora vamos comparar o que eu marquei como acionável e não acionável com o que o avaliador marca como acionável ou não acionável. Mas, antes de fazermos isso, mais algumas palavras sobre conjuntos de dados de referência: mantenha suas tarefas inequívocas. Se seu agent recebe consistentemente uma pontuação de 0%, quase sempre há um problema com a tarefa. Quase sempre, você escreveu os critérios incorretamente. Se você

1:23:02 aqui. E agora vamos comparar o que eu disse que era acionável e não acionável com o que o avaliador diz que é acionável ou não acionável. Antes de falarmos — antes de fazermos isso, porém — mais algumas coisas sobre conjuntos de dados de referência: mantenha suas tarefas inequívocas. Se seu agent pontua 0% consistentemente, quase sempre é porque a tarefa está quebrada. Quase sempre, você escreveu sua rubrica incorretamente. Se você…

1:23:35 transformou sua tarefa em algo que só um humano consegue fazer ou, pior, em algo que ninguém conseguiria realmente fazer, então você vai receber uma pontuação zero. Para cada tarefa, crie uma solução de referência, uma saída comprovadamente funcional que passe por todos os seus avaliadores. Isso prova que a tarefa é solucionável, e você também deve testar nos dois sentidos. Deve haver casos em que um comportamento deve ocorrer e casos em que não deve. Então, se você testar, por exemplo, se ele pesquisa na web, vai acabar com um

1:24:06 agent que sempre pesquisa na web, mesmo quando não precisa. Você também deve ter um teste que pergunte: ele deixou de pesquisar na web para esta resposta muito óbvia, em que não precisava fazer isso? E, se estiver fazendo isso de verdade, deve dividir os dados rotulados que acabou de criar em um conjunto de desenvolvimento e um conjunto de teste. Use talvez 75% dos seus rótulos para iterar na sua eval, ajustando os critérios e os exemplos até que o juiz concorde com você. Depois, reserve os 25% restantes para executar o juiz e verificar se ele realmente

1:24:37 obtém as pontuações esperadas. É assim que você sabe que o juiz está generalizando para novos exemplos, em vez de apenas se ajustar ao conjunto de dados específico que você forneceu. Esse é o mesmo princípio das divisões entre treino e teste em machine learning. Não ajuste demais seu avaliador ao seu conjunto de dados de referência. Agora, vamos analisar nosso juiz de acionabilidade. Executei o juiz em alguns exemplos, e ele gerou uma lista dos casos em que concorda e discorda. Só para avisar: marquei aleatoriamente como acionável ou não acionável para gerar muitas discordâncias, porque, na verdade, Sonnet é bastante bom nessas coisas.

1:25:09 Isso nos dá uma taxa de concordância de 46%, seis em 13 vezes. Na prática, é exatamente aqui que você investiga a fundo. É aqui que você perguntaria: minha rubrica está errada ou meus rótulos humanos estão errados? Quando o juiz discordar de você, leia a

1:25:39 explicação dele e decida se o juiz estava certo ou se você estava. Essa é a saída mais valiosa da meta-avaliação. Ela geralmente revela uma ambiguidade nas regras que você definiu. Para corrigir uma rubrica, leia as explicações das discordâncias, encontre a ambiguidade e torne os critérios mais específicos. Então, em vez de apenas “inclui análise voltada para o futuro”, eu escreveria “inclui análise voltada para o futuro com recomendações ou orientações específicas”. Isso é mais preciso. Elimina o caso em que o relatório fala sobre o futuro, mas nunca diz ao juiz

1:26:10 o que fazer a respeito. Depois, eu executaria novamente o juiz nos mesmos exemplos e verificaria se a discordância desaparece. Isso é iteração da rubrica. Seu prompt de eval é uma aplicação. É outra aplicação de LLM. Portanto, precisa de testes e iteração, assim como seu agent. E foi isso que eu quis dizer quando falei que você deve tratar suas evals como código. Agora vou falar brevemente sobre um conceito de machine learning chamado precisão e revocação. A precisão pergunta: quando o juiz diz “não acionável”, com que frequência isso realmente não é acionável? Já a revocação pergunta: de todos os relatórios que realmente não são acionáveis, quantos o juiz identificou?

1:26:42 Com uma amostra minúscula, como 12 exemplos, esses números vão oscilar bastante. Mas, mesmo com os 12 que tenho, dá para ver se o juiz está na faixa certa ou se está completamente fora. Na maioria dos cenários, você quer priorizar a revocação. Essas duas medidas entram em conflito uma com a outra.

1:27:14 Se você priorizar a revocação, vai ter falsos positivos, em que o juiz diz que algo está errado quando não há nada de errado. Isso é muito melhor do que deixar passar acidentalmente coisas que estão erradas. No entanto, em alguns casos, durante o ajuste, você pode dizer: “Na verdade, quero precisão. Quero que ele esteja absolutamente certo quando disser que algo está certo, e não me importo se deixar passar algumas coisas”. Há domínios em que esse é o resultado desejado, mas, na maioria das vezes, você quer priorizar a revocação.

1:27:46 Algumas armadilhas conhecidas do uso de um LLM como juiz. Uma delas é o viés de posição. Se você apresentar duas opções para ele comparar, o juiz tende a favorecer a que aparece primeiro. Isso depende do modelo. Às vezes, o modelo prefere a que aparece por último, mas sempre tem algum tipo de preferência de posição. Também existe o viés de extensão. LLMs gostam de respostas mais longas. Tendem a dar pontuações mais altas a elas e a dizer que são melhores, mesmo que a extensão extra seja apenas enchimento. E a última, que eu adoro,

1:28:19 é o viés de confiança. O juiz é enganado por uma resposta que soa confiante, assim como os humanos. Se o seu LLM disser coisas erradas, mas disser com um tom muito confiante, é mais provável que o juiz LLM acredite nelas. Também existe o viés de preferência própria. Se você usar o mesmo modelo para gerar e para julgar, ele tende a gostar da própria saída. Então, se possível, use, por exemplo, OpenAI e Anthropic. Use um para seu agent e outro para julgar, e será menos provável que eles

1:28:50 concordem entre si. O viés de preferência própria é o motivo pelo qual usei Sonnet como juiz para uma saída gerada por Haiku. Mas funciona ainda melhor se você usar um modelo de outro laboratório. E lembre-se de que o benchmark aqui é o desempenho humano. Os humanos não vão ser perfeitos ao julgar se algo é ou não acionável. Vão errar com bastante frequência. O que você está tentando fazer é criar uma eval que se aproxime razoavelmente

1:29:21 do julgamento humano. O julgamento humano também varia de uma pessoa para outra. A confiabilidade entre avaliadores humanos — ou seja, dois humanos julgando a mesma coisa — costuma ser tão baixa quanto 0,2 ou 0,3. Portanto, dois especialistas com a mesma saída e as mesmas regras discordam com uma frequência surpreendente. Então, se o seu juiz LLM alcançar uma consistência maior que a dos humanos, estará se saindo melhor do que eles. O fato de o juiz às vezes discordar de mim não é, por si só, motivo para desconfiar dele. O que

1:29:52 você deve procurar é um juiz que discorde de você o tempo todo. Esse é o sinal de perigo. Um juiz que discorda de você às vezes está lidando corretamente com uma tarefa genuinamente ambígua. E as falhas também devem parecer justas. Esse é um princípio das equipes de eval da Anthropic que quero deixar com vocês. Quando uma tarefa falha, deve ficar claro o que o agent errou e por quê. Se você olhar para um trace com falha e pensar “essa resposta me parece boa”, provavelmente o problema está na eval, não no

1:30:23 agent. Então, agora que criamos evals e as testamos, vamos usá-las para realmente melhorar nosso agent. É assim que fechamos o ciclo. Eis o problema das correções pontuais. Se você encontrou algumas falhas, leu algumas explicações, sabe o que melhorar, muda o prompt e depois? Como saber se a correção realmente funcionou? Como saber se ela não prejudicou algo que já estava funcionando? Se você simplesmente executar o agent novamente em alguns exemplos e avaliar a olho, estará de volta às impressões subjetivas. Você precisa de uma maneira estruturada de comparar antes e depois. E, como mencionei antes, é para isso que servem os experimentos. Como mostrei antes, você pode filtrar seus traces para ver apenas os que estão falhando e transformá-los em um conjunto de dados como este. Então, selecione todos os seus traces, clique em “add to data set” e crie um novo conjunto de dados. Neste caso, dei a ele o nome “AIEWF financial demo fails”. E eu

1:30:55 em alguns exemplos e olhar por alto, você volta a depender de impressões. Você precisa de uma forma estruturada de comparar antes e depois. E, como mencionei antes, é para isso que servem os experimentos. Como mostrei antes, você pode filtrar seus traces para ver apenas os que estão falhando e transformá-los em um conjunto de dados como este. Então, você seleciona todos os seus traces, clica em adicionar ao conjunto de dados e cria um novo conjunto de dados. Neste caso, eu o chamei de AIEWF financial demo fails. E eu…

1:31:26 já criei meu conjunto de dados de falhas. Mas isso oferece um conjunto menor de casos em que você sabe que seu eval está falhando, para então executar seu prompt alterado apenas neles. Isso é mais rápido e barato. Este é um conjunto de testes de regressão. Desculpe, você também deveria salvar um conjunto de testes de regressão; melhor dizendo, deveria pegar os casos em que não está falhando e garantir que eles também formem um conjunto de dados que você possa verificar com menos frequência, para ter certeza de que, quando tiver alterado seu modelo, desculpe,

1:31:57 quando tiver alterado sua rubrica, não o fez falhar acidentalmente em casos nos quais antes estava tendo sucesso. E seus conjuntos de dados não são estáticos. Na pré-produção, quando você ainda não tem usuários, seus conjuntos de dados provavelmente serão consultas sintéticas que você mesmo gerou ou consultas que pediu a um LLM para gerar. Tudo bem. Isso ajuda você a começar. Assim que o tráfego real começar a chegar, você deve transformar isso em seus conjuntos de eval.

1:32:28 Falhas reais devem substituir as imaginadas. A união dos seus casos de falha e dos seus casos de sucesso é o que as pessoas chamam de conjunto de dados dourado: o conjunto curado e rotulado em que você confia como verdade fundamental para medir a qualidade. Agora vamos melhorar nosso agent. Mas não vamos escrever a correção à mão. Como mencionei, você pode fazer tudo isso com skills. Pode fazer tudo isso com um agent de programação. Como estamos em 2026, parto do princípio de que absolutamente todo mundo está usando um agent de programação para fazer toda a sua

1:32:58 programação. Então, por que modificar seus prompts por conta própria, se você pode pedir ao Claude Code para baixar os traces que falharam, modificar seu código e melhorar sua aplicação? É isso que vamos fazer aqui. O Claude vai baixar todos os traces que falharam. Vai ler todas as explicações. Vai transformar as explicações em ações que executa no seu codebase. E aqui está o mais importante: nada disso é um palpite. O Claude não está inventando

1:33:29 melhorias do nada. Você não se limitou a dizer: “melhore nisso”. Você não se limitou a dizer: “não cometa erros”. Cada alteração que ele propõe está ligada a uma explicação específica de falha. Então, se o juiz disse que faltam recomendações específicas, o Claude vai ler isso e reescrever o prompt para incluí-las. Se o juiz disse que ele apresenta riscos sem evidências que os sustentem, vai reescrever o prompt para corrigir isso também. Isso é engenharia de prompts orientada por dados. E agora podemos automatizá-la.

1:34:02 Então, observe o que passamos para ele. Passamos nossos requisitos, aquilo que estávamos tentando realizar. E passamos um prompt de melhoria, dizendo no que ele deve trabalhar e como pode melhorar. Esta é mais uma aplicação de LLM e mais uma coisa não determinística, com mais uma possibilidade de dar errado. Se tivéssemos mais tempo, poderíamos fazer uma metaavaliação do nosso metaavaliador do nosso metaavaliador e garantir que ele esteja fazendo a coisa certa. Mas não vamos fazer isso aqui, porque fica complicado demais

1:34:33 e também só temos um tempo limitado. Mas bons requisitos mantêm o Claude… Então, você deveria dedicar tempo para garantir que este avaliador seja o mais preciso possível. Neste caso, estamos pegando este prompt e conectando-o ao nosso processo de duas etapas. Estamos pegando as recomendações que recebemos do Claude

1:35:03 com base nos traces que falharam e enviando-as de volta à Anthropic, dizendo: “Com base nestas explicações, escreva um prompt melhor, um prompt de pesquisa melhor, um prompt de escrita melhor”. Depois, vamos passá-los de volta ao nosso agent. Agora vamos executar um experimento. Na interface, temos conjuntos de dados e experimentos. Temos “My Demo Financial Fails”.

1:35:33 Podemos, supondo que eu consiga rolar a página, configurar um agent melhorado usando esses novos prompts aprimorados. Dá para ver o prompt de pesquisa aprimorado e o prompt de escrita aprimorado. Fora isso, este é exatamente o mesmo agent de antes. E você pode criar um avaliador com um experimento. O que estamos fazendo aqui é fornecer uma tarefa. Uma tarefa pode ser qualquer coisa. Por exemplo, a tarefa poderia ser algum subcomponente do que

1:36:06 seu agent fez. Se estivéssemos executando um avaliador para chamadas de ferramentas, por exemplo, sua tarefa poderia ser simplesmente chamar esta ferramenta, ver qual é a saída e então avaliá-la. Neste caso, minha tarefa é executar o agent inteiro novamente, do início ao fim, mas não precisa ser assim. Depois, executamos a mesma avaliação novamente, agora nesta nova execução da tarefa. Então, alteramos o agent. Executamos o agent de novo e executamos o eval novamente. E transformamos

1:36:37 isso em um experimento. É assim que o experimento se parece: Experiments.run. Demos um nome a ele. Indicamos o conjunto de dados em que deve trabalhar. Indicamos a tarefa. Indicamos o avaliador. E pedimos que execute. Isso nos dá os resultados, que estão aqui. Para cada execução, temos a saída obtida e a nova pontuação do eval.

1:37:07 Então, como podem ver, este era um conjunto de dados em que, se vocês se lembram, antes nenhuma resposta era prática. O eval foi executado e dá para ver que agora algumas delas são práticas. Então, melhoramos. E, se olharmos a pontuação geral aqui, na verdade, acertei em cheio, porque tive, sabem, muitas oportunidades de acertar. Acertei meu prompt de primeira: passei de errar 50% das vezes para acertar 100% das vezes. Um eval real não funciona

1:37:38 assim. A iteração real não acontece de forma tão tranquila. É por isso que isto é um gráfico. O que você espera fazer é executar experimento após experimento e observar o gráfico subir aos poucos, à medida que seus evals se tornam cada vez mais capazes. Essa é a subida de que estou falando, aquela que você está tentando escalar. A abstração principal por trás dos experimentos é que uma tarefa é apenas uma função Python. Ela recebe um exemplo do conjunto de dados, executa o que você quiser e retorna uma saída. Então, o AX não se importa com o que a tarefa faz

1:38:10 internamente. Ela pode executar o agent inteiro, ou apenas um componente, como eu disse, ou pode chamar uma API; basta receber uma entrada e retornar uma saída. Você pode executar experimentos com ela. O poder dos experimentos está na comparação controlada. Você usa as mesmas entradas e os mesmos avaliadores; a única coisa que muda são os prompts do agent. Isso significa que qualquer diferença nas pontuações pode ser atribuída à sua alteração. Você não fica se perguntando: “Será que a pontuação foi maior por causa da alteração no meu prompt? Ou foi maior porque a busca na web retornou resultados melhores desta vez?”

1:38:41 Na verdade, você ainda fica se perguntando isso um pouco, porque o agent é não determinístico. Ele poderia ter feito 10 buscas na web em vez de cinco. Mas você eliminou uma grande fonte de variação: os casos de teste. >> [suspira] >> Então, como eu disse, meu agent acertou de primeira, o que é ótimo, mas, na realidade, não vai ser tão simples. O ciclo de avaliar e iterar de que estamos falando aqui, em que você executa um experimento, altera

1:39:12 seu prompt, executa o experimento novamente, repetidas vezes, é onde está o verdadeiro valor. Não na pontuação em si, mas no ciclo. Você executa os evals, analisa as falhas, lê as explicações, identifica um padrão e ajusta seu prompt ou, como neste caso, pede ao Claude para ajustá-lo. “Melhorou?” é uma pergunta que só pode ser respondida com evals. Você pegou a definição de bom e a codificou de uma forma incrivelmente útil. Isso permite

1:39:43 para você passar de “acho que está funcionando” para “posso provar que está funcionando”. Uma pergunta prática que surge rapidamente é: de quantas amostras você precisa? Para experimentos na escala de um workshop, como o de hoje, de 12 a 20 exemplos já dão um sinal direcional. Para decisões reais de lançamento, você vai querer mais. Algo entre 200 e 400 é uma boa meta. Mas observe que 200 a 400 ainda é um número que uma pessoa poderia acumular ao longo de algumas semanas. Não são dezenas de milhares ou milhões, como você usaria ao treinar

1:40:14 um modelo de ML. Há retornos decrescentes. Para reduzir pela metade a margem de erro, você precisa quadruplicar o tamanho da amostra. Então, em algum nível, chega um momento em que você tem sinal suficiente para seguir em frente. Ao iterar, onde você deve investir? Há uma hierarquia. Correções na qualidade dos dados têm o maior impacto. Se o seu agent está pesquisando nas fontes erradas ou sua base de conhecimento contém informações desatualizadas, nenhuma quantidade de iteração no prompt vai ajudar. Você deve

1:40:45 corrigir os dados primeiro. Depois vêm as melhorias nos prompts. Exemplos few-shot, instruções explícitas, o tipo de coisa que mencionei hoje, restrições sobre o que o agent deve e não deve fazer. Essas costumam ser as mudanças de maior retorno sobre o investimento para o seu agent. A seleção de modelo vem em terceiro lugar. Às vezes, um modelo mais capaz resolve problemas que os prompts não conseguem. Mas também vai custar mais e ser mais lento. Então, essa é uma escolha que você precisa fazer. O que não vale a pena dedicar muito tempo é o ajuste de hiperparâmetros. Coisas como

1:41:15 temperature e top p. É muito tentador começar por eles, porque são fáceis de ajustar. Raramente provocam uma mudança de grande impacto, como a que os prompts ou a melhoria da qualidade dos dados podem proporcionar. Então, você pode experimentá-los, mas eles devem ser a última coisa que você tenta. Uma prática que vale a pena conhecer é o desenvolvimento orientado por evals. Escreva o eval antes de criar o recurso. Se você quer que seu agent sempre verifique a identidade do cliente antes de fazer algo, como processar um reembolso, por exemplo, escreva primeiro o eval que verifica isso. Assim, você tem uma definição clara e mensurável

1:41:46 do que é bom, do que significa estar pronto. Depois, você pode criar o recurso até que o eval passe. Essa é a mesma filosofia do desenvolvimento orientado a testes. E algo de que gosto no desenvolvimento orientado por evals é que as pessoas mais próximas dos requisitos do produto estão mais bem posicionadas para definir o sucesso. Então, gerentes de produto, pessoas do atendimento ao cliente e até vendedores podem contribuir com tarefas de eval. Eles podem dizer o que funciona bem e o que não funciona na prática.

1:42:17 Eles não precisam escrever código. Só precisam descrever em linguagem natural o que consideram bom. E você pode resumir isso na sua rubrica de eval. Até agora, mostrei como fazer as coisas tanto offline quanto online. Fizemos tudo em um notebook. Mas você não terminou quando o experimento de desenvolvimento passa. Você terminou quando seu agent continua tendo bom desempenho em produção, com tráfego que nunca viu. E

1:42:50 vale a pena dedicar alguns minutos a esse assunto, embora, nesta sessão de trabalho, a gente vá continuar no notebook. A primeira coisa é o eval online, como eu disse e mostrei antes. Os evals online são exatamente o que parecem: eles pegam os avaliadores que você criou hoje — a verificação do ticker, da fidelidade e da capacidade de gerar ações — e os executam automaticamente nas traces de produção recebidas. O mesmo eval sendo executado em dados novos. Mostrei como executar isso em uma trace. O AX permite fazer isso

1:43:21 em três escopos. Você pode executar seus evals no nível do span. Assim, pode dizer: “Nesta chamada específica de LLM, nesta chamada específica de ferramenta, execute um eval toda vez”. Desculpe, execute uma avaliação toda vez. Ou você pode executá-los no nível da trace, em que o eval tem a árvore completa para analisar e pode avaliar tudo do início ao fim. Você escolhe o escopo que corresponde à pergunta que está fazendo. E não precisa executar evals em todas as traces de predição — quer dizer, em todas as traces de produção. LLM judges custam dinheiro e, em

1:43:52 escala de produção, esses custos podem aumentar. Então, você amostra 10% do tráfego ou 1% do tráfego. Isso dá um sinal direcional sem que você precise executar um LLM as a judge caro em cada iteração, em cada instância da sua aplicação. Se você não quiser escrever seus evals à mão, temos uma boa notícia: criamos um agent dentro do próprio AX. Ele se chama Alex. Você pode descrever seu eval em inglês simples

1:44:24 ou pedir a colegas sem conhecimentos técnicos que descrevam a definição do que é bom em inglês simples, e Alex manipulará a interface para você: criará um eval, escreverá a rubrica, definirá todas as pontuações corretamente, ajustará toda a configuração e, então, apenas avisará que terminou. Isso é especialmente útil para quem não é da área de engenharia. E o ciclo completo em produção funciona assim: você parte da aplicação, que produz traces, e chega aos evals online, que avaliam essas traces e produzem

1:44:55 rótulos e explicações. Os rótulos dos evals alimentam monitores, que não abordamos hoje. Os monitores podem alertar sua equipe quando algo dá errado. A equipe pode investigar, encontrar as traces com falhas, salvá-las como um conjunto de dados de regressão, melhorar o agent, executar um experimento para verificar e lançar a correção. Então, o ciclo pode recomeçar. À medida que se acumula novo tráfego de produção, você vai acumular novos modos de falha e novos casos extremos. Você sempre vai iterar

1:45:27 nos seus evals e no monitoramento da produção. Mas o retorno se acumula. Cada falha que seus evals online detectam se torna um novo caso de teste. Você a salva em um conjunto de dados e, agora, ela é um teste de regressão para a próxima rodada de mudanças. Com o tempo, isso cria um conjunto de dados exclusivo da sua aplicação. Seus modos de falha específicos, seus usuários específicos, seu padrão de qualidade específico: ninguém mais tem esses dados. E essa é uma vantagem competitiva que cresce toda vez que seu agent é executado.

1:45:59 Há um último padrão que quero deixar para vocês, e é o mais poderoso que conheço. Hoje, fizemos a versão mais simples. Enviamos as explicações dos avaliadores de volta para Claude e pedimos que reescrevesse dois prompts. Isso funciona muito bem com dois prompts. Mas um sistema real não tem só dois prompts: há prompts espalhados por muitos arquivos, configurações de recuperação, definições de ferramentas, tudo interligado. Reescrever isso não se resolve com uma única chamada de API. É um trabalho para um coding agent que consiga ver todo o seu repositório. Então, este é o padrão: você deve exportar do AX suas traces com falhas

1:46:31 junto com as explicações e entregar o lote inteiro a Claude Code, Cursor ou outro coding agent como contexto. É aqui que o plugin de skills da Arize que mencionei no começo funciona muito bem, porque você não precisa saber como chamar nossa API. Não precisa saber como fazer nada disso. Você fornece as skills e então diz ao Claude Code: “Ei, baixe algumas traces, veja o que está errado e melhore minha aplicação”, e funciona. Essa abordagem deve ter duas proteções

1:47:02 primeiro. Porém, primeiro você também deve fornecer seus requisitos, e não apenas as explicações das falhas. Portanto, o objetivo não é fazer o eval passar, porque, caso contrário, ele vai trapacear. Ele vai incluir todos os seus dados de teste no eval e fazer com que todos os seus evals passem automaticamente. Então, você precisa deixar claro para o Claude Code que não quer que ele apenas faça os evals passarem. Você quer que ele faça algo específico, o que então fará os evals passarem. E, em segundo lugar, você deve pedir que ele encontre padrões, em vez de perseguir

1:47:32 falhas individuais. É muito tentador para o Claude Code analisar um trace específico que falhou e escrever um monte de código para corrigir aquele trace, quando, na verdade, há 10 traces com falhas causadas pela mesma coisa, e é nisso que ele deveria se concentrar. Não vou fazer tudo isso agora, porque só me restam 12 minutos. Mas, quando você tem evals, essa é uma das coisas de maior impacto que pode fazer com elas. Então, vamos dar um passo atrás e olhar para o quadro geral

1:48:03 dele. A produção gera traces. As evals online os avaliam e produzem explicações. Um agente de programação lê as explicações e propõe correções. E os experimentos verificam se as correções funcionam; então, você faz o deploy. O tráfego de produção que volta é avaliado pelas mesmas evals online que iniciaram o ciclo. E esse é o ciclo de vida do desenvolvimento de software se fechando sobre si mesmo. Seu software de IA está ajudando você a melhorar seu software de IA, e o AX é a base que conecta tudo isso. Seus traces, as evals, as

1:48:33 explicações, os conjuntos de dados, os experimentos, as evals online e os monitores. Então, recapitulando: instrumentamos um agent com duas linhas de código. Rastreamos sua execução e lemos nossos dados. Escrevemos uma eval de código e usamos evals de LLM integradas. Escrevemos do zero uma rubrica personalizada. Validamos nosso judge com rótulos humanos. Salvamos as falhas no conjunto de dados. Pedimos ao Claude para melhorar os prompts. Rodamos um experimento para provar que funcionou. E vimos como o AX leva tudo isso para a produção com evals online.

1:49:05 Esse é o ciclo completo, e agora você já conhece todas as etapas. No entanto, não precisa fazer tudo de uma vez. Foram duas horas de informações extremamente densas, e eu sei disso. Você pode começar bem, bem aos poucos. Pode começar lendo seus traces. Basta adicionar aquelas duas linhas de código e começar a examinar seus traces; isso já vai fornecer informações sobre o que seu agent está fazendo que você ainda não tinha. Quinze minutos lendo resultados reais vão ensinar mais sobre seu aplicativo do que uma hora criando dashboards. Depois, escreva uma

1:49:35 eval de código. Evals de código são mais fáceis do que evals de LLM, além de serem mais rápidas e baratas. E faça isso para o que mais importa: correção, fidelidade ou o que fizer sentido para seu caso de uso. Rode-as, examine os resultados, veja que padrões aparecem e continue a partir daí. Evals são infraestrutura. Não são algo para deixar para depois. Algumas equipes criam evals logo no início do desenvolvimento. Outras as adicionam mais tarde, quando já estão em escala. Mas, de qualquer forma, o importante é tratar as evals como uma parte essencial do seu sistema. Elas devem ser tão rotineiras quanto os testes de unidade e

1:50:07 o valor se acumula, mas só se você continuar investindo. Cada vez que uma regressão aparecer antes de chegar aos usuários, e não depois, você vai entender por que todo esse trabalho vale a pena. Não espere que algo fique ótimo por acaso. Você pode chegar a resultados excelentes de forma sistemática, definindo-os, medindo-os e trabalhando para melhorá-los. Então, agora é hora de experimentar isso de verdade em um aplicativo seu. Espero que você já tenha uma conta no AX, agora que o Wi-Fi voltou. A documentação em arize.com tem notebooks complementares

1:50:40 com código executável para tudo o que abordamos hoje. E, se quiser que seu agente de programação faça o trabalho pesado, você pode instalar os plugins da Arize — o plugin de skills da Arize — com um único comando npx. O link está no notebook de hoje. Se você chegou até o fim, também pode ganhar um ano grátis do Arize Pro usando o código que está na tela agora. E é isso. Muito obrigado a todos pelo tempo e pela atenção. [aplausos]

1:51:24 >> [música]

Transcrição original

[00:12] Hello everyone. Uh I have a packed room for a two-hour workshop which is amazing. Welcome to AI Engineer. I know no one’s officially welcomed you but uh welcome to AI Engineer. Uh this venue is amazing. This crowd is really quite surprising and I have uh a ton of content for you today. Uh my name is Lori Voss. I’m head of developer relations at AriseAI. Uh some of you may remember me from when I used to co-found npm Inc. Uh so you may

[00:45] remember me from like JavaScript days. Uh but these days I talk about AI uh and how to test it uh and how to make it work. So what are we going to be covering today? Uh we’ve got a really good stretch of time together. Uh so we’re going to cover a lot of ground and I’m going to start with fundamentals. That’s why this is called a 101 session. Uh we’re going to start with what eval are, why you need them, uh and why agents make evaluation harder than simple LLM applications. Uh then we’re going to set up tracing in Arise AX, uh

[01:17] which is how you capture the raw data you need to run evals in the first place. Uh, we’re going to build a simple AI agent uh with the claw agent SDK. We’re going to run it and we’re going to look at uh the traces it produces. Can I get a show of hands if you’ve already built an agent? All right, great. I’m going to spend no time at all on how the agent works because I assume everybody knows how an agent works and you’re here to learn how to evaluate them. Uh once we’ve got some data, uh we’re going to do something that a lot of tutorials skip, which is

[01:48] we’re going to actually look at the data. Uh we’re going to read our traces. We’re going to categorize what went wrong. Uh and we’re going to figure out what to measure before we write a single eval. Then we’re going to write three kinds of evals. There are code evals, which are simple deterministic checks, uh very similar to unit tests. Then we’re going to use built-in LLM evals uh like faithfulness uh where a second LLM judges the uh output of your first one. Uh and we’re going to do a custom eval

[02:19] uh LLM as a judge from scratch. Uh and we’re also going to test whether our judges are judging correctly, a process called meta evaluation. Then we’re going to finish with data sets and experiments, which is how you iterate on your agent uh and actually measure whether it’s getting better. uh including we’re going to use cloud code to automatically improve our app in response to feedback from our evals. So, first things first, uh get your notebook. Uh I messed up earlier and

[02:51] didn’t have permissions set correctly. So, if you scanned this earlier and it didn’t work, it works now. Uh grab this notebook and make a copy for yourself. That is where we’re going to be living all day. And I’m going to wait for that to happen because otherwise I’m going to have to keep swapping back to this slide. All right, most of those are down. No, no, I’m still seeing people taking pictures. All right, cool.

[03:22] We’re also going to need a certain amount of AI infrastructure. I’m going to be using anthropic and cloud code today. Uh, Arise AX works with OpenAI. It works with every other uh, lab provider, but I had to pick one in order to do a workshop about it. So, I’ve used Claude. So, this is going, this notebook is going to expect you to have uh, an anthropic API key, which you can get from console.anthropic.com. If not, you can, if you are very clever, do a fast swap to OpenAI. Um, you’re also going to need an Arise account. Go

[03:53] to arise.com and start a free trial. Um, from there you will need an Arise Space ID and an Arise API key, both of which you can get from the settings page. Uh, my lovely assistant Dat is here. Uh, that’s him in the corner. If you run into any problems getting your API keys or anything like that, uh, just flag him down and he will run over to you and help you figure it out, which is, uh, incredibly nice of him. Thank you, Dad.

[04:24] Um, [sighs] yes. So, uh, who who had all that stuff already? Anybody already got an Aris X account? [laughter] All right, I’m going to let you hang out for this. I’m going to let you set that one up for a little while. The way you do it is you go to arise.com

[04:57] and you hit Oops, it’s sent me to the docs because I always live in the docs. You go to arise.com. Thank you. Uh and you hit the big pink get started button and then you sign up from here. Do not accidentally sign up for Phoenix. Phoenix is our lovely open- source project which also has a hosted service underneath Phoenix. Uh sometimes when you Google Arise, you get sent to Phoenix instead. Don’t sign up for Phoenix. You’re doing AX today.

[05:34] All right. While you are signing up, uh I’m going to say a little bit more bit more about what AX is. It is an observability and evaluations platform. It captures traces from your AI application. It stores and runs your evaluations and it watches your app in production and alerts you when something goes wrong. Uh by default, we host it for you. That is why we’re using it today because you don’t have to like run some software to make it run. Uh so there’s no infrastructure to manage. Uh though if you are from an enterprise that is super precious about your data

[06:04] and you’re like no, we need to run it ourselves, you can absolutely do that if you want to. Um, and like I said, uh, if you’ve used Arise Phoenix, which is our open source tool, a lot of this will feel familiar. Uh, they have the same core ideas. One is, uh, built for open source accessibility, and the other one is built for, uh, enterprise with production and teams and things like that. So, how are we doing on signing up for keys right now?

[06:35] >> Wi-Fi sucks. >> The Wi-Fi sucks. That is predictable really, isn’t it? All right. Is anybody like desperately in need of assistance right now? >> All right.

[07:12] Okay. Well, the advice is to switch to your phones as a hot spot. I apologize for the Wi-Fi. I’m really worried about my 2PM workshop where I have a Git repo that I know is 200 megabytes large and I’m like, no one is going to get the repo because it’s too big. >> Yeah, start cloning that repo now. Anyway, uh let’s talk about these these fundamentals. There’s a lot of theory in this workshop which gives you time to uh catch up. Um here’s the mental model. Evals are testing for AI and traces are

[07:45] logs for EI AI. Why we had to come up with two completely new names for those things? I don’t really know. Uh you write tests for your code. Given this input, I expect this output. Uh eval do the same thing, but for AI outputs where the outputs are never exactly the same twice. Just as logs record what your server did at runtime, uh, traces record what your AI did. So, every agent call, every tool call, every LLM invocation with the inputs and outputs at each step. The building blocks of a trace are

[08:17] called spans. Uh, in this little screenshot, you can see a trace in Arise AX. It’s made up of a bunch of spans. It’s got this tree structure. Uh, and each span represents one step in the execution. An LLM call is a span. A tool call is a span. And a full agent turn is a span that contains other spans inside of it. Each span records its input, its output, uh timing, token counts, and a whole bunch of metadata. Uh everything that you need to understand what happened at that step. Traces tell you what happened. Evals tell you whether it was any good. That is the model for

[08:49] mental model for today. This is not rocket science. But let me talk about why we even need evals. Uh and that is the vibes problem. Uh AI features usually get shipped by building an AI feature, running a few queries, saying does this look right? Yeah, it looks good. And then you ship it. That is by far the most popular method of shipping AI applications today. Uh and the problem is that then it fails on inputs that you didn’t test. Uh and the thing is it probably looks

[09:20] good on your test queries, but the problem is that you ran it three times. Three times is not a test suite. Uh the usual fix for uh flaky software is unit tests and they don’t work here because the output is non-deterministic. Uh the same prompt produces different text every run. So two different responses might both be correct. So there’s no expected string that you can assert against. So teams fall back on human review. They watch it run. It looks fine and they ship it. Uh that doesn’t scale. It doesn’t catch regressions. And most importantly, it

[09:51] doesn’t run in CI. Here’s some things you can’t do without evals. Uh if you change your system prompt to fix a tone issue, then the tone would get better. Uh but now your uh bot is hallucinating product features. Without eval catch that uh until a user reports it. With a faithfulness eval, you would have seen the spike before it shipped. Uh and every prompt potentially affects every kind of input that users send. So you can be changing the prompt for one thing and have a completely unexpected effect

[10:21] at some totally different part of your application because the prompt is just a huge block of text that you’re sending to your AI. Uh you can’t manually test every combination. So without eval you’re playing whack-a-ole. You fix one problem and you break something somewhere else. Evals instead give you a number that you can track and compare and act on. You also can’t switch models without eval. This matters more and more because this field moves so fast. Uh new models drop every few months. Uh without eval

[10:51] switching models means weeks of manual testing. Is it better? Is it worse? Did something get did something break? You don’t know. With evals, you run the suite. You compare the scores uh and you know within hours. And that is the difference between flying by the seat of your pants and flying by instruments. And this is not theoretical. uh real teams, Dcript, Bolt, Anthropic’s own clawed code all follow the same arc of shipping on vibes and then discovering that vibes don’t scale uh and then uh building evals and that is the same arc

[11:23] that we’re going to follow in today’s workshop. As I mentioned earlier, there are two broad types of evals. Code evals are deterministic functions. They run in milliseconds and they cost nothing and they give you an immediate unambiguous answer like did the output parses JSON? Is the output less than 500 tokens? Did it mention the thing that I asked about? The big advantage of Kodi valves is that they are fast and cheap and totally reproducible. They get the same they get the same input and they give the same answer every time. That makes them very

[11:53] similar to old style unit tests. The downside is that like old style unit tests, they can be brittle. Uh we have some strategies that can help avoid that and I’m going to be covering those later. um because two perfectly correct answers might be worded completely differently and you have to adjust your expectations of unit tests to be able to handle that. The second type of eval is an LLM as a judge eval. These use a second LLM to grade your outputs against a rubric. Rubric being yet another word that we made up uh that just means rules. It is

[12:25] your set of rules that you put in your prompt about what counts as good. Uh LLM evals are much more flexible. uh they can handle the kinds of questions that Kodi valves can’t answer. Uh is this response uh factually accurate? Did it stay faithful to the source material? Is the tone right? Uh for a customer service context, the strength of LLM judges uh is that they understand meaning uh not just the strings that are in your output. But LLM judges have trade-offs. The weakness is that they cost money to run

[12:56] and they are nondeterministic themselves. Uh so they can be wrong which means that you need to calibrate them against human judgment and we’re going to do that later today. Um there’s also a third type of eval which is human evaluation. Uh a domain expert can read your output and grade it. Uh and that is the gold standard for quality. Uh but it is slow and expensive and humans get tired which is why we can’t use it all the time. Uh fun fact that’s not very fun. Human annotators miss up to 50% of

[13:26] defects due to fatigue. So they’re not perfect either. So when you build an LLM as a judge and you’re like, well, it doesn’t always catch my errors. Remember that if you were judging with a human, the human would also not always catch your errors. Uh but these are complimentary approaches. Most real applications are going to use a a collection of Kodi valves, LLM as a judge, and human evaluation. So when do you use which? Use Kodi valves when the answer is deterministic. So, format validation, length limits,

[13:56] forbidden phrases, uh required fields, use LLM judges when you need semantic understanding, a correctness, eval accurately, a faithfulness eval asks, did it stick to the source documents without hallucinating? Uh, and you should keep humans in the loop for failure modes that you haven’t seen before. Uh, and to verify that your LLM judges are actually judging correctly. LLM judges can be wrong. uh judging them against human judgment is how you know whether or not you can trust them.

[14:27] All of that is true of any application that uses LLMs. Uh but agents make things even harder in some ways that are uh worth calling out. You can think of it as a ladder of complexity. A single LM call is relatively simple. You get an input, you get an output. When you’re talking about an agent, an agent is making a series of tool calls and a series of decisions, which means that at every single step in the uh chain, it is the chances that it has made a mistake are getting higher and so the chances that it will go off the rails uh are going to get uh greater. So you have to

[15:01] judge the intermediate steps as well. You have to uh check whether your agent is using the right tool. Did it pass the right arguments? Did it know when to stop? getting stuck in loops is a real failure case for agents. Uh and then multi- aent systems if you are building those add yet another level of complexity. They add handoffs. One agent decides to pass work to another. Did the triage agent route correctly? Did the specialist agent handle the the handoff gracefully. Each layer adds new ways that things go wrong. Uh and

[15:31] non-determinism means that you need to have more evals because errors can cascade. Uh here’s what an example of an cascading failure looks like. If you’re you ask a query about Tesla, meaning the car company, your agent searches the web, finds a whole bunch of information about an 18th century inventor, passes that back to your agent, which writes a beautiful, well- formatted report about an 18th century inventor, and passes that to your boss. Nothing that it did there was wrong. It you told it to search the web for Tesla. It searched

[16:02] the web for Tesla. It got information about Tesla, and it wrote a report about Tesla. where where did it go wrong? Uh this is worse than an obvious failure because you have to be reading your inputs and outputs for that to work. You can’t there was no unit test that would have caught that. Uh but agents can also do the opposite. They can get things right in a way that your tests weren’t expecting and get graded wrong as a result. This happened to Anthropic when they ran a benchmark called Tao Squared Bench uh which simulates multi-turn customer to service

[16:33] tasks. uh they asked the agent to book flights uh and asked it to do something that they thought was impossible which was reschedule an economycl class flight. Uh but it turned out that the policies that they gave the agent allowed the agent uh to first upgrade the flight to first class. First class flights can be rescheduled which uh economy flights cannot. So the agent found a way to reschedule an economy flight uh and failed the test because it

[17:03] was supposed to be not able to do that and it was able to do that. Uh so this is an example of how agents being flexible agents finding things that you didn’t think of uh needs to be accounted for in your tests. Uh there is a difference between creatively correct and wrong and we’re going to come back to that when we talk about grading your agents later or rather grading your evals. Um there’s also a second way of categorizing your eval into two categories uh which is uh capability evals and regression evals. A capability

[17:35] eval asks uh can my agent do this thing at all? Um capability evals are expected to mostly fail. Your agent is expected to get a very low score on them. Uh because they give you a hill to climb. It gives you something for your agent to try and get better at. Uh once you’ve climbed that hill, your capability eval turns into a regression eval. A regression eval is an eval that you expect your agent to pass completely or nearly completely every single time. So as your agent matures, you’ll be giving

[18:05] it capability eval after capability eval and slowly turning them into a suite of regression evals that you run all the time to make sure that uh previous behavior has not regressed. This is what an eval result looks like. Uh every eval produces a score and a label. In this case, it’s a numeric score just often just zero or one. Binary scores are very easy for uh LLMs to do. [snorts] Uh and it comes with a human readable label like correct or incorrect or valid or invalid. Um LLM

[18:35] judges add a third thing which is the explanation. Um code eval produce explanations because they are just code. Um but LLM, an LLM as a judge will say not just that something is incorrect, but it will say why it decided that something is correct. And this is incredibly valuable uh because if you are living in a world of coding agents, you can take a whole bunch of explanations from a bunch of evals and pass them back to your coding agent and say here is all the reasons that you messed up in the last test. What could

[19:05] you do that would make you better at this? And your coding agent will just go cool thank you for the feedback. Improve your application uh and it will get better at it next time. This is something I’m going to show you uh in today’s workshop. It is how you turn a failing eval into a prompt improvement. This is a real judge explanation. Um, in this example, it it’s a travel planning agent. Um, and you’re running a correctness eval. The judge doesn’t just say incorrect. It tells you exactly what’s missing. You asked for a budget flight. It didn’t give a budget

[19:36] breakdown. It says the agent gave destin destination info and recommendations. Uh, but the user asked about budget travel and there were no cost estimates. That explanation makes the eval actionable uh because you now have a concrete failure. You know what to fix in the prompt. Uh and the explanation is what makes evals into a useful debugging tool and not just a scoreboard. Uh and if you’re seeing the same explanation across 50 different traces, uh you know you have a systematic problem and not a one-off edge case, which makes it the first thing you should fix. So you have

[20:07] to take your eval explanations uh and categorize them into types of failures uh and count up the categories. This is called coding. Again, we can make up words from the L from the ML word uh from the ML world. Um but categorizing things is known as coding. Um and of course each explanation is natural language. Uh so it is hard to do this coding uh unless you use yet another LLM to do the categorization for you. We’ll be seeing how that works uh towards the end of today. Um, and like I

[20:40] said, you can hand a whole pile of these explanations to a coding agent and let the app fix it for you. Uh, this is the full loop that we’re going to build today. We’re going to, uh, instrument, trace, eval, and iterate. Each step feeds the next. You define what you want. Uh, you build it, you measure how well it works. You ship it, you monitor it in production, and you iterate based on what you see. Every traditional software product goes through a loop like this. Uh but for AI the measurement step is where most teams fall down and evals are how you measure.

[21:12] Evals are the connective tissue uh across this whole life cycle. Uh so let’s get started building it. Step one is setting up tracing with Arise EX AX before we can run evals. We need something uh some data to run our evals on. Uh and you can’t evaluate what you can’t observe. So observation comes first. So hopefully you’ve conquered the Wi-Fi uh and you have our notebook at this point and that is running around to make sure

[21:43] uh that you do. Uh let’s go to our very first code cell which is where I install our dependencies. Uh claude agent SDK is self-explanatory. That is the claud agent SDK. uh open inference open inference instrumentation claude agent SDK is the auto instrumentation package for the claude agent SDK. This is how it knows to capture traces from cloud agents uh without you changing your application code. Uh as I mentioned earlier, you can use open AI instead if

[22:15] you want to uh or some framework. Um we have packages for all of those as well. You just need to swap them in. Um, Arise and Arise Otel are the packages that send uh your traces to AX and let you read them back. Uh, and there’s a Phoenix package in there that we use as utility package. Don’t worry about it. Um, the anthropic package lets you use Claude both to power our agent and to judge its output later. Uh, so uh, go ahead and run this cell if you haven’t

[22:45] already. And while it’s installing, I’m going to talk about what it is that we’re going to actually build. Um the claude agent SDK if you haven’t already used it is Anthropic’s framework for building agents. So Anthropic’s answer to lang chain and things like that. Uh it can use tools, it can search the web, it can maintain conversation context across turns. Uh open AI has their own uh agent SDK and of course there are whole agent frameworks like crewa align chain and mastra and uh AX is compatible with all of those. So no matter what framework you’ve built uh your agent in

[23:17] uh it is already instrumented and you can just turn on logging and all of your traces will light up. Um hopefully your install is done by now which is uh optimistic timing on my part. Um next set your keys. Uh in this case I have stolen my keys from uh collab. If you are feeling naughty, you can just paste them in directly to your cell and put them there. Um, three things go in here. Like I said

[23:48] earlier, you need an anthropic API key, uh, which is going to power our agents LLM calls, and it’s also going to power the judge later. You need an Arise API key, which you get from your settings, which authenticates your traffic to the AX service, and you need an Arise space ID, which tells AX which uh, workspace to put all of your data in. Uh if your keys aren’t working, the usual culprit is a copype error. Uh and of course that is still running around to help you if uh your keys aren’t working. That is has been described as a walking

[24:18] security hole. Uh so he will definitely give you a key if you can’t figure out how to get your keys to work. So now we scroll to the register section. Uh I’m going to bump up my fonts here. One more time. >> The QR up one more time. Sure. Probably.

[24:56] >> Sorry. >> Uh, yeah. I didn’t put my mine lives in Collab. So, Collab’s secrets feature pulls it out. All right, I’m going to go back to where I was. Hopefully, I can do that. All right. Uh so

[25:29] we’ve installed dependencies, we’ve talked about the SDK, we’ve talked about the secrets. [gasps] Uh and now we’re at the register. So this is the magic. Uh anybody who works for Arise will tell you that you only have to add two lines of code to your application in order to instrument your call. And this is these are the two lines of code. Uh what we’re doing here is we’re passing in our arise space ID, our API key, uh and a name for it to trace everything to. Um the register function is setting up open telemetry.

[25:59] Open telemetry is the industry standard for application observability. Uh and it has a layer on top called open inference which adds LLM specific attributes. Things like prompt text, completion text, token counts, which model was called, which tools were invoked. um we point it at ax uh and we give it a project name and that is how your traces get grouped in the UI. Uh in this case we’re also passing batch equals false because uh when you run in a notebook uh you want to send your telemetry as soon as it happens and not batch stuff up

[26:31] which it does for efficiency in production. Um that one line at the bottom, the claude agent SDK instrument tells the cloud SDK to send a span to ax every time it makes an LLM call or invokes a tool. Uh and that is now instrumented. The reason this works with so little code is because open telemetry is an open standard that nearly everybody uses. So the cloud the cloud SDK authors, the open AAI SDK authors, the lang chain authors, all of them have already written the code inside of their

[27:01] SDKs that calls open that calls open inference and sends data back. So all you have to do is say, “Hey, I’m an open inference collector. I live here. Send it to me.” One more bit of setup is that the register call sends data to AX. Uh and the Arise client reads data back out of AX. Uh so we’ll use it to pull our spans back into the notebook. Uh that is what this line is about. So you need to make sure that you’ve put in the same keys there or uh copied them across.

[27:40] >> Oh, you need to make a you need to make a copy of the notebook from the file menu to be able to edit it. Cool. Um, all right. So, if you’ve run that run those cells, then we are ready to build. Uh, before we build, one thing worth knowing about, uh, everything we’re going to do by hand today, you can also get your coding agent to do for you. The reason we are doing it by hand is so

[28:11] that you have a fundamental understanding of what it is that you’re doing and you’re not just vibing your way to success. Um but we publish a set of skills called the Arise skills uh which know how to do all of this for you at the skill level. So you can install your Arise skills uh and um run evaluations, create data sets, uh instrument your app in the first place. Um they all use uh AX’s recommended patterns and you install them once with a single npx command. They work in cloud code, they work in cursor, they work in codeex and dozens of other coding

[28:43] agents. Um, so we’re going to do stuff manually today, but in production in a real life environment, we are using our own skills every day to do this stuff. Uh, so now let’s build our agents. Uh, when I asked if everybody had built an agent before, everybody put their hand up. So I’m not going to spend a lot of time explaining how this agent works. I’m going to assume that you already have an agent somewhere and you’re just trying to instrument it and make it work for you. Um, the fake agent that I’m using today is a financial analysis

[29:13] chatbot uh using the cloud agent SDK. You give it a stock ticker and a focus area and it searches the web for the latest information about that stock ticker. Uh, researches real current financial data and writes a report for you. Uh, this is a a real use case that whole startups are built around. Although uh my agent version is extremely simple. Um, I’m assuming uh that you built an agent already. Our agent works in two turns. Um there’s first a research turn that uses tools to search the web and gather data. Then

[29:43] there is a writing turn that compiles the research into a readable report. Uh so let me walk you through that. Uh here is my research prompt and my write prompt. These are deliberately extremely simple. They are going to cause errors later and those are the things that we are going to use our evals to debug. Uh and then I’m setting up my claude agent options. I’m using uh Claude Haiku uh as the agent underneath because Haiku is you know capable but it will make mistakes and we want some mistakes so that we can fix them. Uh and it’s also

[30:14] fast and cheap so I don’t burn a lot of money uh of your money when as we do this. Um the permission mode controls uh what the agent is allowed to do autonomously. There is a catch hiding in the in the specific choices that I have made and the specific allowed tools. uh that I am giving this agent right now as we’re going to find out later. Uh and now let’s look at our two turns. Um turn number one is research. There is a

[30:45] [snorts] bunch of boiler plate in here that I’m not going to explain which is just about outputting the output so that we can see what it’s doing as it’s going. Uh turn two is writing the report with again a pile of boiler plate. Um the prompts are critical. So this is where I want you to start doing your own changes in your own notebook. I have given it extremely basic prompts at the top. If you can see if you can think of a better prompt just off the top of your head uh that is going to do a better job than the prompts that I put in uh at

[31:15] solving this problem. What would be better than what I put in to uh do the research in the first place? What would be better than what I put in uh to do the report writing? Um, and if you oneshot it, then you’re going to have uh less stuff to do later on. Um, one of the things we do here is we wrap the whole thing in an open telemetry span. Uh, this is because if I don’t do that, then claude inter Claude sends this as two the two turns as two

[31:47] separate spans and we wanted them to be grouped together in the UI. Uh, so I’ve wrapped them in a span together so that they come out as a single agent turn. Um, this is just saving us some time later. I wanted to be clear about why I’m doing this uh bit of code. Um, and now we can run our agents. Uh, I have run my agent in advance because I wanted to know exactly what it was going to do. Um, but now is the time to kick off your own agent. Um, I’ve asked it to analyze

[32:17] Tesla, specifically its financial performance and growth outlook. Um, you should go ahead and run this cell. It’ll take a minute or two because the agent will actually search the web. Uh, and the LLM is doing multiple rounds of reasoning. Um, the agent receives our research prompt. It decides it needs to search the web, which is a tool call. It reads the search results. It decides if it has enough information and maybe searches again. That is the agentic part. You didn’t say do a web search, take the web information from the web search and write a report about it. The agent is deciding is this web search

[32:49] enough information? And if not, I will write I will run more web searches. It will run an in indeterminate number of web searches to get enough information until it has decided what enough means. Uh and then it will write the report. This execution path is non-deterministic by design and that is the key here to understand. Uh if you run this again with the same input, your agent might search for different things. It might find different results. It might write a different report. Uh and both reports might be good. Um or one might be good and one might be bad. And that is exactly why we need evals. We can’t

[33:21] predict the output from the input alone. Uh, and every single one of those decisions is being captured as a trace. Uh, so I’m just going to pop open my last 12 hours or my last 24 hours, I guess. Cool. This is a pile of traces. You’re going to understand what all of this is later, but here you can see the Tesla one that I ran earlier. This is what it looks like when I go through. You can see every single turn. Uh it’s calling a skill. It’s doing a tool

[33:52] search. It’s doing a web search. Uh you can see every single thing that it does. You can see that it ran four web searches before finally deciding that was enough information. Then it did the second uh call in the step and it wrote the report. Uh one of the things that it does uh that we’re going to see later is uh I told you there was a catch in the tools that I gave it. Uh here’s this step that was unexpected when we were putting this demo together. It tried to write the report. I told it to write a report. It

[34:23] tried to write the report as a markdown file to disk. It is living in a collab notebook. So there is no uh there’s no file system for it to write to. Uh so the write step would fail. Uh and this is something that you need evals for. You need evals to detect when your agent is doing something helpful but incorrect. Uh because this fails silently. It gives you output anyway, but it’s doing this unnecessary extra step of trying to write to disk uh without you knowing that it was there. Um,

[34:54] so back to the collab, this is a pretty good report. Um, it’s a financial performance table with real numbers, growth drivers, risk factors, analyst price targets, and a conclusion. Um, it’s not bad for a first pass, but it not bad as a vibe. And we are here to replace vibes with actual numbers. Um, [sighs] so like I said, uh, you can see all of that stuff in the uh, traces.

[35:25] We didn’t have to do anything to get all of that information. We didn’t have to like instrument every single line to get the LLM call and get the tool call and all of that stuff. All of that is built into cloud agent SDK. just it is like it’s built into open AIS SDK. Uh and each one of these rows in this table is a span. Um traces reveal every decision the agent made. Without them, all you see is I gave it a prompt and I got a report. With traces, you see every step. Uh if you click into any span, like I said, you’ll see exactly what the model received as input and exactly what it

[35:56] returned. Um, and that is what observability means in practice. Not just did it work, uh, but how did it work and where exactly did it go wrong? Uh, when we run our eval in a few minutes, uh, we’re going to pull the input and attribute output attributes out of these spans and feed them to our evaluators. The input becomes the evaluator’s input. The output uh, becomes what gets graded. Uh now we need to generate some test

[36:28] data to run meaningful evals. Uh we need more than the one trace that you’ve generated so far. We need a body of data. Uh in the notebook there are 12 test queries covering different tickers and analysis types. Uh you should kick those off now. They take about 5 to 10 minutes to run assuming that you’ve got Wi-Fi and everything’s working for you. [snorts] Um I’m going to show you what they look like. Uh and oops this is them here.

[37:01] So the key thing here is uh diversity. I’ve given it a bunch of obvious queries that should work. I’ve also given it some edge cases. For instance, I’ve given it one where I gave it two tickers, Apple and Microsoft, and told it to run a comparison. Uh which is something it could theoretically do. uh I’ve also given it the same uh tickers multiple times uh in places so that we can see uh the non-deterministic output uh when we say uh Amazon profitability trends and outlook versus Amazon AWS

[37:33] performance and profitability um different tickers and different questions different levels of complexity are important uh to generate test data that’s going to cover the range of things that users will actually ask although spoiler alert in reality your users are going to ask really weird things that you’re not going to be able to predict in advance and that is another one of the reasons that eval are important. Um the uh Rivian query rivn uh asks about a company with much less public data than

[38:03] Apple or Microsoft and the Coca-Cola dividend yield query is a very different kind of analysis from a growth growth stock query. Um again this is diversity that is important. Um, diversity in your test set is how you catch uh things that your agent is going to be not good at. Uh, so while yours are running, mine have already loaded so I can show you all of my data. Uh, these are all of my spans from all of those runs. Um, you can see uh at the

[38:36] bottom there are 13 uh the which is the initial Tesla run and 12 test queries. Each one is a complete execution of the cloud uh financial analyst. So now we have the data but before we write any evals uh we need to actually uh look at the data. Um this is error analysis. Uh and the whole step is one instruction. Read your traces before you write eval. Before you write a single evaluator start with your data. Uh read or a dozen or more of your

[39:06] traces end to end. This is the most important practice in this entire workshop. uh focus on the ones where something went wrong. What was the input? What was the output? What specifically is broken? This sounds extremely old-fashioned. Just read the input. Uh but it is one of the highest value activities in agent development. Uh Anthropic, for instance, invested in tooling specifically for viewing eval transcripts and their team spends a whole lot of time just looking at eval transcripts every day. Um, a trace tells you whether the agent

[39:36] made a genuine mistake or whether your graders rejected a valid solution. Uh, if you automate before you understand your failures, then you’re going to create an eval that measures what’s easy to measure instead of what actually matters. You need requirements first before you can categorize failures. You need to know what success looks like. You can’t say it doesn’t work if you haven’t defined what it works means. Uh for our financial analyst, what does a good report look like? Uh it should reference

[40:08] the correct ticker. It should include some re real recent actionable financial data uh and include actionable recommendations. It should distinguish between forward-looking analysis and historical summary. Those are our success criteria and they seem obvious uh when you write them down, but lots of teams never do. Um they ship an agent and then react to complaints instead of defining the bar up front. Uh, writing requirements down turns vague disappointment into specific testable criteria and those criteria are what turn into your evals.

[40:40] Here’s the thing about defining success that it’s important to note though, which is that it is not something that your engineers can do or not something your engineers can do alone. The definition of good usually lives in the domain knowledge and the domain knowledge lives in the people that your company will often laughably refer to as non-technical. So your product managers, your QA, your support team, those are the people who know what the definition of good really is. They know what the failures are going to look like. Those are the people who should be helping you write your evals. Uh OpenAI put it

[41:11] really nicely. They said that people management skills are AI skills. So clear goals, uh direct feedback, knowing what your value proposition is, uh those skills matter more than ever when the system is probabilistic. Uh and this is one of the things that AX is built around. Anyone on your team can read traces or add annotations and contribute to your criteria. This is not just an engineering surface. You’re expected to have other members of your team in here. A quick note on where to get this test data. Uh we have these traces because we

[41:43] already ran the agent ourselves. But what if you’re building something new and you don’t have real traffic yet? Uh you can do what we just did, which is you can use synthetic data. You can have an LLM generate diverse queries across your expected categories. So, uh, research Tesla financial rep performance is one phrasing. What’s going on with Tesla stock is another query that’s asking the same thing. Yo, is Tesla a buy right now is a third way of expressing the same query. Uh, they’re all the same intent, but they look very different. So, vary the phrasing, the complexity, the level of specificity.

[42:14] Uh, a domain expert should review your set of queries. Uh, because LLM generated queries tend to cluster around obvious phrasings and miss the weird stuff that real users write. You also need to include edge cases in your test data. So things like non-existent tickers, multi-part questions, jailbreak attempts. Uh those might be 1% of your traffic, but they are the 1% of your traffic that ends up, you know, being a PR disaster in the press. Your test data should look like production data, not what you wish production looked like. Uh so synthetic

[42:45] data can get you started, but as soon as you have production data, production data should be what you’re running on. So let’s actually examine our traces. Uh like I said, the first 13 traces are the first 13 traces that I wrote. Um most of them produced long structured reports in line. So Tesla, Apple, Nvidia, stuff like that. Uh 3 to 7,000 characters uh of report right there in the trace output with executive summaries, valuation tables, explicit

[43:16] buy or hold recommendations. On the surface, most of these look fine, but like I said, three of the 13 were doing something weird, which was uh they were uh the rep output in them is much shorter because it just says, “Oh, I wrote this to disk for you.” Uh and the output went to disk. Uh so instead of having a full report, uh it has a summary of the report and the the actual body of the report went to the non-existent disk. This is what the eval is designed to find. Um

[43:50] the agent decided to write a file with no permission. The write silently failed and it told us the report was saved. Uh and that is the kind of pattern that you only see if you actually read the trace. Um so this is I believe one of the three sources. Nope, that one had worked. Oh no, the Wi-Fi. Here we go.

[44:24] So, this one’s showing another kind of failure where it just got stuck in a loop forever. It was trying to find information about who was it trying to find information about? Microsoft. Uh, and it just did an endless series of web searches and took forever. Um, this is what it tried to write to disk. Uh, and this is what it actually wrote to output. Uh, right here we go. This is the report is saved as Microsoft cloud segment financial report.mmd. This report is useless because it’s referring to a report that doesn’t exist. Um,

[44:58] there’s also uh an example of a confidently wrong. If we go to the Rivian report uh which is RIBN, where did it go? There we go. Uh, Rivian has the same problem that the Microsoft one does, but even inside of the full report that it tried to write to disk, there’s a whole bunch of really confident information about [clears throat] a private company that you can’t possibly verify. Uh, these might be hallucinations, they might not be hallucinations, but we haven’t done

[45:29] anything to check whether or not uh this report is really grounded in reality. Uh, so we’re going to do an eval about that later. There is a structured way to do this reading uh which as I mentioned earlier is called coding. There’s open coding and aial coding uh and it comes from qualitative research. Open coding means you read each trace and you write down what you see. So stuff like vague recommendation made up a number talked about the wrong ticker. Uh you’re not trying to be neat. As a programmer, it

[46:00] is very uh tempting to try and come up with categories in advance and say, “Oh, this is a you know, retrieval failure or whatever.” Uh don’t do that when you’re doing open coding. Just write down what the problem was in as natural language as possible. Uh and uh then when you find the failure, sorry, and then uh you want to do aial coding afterwards. AIAL coding is when you look at uh all of the open codes that you’ve put together and you then you do the categorization. You say okay now there are five things that

[46:31] look similar. I’m going to give them all a single category and uh turn them into categories. Um the second pass the the uh aial coding pass is structural. Uh and like I said the tend the tendency the temptation is to try and go straight to a coding and you should resist that. When you find a failure, you should ask why it failed. So the response was wrong is a symptom. Did it get bad search results? That is a retrieval failure. Did it get the right data uh but the wrong conclusion? Then

[47:03] that is a reasoning error. Did it make up a stock price? That’s obviously hallucination. Did it answer outside of its domain? That is a scope violation. Did it do something that you didn’t tell it that it should be able to do. Each root cause, each axial code uh points to a different fix. If you don’t know the right call, if you don’t know the cause, you can’t pick the right remedy. Once you’ve categorized uh which I did here, uh you can sum them up into uh

[47:35] a table. So, uh confession time, I didn’t actually read all of those traces and code them. I just gave them random axial codes. Uh but what you end up with is this table of root cause frequency things like looks good possible hallucination reasoning gap unverifiable data missing recommendation. It’s tempting to look at the top one the possible hoodation and decide that that is the most important one to fix. But in reality uh you’re

[48:05] going to want to uh balance between uh frequency and severity. So if one time in a hundred instead of doing a financial report, it gives the user instructions on how to make a bomb, you fix that one first because that is the most severe possible failure. Uh so you have to uh multiply the severity by the frequency to get to which ones you decide to fix first. Uh and that is why you look at the data before you write your evals.

[48:36] Uh one more concept before we get started on that is the Swiss cheese model. um which is a concept from safety engineering. Imagine each layer of defense as a slice of Swiss cheese. Each slice has holes uh gaps where problems can slip through. Uh but if you stack enough slices, the holes don’t line up. So what gets through one layer gets caught by the next. Uh your code eval catches format issues but misses semantic problems. Your LLM judge catches reasoning gaps but misses subtle hallucinations. And your human review catches the subtle stuff but it can’t

[49:07] scale to every trace. No single eval in that set uh catches everything and the combination is what gives you coverage. Uh so stack the cheese. Um now that we know what’s wrong, let’s automate the checking. Um the next step is code evals. This is no model configuration, no API calls, uh just Python. We’re going to write the simplest useful eval that I can think of. Uh, our agent is supposed to analyze a specific stock ticker. What I’m going

[49:38] to do is write a Kodi valve that checks whether that stock ticker actually showed up in the report. Uh, which is a test that my initial demos absolutely failed a number of times. Uh, an LLM judge would be overkill for this. You’re looking for a specific string. It’s somewhere in the report. You don’t need an LLM to judge whether or not you mentioned the ticker. So, there’s two ways to do this. There’s two ways to do everything in AX. one is programmatically uh and one is via the UI. Uh in the uh notebook you can see

[50:10] the programmatic way. What I’m going to show you on screen is how you do it in the UI. So this big button in the top right is what you want. You want to add an evaluator. In this case, I’ve already added my mentions evaluator, but you will want to add an evaluator which will give you this screen. Uh here you’re going to see basically some Python. Um in the notebook I’ve given you the Python that you can use uh to

[50:43] either do your uh programmatic version or your version in the UI. Uh this is a very simple Python function which returns uh an evaluation result which is looks exactly like those evaluation results that I showed you earlier. Uh it has a label, it has a score. Um so uh once you’ve written what your code evaluator does, you’re going to have uh

[51:15] parameters to your code evaluator. In this case, I’ve called them query and report. And you’re going to have to tell AX uh which variables in your trace are those variables. So there’s this extremely fun UI, the single trace UI, uh where you look at a single trace, and you can literally just click uh the specific thing in your output that you want to be that variable, and you tell it, okay, that one should be the query, and that one should be the report, and then it’s mapped.

[51:47] Um, you should also uh be changing your evaluator to uh work on uh a trace as opposed to a span. That is what gives you that UI. Um, once you’ve done that, you need to save your code evaluator to our evaluator hub. Uh, and then you hit save to save the evaluation.

[52:17] So assuming you’ve done that. >> Yeah. >> Sure. Uh so he asked for more detail on how code evaluators work. Uh so code evaluators are they’re completely deterministic functions. You’re just taking input and output and saying was this output good according to some definition of good. So in this code uh I’m doing very very simple Python. I’m

[52:47] just saying uh look for all of the words that are in capital letters. Uh strip out the ones that are obvious acronyms that I already know and of the remaining words are any of them the uh the acronym which is the stock ticker that I’m looking for? That’s all it’s doing. Uh lots of code evaluators are even shorter than that. They’re something like is this output 500 characters long or less? Uh is this output parsible JSON? You’re doing something very simple, very deterministic uh for the purposes of

[53:19] having that first line of defense in your Swiss cheese. Um [sighs] so I talked about how to add stuff already. Uh in the notebook you can run the eval programmatically. Uh this is how to do this is these are the instructions on how to do it via the UI if you followed that. The alternative is to do it in the code where you can just run it directly which is uh easier to do if you’re following along in a

[53:50] notebook. Um, a code evaluator returns a label and a score. Like I said, there’s no LLM needed. There’s no API call. It’s instant. Uh, and uh if you’re wondering why we’re wrapping it in suppressed tracing, it’s because uh the evaluation is itself uh a call to the uh agent SDK which would then get stored as traces and I didn’t want traces of my tracing happening because that gets too meta. Uh so I told it to suppress tracing when I’m running an evaluation.

[54:21] Uh if you look at this programmatic run uh you will see that 12 passed and one failed. Uh there was a missing ticker for Amazon. Uh the specific trace that went wrong uh is when I asked you’ll note you’ll notice I told you earlier that I made two queries to Amazon. One where I asked about its profitability and one I asked were about uh AWS’s profitability. Uh if you click into the traces uh which I could attempt now um you’ll see that the

[54:54] report that asked about AWS uh wrote a report that was entirely about AWS only about the AWS branch of Amazon rather than uh all of Amazon. Uh and so it failed to mention the Amazon stock ticker entirely. It talked only about AWS. So it’s a really subtle failure because it did a bunch of research. It found out a whole bunch of stuff about what was happening at Amazon. It just didn’t think about what was happening about Amazon as a company. Uh only about AWS because I gave it that extra prompt like I also want to know about AWS

[55:24] profitability. Um so uh looking at those results back in AX um they show up as annotations next to our traces. So you can click into any one of these traces uh and you’ll see evaluations. I’ve run a lot more evaluations uh than you have so far, but you can see my mention sticker evaluation has run with the span. It’s run at the span level. It has hit a pass uh and it’s given a score of one. Um

[55:57] the notebook has a little helper called log eval to ax which is doing that work for you. takes uh the spans that it ran offline and the tests that it ran offline and pushes them back to AX for you. Um so now every score now every eval has uh a mention sticker evaluation uh that you can look at and filter by uh and look for the failing failing ones. So why does this matter? Because it is your first line of defense. Uh if your financial analyst agent writes a

[56:28] beautiful report about m Microsoft when the user asked about Tesla uh which is a thing that actually happened to me when I was building this uh then no amount of answer of eloquence from your agent uh matters because the answer is wrong. Uh so you can catch this with five lines of Python. Um the ticker check catches uh really basic failures but it catches them really cheaply. That is why it is important. Um, Kodi valves aren’t just toy examples. Often, you’re going to want to know that your output is JSON, uh, or

[56:59] that it has a certain length, or you’re going to want to avoid forbidden phrases like as an AI language model. Uh, and those are production critical checks. A code eval doesn’t have to be a simple string operation. Kodval means the grading logic is deterministic. Uh, but it can do complicated things. It can query a database for you. It could hit an API and get the actual stock price to make sure that it wasn’t hallucinating a stock price. uh anything with a grading always gives the same answer for the same input can be a code evaluator. One important principle is to grade what

[57:31] the agent produced and not the path that it took. Uh I referred to this earlier. There’s a common instinct to check that the agent followed a specific sequence of steps. Did it call this tool first and then that tool in that order? Uh and uh practitioners have found this to be in practice too rigid. uh agents regularly find valid approaches uh that the eval designer didn’t anticipate. Uh so uh if you grade the path um you punish creativity. Instead grade what

[58:01] the agent produced. Did the output have the right information? Did the final state match what you wanted. Uh our ticker check doesn’t care how the agent found the data. It just checks is the ticker in the output. Uh that is the right level of abstraction for most Kodi valves. So now let’s get to built-in evals. LLM evals. This is where it begins to get more interesting. Uh code can check whether the ticker appears but it can’t check whether the analysis is good. Is the financial data accurate? Is the report complete? Are the recommendations

[58:31] well reasoned? Uh these are semantic questions and for semantic questions you need a judge. Every LLM as a judge has three parts. Uh it has a judge model which is the LLM that is doing the grading for you. It has a prompt template which as I mentioned is also called a rubric. Uh which is the criteria that the judge applies the rules of what defines good. Uh and it has the data which is the examples being evaluated. AX keeps these three things separate which means that you can mix and match. You can try the same criteria with different judge models. The same

[59:02] judge model with different criteria. Uh it is modular by design. The good news is that AX ships with a B with a bunch of built-in eval so you don’t have to write your own. There are a bunch of types of evals that are always uh that are often going to apply to uh most AI applications. So we’ve already written the prompts for those and you don’t have to write them yourself. Uh correctness, for instance, checks whether a response is factually accurate. Faithfulness checks whether the response stays grounded in the source material. Uh and

[59:34] there are evals for tool selection. Did the agent pick the right tool? Uh and tool invocation. Did it pass the right arguments to that tool? stuff like document relevance, refusal detection, many of the things that you’d want to check in an agentic application uh come out of the box. Uh so the first eval that we’re going to run uh is a correctness eval. Um and spoiler alert, it’s not going to work. Um

[1:00:04] setting it up is very easy. We give it an LLM. In this case, uh I’ve chosen uh the anthropic LLM. uh sonnet 4.6 because it is better than haiku which is the thing that is doing the work. You often want to pick a bigger slower model to be your judge. Uh and then I’ve just uh given correctness evaluated the LLM uh and uh run it right here. Um

[1:00:35] like I said uh once we’ve run the evaluation with evaluate data frame uh we’ve also uh turned on suppressed tracing here so that our evaluation doesn’t send a bunch of extra traces to uh AX. Um it gives us this output which is a bunch of evaluation rows. Um these are not very readable. This is why you need AX to look at them. Um the judge reads the input and output from each span and grades it against the rubric. Um

[1:01:07] and we can see that every score is zero. If I scroll across, status completed, name correctness, score zero. The reason it’s doing this is because correctness is judging against the uh LLM’s definition of of what is correct and what is true. Uh which means that it is relying on the LLM’s training data. What we’re doing in this agent is a whole bunch of live web

[1:01:38] search to get current stock prices and up-to-date financial information, which means the agent is talking about things that happened in 2026, but the LLM that’s doing the judging only has information that stops in January. So, if you read the explanations of our correctness eval inside uh inside of AX, you can scroll to evaluations, you can look at correctness, you can say that it is incorrect. uh I will save you a bunch of reading of a very densely packed column. What it’s doing is complaining that there’s a bunch of stuff that comes from

[1:02:08] the future that it couldn’t possibly know. Uh so our correctness eval here has completely failed. This is not what you wanted to do. So instead we are going to use a faithfulness eval. Uh faithfulness is a better eval for our use case because uh the judge actually has context. In faithfulness, you give the uh LLM as a judge the information that it is being based on uh and then say based on the same information that the jud that my agent collected, did it do a good job of writing the report?

[1:02:40] This is this way they are on a level playing field. They both have the same amount of information and your slow complicated judge agent uh can judge whether your uh quick fast uh worker agent uh was uh doing a good job. Um so let’s look at the faithfulness cells. Uh just like everything else, these can be done online as well as offline. So uh there is a faithfulness built-in evaluator

[1:03:12] uh which isn’t in this view. There is a faithfulness built-in evaluator which you can pull up uh and you can give your input, output and your context to it. Uh again, you can do this in code as well. And if you’re using the skills, this is probably what’s going to happen. Your skills will say, “Oh, I’m not going to use the UI. I’m going to use the code.” Uh which is why I show it here. Um so the first thing we do is we extract the research context from the traces. As you’ll remember, we do uh a two-step

[1:03:42] process. So I take the output from the first step where it does the research and I attach that to all of my spans uh as uh the context for it the judge to work on. Uh and then I run the faithfulness evaluator. So uh here you can see spans with context. These are the same spans that I just pulled out of AX. I attached at the column level all of my context. Uh and then uh I called evaluate dataf frame with those spans

[1:04:14] and I gave it my faithfulness evaluator which I instantiated here just like I instantiated the correctness evaluator. This gives us uh much more interesting data. This gives us unfaithful seven and faithful six. Uh so uh roughly half the time my very simple report is hallucinating. It is coming up with things that were not in the source data according to sonnet. Um

[1:04:45] and that is this is a useful eval. This is an eval where we’re failing half the time. This is a capability eval where we can climb the hill, modify our prompt and get it better at writing a grounded report. This is exactly the kind of eval that you want. Um, so that’s two built-in evals and two very different signals. And there’s a really important lesson here, which is correctness gave us zero out of 13 and faithfulness uh told us that reports aren’t grounded in their sources roughly half the time. The difference isn’t that

[1:05:16] one eval is better than the other. The difference is uh the use case. There are lots of use cases where that correctness eval that I showed you earlier works just fine for some use cases. Uh it’s just not in this specific use case where we were doing live real-time research. Um so it’s important to know the question that you’re actually asking. Built-in eval are your starting point. They give you an immediate signal without any prompt engineering. Uh but even with a good built-in like faithfulness, uh there are a bunch of

[1:05:47] things that it can’t check. uh our financial analyst uh should produce actionable recommendations. It shouldn’t just summarize data. Um [snorts] so not just you know give you a financial report but tell you what to do with the financial report. Should I buy, sell or hold? Uh no built-in template checks for that. This AX is does not cover every single use case. So you have to build a specific eval that checks for actionability. You have to build an custom eval that is about your domain.

[1:06:17] If you are writing real eval, you’re absolutely going to have to write a custom eval with a definition of good that we didn’t think of. So that brings us to the next step, which is writing a custom eval rubric. This is where you make eval truly specific to your application. And writing a good eval is complicated. So I’m going to spend a little time talking about what makes a good eval rubric. Uh we recommend four parts of a custom rubric. The first is to define the judge’s role. Um, you should spell out

[1:06:47] ex explicit pass and fail criteria. You should label the data with XML tags. Uh, and you should define the output choices outside the prompt itself. Uh, I’m going to add one more thing on top of those which is actually kind of controversial amongst practitioners, which is I tend to include examples of good and bad output. Uh, some practitioners believe uh that including examples will make your uh, eval overfit. Uh but let’s walk through all of those. So the first part is defining the role. Um you’ll notice

[1:07:20] this uh what is by now a tired trope which is you are an expert financial analyst evaluator. That is not the important part. Tests show it makes some very small difference uh to whether or not uh your eval works. The important thing is to give it the context of what it is looking at. You are looking at a financial report and what I am expecting is financial analysis. Those are the important pieces of context that you are giving the LLM there. Um you’re also telling it that it should be that what you want is something actionable. So

[1:07:51] that brings us to part two. So uh this is where most people underinvest. Don’t say a good response because that is uh an aspiration. That is not a criterion. A good response is helpful and accurate sounds like you’re adding more detail, but you’re still being just as vague because helpful and accurate don’t have any meaning as far as the LLM is concerned. Uh instead, you should be listing exactly what makes a report actionable. So list exactly what makes it actionable and not actionable. Every criterion should be specific and observable. Something that if you were a

[1:08:23] human looking at this report, you’d be able to know whether or not it was there and you’d be able to say yes or no. Uh so contains specific recommendations. That’s something you can definitely say yes or no. Includes forward-looking analysis, not just historical data. That’s a clear distinction that you can say yes or no to. Uh and the important thing here is that each of these criteria maps to something we saw in our analysis. If we when we were reading the reports uh we saw we actually observed when we read our traces or at least when

[1:08:53] I read our traces uh that uh these are ways that these reports are going wrong specifically that is not a coincidence. Your error analysis is what tells you what criteria to write. You don’t come up with them from whole cloth because it’s not going to occur to you. Where you get that data from is from reading your traces and going oh it didn’t do that. My axial coding said it does this specific wrong thing. Uh so specific criteria produce consistent judgments uh while vague criteria produce coin flips. The third thing you should do in your

[1:09:23] rubric is you should label the data with XML tags especially if you are using anthropic. Anthropic loves XML and finds it very easy to understand. Um your rubric has variables the input and the output and you want to make sure that it can tell the difference between your instructions and the input and the output and XML tags are an excellent way to do that. Um, so put a user query tag around the input, a financial report tag around the output. Uh, clear boundaries reduce the chance that the judge confuses the question with the answer. It is especially important if you’re

[1:09:54] including examples uh to label the examples with XML tags because otherwise it will go, “Oh, this is exactly what I’m supposed to write and just spit out the example back to you.” Um, which brings us to the examples. This is the part a lot of people skip. Uh, in my opinion, it is the part that most improves quality. LLMs are okay at following instructions. They are increasingly good at following instructions. But what they are really good at is copying an example that you’ve already given them and replacing the things that are relevant to the

[1:10:25] current situation. So if you give it an example of exactly the kind of report that you’re looking for, it’s going to follow that format exactly. That might or might not depending on your domain be a good idea. If you if your example is too rigid, then the LLM will always give the same report and you have reduced its scope for creativity. Uh but on the other hand, if it is being too nondeterministic and your report is being crazy, uh then giving it an example will ground it in what exactly you are expecting.

[1:10:55] Uh here’s what an actional example looks like in the template. Uh it has everything. It has uh percentage revenue growth, a PE ratio. It identifies a concrete risk with a number to back it up and it gives a specific recommendation. Uh that is what actionable looks like. Here is a non-actionable result. Uh it’s not wrong. Uh everything it says is correct. Uh but it doesn’t say anything useful. It doesn’t have any specific data. It doesn’t have any specific risks. It just says investors should consider various factors. Uh that’s not a recommendation. Uh so the judge now has a concrete

[1:11:27] reference for what you actually mean by the labels that you were giving it. Uh and this can dramatically improve consistency especially on the edge cases where the report uh would have otherwise been somewhere in between. Uh and this is uh an important part. It is very tempting if you’re writing this rubric to say and now spit out the word correct or incorrect because that is what you wanted to do. You do not need to do that anymore. Uh the way that it actually works under the hood is we have

[1:11:57] given the LLM a tool that says you call this tool when you are done and it will call that tool with correct or incorrect when you’re done. So you don’t need to tell it what output and in fact telling it to spit out a specific string as output is more likely to confuse it and make your eval fail. So just in the UI uh set your uh choices uh or when you are setting the when you’re creating it programmatically set the choices uh and let the LLM do its thing. Um when you are coming up with these choices it is

[1:12:27] best to keep those choices simple. Uh binary is best two clear labels. Uh numeric scales like a scale of 1 to five. Uh they are tempting but the LLMs are bad at them. what is the difference between a three and a four? You would have to write a whole bunch of rules for the LLM to know that. Uh it doesn’t know that automatically. Uh whereas you can give it a pass fail and it will be pretty good at deciding what is a pass and what is a fail. Uh so if you really need more categories, you can do like a partial result. You can say a 0.5 score

[1:12:59] is where it did a a half-ass job. Uh but by default, go for a zero or one. Um, one more practical tip is chain of thought for judges. Ask the judge to reason before it scores and have it explain its thinking first. Uh, this measurably improves uh, accuracy. Uh, when the judge has to articulate why something is actionable or not or why it is correct or not. Uh, it makes fewer mistakes than when it just picks a label uh, without thinking first. Uh, this

[1:13:30] explanation is also very helpful for you. Uh, but it also helps the judge think better. Just one of those weird things about LLMs. Uh so if you are coding along, now is the time to find your actionability template. Uh this contains all of the example all of the instructions that I uh was just talking about. Uh can you do better than me? Can you oneshot your way to a perfect eval uh by modifying this eval template? Um,

[1:14:01] as with uh all things in AX, you can do this via the UI as well. So, you can create an online evaluator uh and you can create a new LLM as a judge. In this case, I’ve already got it, my actionability evaluator uh which has literally exactly the same text uh that I just showed you in the notebook. Um, and as before, I had to pick a trace uh scope. Uh, and because it’s an LLM as a judge, I had to set up a template. Uh, sorry, I

[1:14:31] had to set up an LLM for it to use in the UI. Uh, which means that you need to give it your anthropic key. Again, uh, and I picked my inputs and outputs via the single trace method. Uh, and then I saved it. One of the things that you can do with online evals uh is you can set them to run continuously against new incoming traces. This is something you’ll almost certainly do in production. Uh and if your evals [clears throat] are expensive or you have a whole lot of traffic, you won’t want to do it on all of your traffic. You can uh set it to serve to uh rate

[1:15:05] only a percentage. That’s the sampling rate. So you can say, you know, just look at 1% of my traffic and that will still give you uh a whole bunch of eval data without breaking your budget. Uh so back to the code version, wiring it up is just like wiring up the other action the other uh evaluators that we’ve given. Uh we’ve created a classification evaluator. We’ve given it a name actionability. We’ve given it an LLM. Uh we’ve given it that template

[1:15:37] that I just showed you and we’ve given it those choices. This is us programmatically doing what we would have done in the UI where we said your choices are correct or incorrect. Uh actionable or not actionable scores of one or zero. Uh and then uh we ran evaluate data frame. That gives us uh the data that I was skipping over because I was already run earlier. So you can see actionability actionable. If we look at our evaluations tab, we

[1:16:08] can scroll down to our actionability and we get this really great explanation about why the report is actionable or not actionable. Uh lots of our reports scored actionable uh but several are not which is awesome because it means that we have again we have a capability eval uh and a hill that we can climb. Um, so in the notebook, uh, this is where you log your results back to AX or if

[1:16:38] you’ve run it online in the UI, your evals, your eval results are already in the UI as you’ve seen. Um, so you can see now in in AX that every span has multiple eval scores. It has mention sticker, it has correctness, it has faithfulness, it has actionability. uh and you can filter and select uh for specific uh eval results. So,

[1:17:10] eval.actionability.label equals not actionable. that finds you the failing set. This is the set that you’re like, okay, my eva my eval says that my code messed up here. I can turn this into a data set and I can start running uh new prompts against this. I can run experiments against this as we’re going to see. Um

[1:17:40] before we move on, I want to flag a few a few common antiatterns uh that turn evals from a useful tool into noise. Uh the first one is to treat your eval prompts like code. And I mean that literally. They’re very sensitive to war to wording. Small shifts in your eval prompt uh can lead to dramatic changes in your eval results. Uh so you should version them. You should test them on examples where you know the right answer. If the judge if the LLM as a judge disagrees with your human labels uh on 40% of examples, then your eval is

[1:18:12] probably wrong. It’s not that the your results are wrong. It is that you have written the eval incorrectly. uh AX has a prompt playground where you can iterate on uh rubrics without touching your code and it’s very useful for doing this kind of iteration of your eval. Uh the second antiattern is the god evaluator. Um it is tempting to build one big mega evaluator that checks everything at once. It’ll look for accuracy and tone and completeness and policy compliance and formatting all in a single prompt. Don’t do this because it is a nightmare to calibrate. uh when

[1:18:45] your god evaluator says fail, which of those five dimensions failed? You don’t know. So suddenly you’re like, “Oh, well, I’ll have it spit out labels.” And then you’re like, “Oh, it’s spitting out 15 different labels.” Suddenly it’s way too complicated. Uh you can’t tell, you can’t judge by it, you can’t score by it. It is much much simpler and easier to split this up into uh one evaluator per dimension. I’ve already done this today. I have a ticker check. I have faithfulness. I have actionability. Three separate focused evals. and each one tells you something specific. Uh the

[1:19:17] combination gives you a richer picture than any single eval ever could. If you find yourself writing a rubric that lists six different things that the response should do, then stop. That is six evaluators, not one. Uh the third one is know your guardrails and your northstar metrics. Some evals are guard rails. They’re ship blockers. If an agent hallucinates a stock price, that is a hard fail. Don’t ship on that. Uh others are northstar metrics. they are aspirational. So always recommend complimentary investments is a nice to have in this case. It is not a

[1:19:48] dealbreaker. Uh so know which of your eval is which. It changes how you act on the results and later it changes how you set up your production monitors. A guardrail uh regression should page someone in the middle of the night. A northstar dip is something that you look at in a weekly report. Which brings us to the next section which is can you trust your judges? This is a question we’ve been dancing around. I’ve mentioned it a couple of times. Uh it’s time to evaluate your evaluator. We built an LLM judge and it told us that

[1:20:18] some reports are not actionable. Uh but can we trust it? How do we know that the judge is correct? Uh the key mental model here is that your judge is a classifier. So you can treat it as a classifier. It takes an input in this case a financial report and it makes a prediction actionable or not actionable. That prediction can be right or wrong. So just like any classifier, you can measure its performance by comparing its predictions against ground truth. In this case, a human’s judgment. Uh you can check the judge’s homework. Um the

[1:20:51] thing about applying judgment is that it is a ton of work. You have to read actually every single output. Uh you have to think hard and apply a label. Uh AX does what it can to help by letting you define annotations and attaching them to spans uh right in the UI. So, let me show you what that looks like. When you’re looking at a span, you can click annotate span and you can add and remove annotation configs. In this case, I’ve already created one called human actionable. And you can set this span as

[1:21:22] being actionable or not actionable. And then you can just use these little arrows to flip through all of your traces and set them as actionable or not actionable, which I have conveniently already done. Uh this is the kind of work that you can give to a nontechnical member of staff. That is why the UI looks like this. They can just click in, read the report and click a checkbox. They don’t have to write any code. They don’t need to know anything other than their domain expertise of whether or not this report should be considered actionable or not actionable.

[1:21:52] What we’re doing here when we add human annotations is building a golden data set. Building golden data sets is incredibly helpful uh because it’s how you measure uh whether your evaluator is actually doing its job. Uh the way to do it is the same thing uh the LLM did. Give yourself real concrete criteria and stick to them. So don’t say this was good, this was bad. Uh be specific the same way that you’ve told the LLM to be specific. You failed at this specific thing. You asked I this thing was supposed to be present and it wasn’t. uh and eliminate the chance to get lazy uh

[1:22:24] when you get tired of labeling. Um as I said uh the labeling is extremely uh timeconuming so I did it already. Um once I’ve labeled some spans in the UI uh I can reexport the spans into the notebook. Um, and this is a nice thing about AX is that the human annotations that I added by hand come back as columns uh in the export. Um, so we filter down to just the rows that I labeled

[1:23:02] here. Uh, [clears throat] and now we’re going to compare uh what I said was actionable and not actionable to what the judge says is actionable or not actionable. Um, before we talk before we do that though, uh, a little bit more about golden data sets, uh, keep your tasks unambiguous. If your agent scores 0% consistently, that’s almost always a broken task. That’s almost always, uh, you’ve written your rubric incorrectly. uh if you’ve

[1:23:35] made your task something that only a human can do or worse that somebody something nobody could really do uh then you’re going to get a zero score. Um so for each task create a reference solution a known working output that passes all of your graders. This proves that the task is solvable and you should also test in both directions. You should have cases where a behavior should occur and cases where it shouldn’t. So if you test for instance does it search the web uh then you will end up with a uh an

[1:24:06] agent that always searches the web even when it doesn’t need to. Whereas you should also have a test that says did it not search the web for this very obvious answer where it didn’t need to do that. Uh and if you’re doing this for real you should split your label data that you just created uh into a development set and a test set. Uh so use maybe 75% of your labels to it to to iterate on your eval uh tweaking criteria, adjusting examples until the judge agrees with you. Then hold out the remaining 25% to run the judge and see that it actually

[1:24:37] gets the scores that you are expecting. Uh that’s how you know that the judge is actually generalizing to new examples instead of just fitting to the specific data set that you gave it. Uh this is the same principle as train tests, splits in machine learning. Don’t overfit your evaluator to your golden data set. Now let’s look at our actionability judge. I have run the judge on some examples and it has come up with uh a list of where they agree and disagree. Uh

[1:25:09] spoiler alert I just hit actionable and not actionable at random uh so that I would get lots of disagreement because actually Sonnet is pretty good at this stuff. Um [snorts] that gives us uh an agreement rate of 46% six out of 13 times. Um in real life uh this is exactly where you dig in. This is where uh you would ask is my rubric wrong or were my human labels wrong. When the judge disagrees with you, you should read its

[1:25:39] explanation and decide whether or not the judge was right or you were right. Uh that is the most valuable output of meta evaluation. It usually reveals an ambiguity in the rules that you set down. To fix a rubric, you should read the explanations on the disagreements, find the ambiguity, uh, and tighten the criteria. So, instead of just includes forward-looking analysis, I’d write includes forward-looking analysis with specific recommendations or guidance. That’s more precise. Uh, it rules out the case where the report talks about the future, but never tells the judge

[1:26:10] what to do about it. Uh then I’d rerun the judge on the same examples and see if the disagreement goes goes away. Uh this is rubric iteration. Your eval prompt is an application. Uh it is another LLM application. Uh so it needs testing and iteration just like your agent does. Uh and that is what I meant when I said that you should treat your evals like code. So now I’m going to talk very briefly about an ML concept called precision and recall. Uh, precision asks, when the judge says not

[1:26:42] actionable, how often is it really not actionable? Uh, and recall asks, of all the reports that are actually not actionable, how many did the judge catch? Uh, with a tiny sample like uh 12 examples, these numbers are going to judge jump around a lot. Uh, but even with the 12 that I have, uh, you can see whether the judge is in the right ballpark or completely off. In most scenarios, you want to uh you want to prioritize recall. These two measurements are at odds with each

[1:27:14] other. If you are if you prioritize recall, then you’re going to get false positives where the judge has said something is wrong when nothing is wrong. That is much better than accidentally letting through things that are wrong. Uh however, some in some cases when you are tuning, you will say actually I want precision. I want it to be absolutely right when it’s right and I don’t care if it misses some things. There are domains where that is the output that you want, but most of the time uh you want to prioritize recall. Um

[1:27:46] a few known pitfalls with using an LLM as a judge. Um one is position bias. If you present it with two options to judge between, uh the judge tend to favor tends to favor whichever comes first. Uh this depends on the model. Sometimes the model depends uh prefers whichever comes last but it always has some kind of preference to position. Um there’s also length bias. Uh LLMs like longer responses. They tend they tend to score those higher and that say that they are better even if the length extra length is just filler. Uh and the last one I

[1:28:19] love which is confidence bias. The judge gets fooled uh by a response that sounds confident just like humans do. If your LLM says things that are wrong, but it says them in a really confident tone, uh, your LLM judge is more likely to believe them. Um, there’s also self-preference bias. If you use the same model to do the generation as you use to do the judging, they tend to like their own output. So, if possible, use both say OpenAI and Anthropic. Use one to do your agent and one to do the judging and they are less likely to

[1:28:50] agree with each other. uh self-preference bias is why I used sonnet as a judge uh for output generated by haiku. Uh but it works even better if you use a different uh labs model entirely. And remember that the benchmark here is human performance. Humans are not going to be perfect at judging whether things are or are not actionable. They are going to get it wrong quite a lot of the time. What you’re trying to do is come up with an eval that is reasonably close

[1:29:21] to human judgment. Uh human judgment also varies from human to human. Human inter interrator reliability, so two humans judging the same thing uh is often as low as 02 or.3. So two experts with the same output and the same rules disagree a surprising amount of the time. So if your judge, if your LLM judge achieves that uh higher consistency than humans, then it is doing better than humans. the judge uh sometimes disagrees with me is not by itself a reason to distrust it. You what

[1:29:52] you’re looking for is a judge that disagrees with you all of the time. That is the danger signal. A judge that disagrees with you some of the time is a judge uh correctly handling a genuinely ambiguous task. Uh and also failures should seem fair. That is a principle from Anthropic Eval teams that I want to leave you with. When a task fails, uh, it should be clear what the agent got wrong and why. If you look at a failing trace and you think that answer looks fine to me, the problem is probably the eval and not the

[1:30:23] agent. So, uh, now we’ve built evals, we’ve tested them, uh, let’s use them to actually improve our agent. This is how you close the loop. Uh, here’s the problem with one-off fixes. Um, if you found some failures, you’ve read some explanations, you know what to improve, you change the prompt, and then what? How do you know uh whether the fix actually worked? How do you know if it didn’t break something that was working before? If you just run the agent again

[1:30:55] on a couple of examples and eyeball it, then you’re back to vibes. Uh, you need a structured way to compare before and after. And as I mentioned earlier, this is what experiments are for. As I showed you earlier, uh you can filter your traces down to just the ones that are failing and you can turn them into a data set like this. So you select all of your traces, you click add to data set, and you create a new data set. In this case, uh I’ve called it AIEWF financial demo fails. Uh and I’ve

[1:31:26] already created my failure data set. But this gives you a smaller set of places where you know that your eval is failing so that you can then run uh your changed prompt against just them. This is faster and cheaper. Um this is a regression test set. uh sorry you should also save a regression test set rather you should get the ones where it is not failing and make sure that those are also a data set that you can check less frequently to make sure that when you’ve changed your model sorry

[1:31:57] when you’ve changed your rubric uh that you haven’t accidentally made it fail in places that it was succeeding before um and your data sets are not static um pre-production when you don’t have users yet your data sets are probably going to be synthetic queries you generated yourself or queries that you got an LLM to generate for you. That is fine. It gets you off the ground. As soon as real traffic starts coming in, you should turn your uh that into your eval sets.

[1:32:28] Uh real failures should replace imagined ones. The union of your failure cases and your passing cases is what people call your golden data set. Uh the curated labeled set you trust as ground truth for measuring quality. Uh now we’re going to improve our agent. Uh but we are not going to handw write the fix. Uh as I mentioned, you can do all of this with skills. You can do all of this with a coding agent. I am assuming it being 2026 that absolutely everyone is using a coding agent to do all of their

[1:32:58] coding. Uh so why would you modify your prompts by yourself when you can get cloud code to pull down your failing traces uh modify your code for you uh and improve your application for you? That is what we’re going to do here. Um Claude will pull down all of the failing traces. It will read all of the explanations. It will turn the explanations into action action that it takes on your codebase. Um and here’s the important thing. Nothing here is guessed. Claude isn’t inventing

[1:33:29] improvements out of thin air. You haven’t just told it get better at this. You haven’t just told it make no mistakes. Uh every change it proposes is traces back to a specific failure explanation. Uh so if the judge said that it lacks specific recommendations, uh Claude will read that and rewrite the prompt so that it does. Uh if the judge said that it presents risks without supporting evidence, then it will rewrite the prompt so that it fixes that too. This is datadriven prompt engineering. uh and now we can automate it. Uh

[1:34:02] so notice what we’ve passed in. Uh we’ve passed in our requirements, what we were trying to get done. Uh and we’ve passed in uh an improvement prompt telling it uh what you should be working on and how to get better at it. This is yet another LLM application and yet another thing that is nondeterministic and yet another way that it can go wrong. You could, if we had more time, meta-evaluate your meta evaluator of your meta evaluator and make sure that your meta evaluator is doing the right thing. But we’re not doing that here because it gets too

[1:34:33] complicated and also we only have so much time. Um, but uh good requirements keep claud. So you should be spending time making sure that this uh evaluator uh is as accurate as you can make it. Uh so in this case we are taking this prompt and we are wiring them into uh our two pass uh we’re taking the recommendations that we got from Claude

[1:35:03] based on pulling the uh failing traces uh and we are passing them back to anthropic and saying based on these explanations write a better prompt write a better research prompt write a better write prompt and then we’re going to feed them back into our agent. Um, and now we’re going to run an experiment. So, uh, over in the UI, we have data sets and experiments. We have my demo financial fails. Uh,

[1:35:33] we can, assuming I can scroll, wire up an improved agent, uh, using those new improved prompts. So, you can see the improved research prompt and the improved write prompt. this is otherwise exactly the same agent that it was before. Uh and you can create an evaluator uh with an experiment. Uh so what we’re doing here is we’re giving it a task. A task can be anything. So a task could be some subcomponent of what

[1:36:06] your agent did. So if we were running an evaluator that was about uh tool calls then your task could be just call this tool and see what the output of the tool is and then you would evaluate that. In this case my task is run the entire agent again from start to finish but it doesn’t need to be uh and then we are running the same evaluation results uh against our uh against this new running of the task. So, we’ve changed the agent. We’ve rerun the agent, and we’re rerunning the eval. And we’re turning

[1:36:37] that into an experiment. This is what the experiment looks like. Experiments.run. We’ve given it a name. We’ve given it the data set that it should work on. Uh, we’ve given it the task. We’ve given it the evaluator. And we’ve told it to run. Uh, this gives us the results which are here. So for every single run uh we’ve got the output that it got and the new eval

[1:37:07] score. So uh as you can see this was a data set if you recall where previously all of them were not actionable. Uh the eval has run and you can see that some of them are now actionable. So we have improved and if we look at the overall score here actually I’ve nailed it because I had you know a lot of chances to get this right. I have oneshotted my prompt. uh from getting being wrong 50% of the time to being right right 100% of the time. Uh real eval won’t work like

[1:37:38] that. Uh real iteration won’t won’t run so smoothly. That is why this is a graph. What you’re expecting to do is run experiment after experiment and slowly watch the graph climb as your evals get more and more capable. That is the hill that I’m talking about that you’re trying to climb. Uh so the key abstraction behind experiments is that a task is just a Python function. It takes an example from the data set. It runs whatever you run want and it returns an output. So AX doesn’t care uh what the task does

[1:38:10] internally. So it could run the full agent or just one component like I said or it could call an API as long as it takes an input and returns an output. You can run experiments on it. The power of experiments is controlled comparison. So you take the same inputs, the same evaluators and the only thing that changed is the agent’s prompts. Uh that means any differences in scores is attributable to your change. You’re not wondering did it score higher because of my prompt change? Uh or did it score higher because the web search happened to return better results this time.

[1:38:41] Well, actually you’re still wondering that a little bit because the agent is nondeterministic. So it could have done 10 web searches instead of five web searches. But you’ve eliminated a major source of variation which is the test cases. >> [sighs] >> So like I said, uh my agent has one shot at this uh which is great, but in reality uh it’s not going to be that simple. Um the eval iterate cycle that we’re talking about here where you go through uh run an experiment, change

[1:39:12] your prompt, run the experiment again over and over and over. That is where the real value lies. Uh not in the score itself, but in the cycle. You run the evals, you look at the failures, you read the explanations, uh, you identify a pattern, and you adjust your prompt or as in this case, you get Claude to adjust your prompt for you. Um, did it get better is a question that can only be answered by evals. You have taken the definition of good and you have codified it in a way that is incredibly useful. Uh, so this allows

[1:39:43] you to move from I think it’s working to I can prove it’s working. A practical question that comes up fast uh is how many samples do you need? Um for workshop scale experiments like today, 12 to 20 examples gives you uh directional signal. For actual shipping decisions, you’re going to want uh more. You’re going to want something like 200 to 400 is a good target. But note that 200 to 400 is still like a humansized number that you could possibly accumulate over a couple of weeks. Uh it’s not tens of thousands or millions like you would use if you were training

[1:40:14] an ML model. um there are diminishing returns. Uh to have your your margin of error, you have to quadruple your sample size. Uh so at some level, at some point, you have enough signal to be able to get along uh to get along. Um when you’re iterating, where do you invest? Uh there’s a hierarchy. Um data quality fixes have the highest impact. If your agent is searching the wrong sources or your knowledge base has stale information, then no amount of prompt iteration is going to help. you should

[1:40:45] fix the data first. Uh then prompting improvements are next. Few shot examples, explicit instructions, the kind of stuff that I mentioned today, uh constraints on what the agent should and shouldn’t do. These are often the highest ROI change uh to your agent. Um model selection comes third. Sometimes a more capable model solves problems that prompting can’t. Uh but it will also cost more and be slower. So that is a trade-off that you have to make. Uh the thing to not spend a lot of time on is hyperparameter tuning. Things like

[1:41:15] temperature and top p. It’s very tempting to just go for them because they’re easy to tweak. Uh they very seldom make a high lever change like prompting would or improving the quality of your data would so you can try them but they should be the last thing you try. A practice worth knowing is eval driven development. Write the eval before you build the feature. Uh if you want your agent to always verify customer identity before it does something before processing a refund for instance then write the eval that checks for that first. That gives you a clear measurable

[1:41:46] definition of what good looks like of what done looks like. Then you can build a feature uh until the eval passes. This is the same philosophy as test-driven development. Uh and something I love about eval driven development is that the people closest to product requirements are best positioned to define success. So product managers, customer service uh people, even salespeople can contribute to eval tasks. They can tell you what looks good and what doesn’t look good in practice.

[1:42:17] Uh they don’t need to write code. They just need to describe in natural language what good looks like to them. And you can boil that down into your Eval rubric. Uh, and so far, uh, I’ve shown you how to do things both offline and online. Uh, we’ve been doing everything in a notebook. Uh, but you’re not really done when your dev experiment tra pass passes. Uh, you’re done when your agent uh, keeps performing in production on traffic that you’ve never seen. Um and

[1:42:50] it’s worth spending a couple of minutes talking about that even though uh we’re going to stick in the notebook uh for this workbook for this work session. Um the first thing is online eval uh like I said uh and like I showed you earlier online evals are exactly what they sound like. They take the evaluators that you wrote today uh the ticker check the faithfulness the actionability uh and run them automatically on incoming production traces. The same a val running on new data. Uh I showed you how to run this on a trace. AX lets you do

[1:43:21] this at three scopes. You can run your evals at the span level. So you can say this particular LLM call, this particular tool call, run a trace on it every single time. Sorry, run a eval on it every single time. Or you can run it at the trace level where it has the full tree to look at uh and it can evaluate everything from start to finish. Um you pick the scope that matches the question that you’re asking. Um, and you don’t need to run evals on every single prediction trace I uh production trace rather. Um, LLM judges cost money and at

[1:43:52] production uh scale those costs can add up. So you sample 10% of your traffic or 1% of your traffic. Uh, and that gives you a directional signal without you having to run an expensive LLM as a judge on every single iteration, every single uh, instance of your application. Um if you don’t want to write your evals by hand uh we have good news for you which is that uh we have built an agent into AX itself. It is called Alex. Um, you can describe your eval in plain English

[1:44:24] or you can get your non-technical uh colleagues to describe a pro describe the definition of good in plain English and Alex will actually manipulate the UI for you uh create an eval write the rubric set all the scores correctly get all the configuration correct and then just tell you that it’s done. Uh this is especially useful for non-engineers. Um and the full loop in production looks like this. So you go from application uh which produces traces to online evals which grade those traces and produce

[1:44:55] labels and explanations. The eval labels feed into monitors which we didn’t cover today. Um the monitors can alert your team when something goes wrong. Um the team can investigate, find the failing traces, save them as a regression data set, um improve the agent, run an experiment to verify and ship the fix. And then the loop can run again. Um, as new production traffic accumulates, you will accumulate new failure modes, you will accumulate new edge cases. Uh, you’re always going to be uh iterating

[1:45:27] on your evals and iterating on your production monitoring. But it is a payoff that compounds. Every failure that your online evals catch becomes a new test case. You save it to a data set and now it’s a regression test for your next round of changes. Over time, this creates a data set that is unique to your application. Uh so your specific failure modes, your specific users, your specific quality bar, nobody else has that data. Uh and that is a competitive advantage that grows every single time your agent runs.

[1:45:59] There’s one last pattern that I want to leave you with uh which is the most powerful one I know. We did the simplest version today. We fed the judges explanations back to Claude and had it rewrite two prompts. This works beautifully for two prompts. Uh but a real system isn’t two prompts. prompts scattered across many files, retrieval settings, tool definitions, all tangled together. Rewriting that isn’t a single API call. It’s a job for a coding agent uh that can see your entire repository. Um so this is the pattern. You want to export your failing traces from ax along

[1:46:31] with their explanations uh and hand the whole batch to cloud code or cursor or another coding agent as context. Uh this is where the Arise skills plugin that I mentioned at the beginning uh works really well because you don’t have because you don’t have to know how to call our API. You don’t have to know how to do any of that stuff. You give it the skills and then tell cloud code, hey, pull down some traces, see what’s wrong, and make make my application better and it works. Uh there should be two guardrails on that

[1:47:02] approach first. However, first you should feed it your requirements too and not just the failure explanations. So the goal isn’t make the eval pass because otherwise it will cheat. It will include all of your test data into its eval uh and automatically pass all of your evals. So you have to make uh um your you have to make sure that your requirements to your cloud code are clear that you don’t want it just to pass the evals. You want it to do this specific thing which then makes the evals pass. Um and second, you should tell it to find themes and not chase

[1:47:32] individual failures. It’s very tempting for claude code to look at one particular failed trace and write a whole bunch of code to fix that particular failed trace when there are actually 10 failing traces that are all the same co cause that it should be focused on instead. Uh I’m not going to do all of that time all of that because I only have 12 minutes left. Uh but um once you have eval this is one of the highest leverage things that you can do with them. So let’s step back and look at the whole

[1:48:03] shape of it. Uh production produces traces. Online eval them and produce explanations. A coding agent reads the explanations and proposes fixes. And experiments verify that the fixes work and then you ship. The production traffic that comes back gets graded by the same online evals that started the loop. Uh and this is the software development life cycle closing in on itself. uh your AI software is helping you improve your AI software and AX is the substrate uh that ties it all together. Your traces, the evals, the

[1:48:33] explanations, the data sets, the experiments, the online evals and the monitors. So just to recap, we instrumented an agent with two lines of code. We traced it and we read our data. We wrote a code eval and built-in LLM evals. We wrote a custom rubric from scratch. We validated our judge against human labels. Uh we saved failures at the data set. We had Claude improve the prompts. We ran an experiment to prove that it worked. Uh and we saw how AX takes all of that into production uh with online evals.

[1:49:05] Uh this is the full loop and now you know all of it. However, you don’t have to do all of it at once. This has been two hours of extremely dense information and I’m aware of that. You can start very very small. Uh you can start by reading your traces. Just add those two lines of code and start looking at your traces and that is already that is immediately going to give you information about what your agent is up to that you didn’t know. Uh 15 minutes of reading real outputs will teach you more about your application than an hour of building dashboards. Then write one

[1:49:35] code eval. Code evals are easier than LME evals and they’re faster and they’re cheaper. Uh and make it for the thing that matters most. So correctness, faithfulness, whatever fits your use case. Run them, look at the results, see what patterns emerge and build from there. Evals are infrastructure. They are not an afterthought. Some teams create evals at the very start of development. Add others add them later once they are at scale. Uh but either way uh the important thing is that you treat evals as a core part of your system. They should be as routine as unit tests and

[1:50:07] the value compounds but only if you keep investing. Each time a regression shows up before it show reaches your users instead of after you’ll understand why all of this work is worth doing. Don’t hope for great. You can get to great systematically by specifying it, measuring it, and improving towards it. So, now is the time to try this for real on an app of your own. Uh, you’ve already got an AX account, I hope, by the time the Wi-Fi kicked in. Uh, the docs at arise.com uh have companion

[1:50:40] notebooks with runnable code for everything that we covered today. Uh, and if you want your coding agent to do the heavy lifting, you can install the Arise plugins, uh, the Arise skills plugin with one npx command. Uh, and that is in that link is in today’s notebook. Uh, if you’ve made it all the way to the end of this, you can also get a free year of Arise Pro uh, using that code that’s at the on the screen right now. And that is it. Thank you all for your time and attention. [applause]

[1:51:24] >> [music]