Pular para o conteúdo

Melhoria contínua de agentes com Langfuse — Annabell Schäfer e Lotte Verheyden, ClickHouse

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: Continuously Improving Agents with Langfuse — Annabell Schäfer & Lotte Verheyden, ClickHouse · Canal: AI Engineer · 43:51 · Assistir no YouTube

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

O workshop apresenta o ciclo de AI engineering para melhorar agentes continuamente, com foco em tracing e monitoramento em produção. Usando um agente de suporte de TI como exemplo, as apresentadoras configuram evaluators para detectar discordância do usuário, frustração e solicitações fora do escopo. Em seguida, mostram como usar um coding agent para analisar traces e encontrar problemas que os monitores configurados não detectaram. Por fim, explicam como transformar sinais da produção em critérios de avaliação e conjuntos de dados para testar mudanças offline e fazer deploy com mais confiança.

  • Agentes não são determinísticos: o sistema pode parecer saudável enquanto suas respostas ou ações estão erradas.
  • O ciclo de AI engineering combina atividades online — tracing e monitoramento — com atividades offline — conjuntos de dados, experimentos e avaliações.
  • Traces bem instrumentados são essenciais para que o monitoramento e as decisões posteriores sejam confiáveis.
  • O monitoramento combina métricas agregadas, feedback dos usuários, evaluators automáticos e revisão humana.
  • Os evaluators devem refletir os modos de falha específicos da aplicação, em vez de serem copiados sem adaptação.
  • O exemplo configura detecção de discordância do usuário, mensagens em letras maiúsculas e solicitações fora do escopo.
  • Um coding agent pode analisar traces em escala e apontar problemas não cobertos pelos evaluators existentes.
  • Sinais e exemplos da produção devem atualizar os critérios de avaliação e os conjuntos de dados usados nos testes offline.
  • Executar experimentos e avaliar mudanças antes do deploy ajuda a detectar regressões e a fazer deploy com mais confiança.
Início Capítulo Resumo
00:13 O ciclo de AI engineering As apresentadoras explicam por que agentes não determinísticos exigem práticas específicas para detectar erros e melhorar seu comportamento.
02:25 Tracing e monitoramento O workshop apresenta as etapas online e offline do ciclo e destaca a importância de traces bem instrumentados.
07:43 O agente de suporte e a preparação do ambiente O exemplo Specs e as instruções para clonar o repo, configurar as chaves e iniciar a aplicação são apresentados.
13:04 Primeira interação e inspeção de traces A demonstração mostra o agente respondendo a uma pergunta e as observações registradas no trace.
15:12 Evaluator de discordância do usuário As apresentadoras configuram um evaluator com LLM para identificar quando o usuário discorda da resposta do agente.
21:13 Detectar frustração e solicitações fora do escopo O workshop adiciona uma verificação por código para mensagens em letras maiúsculas e um evaluator para solicitações fora do escopo.
30:35 Dados de produção e análise com um coding agent Traces de exemplo são carregados e um coding agent é usado para encontrar problemas em escala.
37:13 Problemas encontrados e possíveis correções A análise aponta falhas na recuperação de informações, impactos em latência e custo e lacunas na cobertura de avaliações.
39:34 Manter evaluators e conjuntos de dados As apresentadoras explicam como sinais da produção devem atualizar critérios de avaliação e exemplos de teste offline.
41:43 Fechando o ciclo e próximos passos O workshop resume a necessidade de repetir o ciclo de observação, avaliação e experimentação e indica outros módulos disponíveis.

Agentes de IA não são determinísticos. — 01:19

Tudo começa com o seu trace. — 05:05

É sobre pensar nos modos de falha típicos da nossa aplicação. — 31:07

Assim, você também pode iterar e fazer deploy com confiança. — 41:11

  • AI engineering loop (conceito): Ciclo de práticas online e offline usado para observar, avaliar e melhorar aplicações com IA.
  • tracing (conceito): Instrumentação que registra as etapas, chamadas e dados envolvidos na execução de um agente.
  • monitoring (conceito): Acompanhamento de traces com métricas, feedback e avaliações para identificar problemas em produção.
  • evaluator (conceito): Verificação automática ou baseada em código que avalia aspectos específicos das interações do agente.
  • Langfuse (ferramenta): Plataforma open source e independente de modelo e framework apresentada para executar práticas de AI engineering.
  • specs (conceito): Agente de suporte de TI usado no workshop para responder a perguntas sobre dispositivos e aplicativos.
  • OpenAI (empresa): Empresa cuja API é usada no exemplo para gerar respostas e conectar um modelo ao evaluator.
  • Codex (ferramenta): Coding agent usado para analisar traces de produção e procurar problemas na aplicação.
  • Annabell Schäfer (pessoa): Apresentadora do workshop que conduz a demonstração prática.
  • Lotte Verheyden (pessoa): Apresentadora do workshop sobre melhoria contínua de agentes com Langfuse.

00:13 Olá, pessoal. Bem-vindos ao workshop sobre como melhorar continuamente agents com Langfuse. Vocês já podem acessar langfuse.com/workshop. Lá há etapas que vamos abordar hoje e, assim, vocês também poderão revisá-las em casa mais tarde, quando quiserem, por conta própria. Há também algumas etapas extras que não vamos abordar hoje, mas que vocês poderão encontrar lá. Vamos mostrar este QR code novamente mais adiante na apresentação. Então, melhorar continuamente agents: o que isso significa? Vamos falar um…

00:46 …bastante sobre diferentes processos que as equipes usam para melhorar seus agents ou detectar mudanças e aprimorá-los de diferentes maneiras. Vocês podem combinar esses processos em um ciclo contínuo e, como sabemos, em San Francisco gostamos muito de ciclos. Esse processo, ou esse conjunto de processos, também é chamado com frequência de engenharia de IA. Então, o que é engenharia de IA, por que precisamos dela e em que ela difere da…

01:19 …engenharia tradicional? A principal diferença é que agents de IA não são determinísticos. O sistema, ou o estado do sistema, pode parecer saudável, enquanto as respostas ou ações do agent estão erradas. Às vezes, estão realmente erradas. Às vezes, também não têm qualidade suficiente. E é isso que a engenharia de IA resolve. Para quem não está…

01:50 …familiarizado, a Langfuse oferece uma plataforma para executar esses processos. Somos open source, independentes de modelo e de framework, então vocês podem nos usar com a configuração que já tiverem. Algumas grandes empresas já nos usam no dia a dia, mas também temos uma grande comunidade de usuários individuais e menores, que nos ajudam muito porque trabalham com muitas configurações e projetos de agents diferentes. E essa é, sem dúvida, uma das maneiras pelas quais acompanhamos os rumos deste campo, que muda muito rapidamente…

02:25 …está tomando. A propósito, este workshop será conduzido hoje por Annabelle e por mim, e Mark, nosso fundador, também está em algum lugar da sala. Ah, está ali. Também vamos circular para ajudar vocês durante o workshop, se precisarem de alguma coisa. Então, engenharia de IA: gostamos de mostrar ou visualizar neste gráfico o conjunto de processos que as pessoas usam. É o que chamamos de ciclo de engenharia de IA. A configuração exata depende um pouco também da configuração…

02:58 …das empresas. Depende de necessidades diferentes, mas, em linhas gerais, vocês podem categorizá-las nestas cinco etapas. O principal a lembrar aqui é que temos duas grandes partes: uma parte online, com tracing e monitoramento, e uma parte offline, com criação de conjuntos de dados, experimentação e avaliação fora de produção. Hoje, vamos nos concentrar principalmente na parte online: tracing e monitoramento. Então, tracing: vocês instrumentam…

03:28 …a aplicação, fazem o deploy dela em produção e veem traces chegando, mostrando o que o agent está fazendo e como está interagindo com os usuários. Com base nisso, vocês monitoram esses traces. O monitoramento é feito, por um lado, automaticamente, com avaliadores e dashboards, mas a parte de feedback humano também não pode ser subestimada. Vocês também vão coletar feedback implícito ou explícito dos usuários e analisar manualmente algumas amostras desses traces. Tudo isso junto… Não sei se vocês conseguem…

04:03 …ver. Ah, a caixa amarela está bem visível. Ótimo. Essa parte online do ciclo de engenharia de IA já é bastante coisa. Muitas equipes que não atuam em setores de alto risco podem começar apenas com essas duas etapas e, com base no que encontram durante o monitoramento dos traces, já fazer correções ou melhorias simples nos agents, fazer o deploy em produção e observar os traces que chegam. Esse é um ótimo primeiro passo e já vai levar vocês bem longe. É uma ótima maneira de iterar rapidamente nos agents…

