Como testar agentes de IA quando não existe benchmark — Nathanael Weill, Air Canada
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: How to Test AI Agents When No Benchmark Exists — Nathanael Weill, Air Canada · Canal: AI Engineer · 19:33 · Assistir no YouTube
Tópicos: Agentes de IA, Aplicações empresariais de IA, Avaliação e benchmarks de IA, RAG, busca e recuperação de informação
Nathanael Weill explica como a falta de benchmarks públicos e o acesso limitado a especialistas dificultam a avaliação de agentes criados para tarefas específicas. Com base em uma experiência com RAG e em um projeto de análise de contratos na Air Canada, ele mostra como inverter o problema: gerar casos de teste com respostas conhecidas e verificar se o agente encontra os resultados esperados. A equipe criou testes a partir de regras, contratos alterados, mudanças que não deveriam afetar os resultados e templates. Ele conclui que os testes aceleram o desenvolvimento, mas não determinam, por si só, se uma solução está pronta para ser lançada.
Pontos-chave
Seção intitulada “Pontos-chave”- Tarefas específicas de negócio muitas vezes não têm benchmarks públicos aplicáveis.
- O acesso limitado a especialistas torna a avaliação manual lenta e sujeita a divergências.
- Para avaliar sistemas RAG, a equipe partiu de documentos conhecidos, gerou perguntas e verificou se o sistema recuperava as fontes corretas.
- A abordagem aumentou a frequência de avaliações de uma por semana para dezenas por dia.
- No projeto de análise de contratos, a equipe criou testes a partir de regras, cláusulas removidas, alterações irrelevantes e templates.
- Sempre que possível, verificações baseadas em código evitam a complexidade e o ruído de usar LLM as a judge.
- O feedback de especialistas pode ser usado para criar testes melhores, não apenas para ajustar o agente.
- Uma suíte de testes ajuda a antecipar problemas, mas não é, sozinha, uma decisão de aprovação para lançamento.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:01 | O desafio de avaliar agentes sem benchmarks | O apresentador introduz o problema de desenvolver agentes para tarefas específicas sem benchmarks públicos e com acesso limitado a especialistas. |
| 02:05 | A experiência com RAG e avaliação automatizada | A equipe transforma documentos conhecidos em perguntas de teste e automatiza a verificação das fontes recuperadas. |
| 07:17 | Aplicação ao projeto de análise de contratos | O apresentador descreve a tarefa de analisar cláusulas de contratos e a necessidade de criar testes próprios para o agente. |
| 10:51 | Cinco técnicas para gerar testes de contratos | A equipe explora decisões anteriores, regras, cláusulas removidas, alterações irrelevantes e templates para criar casos com resultados conhecidos. |
| 16:29 | Limites dos avaliadores e conclusão | O apresentador discute o ruído de LLM as a judge, outras estratégias de avaliação e o papel dos testes como apoio, não como decisão final de lançamento. |
Citações
Seção intitulada “Citações”Podemos usar código para avaliar isso. Sem opiniões, sem discussões: podemos automatizar a tarefa. — 06:15
Se você não consegue avaliar o agente, não consegue melhorá-lo. — 07:17
Você não precisa usar LLM as a judge. — 15:27
Gerar esses testes não basta para saber se você pode lançar o produto. É só um ponto de partida. — 19:03
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- Nathanael Weill (pessoa): Apresentador que relata experiências de avaliação de agentes em projetos empresariais.
- Air Canada (empresa): Empresa em que a equipe do apresentador desenvolve soluções de IA para diferentes áreas de negócio.
- RAG (conceito): Abordagem discutida na apresentação para buscar documentos relevantes e formular respostas com base neles.
- benchmark (conceito): Referência ou conjunto de testes usado para avaliar o desempenho de um sistema.
- LLM as a judge (conceito): Uso de um LLM para avaliar respostas, abordagem que o apresentador considera trabalhosa e sujeita a ruído.
- BM25 (conceito): Método de recuperação de informação mencionado como um dos elementos ajustados no sistema de busca.
- embedding (conceito): Representação usada na busca semântica, citada como um dos componentes a ajustar no sistema RAG.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:01 [música] >> Obrigado por participarem desta sessão. É um assunto um pouco emotivo. Meu nome é Nathaniel. E eu sou um não avaliador. Faz bastante tempo que não lanço um agent sem nenhuma avaliação. E hoje quero contar a história de
00:32 como superei esse vício de lançar um agent sem nenhuma avaliação. Então, trabalho na Air Canada. Em comparação com a palestra anterior, esta é mais focada em um negócio específico. Entrei na Air Canada em junho deste ano. A Air Canada é uma empresa enorme. Atuamos em operações, áreas corporativas, comercial e fidelidade. Cada um desses segmentos tem seus próprios desafios. Então, minha equipe é responsável por entregar soluções de IA para todos eles.
01:04 E o problema é que, quando abordamos uma tarefa, criamos um agent para algo tão específico que não temos nenhum benchmark público em que possamos nos apoiar. E esse é o principal problema que estou tentando abordar nesta apresentação. Mais importante ainda, não é que não tenhamos um benchmark: é que somos cientistas de dados que podem criar agents, ou engenheiros de IA que podem criar agents, mas não somos especialistas no domínio. E esses especialistas estão alocados em
01:34 diferentes unidades de negócio. E estão muito ocupados com as próprias tarefas. E temos acesso limitado a eles. Então, essas duas coisas juntas criaram uma situação em que é muito difícil construirmos qualquer avaliação ou benchmark para nossa tarefa. Antes de ir para a Air Canada, eu trabalhava em outra empresa. Era uma empresa em que a tarefa era criar um assistente de perguntas e respostas para engenheiros de telecomunicações.
02:05 Então, não sei se vocês conhecem esse domínio. Telecomunicações é um domínio enorme. Há cerca de 10 mil documentos. Além disso, há muitos documentos de fornecedores. Existe uma lógica para saber qual documento você deve encontrar para responder à pergunta. Então, é uma tarefa um tanto complexa. E, em 2024, todo mundo queria criar RAGs. Então, começamos a fazer isso. É, no LinkedIn é super fácil. Não é. Então, a questão é que, quando começamos esse
02:36 projeto, enfrentamos o mesmo problema que na Air Canada: não tínhamos acesso aos especialistas. Nosso acesso aos especialistas era limitado. E não conseguíamos avaliar as respostas por conta própria. Então, esse é o problema de que quero falar hoje. Curiosamente, estávamos competindo com outras equipes: duas externas e uma interna. Não era tudo ao mesmo tempo, mas em etapas. E nossa solução realmente funcionou. O que quero dizer com funcionou é que entregou valor. As pessoas gostaram da solução e, na verdade,
03:07 a usaram. Mas, para ser sincero, não sei por que conseguimos fazê-la funcionar em comparação com a outra equipe. Então, hoje vou mostrar o que eu fiz, ou o que minha equipe fez, para que funcionasse. Então, todos tinham os mesmos documentos, a mesma tarefa, tudo igual, mas, de algum modo, nossa solução funcionou. Para quem conhece RAGs, o princípio é fazer uma pergunta ao sistema, o sistema encontrar
03:38 os documentos relevantes e, com base neles, formular uma resposta. É algo que existe há bastante tempo. E, para quem já experimentou, se você encontrar a página ou os documentos certos, em 90% das vezes terá a resposta certa. Então, o desafio, pelo menos nessa tarefa, é encontrar os documentos certos. Criamos um pipeline muito complexo, que foi ficando mais complexo com o tempo. Se você encontrar publicações antigas, verá que todo mundo tem uma técnica incrível para melhorar a solução.
04:10 Nós as experimentamos. Na verdade, elas não melhoraram a solução. Então, no papel, funcionavam para aquelas publicações, mas, para nós, não ajudaram muito. E, mais importante, quando adicionamos complexidade, descobrimos que acabávamos quebrando outra coisa. Algo que costumava funcionar deixava de funcionar. E esse é, na verdade, o problema real. Podemos continuar acrescentando ideias para resolver os diferentes problemas, mas continuamos quebrando
04:41 coisas sem parar. Então, a complexidade nem sempre ajuda. E o outro problema é este. Podemos mudar um agent em poucos minutos, adicionar uma camada de formulação de consultas ou qualquer etapa de raciocínio. Mas, para avaliar isso, tínhamos aquelas reuniões malucas com especialistas uma vez por semana. Colocávamos uma tela gigantesca com cinco chatbots diferentes, fazíamos a mesma pergunta a todos e pedíamos aos especialistas que os avaliassem. “Prefiro este. Prefiro
05:13 este.” E, curiosamente, eles nem sempre concordavam. É muito difícil pedir aos especialistas que expliquem suas opiniões; você acaba com três opiniões diferentes. Então, esse era o problema que enfrentávamos. E nosso limite era testar uma solução por semana, o que não era suficiente para avançar rápido. Antes de continuar, o processo era o seguinte: fazíamos uma pergunta, o agent respondia. Pedíamos ao especialista que lesse. Às vezes, ele não sabia a resposta. Precisava pesquisá-la.
05:44 Isso leva muito tempo. E tínhamos um limite de uma tentativa por semana. Então, não há nada de novo nisso. Essa abordagem bem conhecida consiste em inverter o problema. Começamos com uma página. Pedimos a um LLM que escreva uma pergunta sobre essa página, o que é uma tarefa fácil. Pedimos ao agent que procure a resposta e comparamos o que o agent encontrou com a página usada para
06:15 gerar a pergunta. Podemos usar código para avaliar isso. Sem opiniões, sem nada disso. Podemos automatizar essa tarefa. E isso nos permite avançar muito, muito mais rápido. Para quem trabalha com RAGs, há muitas implementações dessa ideia. Não fui eu que a inventei. Só achei muito, muito inteligente. E essa ideia ficou comigo. Por que esse princípio não poderia ser aplicado a outras tarefas?
06:45 O impacto disso é que passamos de uma avaliação por semana para dezenas por dia. E começamos a ver a precisão das avaliações dos especialistas aumentar cada vez mais. E, na verdade, remover boa parte da complexidade ajudou. Não precisávamos de muitas daquelas coisas. Focar no modelo de embedding certo, no chunking certo e no valor de alfa certo no BM25 era o que precisávamos fazer. E vimos a precisão aumentar ao longo das semanas. >> [fungada] >> Então, não sei por que tivemos sucesso, mas
07:17 tenho quase certeza de que a outra equipe não tinha nenhum conjunto de teste. Então, eles usavam esse tipo de ciclo longo com especialistas, talvez especialistas muito mais qualificados do que aqueles a que tínhamos acesso. Mas nós tínhamos esse conjunto de teste. E o que aprendi com isso, lá em 2024, foi que, se você não consegue avaliar o agent, não consegue melhorá-lo. Isso ficou comigo até hoje; já se passaram dois anos. E agora quero voltar à Air Canada.
07:47 Onde temos um projeto diferente. Em 2026, o projeto é analisar contratos de fornecedores. Dá para imaginar que a Air Canada tem muitos fornecedores. Recebemos muitos desses contratos. Especialistas os analisam um por um. Verificam cada uma das cláusulas. E precisam analisá-las e fornecer um retorno. Algo como: “Esta cláusula não está em conformidade. Esta cláusula precisa ser reformulada.” Há muito trabalho envolvido nisso.
08:18 É uma tarefa muito demorada e muito cara, porque, se precisarmos que algum fornecedor faça uma entrega imediatamente e isso não acontecer, haverá muitos atrasos na cadeia. E, se deixarmos passar uma cláusula, isso também pode sair muito caro, porque, no fim das contas, pode se voltar contra nós. Então, é um problema complicado. E eles vieram até mim, quer dizer, até a equipe de ciência de dados, para criar um agent que pudesse fazer isso por eles. Então, será que podemos automatizar isso
08:48 tarefa? E, obviamente, há muitos documentos, muitas regras, muitas coisas a considerar quando você faz isso. Os especialistas são muito ocupados. Dá para imaginar o preço por hora de um advogado. E não existe benchmark para isso. Não podemos simplesmente acessar a web, encontrar documentos e achar um benchmark existente que possamos aplicar. Então, voltamos ao mesmo problema que eu tinha em 2024. Os ciclos eram muito lentos, e sabíamos
09:18 que queríamos chegar a uma situação em que pudéssemos avançar rápido e tentar, tentar e tentar. E eu sabia que, se aprendêssemos com essa situação, poderíamos ter uma trajetória melhor em termos de precisão. E esse era o desafio deste projeto. Então, o problema de criar respostas a partir de documentos é algo conhecido e bem definido em RAG, mas, para este projeto específico, não há ninguém no mundo que diga: “Ei, você deveria usar esta técnica. Você deveria
09:49 usar esta técnica.” Então, tentamos pensar em como reaplicar, neste projeto específico, o mesmo mecanismo do que aprendi sobre RAG. E temos muitos projetos na Air Canada. Então, estamos usando o mesmo conceito: primeiro obter a resposta e depois tentar fazer o agent encontrá-la. Entrando nos detalhes, isso está um pouco simplificado, mas, na verdade, o agent tem quatro etapas. Precisamos identificar a cláusula no contrato. Precisamos encontrar os documentos relevantes
10:21 para dar suporte a uma alteração. Precisamos redigir a alteração. E, no fim, há um sistema de classificação que informa se devemos manter ou não essa alteração. Então, a primeira etapa, por exemplo, identificar, consiste em classificar todas as seções do contrato em domínios específicos. E depois verificar se há algum problema ou se é preciso fazer alguma alteração naquela seção. Então, usamos aquele truque de RAG. Sabemos como encontrar os documentos. Essa parte está coberta.
10:51 Mas, para as outras partes do agent, não tínhamos nada. Então, vou apresentar cinco técnicas diferentes que usamos neste projeto ou tentamos usar nele. Elas buscam resolver esse problema específico. Meu objetivo não é me exibir. Meu objetivo é inspirar vocês a reaplicar essas técnicas nos próprios desafios. Então, a primeira é usar decisões
11:21 e respostas anteriores. Vocês podem recuperar um contrato anterior e compará-lo com aquele que foi alterado. A segunda é escolher algo que estejam procurando, redigir o contrato em torno disso ou gerar o contrato. A terceira é pegar um bom contrato que foi assinado e danificá-lo. A quarta trata de coisas que não deveriam mudar: não importa o que você faça, não deveria haver mais alertas. E a quinta é, na verdade, a mais
11:52 poderosa. É muito difícil. Trata-se de transformar um exemplo em muitos, usando o conceito de templates. Então, começamos imediatamente com essa abordagem. Pedimos ao especialista o contrato original, aquele que foi assinado. Vamos pegá-lo, fazer um diff, como se faz no código, comparar o que mudou, e o agent deve fornecer exatamente os mesmos alertas. Isso seria perfeito. No entanto, por várias razões, nossa equipe não guarda todos os
12:23 contratos. Não guardam o original; guardam apenas o mais recente. Não têm todas as versões dos contratos. Às vezes, há negociações e muitas outras coisas. Então, não conseguimos obter nenhum desses pares de contratos, e essa abordagem não funciona. Certo, a segunda. Pegamos uma regra. Isso muda um pouco o assunto. Em vez de criar alertas ou um agent que possa fornecer alertas,
12:54 começamos pelas regras. Por exemplo, temos um limite acima de US$ 1 milhão. Todos os contratos da Air Canada devem seguir essa regra, ou várias regras desse tipo em domínios específicos. Então, você conhece a regra, cria uma cláusula sem violá-la e gera o contrato em torno dela. Depois, deve encontrar a regra — o alerta que indica a violação da regra. Isso é simples. Não exige muito
13:24 trabalho. É possível gerar muitas coisas. O problema é que você precisa conhecer as regras. Por sorte, conseguimos obter algumas delas com especialistas ou na documentação disponível, mas não podemos garantir que haja cobertura de tudo. Então, também criamos nossas próprias regras, e assim por diante. No fim, geramos 275 testes que sabemos que podem ser executados e cujas respostas conhecemos. Então, como em RAG, invertemos o problema: inserimos o problema e tentamos encontrá-lo
13:56 de volta. Outra abordagem, que é muito difícil: pegamos um exemplo de contrato assinado, removemos uma cláusula, e o agent deve dizer: “Ei, está faltando algo aqui.” É uma tarefa muito difícil, porque alguns fornecedores usam templates diferentes e têm tipos diferentes de conteúdo. Saber o que deveria estar em cada contrato exige um pouco de reflexão. E combinamos isso com contratos existentes
14:27 que não deveriam gerar nenhum alerta. Essa é a abordagem mais poderosa que temos hoje. Usando-a, podemos gerar muitos contratos e, no fim das contas, descobrimos que nossos agents não identificam a maioria das cláusulas removidas. Então, esse é um benchmark muito, muito forte. Certo. A quarta técnica: você altera algo que não deveria afetar o agent, algo que não deveria mudar nada no
14:57 resultado. Por exemplo, o nome do fornecedor, o endereço do fornecedor, algo que não deveria ter nenhum impacto no número de alertas. Você pode reordenar as cláusulas; um pouco de aleatoriedade também deveria levar aos mesmos resultados. E pode executar o mesmo contrato várias vezes. Verificamos todas essas coisas para garantir que a saída seja consistente em todos esses casos. Neste exemplo, tudo pode ser verificado usando código.
15:27 Você não precisa usar LLM as a judge. O palestrante anterior mostrou que é uma tarefa muito difícil. Então, evitamos usar LLM as a judge tanto quanto possível. A quinta técnica é o conceito de template. Nossos especialistas têm diferentes tipos de templates com espaços em branco. Não sei se vocês já redigiram um contrato. Esses espaços em branco devem ser preenchidos pelo especialista. Em vez de tentar preenchê-los, geramos
15:58 um array de valores para preencher cada um desses espaços em branco. Isso nos permite gerar muitos contratos. Algumas combinações violam regras, outras não. Sabemos disso. Então, sabemos o que deve ser sinalizado como violação e o que não deve. Mais uma vez, isso é uma verificação feita por código. Não precisamos envolver nenhum LLM. O bom dessa abordagem é que nossos especialistas já usam templates, então podemos reutilizá-los para gerar alguns contratos.
16:29 Então, neste caso, o ciclo foi um pouco mais lento: quatro semanas para receber um feedback, e podemos obter um script para executar e receber a avaliação em cinco minutos. Só quero destacar um ponto: passamos por todas essas categorias de avaliação, que aparecem na parte inferior. Correspondência exata ou código são muito rápidos. Quando chegamos ao LLM as a judge, ele pode ser muito sofisticado e muito útil. É muito difícil. Recebemos muito mais ruído
16:59 do LLM as a judge do que do agent que estamos construindo. Resolver esse problema é quase tão difícil quanto resolver o problema certo. Então, encontrar o prompt certo e o harness certo para o LLM as a judge é uma tarefa muito difícil. Há alguns ajustes que você pode fazer. Você pode verificar os fatos. Pode fazer várias outras coisas, mas isso exige muito trabalho, e não conseguimos encontrar a abordagem certa para este projeto. Há muitas outras técnicas. Eu
17:31 Não vou passar por todos eles. Por exemplo, trajetórias. Temos outro projeto que exige que o agent acesse alguns endpoints. Então, com trajetórias, você pode saber qual deve ser o ponto final em determinada ordem. Você gera uma história sobre isso. Pede ao LM para preencher, usar o agent e analisar o trace para ver se a trajetória está correta. Teste de texto para SQL, talvez você já conheça. Não importa qual seja o seu agent. Se você sabe como escolher a resposta, se sabe o que está procurando,
18:01 e mostrei alguns exemplos. Gere a entrada e depois tente encontrá-la. Isso não se aplica a tudo. E, às vezes, tivemos que reprojetar nossa solução para se adequar a esse paradigma, mesmo que nos afastássemos um pouco do projeto original da solução. Com o projeto original, não conseguíamos avaliá-la. Mudamos para algo que de fato pudéssemos avaliar por causa disso. Uma coisa a destacar não é
18:31 o fim do dia. Você gera o teste. Consegue um agent melhor. Recebe feedback real. Então, especialistas podem dar feedback, e não usamos esse feedback para corrigir o agent. Usamos esse feedback para gerar testes melhores. Um prompt melhor. Ideias melhores para remover cláusulas etc. E um ciclo de cada vez. Isso pode ser feito com o Rise. Há muitas ferramentas por aí. Obrigado pelo convite. >> [fungada] >> E esse é o meu slide de conclusão. Por que
19:03 a resposta primeiro? Acho que expliquei isso. Quando você gera esses testes, não basta saber se pode lançar o produto. É só um ponto de partida. É uma ferramenta para ajudar a antecipar as necessidades do desenvolvedor. Não é o critério de aprovação ou reprovação da solução. Espero que tenham gostado desta apresentação. Sei que a entrega em 24 horas é a parte mais difícil. Se quiser parar de
19:33 lançar agents sem avaliação, ficarei feliz em ajudar e receber o seu feedback. Muito obrigado.
Transcrição original
[00:01] [music] >> Thank you for joining this station. It’s a bit of an emotional one. My name is Nathaniel. And I’m a non-evaluator. It’s been a lot of time since the last agent I’ve been shipping without any evaluation. And today I want to tell you the story
[00:32] how I quit this addiction of shipping an agent without any evaluation. So, I’m working at Air Canada. So, compared to the previous talk, it’s more like focus on specific business. I joined Air Canada in June of this year. And Air Canada is a huge company. We work in operation, corporate, commercial, and loyalty. Each of those segments have their own challenges. So, my team is in charge of delivering AI solution for all of those.
[01:04] And the problem when we tackle task we create an agent for a task that is so specific, we don’t have any public benchmark we can rely on. And that’s the main main problem we I’m trying to address in this presentation. More importantly, it’s not that we don’t have a benchmark, is we are data scientists that can build agents or AI engineers that can build agents, but we are not domain experts. And those domain experts sit in
[01:34] different business units. And they are very busy in their own task. And we have a limited access to that. So, both of those things went together in a situation where it’s very hard for us to build any evaluation or any any benchmark for our task. So, before going to Air Canada, I was working for a different company. It was a company that and the task was to build a a Q&A assistant for telecommunication engineer.
[02:05] So, I don’t know if you’re familiar with the domain. The telecommunication is a huge domain. There is about 10,000 documents. A lot of vendor documents on top of that. There’s a logic to know which document you should you should find in order to answer the question. So, it’s it’s a bit of a complex task. And then 2024, everybody wanted to build RAGs. So, we started to do that. Yeah, on LinkedIn it’s super easy. It’s not. So, um The thing is when we tackle this
[02:36] project, the same problem as at Air Canada, we don’t have access to expert. We have the limited access to experts. And we we could not actually grade the answer ourselves. So, that’s the the problem I I want to talk today. Funny enough, uh we were in competition with other teams. Um, two external, one internal. It’s not like in parallel, but in segments. And our solution actually worked. What mean worked is actually delivering the value. The people liked the solution, actually
[03:07] used it. Uh, but to be honest, I don’t know why we actually made it work compared to the other the other team. So, today I’m just going to show what I actually did or my team actually did to make it work. Um, so the the all have the same document, same task, everything is the same, but our solution somehow worked. So, for those that are familiar with RAGs, um the principle is very is is to ask a question to the system, the system found
[03:38] the the relevant documents, based on this relevant document, formulate an answer. It’s something that exists for a long time now. And for those that actually tried it, if you found the right page or the right documents, 19 90% of the time you have actually the right answer. So, the challenge to find the right documents, at least in this task. So, we created a very complex pipeline that get complexified over time if you publication if you found publication back in the time this everybody has an
[04:10] amazing technique to improve the the solution. We try them. It’s actually didn’t improve the solution. So, on paper it worked for them for the publication but for us it didn’t really help. And more importantly when we add complexity, we found that like we break something else. So, something that used to work now is not working anymore. And that’s actually the the real problem. So, we can add and more we can get more ideas on into solving the different problems but we we keep continue we keep breaking
[04:41] things over and over. So, complexity doesn’t always help. And the other problem is this one. Uh we can change an agent in few minutes, add a certain layer of query writing or whatever reasoning step. But to grade that, we had those crazy meeting once a week with experts. We put a giant giant screen with five different chatbot, ask the same question to all of them and ask the the expert to grade them. I prefer this one, I prefer
[05:13] this one. And funny enough they’re not always agreeing. It’s very hard when you when you put expert to explain the room you get three opinions. So, that’s the the the problem we were facing. And so, our budget was we can try one solution a week and this was not enough to go fast. So, the before uh going further so, the the the the process was the following. We ask we ask a question the agent answer. We ask the expert to read. Sometimes they don’t know the answer. They have to look up.
[05:44] It takes a lot of time. And we had the budget of one trial a week. Um, so there is nothing new here. This abiding that is well known is we reverse the problem. So we start with a page. We ask an LLM to write a question about this page, which is uh an easy task. We ask the agent to search for this answer and compare to what the agent found, compared to the to the page that has been used for to
[06:15] generate the question. We can actually use code to grade that. And no longer opinions, no longer anything. We can automate this task. And that allow us to go much much faster. So for those that work in rags, there is plenty of implementation of this thing. I didn’t invented it. I just found it very very uh very smart. And it stick to me. Like why this principle cannot be applied to other task?
[06:45] So the impact of that is we went from one evaluation a week to dozens a day. And we start to see the the accuracy of the the the grading from the expert going up and up. And actually removing a lot of complexity help. Like we didn’t need a lot of those. And focusing on the right uh embedding model, the right chunking, the right alpha in the BM25 uh is the right thing to do. And we we saw the we saw the the accuracy increasing over over weeks. >> [snorts] >> So I don’t know why we succeeded, but
[07:17] I’m pretty sure the other team didn’t had any test set. So they were using this kind of long loop with expert maybe a much more expert than we had access to. But we had it uh we had this test set. And my learning from this uh back in 2024 is if you cannot grade the agent, uh you can’t make it better. So that stick to me until this day has been 2 years now. And I want to go back to Air Canada now.
[07:47] Where we have a different project. So in 2026 the project is about analyzing supplier contract. So you can imagine Air Canada has a lot of suppliers. We get a lot of those contract. There’s expert looking at them one by one. Checking each of those clauses. And they have to analyze it and provide a feedback. Like this clause is not compliant. This clause needs to be rewritten. Like there’s a lot of work to do that.
[08:18] It’s a very long task and very costly because if we need the if we need some supplier to deliver right now and we don’t, then it cause a lot of delay in the in the chain. And if we miss a clause, it’s also very costly because at at the end of the day it can backfire to us. So it’s a tricky problem. Um and they came to me I mean to the to the data science team to build an agent that can actually do that for them. So can we automatize this
[08:48] task? And obviously there’s a lot of documents, a lot of rules, a lot of things to consider when you do that. Uh expert are super busy. You can imagine the price of of a lawyer by hour. And there’s no benchmark for that. We cannot go on the web and found documents I found an existing benchmark we can apply. So go back to the same problem as I was in 2024. Uh cycle were super slow and we knew
[09:18] that we want to be there in a in a in in a in a in a shape where we can go fast and try and try and try. Um and I knew that if we if we learn to this situation, we can have a better trajectory in term of accuracy. And that What the challenge for this uh for this project? So, the the problem is creating the answer from documents is a well-known and defined thing in the rags, but for this specific project, there’s no guy in the world that say, “Hey, you should use this technique. You should
[09:49] use this technique.” So, we try to think how we can reapply the same mechanism from what I learned on rag to this specific project. And we have plenty of project at Air Canada. So, we’re using the same concept of getting the answer first and then try the agent to find it back. So, going into the details, uh it’s a bit simplified, but actually the um the agent has four steps. Uh we need to spot the clause in the contract. We need to find the relevant documents
[10:21] to support an amendment. Uh we need to write the the amendment. And then at the end, there’s a classification system that tells you should we keep it or not uh this amendment. So, the first step, for example, spot is classifying all the section of the contract into specific domain domains. And then found if there’s a defect or there’s a change to be to be done in this section. So, we did have this trick from the rag. So, we know how to find the documents. So, this is covered.
[10:51] Uh but for the other other section of the um of the agent, we didn’t have anything. So, I going to present five different techniques that we use in this project or we try to use in this project. That is trying to address this specific problem. My goal is not to show off. My goal is to get you inspired in how to reapply those techniques in your own uh challenges. So, the first one is to use past
[11:21] decision and answer. So, we we you can retrieve past contract, compare with the one that has been changed. The second one is to choose something you’re looking for, write the contract around or generate the contract. The third one is uh take a good contract that has been signed and break it. Um the fourth one is about things that should not change no matter what you do, you should not get more flags. And the fifth one is actually the most
[11:52] powerful. It’s very hard. It’s to turn an example into many using the concept of templates. So, immediately we jump into this approach. Uh we ask the expert to provide us the original contract, the one that has been signed. We’re going to take that, do a diff like you do in the code, compare what has been changed, and the agent should should provide the same exact flags. That would be perfect. However, for many reason, our our team do not keep all the
[12:23] contract. Um they don’t keep the original one, they just keep the last one, they don’t have all the version of the contracts. It sometimes goes into negotiation, there is a lot of things. So, we could not have any of those pairs of contracts, so this thing doesn’t work. Okay, second one. We took a rule. And so, that’s changing a bit the topic. Um instead of creating um flags or creating an agent that can provide flags,
[12:54] we start from rules. And the rule is, for example, we have the the cap above $1 million. So, that’s every contract that Arcada should follow this rule or many of those in specific domains. So, you know the rule, you create uh a clause without breaking this rule and generate the contract around, and you should found um the rule back the the flag, which is breaking the rule. So, that’s simple. It doesn’t require a lot of
[13:24] uh of work. A a of things can be generated. The problem is you need to know the rules. So, luckily enough, we could actually get some of those from either the expert or the documentation they had, uh but cannot guarantee the coverage of everything. So, we came up we also with our own rules, etc. So, we generate at the end uh 275 tests that we know can run and we know the answer. So, similar to the rug, we inverse it we inverted the problem, we planted the problem, and we try to find
[13:56] it back. Another one which is a very hard, actually, uh we took an example of a contract that has been signed, we remove a clause, and the agent is supposed to say, “Hey, there’s something missing here.” Um it’s a very hard task because some supplier has different templates, have different kind of content. Knowing what should be in what contract require a bit of thinking. Uh and we mix those with existing contract
[14:27] that should not show any flag. So, that’s the most powerful approach what that we had today. Um using this approach, we can generate a lot of contract, and at the end of the day, we found that our agents are missing uh most of the clause that has been removed. So, that’s a very very strong benchmark. Okay. Uh fourth technique, um you don’t change you change something that should not affect the agent or should should not change anything in the
[14:57] result. For example, the name of the supplier, the address of the supplier, something that should not have any impact on the number of flags. Um you can reorder the clause, so some randomness should also lead to the same results. Uh and you can run the same uh contract again and again. All of those are things that we check to make sure that the the output is consistent over all of those. In this example two, everything can be checked using code.
[15:27] You don’t need to do any LLM as a judge. The previous uh speaker showed like it’s very hard task. So, we stay away from uh LLM as a judge as much as possible. The fifth one, um it’s the concept of template. Our expert have different kind of templates with blank. So, I don’t know if you ever write a contract. Those blanks should be filled by the expert. And instead of trying to fill them, we generate um
[15:58] an array for each of those blanks to be filled with. So, that’s allow us to generate plenty of contracts. Some tuples break some rules, some tuples doesn’t. We know that. And so, we know what actually should be flagged as a as a as a breach or not. Again, this is a code check. We don’t need to have any LLM involved. Um What What The good thing is with this one is our expert already use templates, so we can reuse them to generate some contracts.
[16:29] So, the cycle was a bit slower in this case, so 4 weeks to get a a feedback, and we can get a script to run and get the the evaluation back in 5 minutes. So, I just want to highlight one point, and we went through all of those um kind of categories of grading at the at the bottom. Exact match or code that are very fast. As soon as we step into LLM as a judge, uh it’s can be very fancy, it can be very useful. It’s so hard. Like, we got so much noise
[16:59] from the LLM as a judge compared to the noise with the with the agent that we building. Solving this problem is actually almost as hard as solving the the the right problem. So, finding the right prompt of the right harness for the LLM as a judge is a very hard task. There’s some padding you can do. task. You can do fact checking. You can do a bunch of stuff, but actually it require so much work and we could not found the right one for this project. There’s plenty of other techniques. I
[17:31] won’t go over all of them. For example, trajectory. We have another project that require the agent to eat some hand points. So, trajectory you can you you know what the end point should be in some order. You generate a story about it. You ask the LM to fill to use the agent and look at the trace to to see if the the trajectory is correct. Test to SQL, you might already know it. Doesn’t matter what your agent is. If you know how to pick the answer, if you know what you’re looking for,
[18:01] and I showed a couple of examples. Generate the input and then try try to find it. Doesn’t apply to everything. And sometime we had to re-engineer our solution to fit this paradigm, even if we move away slightly from the original design of the solution. We could with the original design we could not evaluate it. We switched to something that we can actually evaluate because of that. Um one thing to highlight is not
[18:31] the end of the day. You generate the test. You get a better agent. You get some real feedback. So, expert can provide some feedback and we don’t use this feedback to fix the agent. We use this feedback to generate better test. Better prompt. Better ideas how to remove clauses, etc. etc. And one loop at a time. Uh that can be done by Rise. There’s a lot of tools there. Thanks for the invitation. >> [snorts] >> Um and that’s my conclusion slide. Why
[19:03] the answer first? Um I think I I explained that. Um When you generate those tests, it’s not enough to know if you can ship the product. Just a starting point. It’s a tool to help anticipate the developer. It’s not the go no go for the for the solution. So I hope you like this this presentation. I know that the 24 hour chip is the hardest one. If you want to quit
[19:33] releasing agent without evaluation and I would be happy to support you and have your own feedback. Thank you very much.