04:35 …da empresa. Quando o produto ou a configuração amadurecer um pouco, ou se vocês estiverem em um ambiente de alto risco, em que qualquer erro tem consequências graves, faz sentido trabalhar também na parte offline. Ela serve para testes estruturados. Os conjuntos de dados são seus casos de teste estruturados. Eles serão bastante inspirados pelo que vocês observarem durante o monitoramento. Quando quiserem fazer uma mudança, executem um experimento com seus conjuntos de dados. Avaliem os resultados dos experimentos. E só façam o deploy em produção quando os resultados forem melhores e vocês não tiverem introduzido…

05:05 …nenhuma regressão. Antes de começar o workshop, queremos nos concentrar rapidamente nas duas partes do ciclo online: tracing e monitoramento, porque são muito importantes. Tudo começa com o trace. Se o trace não for bom, vocês não vão detectar tudo durante a etapa de monitoramento. Se não detectarem tudo durante o monitoramento, seus conjuntos de dados não serão tão bons quanto poderiam ser. Vocês não vão tomar as decisões mais bem fundamentadas sobre o que…

05:35 …avaliar etc. Por isso, é muito importante dedicar tempo suficiente para garantir que os traces estejam bem configurados. Então, como se cria um trace? Um trace é composto por observações, que são as diferentes etapas que um agent executa ao criar uma resposta para o usuário. Elas incluem chamadas de LLM, chamadas de ferramentas ou outras coisas. Também podem ser aninhadas. Cada observação ainda contém muitos dados associados, que dependem do…

06:05 …tipo de observação. Em uma chamada de LLM, geralmente são a duração, o custo em tokens, o uso de tokens, o modelo usado, a versão do prompt usada e tudo o que vocês puderem imaginar que ajude a avaliar a qualidade da chamada de LLM. Para chamadas de ferramentas, os dados podem ser completamente diferentes. Por exemplo, se vocês fizerem uma busca na web, um dos dados pode ser a consulta usada nessa busca. Isso é muito importante para que depois vocês possam fazer o monitoramento. Bem, o monitoramento tem algumas funções diferentes…

06:39 …Uma delas é acompanhar métricas agregadas para observar a tendência geral ao longo do tempo. Como está a saúde do sistema? Isso inclui aspectos como o custo do sistema, por exemplo, mas também a qualidade. Se vocês configurarem avaliadores para medir a qualidade das respostas, precisam garantir que ela não diminua com o tempo. Uma segunda função muito importante é detectar sinais por meio do feedback dos usuários. À medida que a aplicação cresce, vocês terão muitos traces, e será impossível ver ou analisar tudo. O feedback dos usuários…

07:12 …é uma ótima maneira de destacar aqueles que realmente são importantes de analisar. A terceira função é o feedback e os evals. Vocês vão configurar avaliadores automáticos e também fazer algumas anotações humanas para garantir que detectem coisas novas. Um ponto importante: por um lado, os avaliadores automáticos são muito escaláveis. Vocês podem continuar usando-os em todos os traces. Por outro lado, é menos provável que detectem casos muito novos ou sutis…

07:43 …nos quais vocês mesmos ainda não tinham pensado. O feedback dos usuários e as anotações humanas talvez não sejam tão escaláveis, mas é por meio deles que vocês vão detectar coisas nas quais ainda não tinham pensado. É nisso que vamos nos concentrar hoje. Minha colega Annabelle vai apresentar um exemplo prático, e Mark e eu vamos circular pela sala. Se precisarem de ajuda, é só levantar a mão. Então, como L já mencionou, o foco de hoje é aprender a trabalhar de forma eficaz com um trace da aplicação e também decidir o que vocês…

08:15 …realmente querem monitorar. Ou seja, o que é importante na aplicação de vocês, e não em termos gerais. E também como aproveitar coding agents para multiplicar um pouco sua produtividade por dez, mas talvez também entender em que momentos vocês devem participar do processo, em vez de deixar o coding agent fazer tudo por conta própria. Então, vamos começar. Para isso, primeiro queremos apresentar nossa aplicação de exemplo de hoje. Trouxemos para vocês o Specs, o agent de suporte de TI do meu pai. Esse mini repo surgiu de um miniprojeto que fiz para o meu pai, porque ele sempre me faz perguntas…

08:48 pelo WhatsApp, sobre como configurar o celular dele e também como configurar todo tipo de coisa na impressora ou no computador. Então, criei esse pequeno agent que responde a ele, na versão de produção, pelo WhatsApp. Neste caso, agora temos uma interface bem legal. Dá para imaginar o funcionamento assim: temos um usuário, meu pai ou qualquer outro pai, e ele faz uma pergunta ao Specs, que tem algumas ferramentas disponíveis. Podemos obter o contexto de suporte, ou seja, algumas informações sobre que tipo de celular meu pai usa e qual sistema operacional

09:18 ele tem. Que aplicativos ele tem? Também temos uma biblioteca de ajuda com pesquisa. Ela contém algumas perguntas frequentes e contexto sobre como resolver determinados problemas. E, sim, o agent pode usar essas ferramentas. Também usamos a API da OpenAI para gerar respostas e enviar uma resposta ao nosso pai, neste caso. Então, primeiro vamos analisar alguns traces juntos, mas também pensar no que é interessante saber para garantir que meu pai receba o suporte que realmente quer. Então, sim, você pode escanear o código QR

09:52 aqui. Você encontrará o repositório do workshop, e vou fazer a configuração junto com vocês. Não se preocupem, vamos passar por tudo passo a passo. Também há documentação para consultar caso vocês se percam, ou se quiserem explorar mais depois. Também haverá outros módulos disponíveis. Então, vamos acessar langfuse.com/workshop. Como podem ver, esta é uma página em Markdown. Mas, se clicarem aqui em langfuse/langfuse-workshop, chegaremos ao repositório do Git

10:25 e aqui vocês podem clonar o repo no IDE. Eu já fiz isso, então está tudo preparado. Como podem ver, a primeira coisa que precisamos configurar são algumas variáveis de ambiente. Para isso, vamos criar uma conta juntos em Langfuse.com. Podemos clicar em Launch App. Eu já tenho uma organização, mas vocês podem clicar em Launch App ou, se estiverem nesta página, selecionar uma região. Não

10:58 importa qual vocês escolherem. Depois, criem uma conta. Assim que entrarem, verão esta página. Um projeto será criado automaticamente para vocês, e vocês chegarão a esta página. Lá, podem obter suas chaves de API clicando em Create New API Keys. Vou dar um segundo para vocês acessarem nosso site e configurarem isso. Essa será a primeira coisa que precisamos fazer juntos.

11:30 Também vou mostrar aqui as etapas que vocês encontrarão no site do workshop: fazer o cadastro rapidamente e criar uma conta nova. E, para quem já fez isso, trouxemos uma chave da OpenAI para usar hoje. Vocês podem escaneá-la. É claro que vamos trocá-la depois. Mas, por hoje, esta é a chave de API que vocês vão usar. Podem adicioná-la

12:00 ao arquivo .env e aí começamos. Isso. Basta copiar o arquivo .env.example e seguir em frente. Certo. Depois de clonar o repo, a primeira coisa que precisamos fazer é

12:32 instalar rapidamente as dependências. Estamos executando aqui uma aplicação em TypeScript que usa o SDK de agent da OpenAI. Assim, podemos instalar rapidamente todas as dependências. Depois, também podemos iniciá-la executando npm run dev. Vou abrir isso aqui. Está abrindo diretamente. Também vou abrir aqui, e podemos ver nossa aplicação de exemplo.

13:04 A propósito, se eu estiver indo rápido demais, as etapas da configuração estão nesta página: lenfuse.com/workshop. Vocês também podem seguir por lá, passo a passo, ajustando o arquivo .env e executando a aplicação. Vamos ver o que temos aqui. Temos nosso agent de suporte ao pai, que já nos cumprimenta e pergunta se temos alguma dúvida. Também temos algumas perguntas de exemplo que meu pai poderia fazer. Podemos perguntar: “Como ativo o Bluetooth no meu iPhone?”. O Specs leva um segundo e usa nos bastidores as ferramentas de que

13:38 precisamos para chegar à resposta. Então, neste caso, ele responde ao nosso pai com instruções passo a passo sobre como ativar o Bluetooth no dispositivo. E o que aconteceu nos bastidores? Essa é a parte interessante que queremos analisar. Se voltarmos à seção de tracing — e isso também deve acontecer com vocês quando executarem a aplicação e fizerem uma pergunta — veremos o primeiro trace aparecer. Cada linha aqui é uma observação. Também podemos ver que elas têm

14:10 ícones um pouco diferentes, que indicam que são coisas distintas. Se clicarmos em um deles, veremos que tudo está ligado à observação do nosso agent e, abaixo, temos algumas gerações, além de tool calls que buscam determinados contextos. Então, esta aplicação já está totalmente instrumentada, e também há um guia passo a passo sobre como configurá-la. Mas também temos uma skill extensa que vocês podem usar para configurá-la automaticamente. Hoje, queremos nos concentrar em trabalhar com esses traces, em vez de

14:42 configurá-los passo a passo. Então, aqui está nosso trace. Se voltarmos à página lenfuse.com/workshop, podemos acessar o módulo do workshop de monitoramento, que é o que queremos explorar juntos hoje, como a Lotte já mencionou. No contexto do nosso aplicativo de suporte ao pai, o que significa monitoramento? Quando meu pai interage com a aplicação, é claro que não vemos o que ele faz, porque não estamos sentados ao lado dele. Esse é justamente o propósito do agent. Mas

15:12 queremos acompanhar o que está acontecendo, e não apenas registrar o que o agent está fazendo: queremos entender o que isso significa. Pensamos no que pode dar errado em um aplicativo de suporte. A primeira possibilidade é meu pai discordar da aplicação. Por exemplo, se eu perguntar: “Como configuro o Bluetooth?”, posso estar pensando: “Certo, como isso funciona de fato? Onde fica o botão?”. E meu pai pode perguntar isso. Talvez queiramos detectar esse caso, porque algo não ficou claro ou detalhado o suficiente para que a

15:44 pergunta fosse respondida corretamente. Então, vamos configurar isso juntos. Vamos começar copiando este comando do Git: git checkout checkpoint-for-monitoring. Depois, podemos voltar ao IDE e executar o comando. Agora estamos trocando para a etapa de monitoramento do workshop. É um checkpoint. Agora queremos integrar esses avaliadores à nossa

16:17 aplicação. Se descermos um pouco, veremos que a primeira coisa que precisamos fazer juntos é configurar o modelo de avaliador do Langfuse. Vou abrir nossa aplicação aqui, fechar a parte de tracing e acessar a aba de avaliadores. Aqui, posso começar a configurar meus avaliadores, e há duas possibilidades diferentes. Posso configurar avaliadores baseados em código para verificações mais determinísticas da minha aplicação, e também posso configurar

16:48 com alguns LLM as a judge em neerlandês, que são mais voltados para as coisas implícitas que talvez você queira extrair do histórico da conversa e descobrir de fato. E também podemos ver que temos alguns templates aqui, e que o de discordância do usuário é um template que estamos oferecendo. Então, se clicarmos aqui, veremos que precisamos configurar a conexão com o LLM. Vou mudar para cá e parar de compartilhar rapidinho, porque a chave de API não deveria aparecer.

17:24 O laptop morreu. Então, no fim das contas, essa é uma possibilidade de usar um determinado modelo para avaliar o que está acontecendo. Só um segundo. Certo. O que fiz agora foi configurar uma nova conexão com o LLM e, nesta…

17:56 …situação, estou usando novamente a chave de API da OpenAI. Voltar. Isso. Então, conectei a chave de API da OpenAI que configuramos juntos. E, em vez disso, você também pode conectar todos os tipos de outros modelos, é claro, e também pode usar seu próprio proxy, caso tenha configurado um gateway. Agora vamos voltar à página de evaluators. Vamos clicar em criar evaluator. E agora selecionar novamente nosso template…

18:26 …e selecionar o modelo. O que podemos ver aqui é que a primeira coisa que podemos fazer juntos é filtrar as observações específicas que queremos selecionar. Neste caso, não queremos escolher a geração, mas o agent que é a raiz de todo o trace que temos aqui. Você também pode ver que há outras opções. Também é possível selecionar tool calls ou gerações. Mas, no nosso caso específico, queremos olhar apenas para a entrada. Queremos ver a mensagem do usuário sendo…

18:59 …analisada. Olhando novamente para nossas instruções, temos uma maneira específica de selecionar essas diferentes partes da observação. Vamos escolher o agent, temos nosso prompt do evaluator aqui e, mais abaixo, podemos ver que, usando chaves, estamos inserindo contexto. Para selecionar a parte do trace que é relevante para nós, queremos configurar este JSON path…

19:30 …e garantir que estamos selecionando a parte correta neste caso. Para o histórico da conversa, queremos selecionar todo o array de mensagens. Então, vamos copiar isto e colocar aqui. Mais abaixo, podemos ver que isso está mapeando o histórico de mensagens do seu trace. Assim, reúne qual foi a interação, o que foi perguntado, o que as tools fizeram e também que tipo de resposta foi gerada. E, como segunda parte da detecção de discordância do usuário, é claro que também precisamos selecionar a última mensagem que vem…

20:06 …do usuário. Assim, também obtemos essas informações aqui, e podemos ver mais abaixo que a pergunta “como ligo o Bluetooth no meu celular” está sendo mapeada para este evaluator. Se executarmos isso agora, teremos nosso primeiro evaluator em execução ao vivo. Então, imagine que chega um trace em que o pai diz: “Certo, como ligo o Bluetooth?” e depois pergunta como acompanhamento: “Ah, mas esse botão não está aqui. Não sei onde encontrá-lo. E o que você está dizendo não é verdade.” Então, nós…

20:39 …captaríamos isso, porque é um evento interessante, um sinal que nos ajuda a entender onde as coisas estão dando errado. Provavelmente, nas primeiras 500 perguntas, não são todas as 500 que falham, mas talvez haja cinco, seis ou sete diferentes em que não fomos claros o suficiente e que talvez precisem de mais detalhes para investigarmos melhor. Então, a discordância do usuário é nosso primeiro exemplo. Vamos ver o que mais pode ser interessante. No nosso caso, agora temos um evaluator baseado em código que detecta se talvez haja algum uso de letras maiúsculas. Quando penso em como…

21:13 …interajo com o Claude ou o Codex, às vezes, se fico frustrada, posso usar só letras maiúsculas para deixar meu ponto claro. Acho que muitos de vocês também já fizeram isso em aplicativos de chat. E percebemos, especialmente em aplicativos de chat, que essa é uma boa forma de detectar alguma frustração do usuário. Neste caso, são letras maiúsculas. Mas, como alternativa, também poderiam ser palavrões ou certos termos que normalmente talvez não se deva usar em um chat. Mas, com um agent, você pode acabar recorrendo a eles. Para isso, agora queremos configurar um evaluator baseado em código, para que possamos…

21:46 …garantir que detectamos isso quando a pessoa está frustrada. Como podemos ver aqui, temos um pequeno trecho de Python e, se descermos um pouco, veremos que a função do evaluator está definida aqui e está selecionando novamente uma parte usando JSON path. Ela extrai uma determinada mensagem do usuário e verifica se há letras maiúsculas nela. Caso haja letras maiúsculas, retornamos uma pontuação booleana true. Então, vamos copiar isso para configurar. Estou copiando apenas a parte de baixo, porque…

22:21 …a parte de cima é estática. Agora estou configurando mais um evaluator, desta vez um baseado em código. Também oferecemos suporte a código em TypeScript. Então, se você trabalha mais com TypeScript, também é possível. Mas agora queremos usar código em Python. E vamos chamá-lo de “frustrado com letras maiúsculas”. Como vamos usar uma pontuação booleana, vamos também adicionar um “is”, para sabermos sempre que, se for true, então…

22:53 …ele está de fato frustrado e usando letras maiúsculas. E vou substituir também esta parte aqui embaixo, copiando-a novamente. É claro que aqui embaixo você pode escrever todo tipo de código personalizado que…

23:26 …quiser usar. Então, você pode avaliar o que quiser: se está procurando certas palavras ou, por exemplo, se tem algum nome de marca que sempre deve ser escrito corretamente. Por exemplo, com “length”, às vezes o “f” também é escrito em maiúscula. Normalmente, escreveríamos em minúscula. Você também poderia detectar esse tipo de coisa para ver onde talvez algo esteja dando errado. E pronto, vamos configurar isso. Criamos nosso segundo evaluator. Mas, é claro, também precisamos pensar em que tipo de observações queremos selecionar. Vamos olhar aqui de novo. Dizemos que, claro, queremos executá-lo em observações ao vivo. Queremos saber o que está acontecendo em produção. E, novamente, estamos selecionando o tipo de observação agent. Aqui, posso selecionar o agent mais uma vez. E, à direita, também podemos ver que é possível fazer um pequeno teste. Aqui vemos que, neste caso, retorna false, porque estamos perguntando apenas sobre como ligar e desligar o Bluetooth. Assim que estivermos satisfeitos com isso, podemos clicar em…

23:58 queremos executá-lo com observações ao vivo. Então, queremos saber o que está acontecendo em produção. E, novamente, estamos direcionando o tipo de observação agent. Aqui, posso selecionar esta opção, escolhendo o agent one novamente. E, aqui, do lado direito, também podemos ver que dá para fazer um pequeno teste. E vemos que, neste caso, ele está retornando false, porque estamos perguntando apenas sobre ligar e desligar o Bluetooth. Assim que estivermos satisfeitos com isso, podemos clicar em

24:32 …executar. Só uma observação rápida: no momento, estamos executando isso em observações, mas também é possível executar em todos os tipos de experimentos que você talvez queira fazer em um processo de melhoria offline, em vez de executá-lo em dados de produção ao vivo. Então, por enquanto, estamos satisfeitos em executá-lo apenas em observações ao vivo. Vamos clicar em executar aqui também. Ótimo. Vamos conferir como isso ficou, porque, é claro, queremos saber se também funciona. Para isso, vou voltar ao nosso agent de suporte de TI. Vamos começar com “como eu…”

25:06 Ligue o Bluetooth de novo. Vamos esperar um segundo e então receberemos nossas respostas. Aproximando. É, não consigo tentar. Também está pequeno para mim. Antes eu pensei: devia ter trazido mais óculos. E, é, agora conseguimos ver. Perfeito. Então, vamos começar por este primeiro. E, claro, nosso agent está lidando com isso de alguma forma, porque

25:38 temos algumas especificações no system prompt. E talvez eu também precise, é claro, da resposta primeiro. Então, vamos ver. Recebemos mais alguns detalhes e aí talvez eu possa perguntar. Não, não existe esse símbolo de Bluetooth, só para discordar um pouco do agent.

26:13 e ele diz que estou certo. Então, vamos ver no que isso vai dar nos nossos traces. Certo, vemos que agora estão chegando mais alguns. Vamos conferir este aqui, talvez. Certo, também já temos alguns evaluators chegando. Vamos analisar um pouco mais a fundo o que está acontecendo. Então, podemos ver que agora isso não é o… É, temos nossa mensagem do usuário. “Como ligo o Bluetooth?” Recebemos uma resposta e então podemos ver que esta é a saída

26:48 que estamos recebendo. Certo, pai, sem problema. Vamos tentar primeiro o outro jeito. Então, aqui houve uma discordância e, acima, podemos ver essa pequena pontuação. No canto superior esquerdo, provavelmente ainda está pequeno. Aproximando. É, agora podemos ver que nossa observação raiz — ou seja, o agent como um todo — está marcada com user disagreement = true. Porque aqui o usuário disse: “Certo, na verdade, isso não é verdade”, neste caso também em letras maiúsculas, e não funcionou. E podemos ver isso aqui

27:20 agora; temos esses sinais também. Em teoria, poderíamos filtrar as observações que têm user disagreement = true ou também all caps frustration = true e, assim, encontrar aquelas que são realmente interessantes para analisarmos. Certo, são os casos em que extraímos algo do comportamento mais ou menos de produção das pessoas. Há também outra coisa que costuma ser interessante monitorar em uma aplicação em produção, principalmente

27:51 se alguém estiver tentando fazer algo que não deveria ser feito com a aplicação em questão. Chamamos isso de solicitação fora do escopo. No prompt do nosso assistente, especificamos que o agent deve ajudar com todos os tipos de dúvidas de suporte de TI para celulares. Mas, é claro, o pai também tem outros tipos de dispositivos. Talvez uma impressora ou um computador sobre os quais ele queira fazer perguntas. Mas, por enquanto, nosso escopo está limitado a este caso específico. Para isso, também podemos configurar esses

28:22 tipos de evaluators, que neste caso estamos chamando de solicitação fora do escopo. Aqui, a dinâmica é diferente. Não estamos olhando apenas para a última mensagem do usuário ou para o histórico de mensagens. Aqui, também estamos olhando para o system prompt. E, como definimos tudo isso usando esse caminho JSON, podemos direcionar isso especificamente. Então, para concluir, vamos configurar esse evaluator mais uma vez. Para isso, vamos à página de evaluators. Podemos clicar em

28:53 evaluators. Mais uma vez, podemos selecionar o modelo de solicitação fora do escopo. Agora queremos direcionar as gerações, porque também queremos fazer referência ao system prompt. E agora vamos mapear nossas variáveis de novo. Vamos usar o system prompt, que, neste caso, é a primeira mensagem enviada nesta interação.

29:29 E também vamos usar a última mensagem do usuário que chegar. Neste prompt, definimos que queremos sempre comparar o que o sistema deve fazer e o que o agent deve fazer com o que o usuário está realmente tentando fazer. Então, isso fica configurado

30:02 sem mapear as variáveis agora; vamos executar este também. Certo. Então, sempre que Dev tentar fazer algo com a aplicação que não deveria fazer, podemos ficar sabendo e, com base nessas informações, tomar uma decisão fundamentada. Queremos corrigir isso ou ampliar o escopo da nossa aplicação? Ou talvez haja um problema na comunicação com os usuários sobre o que eles deveriam fazer com a aplicação? Neste caso, claro, trata-se apenas do suporte de TI, mas, em aplicações de escopo maior, há

30:35 às vezes coisas que as pessoas tentam fazer e uma compreensão equivocada de como o sistema deve ser usado. Assim, podemos detectar esse tipo de coisa que está acontecendo e analisar com mais detalhes. Perfeito. É assim que podemos configurar evaluators e monitors para a nossa aplicação. E acho que o que dá para ver claramente aqui é que não se trata de simplesmente copiar o que já existe e pode ser usado. Claro, muitas dessas coisas poderiam ser reutilizadas em uma aplicação de chat, mas o importante é

31:07 pensar nos modos de falha típicos que teremos na nossa aplicação, em vez de tentar copiar e colar o que já existe. O importante é analisar o que está acontecendo. Então, se quisermos trabalhar com isso, por exemplo, podemos usar essas pontuações para filtrar determinados traces e resultados. Aqui temos dois e, assim, podemos ter uma ideia de com que frequência essas coisas

31:40 realmente dão errado. Perfeito. Assim, podemos configurar monitors e ver o que está acontecendo. Agora vamos inserir alguns dados de produção para ver o que está acontecendo de fato e como isso se comporta na nossa aplicação. Para isso, vamos até o final do módulo de monitoramento, onde temos um script para inserir algumas informações de produção e, assim, ter mais dados para

32:14 analisar. Vou voltar ao meu repo e copiar nosso comando. O que está acontecendo em segundo plano é que temos um conjunto de traces como um conjunto de dados. Essas informações também incluem algumas pontuações, e estamos inserindo tudo diretamente na nossa aplicação, na nossa instância do Langfuse. Vamos ver se já foi inserido.

32:57 Vamos remover o filtro de pontuação. E podemos ver que, sim, estão chegando dados novos. Agora temos muitos dados, várias páginas de traces. E a pergunta, é claro, é como podemos trabalhar com isso e descobrir o que está dando errado ou também o que está dando certo na nossa aplicação. Normalmente, todos esses dados são usados para orientar o que você quer

33:28 garantir que também funcione em um processo de melhoria offline. Esses traces de produção, especialmente aqueles que você considera interessantes de analisar, podem então ser usados para montar um conjunto de dados que você pode usar no seu processo de melhoria offline para aprimorar a aplicação. Mas hoje queremos nos concentrar na parte de monitoramento e na parte de tracing. Então, vamos ver como podemos usar nosso agent de programação para encontrar os problemas mais amplos desta aplicação. Para isso, vamos

34:00 instalar juntos a skill do Langfuse. Assim, podemos usá-la. Para isso, temos um pequeno comando aqui, na etapa de configuração. Eu geralmente peço ao meu agent de programação que a instale para mim, mas você também pode instalá-la separadamente. Temos uma CLI e também nossa skill; no meu caso, agora posso instalá-las

34:31 com o Claude confiando na minha aplicação. E o que está acontecendo agora é que ele está acessando nossa CLI, e nossa CLI expõe todas as APIs que temos. Assim, você pode acessar seus traces, suas pontuações, seus conjuntos de dados e suas execuções de experimentos, mas também iniciá-los diretamente pela linha de comando ou junto com seu agent de programação. Desse modo, você trabalha de forma mais eficaz com o Langfuse. E isso também é

35:04 quando você está tentando instrumentar sua aplicação pela primeira vez e obter seus primeiros traces. É algo que você pode usar para adicionar tracing automaticamente à sua aplicação e ter seus primeiros insights. Então, agora estou instalando a skill do Langfuse só para ver como se faz. Depois, vou para o Codex. Eu já a instalei em segundo plano e agora quero descobrir o que está dando errado nos meus traces. Que etapas estão dando errado? Que tipo de pontuações temos lá? E agora estou pedindo ao meu agent de programação:

35:37 “Use a skill do Langfuse para encontrar problemas nos nossos traces.” Naturalmente, o Codex vai levar um tempo. Mas, para entender o que está acontecendo, o Codex está acessando os traces ao vivo da nossa aplicação. Ele está procurando que tipo de perguntas são feitas e que tipo de pontuações encontramos. Há muita frustração expressa em letras maiúsculas?

36:09 Também está verificando onde o usuário discordou, além do que configuramos oficialmente. Está verificando se há problemas com a latência, com nossas chamadas de ferramentas ou qualquer coisa que tenha dado errado em relação ao que não queríamos — para encontrar casos em que falha silenciosamente em produção, mesmo que não seja isso que queremos. Como isso vai levar um pouquinho, acho que é um bom momento para esperar pelo Codex e responder a algumas perguntas, caso

36:40 vocês tenham alguma. Certo, vamos ver se já terminou. Sim, recebemos um relatório, e eu poderia salvá-lo como Markdown, mas vou mostrar bem rapidamente o que preparei. E juro que não estou fazendo p-hacking. Também podemos olhar o relatório de verdade, mas só queria mostrar como isso fica. O que nosso agent de programação fez foi percorrer os traces de produção que inserimos. Eram cerca de 120 traces — ou eram 70 — e ele analisou todas as

37:13 diferentes dimensões em que as coisas poderiam dar errado. Agora temos um relatório bastante detalhado sobre quantos traces havia, quantas observações tivemos, quantas delas eram chamadas de ferramentas e o que havia nelas. Em seguida, ele também gerou algumas constatações. A primeira é que temos uma falha silenciosa na qualidade da recuperação de informações na biblioteca de ajuda da busca. Isso é algo que não avaliamos, mas também não tínhamos percebido antes que nossa ferramenta de consulta de informações

37:45 — que tenta determinar que tipo de resposta seria a resposta certa para uma pergunta — está falhando silenciosamente e não está fazendo o que deveria. Essa é a primeira coisa que vemos. Mas também vemos que as falhas na recuperação de informações estão aumentando a latência e o custo. Temos um problema com as novas tentativas de chamadas de ferramentas, em que detectamos alguns problemas. Também vemos uma lacuna na cobertura das avaliações, que abrange o tráfego recente, e, na verdade, não avaliamos

38:20 tudo; só recebemos sinais de um subconjunto dos traces. Vou verificar rapidamente se o Codex chegou à mesma conclusão. Certo, ele também detectou que a versão do prompt está desatualizada. Também menciona o texto da latência das novas tentativas e a divisão da cobertura do monitoramento. Sim. Assim, podemos encontrar esses problemas na nossa aplicação e, depois, garantir que encontremos uma maneira de corrigi-los e, desse modo, melhorar a aplicação ao

38:53 longo do tempo e garantir que corrijamos os problemas que realmente surgirem. Certo, recebemos aqui a proposta de salvar isso. Mas vamos ver se também conseguimos obter uma correção. Qual é a parte mais interessante? Na verdade, quero remover a biblioteca de ajuda da busca, porque, se ela não está realmente nos ajudando a usar essas ferramentas, podemos removê-la. E, para isso, também podemos usar nossa skill

39:34 da ferramenta da biblioteca de ajuda da busca. Como agora temos o contexto do repo, ela também pode nos ajudar a corrigir problemas no código, e não apenas na configuração do Langfuse. E agora ela está voltando ao trabalho para corrigir isso na nossa aplicação. Mas vamos dar um passo atrás e entender o que precisa acontecer nesse processo. Para isso, vamos voltar aos nossos slides

40:05 aqui. Então, hoje nos concentramos na parte de captar sinais dos traces de produção. Primeiro, configuramos o tracing e garantimos que tivéssemos uma visão passo a passo do que está acontecendo de fato: que ferramentas nosso agent está usando, quais são as entradas e saídas, e como obter sinais disso. Mas o que precisa acontecer com esses sinais para que o agent melhore continuamente ao longo do tempo? Por um lado, precisamos manter nossos critérios de avaliação. Por exemplo, surgiu a questão de como garantir que

40:39 ele não dê peso excessivo a algo ou não nos diga nada de fato. Com base nesses sinais, precisamos garantir que, com o tempo, tenhamos uma boa configuração dos nossos avaliadores e obtenhamos as informações de que precisamos. Mas, o mais importante, também precisamos manter nosso conjunto de dados. Quando você cria uma aplicação inicialmente, talvez ache que sabe o que as pessoas estão tentando fazer. Mas, com o tempo, vai perceber que há muitos casos extremos que não previu nem contemplou de antemão. Por isso, com o tempo, você também precisa manter seu conjunto de dados,

41:11 criar bons exemplos de produção, adicioná-los aos seus eventos offline e garantir que também possa iterar e, sempre que fizer uma alteração, lançá-la com confiança. Assim, você pode incluir isso no seu CI/CD e garantir que não haja regressões quando introduzir uma alteração. Hoje, cobrimos apenas a parte do ciclo de engenharia de IA em que analisamos as avaliações online. Mas, é claro, há mais

41:43 do que isso. O importante é garantir que você saiba o que está acontecendo e detecte os aspectos interessantes: se há discordância do usuário, uso de letras maiúsculas, palavrões ou algum tipo de avaliação de qualidade que possa fazer. Com isso, você cria e, em especial, mantém conjuntos de dados ao longo do tempo. Nada disso é uma atividade pontual. Você precisa se dedicar e fechar o ciclo continuamente, para também ter um conjunto de dados que represente o que seus usuários estão fazendo. E, com esses conjuntos de dados,

42:14 você vai querer executar experimentos e avaliá-los. Assim, terá sempre uma boa indicação da qualidade da sua aplicação e, quando fizer o deploy, saberá que pode lançar com confiança. Essa é a parte central do nosso workshop. Só queria mencionar rapidamente algumas coisas. Hoje, analisamos apenas essa parte. Mas, no nosso site, você pode ver que este workshop do Langfuse é, na verdade, um workshop de oito etapas.

42:46 em que você é guiado por cada módulo. Então, hoje só podemos abordar este e este, mas também há gerenciamento de prompts no Langfuse. Você pode configurar esses conjuntos de dados. E este é um passo a passo em que você é guiado por todas essas etapas para configurar tudo corretamente. E, claro, também recomendamos usar a skill para fazer a configuração junto com seu coding agent. E, se estivéssemos no seu lugar e tivéssemos que começar amanhã, é exatamente isso que

43:18 faríamos. Pegaríamos nosso repo e usaríamos a skill do Langfuse para configurar o tracing e realmente saber o que está acontecendo na sua aplicação por meio deste comando. Depois, revisaríamos os traces manualmente e entenderíamos de verdade o que as pessoas estão fazendo. Por fim, começaríamos a criar nossos traces e configurar evals para nossos traces de produção, para então também entrar no ritmo de otimizar offline. Certo, muito obrigada a todos. Vou responder a mais algumas perguntas, mas

43:51 muito obrigada por participarem. Mark está por aqui, Lotte está por aqui, eu estou por aqui, e teremos o maior prazer em conversar com vocês sobre qualquer coisa. Também temos um estande na exposição, então passem por lá nos próximos dias para conversar conosco. >> [música]

Transcrição original

[00:13] Hello everyone. Welcome to the workshop on continuously improving agents with Langfuse. Um you can already go to lenuse.com/workshop. There are steps there that we will go over today and that way you can also later at home when you want to revisit it go over it yourself and there are also some extra steps that we won’t cover today that you can find then as well we’ll show this QR code later in the presentation uh again so continuously improving agents what does it mean we will be talking a

[00:46] lot about um different processes that teams use to then uh to improve their agents or to detect changes and improve their agents in different ways and you can change these together into a continuous loop and as we know in San Francisco we really like loops and so this process and this set of these set of processes together you can it’s also often called AI engineering so what is AI engineering and why do we need it and how is it different from

[01:19] traditional engineering the main difference is that AI agents are not deter deterministic. So your system your status of your system can look healthy while the responses or the actions your agent is taking are wrong. Sometimes it’s actually wrong. Sometimes it’s also not qualitative enough. And so um this is what AI engineering solves. For the people who are not

[01:50] familiar, um, Langfuse offers a platform to actually execute on these processes and, uh, we are open source, model agnostic, framework agnostic, so you can actually use us with whatever setup you already have. There are some large companies that already use day-to-day, but we also have a large community of smaller individual users who really help us because they’re working on many different setups and agent projects. And this is definitely one of the um ways we keep up to date with where this very fastm moving field

[02:25] is going. By the way, uh this workshop is given by Annabelle and me today and Mark, our founder, is also somewhere in the room and there he is. And we will also be walking around to help you um during the workshop if you need anything. So AI engineering um we like to show or visualize the set of processes that that people do in this graph. Uh this is what we call the AI engineering loop. The exact setup depends a bit on the setup

[02:58] also of companies. Um it depends on different needs but high level you can categorize them in these five steps. And the main thing here to um remember is we have two big parts. We have an online part tracing and monitoring and an offline part building data sets experimenting and evaluating not in production and we are today mainly going to focus on the online part here tracing and monitoring. So tracing you instrument

[03:28] your application you deploy your app to production and you will see traces coming in of what your agent is doing how it’s interacting with users. Based on that you will be monitoring these traces and monitoring is on the one hand automatic with evaluators and with dashboards but also the human feedback part cannot be underestimated here. You will also be collecting implicit or explicit explicit user feedback and also manually be going through some samples of these traces. This together I don’t know if you can

[04:03] see oh the yellow um box is actually quite clear. Great. Um, this together the online part of the AI engineering loop is already a lot. A lot of teams that are not in high risk industries can actually just start with these two and based on what they find during monitoring of their traces can already um make simple fixes or improvements to their agents, deploy these to production and see their traces coming in. This is a great first step and it will already get you very far. Um, and it it’s a great way to iterate on your agents

[04:35] fast. Once your product matures a bit, your setup matures or you are in a high-risk environment where any mistake has bad consequences, um it makes sense to also work on the offline part. So that’s really for structured testing. So your data sets are your structured test cases. These will be heavily inspired by the way by what you see during monitoring. And when you want to make a change, you run an experiment on your data sets. You evaluate the results of the experiments. And only when the results are better, you didn’t introduce

[05:05] any regressions. That’s when you deploy to production. Before we go into the workshop, we very quickly want to focus on the two parts in the online loop. Um, so that’s tracing and monitoring because this is really important. Everything starts with your trace. So because if your trace is bad, you will not be catching everything during the monitoring step. If you don’t catch everything during the monitoring steps, your data sets will be not as good as they could be. You will not make the best informed decisions on what to

[05:35] evaluate, etc. So, it’s really important to take enough time to make sure your traces are set up well. So, what’s how do you build a trace? A trace exists um consists of observations and observations are different steps an agent is taking while creating an answer for the user. These consist of LLM calls or these can also be tool calls or other things. These can also be nested. Um each observation also has a lot of data attached and this depends on the

[06:05] kind of observation. For an LM call, this is usually the duration, token cost, um token usage model that was used, a prompt version that was used, everything you can think of that will actually help you assess the quality um of your LM call. And for tool calls it can be completely different. For example, if you do a web search, one data point can be the query that was used to do this web search. So this is really important so that you can then do monitoring. Well, monitoring there are a couple of different

[06:39] functions of monitoring. One is you want to have aggregate metrics to then see overall contingency over time. How is the health of your system? both things like the cost of your system for example but also the quality. So if you set up evaluators uh to measure the quality of your responses uh you want to make sure this is not going down over time. A second very important one is signal detection via user feedback. You will have as your application scales a lot of traces and will be impossible to see um or go through everything and user

[07:12] feedback is a great way to surface the ones that actually are important to look at. Third one is feedback and evals. So you will set up automatic evaluators and uh also you will do some human annotation to make sure um you catch new things. One important thing here. So you have the automatic evaluators. These on the one hand are very scalable. You can keep on doing them on all your traces. On the other hand, you will you’re less likely to catch very new or nuanced

[07:43] cases that you didn’t think about on by yourself. But user feedback and human annotation might scale a bit less well, but these are where you will detect really things you haven’t thought about yourself. So this is what we’ll focus on today and my colleague Annabelle will go through a practical example and Mark and I will be walking around. If you need help, just raise your hands. So today’s focus as L already mentioned is all about how to effectively working with a trace of your application also how to decide what you

[08:15] actually want to monitor. So what is interesting for you in your application and not like generally and then also um how you can leverage coding agents to uh 10x yourself a little bit but also maybe where you should uh be in the loop and not let the coding agent do everything on its own. So uh let’s dive into it and um to do so uh we first want to meet our sample application for today and we brought for you specs the dad IT support agent. So this uh mini repo came out of a a mini project um I did uh for my dad because my dad always asks me questions

[08:48] on WhatsApp uh about how how to set up his phone and also how to set up all kinds of things with his printer or his computer. Um so I built this little agent that is replying to him um in the production version via WhatsApp. In this case, we now have a a nice little UI. So, how you can imagine working it is we have a user, my dad or whatever dad and um the dad is asking specs a question and specs has a few tools available. So, we can get support context. So, some um information about what kind of phone is dad using and what kind of operating

[09:18] system is it on? What kind of apps does he have? And we also have a search help library. saw some frequently asked questions where there’s some context on how to go about solving certain issues and um yeah it can use these tools and then we also use the uh use openai the API endpoint uh to generate replies and get a reply back to our uh dad in this case. So this application we’re going to first um look at traces together but then also think about what is actually interesting that we want to know about uh to make sure dad gets the support he actually wants to have. So um yeah, you can scan the QR code

[09:52] here. Um you will find the workshop repository and um I’ll get uh the setup together with you. So no worries and we’re going to go through step by step. There’s also documentation in case you get lost, you could also reference there and if you want to explore more afterwards. Uh there’s also be going to be some more um modules available. So let’s go to lenfuse.comworkshop and we can see that um yeah this is a a markdown page here. Uh but if you click here on the lenfuse/langfuse workshop, we actually get to git

[10:25] repository and right here on um yeah, you can clone uh the repo into your um IDE. I already did that. Um so it’s prepared and we can see here that the first thing um we need to get set up is of course some uh end variables. And for this um let’s create a or together on languis.com. We can go to launch app. I already have an organization. Um but you can go to uh launch app or also if you’re on the page here and then uh select a region. It

[10:58] doesn’t matter which one you’re taking. And then um you can create an account and as soon as you’re in there uh what you will see is this page. So there will be a project autocreated for you and you will land um on this page and there you can get your um API keys by uh clicking on create new API keys. Um, so maybe I’ll give you just a second uh to get to our website and get this um get this set up. And this will be the the very first thing we have to do together.

[11:30] And I’m going to show also here the steps that you will also find on our um workshop website. So quickly signing up, creating a new account. And for everyone who now did that already, um we brought uh for today an open AI key. So you can scan it. We’re going to rotate it afterwards, of course. Um but for today, um this is your API key to use and you can add this

[12:00] into your N uh file and then we’ll uh get started. Yeah. So just copying the NF sample and then getting there. Okay. So when we have the uh repo cloned, the first thing we have to do is

[12:32] um we have to quickly install the dependencies. So we’re running here a TypeScript application that is using the OpenAI um agent SDK and uh yeah like this we can quickly install all the dependencies um it is available and then we can also start it by running npm rundev and I’ll pull this out here. It’s opening here directly. I’m also going to open it here and we can see our um yeah our sample

[13:04] application and by the way if I’m a little too fast like here are the steps uh in the setup page on lenfus.com/workshop um how you can also get there um step by step by adjusting the um end file and then running uh the application. So let’s see what we have here. we have our um dad support agent and it’s already greeting us uh with certain questions if I have maybe questions and also we have some um sample questions that dad might ask um so we can say here how do I turn on my Bluetooth on my iPhone and then specs is taking a second and using in the background the tools um that we’re

[13:38] like needing um to get there and then we replies to our dad in this case uh now with a step-by-step in instructions on how to um yeah how to turn on Bluetooth on the device and um what happened now in the background. That is now uh the interesting part um that we want to look into. And if we now click back into tracing and this is now also what should happen for you if you run the application and ask a single question then uh we see the first trace popping up. So every row here is an observation and we can also see that they have

[14:10] little different icons and these different icons mean that they are different things. So if we click into one of them, we can see that the whole thing is rooted in our um our agent observation and then below we have a few generations but also tool calls where certain context is pulled. Um so this is now already a fully instrumented application and there’s also a step-by-step um guide on on how to get this actually set up. But we also have a lengthy skill that you can use to automatically get it set up. And for today, we actually want to focus on working with those traces instead of

[14:42] step by step uh setting them up. So, um yeah, here we have our trace. And if we now uh get back to our um lenfuse.com/workshop page, we can go into the monitoring workshop uh module, which is the part that we actually want to check out together today as lot already mentioned. So, um in our context of our dad support app, what does monitoring actually mean? So whenever dad is interacting with the application, we of course don’t see what he does uh because we don’t sit next to him. That’s the whole point about the agent. H but

[15:12] we actually want to track what’s going on and we don’t only want to track um what kind of things the agent is doing but we actually want to make sense of it. So we thought about what are actually things that can go wrong in a support application. And the first one is maybe the dad is disagreeing with the application. So for example um if I’m asking a question, how do I set up Bluetooth? Um, then I’m wondering, okay, um, how does it actually work? Where’s the button? And dad is, um, asking this, and we might want to catch this because there was something maybe not clear enough, not detailed enough, um, for the

[15:44] question to actually be properly, um, done. So, um, let’s get this set up together. We’re h starting with the um, yeah, with copying this git command here, get checkout checkpoint for monitoring. And then we can get back into our um, IDE. and run this command. And we can see now that we swapping or switching to the uh monitoring uh step of our workshop. So it’s a checkpoint. And now we want to wire up those um those evaluators in our

[16:17] application. So um if we go down a little bit, we can see that the first thing um that we have to do together is configuring the Lenfuse evaluator model. So I’m going to jump into our uh application here. I’m going to close the tracing part and I’m going to hop into our evaluator tab. So here I can see I can get started with my evaluators and there’s two different possibilities. I can either set up codebased evaluators for more deterministic checks about my application and I can also get set up

[16:48] with some LLM as a Dutch evaluators um which are like more for the implicit things that you might want to get out of the conversation history uh and actually want to find out there. And we can also see that we have some uh templates here and that our uh user disagreement one um is actually one template that we are uh providing here. So if we click on here we can see okay we need to get up uh set up with the um LLM connection. So I’m going to jump over here and very quickly stop sharing because shouldn’t see the API key.

[17:24] laptop died. So this is in the end um a possibility to use a certain model to evaluate um what’s going on and to give one second. Okay. Yeah. So what I now did is I um set up a new LLM connection and in this

[17:56] case I’m using again the OpenAI API key. Go back. Yeah. Um so I connected the OpenAI API key now that we um set up together. And um in instead you can also connect all kinds of other uh models of course and you can also um use your own proxy in case you have a have a gateway configured yourself. And now we’re going to um jump back into our evaluator page. We’re going to click on create evaluator. And now select our template again

[18:26] and select the model. And what we can see here now is that the first thing we can do together is we can filter for the actual um observations that we want to target. And in this case uh we want to go um not for the generation um but for the agent that is the root um of the whole uh trace that we’re having here. And then you can also see that there are some other options. So you can also target tool calls or generations. But in our specific case, we want to look at the um input only. So we want to see uh the the message of the user um being

[18:59] looked at. So looking at our instructions here again, um we have a certain way to target those different different parts um of the observation. So we’re taking the agent, we have our evaluator prompt here, and down here we can see that um via um curled brackets, we’re actually pulling in um context here. And to target the part of the trace that is actually relevant for us, uh we want to set up this JSON path here

[19:30] and make sure that we’re targeting the part um that is that is correct in this case. So for the conversation history, we actually want to target the whole message array. So, we’re going to copy this here and we’re packing it in here. And what we can see down here now is that it’s mapping in the message history of your trace. So, it’s pulling together what was the interaction, what did that ask, what the tools um do, and then also what kind of reply was generated. And as a second part of um detecting if a user disagrees um we of course um need to also target the last message that is

[20:06] coming from the user and like this also get information here and we can see that down here now we’re mapping how do I turn on Bluetooth on my phone into this um evaluator and if we now execute this we have our first live running evaluator. So you can imagine if now a trace is coming in where um dad is saying okay how do I turn on Bluetooth and then he asks as a follow-up oh but this button is actually not there I don’t know where to find it and um it’s not true what you’re saying then we

[20:39] would catch this because this is actually an interesting event a signal for us to understand okay where are things going wrong and probably like in the first 500 questions there it’s not like all 500 fail but maybe there’s five or six or seven different ones where we’re not clear enough and that might need some more detail to actually go deeper into it. So user disagreement is our uh first example. Let’s look at what also might be interesting. And in our case, we now have one um where we’re catching with a codebased evaluator if maybe there’s some all caps used. So if I think about how I’m

[21:13] interacting with cloud or codeex sometimes if I’m getting frustrated, I might just use all caps to get my point across. And I think many of you have also done this in chat applications. And we see especially in chat applications that this is actually a good way of catching some frustration from the user. And um in this case it’s all caps. But as an alternative this could also be maybe cuss words or um yeah certain terms that you should maybe not usually use in a chat. Um but when it’s an agent you might tend to rather um go for it. And uh for this we now want to set up a codebased evaluator so we can actually

[21:46] make sure uh we get that uh when he’s frustrated. So um as we can see here we now have a little um Python snippet here and if we go down a little bit um we can see uh that here the actual evaluator function is defined and um it’s targeting again a part of the JSON path. So it’s like extracting uh the certain user message and then it’s checking if there’s all caps in there and in case it’s doing all caps then we return a um a boolean score true. So let’s copy this here so we can get this wired up. And I’m only copying the bottom part because

[22:21] the upper part is actually static. And I’m setting up an additional evaluator in this case now a codebased one. And um we also support TypeScript code. Uh so in case you’re rather operating on TypeScript, this is possible. But we now want to go for um Python code. And um we call it all caps. frustrated. And since we’re going for a boolean score, let’s also add a little is um so we always know if it’s true, then it’s

[22:53] um he is actually frustrated uh with all caps. And then I’m going to also down here replace this part um with our of course copying it again. And of course down here you can um write all kinds of custom code um that you

[23:26] want to go for. So whatever you want to evaluate if it’s certain words you’re looking for or uh for example also if you have some brand name that always should be written the right way. So for example for length use also sometimes the f is written big. We would usually write it small. So you could also catch these kind of things to see where maybe things are going wrong. And yeah let’s get this set up. So we have our second evaluator created. But then of course we also need to think about what kind of observations do we want to target. So let’s look again here. Um we say okay of course we

[23:58] want to run it on live observations. So we want to know what’s going on in production. And we’re again targeting the um the observation type agent. And here I can select this going for the agent one again. And here on the right side, we can also s that see that we can do a small little test run on it. And here we see that in this case it’s um returning a false because we’re here only asking the questions about the turning on and off Bluetooth. And as soon as we’re happy with it, uh we can then uh click on

[24:32] execute. Uh just as a short note here like right now we’re running on observations but this of course is also possible to run on all kinds of experiments that you might might want to do in an offline improvement process instead of running it on live production data. So yeah right now we’re happy with uh just running it on live observations and let’s also click on execute here. Nice. Uh so let’s check how this actually turned out. Uh because we of course want to know if it also works. And for this I am jumping back into our IT support agent. Let’s kick it off first with a how do I

[25:06] turn on Bluetooth again. We’re taking a second and then we’re getting our replies. Zooming in. Yeah, I can’t try. It’s also small for me. I was earlier like I should have brought more glasses and yeah, now we can see it. Perfect. Um, so let’s get frustrated this one first. And of course, our agent is somehow dealing with it because we

[25:38] have some specifications in the system prompt. And I might also um need of course the reply first. So let’s see. We get some more details and then I can maybe ask. No, there is no such Bluetooth sign just to disagree a little bit with the agent

[26:13] and he says that I’m right. So let’s see how this turns out in our traces. Okay, we see we have a few more um now here coming in and let’s check maybe on this one. Okay, we also have some evaluators coming in already. Let’s dive in a bit deeper into what’s actually going on here. So uh we can see that this is now not the Yeah, we have our user message. How do I turn on Bluetooth? we get a reply and then we can see that this is the output

[26:48] we’re getting back. Okay, dad, no worries. Let’s try the other um way first. So here we had some um disagreement going on and up here we can see actually this little score. So on the top left is probably still small zooming in. Yeah, we can see now that our root observation like the overall agent is actually tagged with a user disagreement um true. Uh because here the the user actually said okay it’s actually um in this case also all caps um is actually not true and it didn’t work out. And uh we can see this here

[27:20] now and have like this also signals. So we could in theory now filter for the observations that are having a um maybe user disagreement true or also um all caps frustration uh true and like this find the ones that are actually interesting for us to work with. Okay, so these are the ones where we get something out of the more or less um production behavior um of the people. There’s also one additional thing that is often interesting to monitor in a production application mainly being um

[27:51] if someone is trying to do something that is actually not supposed to be done um with the respective uh application. So we call this out of scope request. So in our assistant prompt um we are specifying here that the agent is supposed to help with all kinds of phone IT support questions. Uh but of course dad also has different kinds of devices. So maybe a printer also computer that he wants to um get uh get questions answered with. But right now we’re scoped um to this um specific scope. So for this we can also um set up these

[28:22] kinds of evaluators and we are calling them in this case now out of scope request. And here we have a different uh dynamic. We’re not looking at only the last user message or the message history. Um but here we’re actually also looking at the system prompt. And because we are defining all of this via this JSON path, we have the possibility to target this also specifically. So, um, one final time, let’s get this evaluator, uh, set up. And for this, we’re jumping into our, um, evaluators page. We can click on

[28:53] evaluators. And once again, um, we can select our out of scope request template. We now want to target um, generations because we also want to reference the system prompt. And let’s now map our variables again. So we are taking the system prompt which in this case is the very first message that is sent in this interaction.

[29:29] And then we’re also taking our last user message that is coming up. And in this prompt now we define okay we also wanna we want to always compare like what the system is actually supposed to do and what the agent is compared to do uh supposed to do um to what the user is actually trying to do. So this is now wired in

[30:02] not mapping the variables right now and let’s execute this one as well. Okay. So whenever now dev would try to do something with the application that he’s actually not supposed to and then we can know about this and then we can based on this information take an informed decision. Do we either want to fix this so or expand the scope of our application or do we maybe have an issue in communicating to our users what they’re actually supposed to do with our application and in this case of course it’s only the IT support but maybe in bigger scope application there’s

[30:35] sometimes things people are trying to do and really misunderstand how the system is supposed to use supposed to be used and like this we can uh yeah catch these kind of things um that are going on and go into more um detail here. Perfect. So this is how we can set up evaluators and monitors um for our application. And I think what you can uh clearly see here is that this is not about um copying just what’s out there and what can use. And of course like many of these things you could now reuse for chat application but it’s really about

[31:07] thinking what is what are the typical fail modes we will um endure in our kind of application and not about like trying to copy paste u what’s out there but really looking into what’s going on. So whenever we would want to work uh work with this now we could for example now go for um use like using these um scores now to also filter for certain um for certain traces and results. Here we have two and like this get like an insight on how often these things are

[31:40] actually going wrong. Perfect. So um like this we can wire up monitors and see u what’s going on and um let’s now seat some production production data in to see what is actually um happening and how this performs in our app. And for this uh we go down to the end of our um mon monitoring module and we have a script here to seat some um production information and like this have a bit more data to

[32:14] actually look at. So I’m jumping back into my um repository and I’m copying our command. And what you can imagine is happening in the background is we have just a set of traces as a data set. And this information um also includes some scores and we are seeding this um into our um into our application into our language instance um directly. So, let’s see if it already is seated.

[32:57] Taking out our score filter again. And we can see now, yes, there’s new things coming in. We actually now have a lot of um a lot of data, multiple pages of traces. And now the question is of course how can we work with this and how we can we find out um what is actually going wrong or also what is going um right in our application. And um all of this data is usually then used to inform what you actually want to

[33:28] make sure that it’s also working in an um offline uh improvement process. So these production traces and especially the ones that you find that are interesting to look at h can then be used to build up a data set that you can use um in your offline improvement process uh to to make a better application. Um but today uh we want to focus on the uh monitoring part and the tracing part. So let’s see how we can maybe use our coding agent to find the larger scale issues that are in this application. And for this um let’s

[34:00] install the lenfuse skill together. Uh so we can um use this and for this we have a little command up here in the setup step and I I usually go actually with just um telling my coding agent uh to install it for me but you can equally also just um install it separately. So we have a CLI and we also have our skill and this can be installed then in my case now

[34:31] with claude trusting my application and what is now going on is that it’s pulling our CLI and our CLI is exposing all APIs that we have so you can always access your traces your scores your data sets experience ment runs but also start them through your um yeah command line directly or also with your coding agent together and like this work more effectively um with lenfuse and this is actually also

[35:04] when you are trying to instrument your application in the first place and try to get your first traces and this is something you can uh use to automatically add tracing to your application and get your first insights so here I’m now um installing language skill and uh just to see how it’s done then running I’m going uh over to codex I already installed it in the background and what I now want to find out what is actually going wrong in my traces. So what are the kind of information um steps that are going wrong? What kind of um scores do we actually have in there? And I’m asking my coding agent here now

[35:37] please use the length fuse skill to find issues in our traces and naturally cudex will take now some time uh but just to understand what’s going on um cudex is now accessing um the live traces that we have in our application so it’s looking for what kind of questions are asked what kind of scores do we find in there? Um what is maybe a lot of all caps frustration um

[36:09] going on there also where did the user disagree but also beyond what we officially set up. So it’s also checking on is there maybe issues with our latency is there issues with our tool calls um anything that has been going wrong in terms of what we didn’t want to um so to find where it’s silently f failing in production h even though we don’t want it um wanted to do this of course and since this is now going to um just run a little bit I think this is a good moment to also um wait for codeex and just take a few questions um in case

[36:40] you have any okay let’s see if the um if we’re there yeah uh we actually got report and I could save this now as a markdown but I’m just going to um very briefly show you the one that I prepared and I’m swearing I’m not p hacking and we can also look at the proper one but just wanted to show you how this looks like. So what our coding agent now did is ran it ran over the um production traces that we we seated in there. It was like around 120 traces or it was 70 traces and it actually looked at all the

[37:13] different dimensions where things could be going wrong. And we get a quite um detailed report now um about like how many traces were there, how many observations did we have also how many of those were tool calls and what we have in there and then it also generated us some findings and the first finding here is actually that um we have a silent retrieval quality failure and search help library. So this is actually something we didn’t evaluate for um but uh we also didn’t realize before that our um lookup of information uh tool uh

[37:45] where we’re looking like what kind of um question could what kind of answer could be the right answer that is actually um silently failing and not actually uh doing what it’s supposed to do. So that’s the first one we see. Um but we also see that um the retrieval misses are increasing latency and cost. So we have some issue in like tool retry calls um where we are detecting some kind of um problems and we can also see that there’s um an evaluated coverage gap that uh is across like recent traffic and um we we actually don’t uh evaluate

[38:20] everything but we only get um signal from a subset of the traces um that are going on there and just briefly verifying um if Codex now also came up with the same. Okay, it also detected that the prompt version is um is off and then it also says about the latency text for the retries and we have the monitoring cover split. Yeah. And like this we can find um those issues in our application but we can then also make sure that we find a way to um to fix them and uh like this um yeah improve the the application over

[38:53] time and make sure um that we yeah that we fix the issues that are actually coming up. Okay, so we get the proposal here to save this. Um, but actually let’s see if we can get also a fix in here. So what is the most interesting part? Um, I actually want to get rid of the search help library one because if it’s not really helping us to use those tools, then we can also um remove this. Um, and for this we can also use our skill

[39:34] our search help library tool. And because we now have the repository context, it actually can also help us um fix um issues in the code and not only um in our Langu setup. And yeah, now it’s getting um it’s getting back to work and um fixing this uh for us in our application. But let’s now take a moment to zoom out and understand what actually needs to happen um with this. And for this um we’re coming back into our um slides

[40:05] here again. Uh so what we now focused on today is actually the part of catching signals from our production traces. So we initially set up our tracing and made sure that we have a step-by-step view into what is um actually going on. What kind of tools is our agent using? What’s the inputs and outputs and h get a signal from this. But what does need to happen with those kind of signals to make a continuously improving agent over time and uh for this like on the one hand we need to maintain our evaluation criteria. So um we had this question for example on how can we make sure that

[40:39] it’s like not overindexing on something um or like not really telling us anything. And um yeah from this signal we need to make sure that over time we actually have a good um setup of our evaluators and get the information we need to get. Um but most importantly we also need to maintain our data set. So when you initially build an application um you might think you know what kind of things that people are trying to do. Um but over time you will realize that there’s a lot of edge cases that you did not account for and not cover um beforehand. And that’s why you need um to over time uh also maintain your data

[41:11] set um create good production examples um add them to your offline events and then make sure that you also can iterate and whenever you make a change also ship um with confidence so you can make it part of your CI/CD and uh make sure that is um yeah actually not regressing whenever you introduce a change. So um we today only covered the part of the AI engineering loop uh where we are looking into the online evaluations. Uh but actually of course um there’s more

[41:43] to it. So it’s all about uh making sure you know what’s going on, you catch the interesting parts. um if it’s a user disagreement or all caps or if it’s cussing um or also some kind of quality evaluations that you can do and out of this um you’re building and especially also maintaining data sets over time. So all of this is not a one-off. You actually need to make sure that you are like putting in the reps and close the loop continuously to to also have then a data set that represents what your user users are doing. And on those data sets

[42:14] you then want to um run experiments and evaluate those experiments. Um so you always have a good uh indication of how good the quality of your of your app is and um whenever you deploy then also know um that that you can ship with confidence. So this is the core part of our workshop. I just wanted to briefly mention some things. So today we only looked into that part. Uh but on our website you can see in this length workshop that this is actually a eightstep um uh workshop

[42:46] where you are guided through every single module. So, we can only touch upon this one and this one today, but there’s also prompt management to Lenfuse. You can set up those data sets. And um this is a step-by-step walkthrough where you’re guided through um uh all of these steps and like this uh can get it set up properly. And um we of course also recommend to to uh to use the the skill um to get the setup together with your coding agent. And if we uh were you and we would have to start tomorrow um this is exactly what

[43:18] we would uh be doing. So we would take our repository um we would um use the length view skill to get up set up with tracing to really know what’s happening in your application um via this command. We then would review traces manually and really understand uh what people are doing and then um yeah finally get into the motion of building out our traces and set um email setup for our production traces to then get also into the motion of um optimizing offline. All right, thank you so much everyone. Um I’m taking a few more questions but

[43:51] thank you so much for participating and Mark is around lot is around I am around and we’re super happy um to discuss anything with you and we also have a expo booth so please come around the next few days and uh chat with us >> [music]