Busca vetorial não basta: busca híbrida e recuperação — Jeff Vestal e James Williams, Elastic
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: Vector Isn’t Enough: Hybrid Search & Retrieval — Jeff Vestal & James Williams, Elastic · Canal: AI Engineer · 1:15:58 · Assistir no YouTube
Tópicos: Agentes de IA, Avaliação e benchmarks de IA, Dados, bancos de dados e embeddings, RAG, busca e recuperação de informação
Jeff Vestal e James Williams, da Elastic, conduzem um workshop prático sobre recuperação de informações para aplicações com LLMs e agents. Eles explicam como combinar busca semântica com busca lexical BM25, quando usar hybrid search e como ajustar a combinação com Reciprocal Rank Fusion (RRF) ou combinação linear. O workshop também demonstra o uso do Agent Builder para recuperar dados, citar fontes e executar tarefas com ferramentas, além de apresentar rerankers para melhorar a relevância. Os palestrantes destacam que a escolha das técnicas depende dos dados, das metas de relevância e do orçamento de latência.
Pontos-chave
Seção intitulada “Pontos-chave”- A qualidade das respostas de um LLM depende da qualidade das informações recuperadas e fornecidas a ele.
- A busca semântica é útil para encontrar conteúdos com significado semelhante, mas pode falhar em consultas com termos exatos, como IDs de produto.
- BM25 continua sendo útil para consultas por palavras-chave e, combinado à busca semântica, pode melhorar a recuperação.
- RRF combina resultados com base na posição de cada documento nas listas, enquanto a combinação linear normaliza e pondera pontuações.
- Filtros por palavras-chave, localização ou data podem reduzir o conjunto de candidatos e melhorar a recuperação.
- Rerankers reavaliam um conjunto menor de resultados, combinando a consulta e os documentos durante a pontuação; isso pode melhorar a precisão, com custo adicional de latência.
- O Agent Builder permite criar agents, skills e ferramentas, consultar dados e conectar-se a workflows, APIs e servidores MCP.
- A citação de fontes ajuda a verificar respostas geradas com informações recuperadas.
- A busca precisa ser avaliada e ajustada para o corpus e os objetivos de relevância específicos de cada aplicação.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:12 | Apresentação e início do workshop | Jeff Vestal e James Williams se apresentam e explicam como acessar o ambiente prático. |
| 06:35 | Inferência, modelos e chunking | Os palestrantes apresentam o Elastic Inference Service e explicam as opções de divisão de documentos em chunks. |
| 12:00 | Busca semântica e embeddings | A demonstração explica como a busca vetorial usa embeddings e em quais consultas ela pode falhar. |
| 17:27 | Busca lexical e limitações da busca vetorial | BM25 e outras técnicas lexicais ajudam a recuperar termos exatos, como IDs e palavras-chave específicas. |
| 21:16 | Grafos, classificação e extração de entidades | A conversa aborda a busca baseada em grafos e o uso de modelos de classificação e reconhecimento de entidades. |
| 27:14 | Escolha de métodos e reranking | Os palestrantes recomendam começar com BM25 e busca semântica e adicionar reranking quando necessário. |
| 33:46 | Ajuste de relevância e telemetry | A discussão explora como consultas, cliques e feedback dos usuários poderiam orientar o ajuste da relevância. |
| 37:01 | Combinação de busca semântica e lexical | O workshop compara RRF e combinação linear e mostra como filtros e conjuntos de julgamento ajudam a ajustar resultados. |
| 44:00 | Recuperação de dados para agents | A demonstração mostra como informações recuperadas afetam as respostas de um LLM e introduz o Agent Builder. |
| 50:12 | Citação de fontes e componentes do Agent Builder | Os palestrantes mostram como fornecer fontes ao modelo e descrevem skills, tools e agents. |
| 55:06 | ESQL, índices e tools | A apresentação explica como ESQL e ferramentas de busca de índices ajudam agents a consultar dados. |
| 1:00:31 | Consultas ESQL e busca híbrida | Os palestrantes destacam recursos de ESQL e demonstram uma consulta de busca híbrida com trilha de auditoria. |
| 1:05:24 | Rerankers e recuperação em duas fases | O workshop explica como rerankers reordenam um conjunto reduzido de candidatos e compara métodos pointwise e listwise. |
| 1:12:08 | Encerramento e recursos adicionais | Os apresentadores mostram como executar reranking e indicam workshops e materiais complementares. |
Citações
Seção intitulada “Citações”Se você fornecer dados ruins a esses modelos e disser com confiança que essa é a resposta, eles provavelmente vão acreditar. — 02:51
Se a combinação de BM25 e busca semântica atingir a meta de recall ou precisão, pare por aí. — 27:48
Uma das coisas que surge cada vez mais é a capacidade de citar as fontes. — 50:43
Se a precisão dessa ordenação for crítica, é aí que entra o custo adicional de latência. — 1:08:18
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- Jeff Vestal (pessoa): Arquiteto de IA da Elastic e um dos apresentadores do workshop.
- James Williams (pessoa): Arquiteto de soluções focado em busca na Elastic e um dos apresentadores do workshop.
- Elastic (empresa): Empresa cujas tecnologias e recursos de busca são apresentados no workshop.
- Elasticsearch (ferramenta): Plataforma de busca usada nos exercícios para indexar dados e executar consultas.
- hybrid search (conceito): Abordagem que combina busca lexical, como BM25, e busca semântica vetorial.
- BM25 (conceito): Método de busca lexical que recupera documentos com base em correspondências de termos.
- semantic search (conceito): Busca que usa embeddings para encontrar documentos semelhantes em significado à consulta.
- embedding (conceito): Representação vetorial de texto usada para realizar busca semântica.
- Reciprocal Rank Fusion (conceito): Método de combinação de resultados que usa a posição dos documentos em diferentes listas de busca.
- reranking (conceito): Reordenação de um conjunto de resultados recuperados, pontuando em conjunto a consulta e os documentos.
- Elastic Inference Service (ferramenta): Serviço de inferência apresentado como opção para executar modelos usados na geração de embeddings e no reranking.
- Agent Builder (ferramenta): Plataforma da Elastic apresentada para criar agents, configurar ferramentas e consultar dados.
- ESQL (ferramenta): Linguagem de consulta semelhante a SQL, com comandos encadeados por pipes, usada na Elastic.
- MCP (conceito): Protocolo que permite conectar tools e agents a serviços externos.
- HNSW (conceito): Estrutura de grafo usada para acelerar a busca aproximada de vizinhos mais próximos em vetores.
- GINA (modelo): Família de modelos mencionada para tarefas de embeddings densos e reranking.
- Elastic Serverless (ferramenta): Ambiente serverless usado nos exercícios para provisionar uma instância de busca.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:12 Obrigado por virem. Meu nome é Jeff Vestal. Trabalho na Elastic. Sou arquiteto de IA. Escolhemos um novo título este ano para deixá-lo relevante. Este é o James. Quer se apresentar? >> Sim, sou James Williams. Sou arquiteto de soluções, com foco em busca. Então, ajudo os clientes com toda a parte técnica que vocês vão ver hoje. >> Este será um workshop bem prático; não pretendo falar muito. Tenho falado bastante ultimamente nas viagens, então vou falar pouco aqui.
00:43 Vocês vão trabalhar com atividades práticas. No canto superior direito, vocês verão aquele URL curto. É uma URL da Elastic. Esse é o ambiente do workshop. Uma observação rápida: nunca me disseram quantas pessoas viriam, então chutei 75. Parece que subestimei um pouco. 75 de vocês vão conseguir iniciar o ambiente bem rápido. Para o restante, que está um pouco mais lento para começar, vai levar só alguns minutos a mais. Basicamente, isso vai levar vocês a
01:14 um ambiente do Instruqt. Depois, vou fazer uma breve introdução. Estou explicando isso enquanto o ambiente inicia. Vamos lá. Vocês vão acessar aqui e clicar em “Start”, e isso vai iniciar um ambiente para vocês. Enquanto isso acontece, quantas pessoas conhecem a Elastic, a empresa, ou o Elasticsearch? Muito bem, temos uma boa participação. E quantas já usaram a Elastic para criar um aplicativo baseado em RAG, com geração aumentada por recuperação
01:47 de informações? Ótimo. Quantos estão cansados de ouvir o termo RAG nos últimos dois ou três anos? Excelente. Sei que falei isso umas mil vezes em várias conferências, e meu chefe, que já não trabalha mais aqui, costumava ficar muito irritado quando continuávamos falando de RAG. A questão é que a geração aumentada por recuperação não desapareceu de verdade. Felizmente, só ficou um pouco em segundo plano. Mas, à medida que os agents foram ficando cada vez mais capazes e eficazes, eles acabaram assumindo a tarefa de conseguir
02:20 recuperar dados e analisá-los. Então, os modelos estão ficando cada vez mais inteligentes. O Fable apareceu por um instante, nos provocou e depois foi embora. Mas ainda é necessário trazer informações para esses modelos, sejam informações que mudam com o tempo, informações proprietárias, dados de preços ou qualquer outra coisa com a qual, esperamos, o modelo não tenha sido treinado, quer nos digam isso ou não. Essa necessidade existe, e é aí que entram coisas como o Elasticsearch. Ele é a camada de recuperação
02:51 que ajuda a tornar esses agents muito capazes. E o truque, ou o porém, é que, se vocês alimentarem esses modelos, por mais inteligentes que sejam, com dados ruins e disserem com confiança que aquilo é a resposta, eles provavelmente vão acreditar, porque é isso que vocês estão dizendo a eles. Então, queremos conseguir fornecer informações precisas e apresentá-las. É mais ou menos disso que trata este workshop. Tenho certeza de que há outros 20 workshops que explicam como criar agents, e nós também temos alguns, caso queiram acessar nosso site, mas
03:22 este vai relembrar vocês sobre busca vetorial e busca semântica, por que são importantes e onde são úteis, mas também onde falham. Depois, vamos abordar a busca lexical, o BM25, ou seja, a busca por palavras-chave que fazemos há décadas, e em que ela ainda é relevante e útil hoje, além de ver onde ela também falha. Em seguida, vamos combinar as duas abordagens na busca híbrida, para aproveitar o melhor de ambas. Faremos combinações com RRF, que é uma combinação pronta para uso.
03:54 Depois, faremos uma combinação linear um pouco mais avançada, na qual vocês podem ajustar um pouco esses pesos. E, se tiverem tempo, vamos colocá-la na plataforma Agent Builder da Elastic, para vocês verem o que acontece quando recuperam informações ruins e dizem ao agent que elas estão corretas: não funciona. Quer dizer, funciona, mas ele dá uma resposta ruim. E, se vocês fornecerem as respostas corretas e coisas do tipo… Se forem muito rápidos e chegarem até o fim, há um
04:24 bônus sobre rerankers. Vamos ver em que situações o reranking é útil. O workshop é basicamente composto por quatro capítulos de atividades, mais um bônus. Cada capítulo tem duas partes. A primeira é no console Dev Tools, onde vocês executam comandos de API no Elasticsearch. Em cada um desses ambientes, quando vocês clicam em “Start” e tudo mais, o que acontece é que uma instância serverless é iniciada para vocês. Depois, vocês carregam alguns dados. É um conjunto de dados pequeno, afinal, é um workshop, então
04:56 nada muito complicado. Vocês vão executar a versão resumida de cada atividade no console Dev Tools e depois passar para uma aba com um notebook Python, onde vão executar a versão mais detalhada. O que eu diria é que vou parar de falar daqui a pouco e deixar vocês trabalharem no workshop; depois, a cada 20 ou 25 minutos, vamos fazer uma pausa para ver como vocês estão indo. Vou fazer um breve resumo do desafio do capítulo em que estiverem. Para aproveitar ao máximo este workshop, eu recomendo que vocês leiam o que está no notebook Jupyter, especialmente porque ele explica
05:29 por que os documentos aparecem naquela ordem, como ajustar isso, como fazer o tuning e por que isso é importante. Se vocês simplesmente clicarem em “Run All” no notebook e passarem por tudo rapidamente, vão terminar em 10 minutos. Mas, se realmente dedicarem tempo ao conteúdo, provavelmente vão precisar de mais tempo do que dura esta sessão do workshop. Então, com isso, vou deixar vocês começarem. Alguns devem conseguir iniciar o ambiente imediatamente. Para outros, vai levar mais alguns minutos. Enquanto isso, alguém já conseguiu começar? Às vezes, leva alguns minutos. É isso. Sim, >> conseguimos. >> Certo. >> Se ficarem presos, levantem a mão.
06:01 Sou basicamente o facilitador. Vou conferir o que está acontecendo no sistema de vocês e, se for algo simples, tentar ajudar a resolver. Se tiverem alguma pergunta, fiquem à vontade para levantar a mão. Será um prazer explicar um pouco melhor o que está acontecendo no exercício, caso estejam olhando para algo e estejam um pouco confusos e queiram fazer uma pergunta. Tudo isso também está disponível em um repo que deve ser público. Sim, eu o deixei público.
06:35 Assim, vocês podem executar os notebooks fora do Instruqt, depois ou quando quiserem. >> Passei por isso meio por alto, mas acho que a grande mudança no RAG ao longo do último ano, ano e meio, é que alguns provedores de bancos de dados vetoriais — e nós estamos nesse grupo — passaram a incorporar inference ao banco de dados vetorial. Então, vocês vão ver a geração de embeddings acontecer no Elasticsearch Serverless. Temos um serviço de inference chamado Elastic
07:09 Inference Service. Um nome muito criativo, que disponibiliza os modelos usados nestes workshops. Temos modelos da Jina, de uma aquisição que fizemos. Então, agora também desenvolvemos nossos próprios modelos. O foco está principalmente em modelos de vetores densos e modelos de reranking. Assim, vocês vão conhecer algumas tecnologias novas que não faziam parte do Elasticsearch há um ano. Era só isso que eu queria acrescentar. >> Já ouvimos falar de chunking. >> Nós ajudamos com chunking, sim.
07:43 Sim, podemos responder a isso, e fique à vontade para entrar na conversa. Ele é gerente da equipe de especialistas em busca. Eu só fico circulando por aí. Como James mencionou, temos o campo de texto, o semantic text, no Elasticsearch. Há algumas maneiras de fazer isso. O semantic text é meio que a maneira automática e fácil, pronta para uso. Por padrão, dividimos o texto em partes nos limites entre frases, até chegar a uma determinada quantidade. Não lembro de cabeça qual é o número. >> 250. >> Isso mesmo. E isso é configurável. Por padrão, a divisão é feita nos limites entre frases, mas você também pode dividir nos limites entre palavras.
08:16 Você pode mudar isso. O modelo Jina que James mencionou — agora a Jina faz parte da gente, ou nós fazemos parte da Jina, seja como for. Ele tem uma context window muito, muito grande, mas nem sempre você vai querer preenchê-la, por vários motivos. Assim, você pode configurar a divisão em partes para ocorrer nos limites entre palavras, parágrafos, páginas e coisas do tipo. >> Temos um campo de mapeamento semântico no Elastic que basicamente recebe um trecho de texto e o divide em partes. Então, se você nos enviar cinco páginas de texto, vamos dividir esse texto
08:48 em partes de 250 token, com uma frase de sobreposição, e armazená-las no sistema para recuperação. Há frameworks que falam sobre divisão semântica em partes, e também há outros termos para o que vou chamar de divisão em partes para context window grande. Na verdade — e isso é abordado no laboratório, nas seções posteriores —, temos uma técnica que usamos chamada late chunking, que funciona com context windows grandes, mas ainda não está disponível pelo serviço de inference do Elastic.
09:20 Mas é algo compatível com os modelos Jina. É o mais próximo do que eu diria que temos de divisão semântica em partes. Mas, na verdade, não precisamos desse conceito, porque o próprio campo semantic text nos permite oferecer o mesmo resultado que você teria com a divisão semântica em partes, simplesmente dividindo os dados em partes e depois fazendo buscas sobre eles com uma abordagem semântica. Você vai ver isso em um laboratório. Então, resolveríamos o problema com a divisão tradicional em partes
09:50 e busca híbrida, não com algum esquema exótico de divisão semântica em partes. >> De nada. >> Certo. É. >> Sim. Deixei o acesso disponível por uma semana porque sei como as coisas são. Então, o acesso fica disponível por uma semana. E isso não está hospedado em nenhum lugar. O workshop está no meu repo, para o bem ou para o mal.
10:23 E todos os notebooks estão aqui. Então, se você quiser executar só os notebooks, pode conectá-los ao seu cluster serverless ou a qualquer tipo de cluster que deve funcionar, desde que tenha semantic text. Mas, sim, o workshop em si fica disponível por uma semana. Onde eu estava?
10:54 E, sim, como mencionei, a primeira parte, a primeira metade de cada laboratório, é este Dev Tools, onde você executa um mapeamento. O lado esquerdo é a entrada da sua API. O lado direito é a saída. Depois você chega à parte dois, em que abre o notebook Python, e ele se conecta automaticamente ao ambiente do Elasticsearch que foi iniciado para você. Vejo que estão deixando as pessoas entrar à medida que outras saem, para garantir que a sala continue cheia.
11:27 O canto superior direito tem o URL que você deve acessar. É lá que está todo o conteúdo do workshop. E há um segundo URL, que é o repo do código-fonte de todos os notebooks do workshop de hoje. Esses são os dois recursos mais úteis. Então, se você está chegando agora e ainda não iniciou o workshop, acesse o canto superior direito. E, se tiver interesse nos notebooks Python que dão suporte ao conteúdo que você vai acompanhar hoje, o URL está no canto inferior direito.
12:00 Provavelmente vou repetir essa mensagem sempre que vir alguém entrar. Essa é uma ótima pergunta. Vou repeti-la para que as outras pessoas também possam ouvir: um dos principais objetivos desta sequência de laboratórios é mostrar que a busca baseada em BM25 — a busca lexical tradicional que fazemos há muito tempo — e a busca semântica com vetores densos precisam ser combinadas para formar a busca híbrida?
12:31 Essa é a tese central que temos agora como empresa. E a única coisa que acrescentamos a isso — além do valor óbvio — é a opção de adicionar rerankers por cima. Mas, sim, essa é uma tese central, acreditamos firmemente nessa abordagem, e ela está alinhada com tudo que tenho visto desde antes mesmo de entrar na Elastic. Mesmo que você use apenas um banco de dados vetorial dedicado, muitas vezes precisa combiná-lo com outro sistema de recuperação e fazer o equivalente à busca híbrida. A
13:06 vantagem do Elastic, como vocês estão vendo nos laboratórios, é que tudo é feito com uma chamada de API. Cuidamos de toda a inference, desde a ingestão e a divisão em partes até a busca em tempo real, em que a consulta é convertida em um vetor de consulta. Fazemos todo o trabalho nos bastidores. É isso que consideramos muito valioso, especialmente em casos de uso em grande escala, em que latência, precisão e capacidade de ajuste são importantes.
13:40 As configurações são ajustáveis. As configurações da divisão em partes podem ser ajustadas? Podem. A documentação explica como alterá-las e quais configurações de divisão podem ser modificadas. Temos uma documentação de API bem detalhada que explica isso. Elas não são descritas em detalhes no workshop, mas, se você consultar a documentação do Elastic, verá quais são as configurações disponíveis para a divisão em partes. Alguns dos nossos clientes também trazem seus próprios vetores e fazem a divisão em partes por conta própria. Damos suporte a isso por meio dos SDKs padrão. Então, se você estiver usando Python, Java, .NET Core ou praticamente qualquer linguagem moderna, como TypeScript,
14:16 ainda pode usar o Elastic no formato destes workshops. Só vai ter mais trabalho como desenvolvedor. >> Tenho certeza de que as pessoas estão avançando, então podem continuar no próprio ritmo. Como eu disse, vou dar uma olhada de vez em quando e falar um pouco sobre os laboratórios. O primeiro, então, tem como objetivo principal mostrar este pequeno gráfico aqui, que explica como funciona a busca vetorial e a busca semântica, e o que você obtém com ela. Quando você usa um modelo de embedding conectado ao Elastic — e falamos da Jina como a opção pronta para uso, mas você certamente pode trazer o seu próprio modelo —,
14:47 você pode se conectar a outros serviços de inference. Só facilitamos para você começar com a Jina; mas, claro, você pode trazer seu próprio modelo e usar buscas semânticas ou também o semantic text. O interessante dessa configuração específica é que, quando você cria um embedding na hora da consulta — não, na hora da ingestão, você cria o embedding do seu documento —, na hora da consulta, precisa usar o mesmo modelo de embedding para processar a consulta. Caso contrário, é como eu tentando falar português: não daria muito certo.
15:18 Quando começamos a fazer isso, alguns anos atrás, nos primeiros tempos, você precisava acompanhar o ID de inference e o modelo. Aí, você tinha todos esses desenvolvedores e precisava garantir que todo mundo estivesse usando o modelo certo, entre outras coisas. Ao incorporar isso ao próprio campo, há duas vantagens. Primeiro, você só precisa configurar isso uma vez. E, como pessoa responsável por configurar o índice, pode haver outras pessoas usando esse mesmo índice para ingerir os próprios dados ou fazer consultas, certo? Então, você configura isso uma vez, seja para o modelo da Jina ou para outro modelo.
15:50 Sempre que você usa esse campo, ele simplesmente passa a ser como qualquer outro campo. Você envia dados ou faz uma consulta. Então, na hora da consulta, como está vendo aqui em cima, o texto é recebido. Ele pode ser dividido em partes ou não, dependendo do tamanho e das configurações. Depois, vai para o serviço de inference do Elastic, que talvez seja a opção padrão, pronta para uso. Ou talvez vá para outro serviço de inference. Tudo bem.
16:21 E então geramos os embeddings e os passamos de volta para o Elastic fazer o HNSW. Também temos outras opções de desconto. Temos ANN em disco, mas, por padrão, usamos HNSW, o grafo de pequenos mundos navegáveis hierárquicos. Basicamente, ele permite percorrer rapidamente o grafo para encontrar os vizinhos mais próximos de documentos relevantes. Depois, você recebe de volta seus documentos top k — cinco, dez, o que quiser — e isso permite, idealmente, se tudo estiver funcionando bem, encontrar documentos ou, sabe,
16:52 trechos que sejam semanticamente semelhantes ao que você está perguntando. E, como aprenderam no laboratório, não são as palavras-chave exatas, mas a ideia do que você está perguntando. Então, se todos nós nesta sala perguntarmos, por exemplo, como configurar a segurança no Elasticsearch, usando TLS, ou algo assim, cada um vai formular a pergunta de um jeito um pouco diferente, mas a ideia é a mesma. E, com sorte, vocês recebem de volta os mesmos documentos. E vocês viram que, às vezes, isso não funciona tão bem. Um dos principais casos é quando há uma palavra-chave muito específica. E, certamente, se a palavra-chave não for uma palavra
17:27 como um ID de produto, que não faz sentido por si só e é muito específico, a busca semântica meio que deixa de funcionar, porque não precisa disso. É aí que entra o segundo laboratório, no qual adicionamos BM25, busca lexical, filtragem por palavras-chave e todas as outras metodologias tradicionais de busca que usamos há muito tempo para complementar isso. Vou mostrar para vocês — tenho certeza de que alguns já avançaram além desse ponto —, mas daqui a alguns minutos vou verificar como estão e revisar o laboratório dois. E, de novo, se houver alguma dúvida, podem perguntar,
18:06 — Certo? Paginação. Sim, paginação. Se você tiver, por exemplo, cem resultados e quiser receber dez de cada vez, é isso que está perguntando? — Ah, sim. Dá para fazer isso. Há um… esqueci o nome exato, mas basicamente é um ID de checkpoint. E então a busca continua. Assim, você não precisa pesquisar de novo. Não está executando novamente a busca para essa parte. Ela continua de onde parou. Então, é isso que nossa API de paginação
18:39 faz. Se você sabe que isso é uma possibilidade, usa esse recurso, e nós enviamos essa chave; é basicamente como dizer: “É daqui que você começa e continua”. — Acho que o nome oficial é point in time. — Isso mesmo. Se estiver consultando a documentação do Elastic, basta pesquisar por point in time. Lá, explicam como usar point in time para fazer exatamente isso. — Ah, boa pergunta. O campo de resumo foi gerado especialmente para este workshop, por um LLM. Não faz exatamente parte disso. O motivo real é que, quando fiz isso pela primeira vez,
19:10 e exibimos todo o campo do corpo, ele ficou longo demais e estava poluindo tudo. Então, ter esse pequeno campo de resumo ajuda. Dito isso, você pode usar, por exemplo, um pipeline de ingestão no Elasticsearch e fazer uma chamada de inference para dizer: “Quero gerar um resumo deste documento” ou “Quero extrair as possíveis consultas que poderiam fazer isso”. Então, dá para fazer isso durante a ingestão. Só fizemos isso neste caso específico para facilitar. Mas o campo vetorial que vocês estão pesquisando é o título. — E, à medida que avançarmos nos laboratórios,
19:42 não usaremos essa estrutura, mas haverá chamadas à API de conclusão de LLM nos laboratórios seguintes, e será exatamente a mesma coisa. Basta conectar isso ao seu pipeline de ingestão. — Pergunta. — Ótima pergunta. Sobre o trabalho que fizemos para tornar o HNSW mais eficiente: isso começou há dois anos, na verdade, há mais de dois anos, quando introduzimos a quantização int8, que, acredito, ainda é o padrão. Por padrão, pegamos vetores float32 e os quantizamos
20:14 antes de armazená-los na memória. Ainda mantemos o vetor completo, mas só armazenamos o vetor quantizado na memória. Também temos BBQ, e temos uma publicação no blog que fala sobre BBQ. Isso foi há pouco mais de um ano, talvez até um pouco mais do que isso: comprimimos ainda mais o vetor do grafo HNSW que usamos, reduzindo-o basicamente a um bit. Há mecanismos sofisticados por trás disso que permitem
20:46 manter uma alta revocação. E então lançamos o disk BBQ, que praticamente elimina a sobrecarga de memória da busca vetorial. A única diferença, eu diria, entre o disk-based como mecanismo subjacente de busca… E a versão mais recente disso é proprietária do Elastic. Ninguém mais implementa isso.
21:16 [limpa a garganta] Busca baseada em grafos. Quer responder a essa? [risos] Busca baseada em grafos. Para deixar bem claro, não somos um banco de dados de grafos. Existem bancos de dados de grafos bem específicos. Grafos têm seu lugar. Em geral, há muita sobrecarga para mantê-los e administrá-los. Se você faz isso, ótimo. Mas, para a grande maioria das pessoas, vemos que isso não é realmente necessário, dada a capacidade de, especialmente com a quantização, pesquisar rapidamente em grandes volumes de
21:48 documentos. Isso é ainda mais relevante agora, com o mundo dos agents, em que você pode fazer várias consultas. Em um dos laboratórios mais adiante, por exemplo, são feitas algumas idas e voltas — acho que apenas duas —, mas você pode fazer a primeira etapa, obter uma amostra de documentos e então perceber: “Ah, certo, todos estão relacionados a esta tag”, e depois continuar a busca. É aí que recursos como filtragem e algumas de nossas outras metodologias de busca ajudam. Então, sim, isso aparece, mas não vemos isso, sabe, com muita frequência como
22:18 um impedimento real que obrigue você a configurar isso. — E a última coisa que vou dizer sobre isso é que vemos com muito mais frequência modelos de machine learning que fazem classificação em tempo real, o que é outra maneira de resolver esse desafio dos grafos. Funciona em algumas situações, mas não em todas. O Neo4j e outros bancos de dados de grafos existem há muito tempo. Não conheço nenhum que escale muito bem, e estamos tentando atender a conjuntos de dados com bilhões de vetores. Por isso, tomamos muito cuidado para não
22:49 introduzir uma estrutura que nos impeça de escalar nesse nível. E ainda não vimos necessidade de seguir por esse caminho, embora o assunto apareça bastante. Foi um grande tema no ano passado nesta conferência. Lembro de estar aqui e ver que Graph RAG foi muito discutido, e provavelmente continuará sendo. Ainda não vi uma tecnologia resolver isso de forma definitiva. Talvez haja alguém da Neo4j aqui que discorde de mim e diga: “Não, não, não. Já resolvemos isso”.
23:20 Acho que resolveram, mas não na escala em que operamos. — Sim. Ah, então você veio da sessão deles. Legal. Certo. Lá no fundo. Acho que a pergunta era se podemos usar modelos de classificação para obter alguns dos mesmos resultados que poderíamos obter com uma travessia de grafo. No Elastic, temos o conceito de executar modelos de machine learning em nós que chamamos de nós de ML.
23:53 Você poderia basicamente carregar qualquer modelo de classificação que tenha identificado como eficaz e conectá-lo ao Elastic dessa maneira. A outra opção seria criar seu próprio modelo, com seu próprio serviço externo de inference, e potencialmente usá-lo no lugar da nossa tecnologia de ML. Espero que, mais adiante, introduzamos mais recursos nessa área. Mas não temos nada importante para anunciar agora. Estamos focados em levar os modelos de genome que temos ao limite do que podemos fazer para lidar com dados não estruturados e vetores densos.
24:27 embeddings e rerankers. Provavelmente vamos acabar mudando de direção depois que acertarmos a parte de reranking e os modelos de vetores densos que estão em desenvolvimento e indo muito bem no mercado. Também vou acrescentar que, além disso, há modelos de classificação, e você também pode executar coisas como modelos de NE, de reconhecimento de entidades nomeadas. Então, se você extrair as entidades — se estiver tentando identificar pessoas, locais, nomes de empresas, coisas assim, ou nomes de produtos —
25:00 você pode executá-los em tempo real como parte da consulta. Quando a consulta chega, você a passa pelo modelo de NE. Os modelos de NE são muito rápidos porque são pequenos. São modelos realmente pequenos, e você extrai essas entidades. E, de novo, agora, com agents e coisas assim, você não precisa conectar scripts complicados e trabalhosos; o agent pode usar essas entidades e criar uma consulta mais adequada para isso. Então, há muitos recursos de ML sobre os quais não falamos tanto quanto antes, porque, como o Jim disse, meio que mudamos o foco para
25:32 outras coisas, mas eles ainda estão na stack e são muito capazes de fazer filtragem. Isso é ótimo. E aí, cara? Um dos nossos ilustres SAs ali no canto pode responder a todas as nossas perguntas. Vou redirecionar agora. Para quem chegou, além do Sneil, o canto superior direito tem a URL curta do workshop, e vocês podem acessá-la. Ela abre uma espécie de laboratório, um ambiente de laboratório para vocês, e também inicia um cluster do Elasticsearch Serverless já configurado para vocês.
26:07 Então, fiquem à vontade para acessá-lo. Há um ajuste principal para o reciprocal rank fusion, ou RRF, e é… estou tentando lembrar de cabeça, mas não sei. Você está abrindo aí. >> Não sei se expomos isso nos atributos do retriever para RRF.
26:43 Qual é a constante padrão? >> A constante de ranking. Ela pode ser configurada. Não sei qual é o intervalo. >> É isso que aparece no laboratório cinco, que é opcional. Ele é todo sobre… bem, o laboratório cinco é sobre reranking. O RRF está em algum lugar lá. Desculpem, por um segundo meu cérebro travou. Está em algum lugar lá; fala um pouco mais sobre o que o Sil está mencionando, com mais exemplos, e você pode mudar coisas assim. Então…
27:14 >> Então, não sei, isso respondeu à sua pergunta? >> Beleza. >> Pode mandar. Essa é uma ótima pergunta. Na verdade, há uma tabela que explica algumas dessas árvores de decisão no workshop mais adiante. Acho que é o workshop
27:48 número quatro. Mas a resposta curta é que, para um corpus pequeno de documentos, minha regra prática é sempre ver o que você consegue alcançar combinando BM25 e busca semântica. Se isso atingir a meta de recall ou precision que você está buscando, ou quaisquer metas de relevância que tenha, pare por aí. Sempre que você acrescenta algo além disso, assume uma latência adicional. Só faça isso se precisar. E o próximo ponto de extensão seria
28:18 usar um modelo de reranking e, depois, escolher aquele que você acha que vai funcionar melhor para o seu corpus, fazer alguns testes e validar se ele melhora os resultados o suficiente. Essa seria, digamos, a abordagem padrão mais direta. Algumas pessoas mudariam um pouco essa recomendação e diriam: olha, use apenas BM25, a busca normal, e depois acrescente a busca semântica se a relevância não for suficiente. Mas eu sou um
28:50 grande fã de vetores densos, então eu os integraria à arquitetura desde o início. Assim, não preciso me preocupar com situações estranhas em que você começa a adicionar sinônimos ou a usar técnicas avançadas de ajuste lexical que talvez não sejam necessárias se a busca semântica conseguir funcionar bem em conjunto com a busca lexical. >> Bem-vindos. Certo, sei que as pessoas estão avançando, o que é ótimo. Vou só fazer um breve resumo do laboratório dois, que, mais uma vez, era sobre sua busca lexical favorita
29:23 . Mas espero que vocês tenham aprendido — que tenha ficado claro — que ela tem seus méritos. Mal arranhamos a superfície da busca lexical, porque, por uns 15 anos — ou cerca de uma dúzia de anos na Elastic — era só o que tínhamos. Então, se você já acessou os sites de documentação do Elasticsearch e foi até a parte de busca e clicou na API de busca, há uma quantidade absurda de maneiras de alterar, ajustar e refinar a busca lexical. Porque
29:56 como o James comentou, antes de podermos fazer busca semântica, tínhamos que fazer todas essas coisas complicadas para obter resultados relevantes. Felizmente, agora não precisamos fazer tanta coisa, pelo menos na maioria das vezes — embora ainda precisemos de vez em quando. Mas a busca lexical tem seus méritos. Ainda assim, tende a falhar quando você deixa de procurar palavras-chave muito específicas ou uma frase muito específica. A vantagem é que ela é… nem quero dizer que geralmente é mais rápida. Embora, agora, com a quantização e coisas
30:27 assim, nem sempre seja o caso, mas, por padrão, ela tende a ser mais rápida. Então, no laboratório três, a maioria provavelmente já está nessa parte, mas vocês passam a combiná-las. E vou dizer que, embora eu seja um grande fã da busca com vetores densos, a busca lexical geralmente tem latência menor em quase todos os casos de uso, porque não há inference de ML acontecendo. Então, sempre que você usa busca semântica com vetores densos, introduz uma chamada a um endpoint de inference e mais
31:00 frequentemente do que não, esse endpoint de inference vai ser um gargalo maior do que o restante do sistema. E esse é outro motivo pelo qual integramos o inference à plataforma de dados: quando você faz testes de ponta a ponta, não importa se o seu banco de dados vetorial retorna vetores muito rápido. Se o inference do qual você depende for lento, sua busca será lenta. Acho que essa questão está mudando à medida que as plataformas de dados integram mais recursos aos sistemas e esses modelos melhoram. E cada fornecedor vai ter sua própria
31:34 abordagem específica. A nossa é que tudo começa com a busca tradicional, o que faz muito sentido, considerando nossa trajetória; depois, você adiciona recursos semânticos e, então, incorpora o reranking, se precisar. Quanto a onde tudo isso acontece, é aí que os detalhes fazem toda a diferença. Como desenvolvedor que tenta criar uma arquitetura em torno disso, você tem muitas opções. E, dependendo da stack com que começa, terá suas próprias percepções sobre o que deveria fazer na plataforma de dados
32:08 versus o que poderia ter em algum tipo de middleware ao redor dela, que faria essa integração. E estou usando a palavra middleware de forma meio vaga, mas existe toda uma estrutura de runtime de aplicações que desapareceu desde que começou esse boom da IA. Ela vai ter que voltar, e pode acabar ficando na própria plataforma de dados, onde fazemos inference e algumas dessas outras coisas que normalmente teriam que ser coordenadas com serviços externos, ou então vão surgir plataformas para tentar fazer isso
32:41 e, depois, usar a plataforma de dados simplesmente como algo que você conecta. Estou pensando em coisas à moda antiga, como quando comecei minha carreira em tecnologia e trabalhávamos com mapeamento objeto-relacional, e o banco de dados era, supostamente, conectável. Você troca as credenciais e não faz diferença, porque não está mais usando SQL. Acho que estamos nos primórdios da IA, em que, para fins de retrieval, assim que você começa a escrever código, fica preso à stack que escolheu
33:13 escolhido. E isso determina várias decisões de design diferentes que vocês precisam tomar, especialmente quando começam a escalar. E é aí que entramos e temos uma vantagem em relação ao que podemos chamar de uma stack mais simples: quando os volumes de dados aumentam e os requisitos de latência ficam mais — não quero dizer rigorosos, mas os SLAs ficam realmente apertados. É aí que vamos nos destacar, porque podemos fazer coisas que as outras plataformas não conseguem, e temos um nível de ajustabilidade, especialmente no lado da relevância, que não pode ser alcançado com outras
33:46 plataformas de dados. Essa é uma pergunta muito boa, que discutimos no laboratório, mas não acho que forneçamos uma resposta definitiva dizendo como construir os pesos com base em coisas que se podem deduzir do formato dos dados ou das buscas que os usuários provavelmente vão executar. A resposta curta é que, hoje, isso é difícil de fazer. A resposta mais longa é que — e acho que isso é algo que vocês vão ver vindo de nós — falta um elemento no ajuste de relevância
34:22 que ainda não foi abordado de uma forma que torne isso pronto para uso. Na verdade, publiquei uma arquitetura de referência há um ano. Ela precisa ser aprimorada. É baseada em Mashra sobre auto e trata de ajuste automático e desse conceito. Mas, num mundo ideal, seria possível usar as buscas que passam pelo sistema e a telemetria dessas experiências dos usuários, coisas como tráfego de cliques, avaliações positivas e negativas — basicamente, telemetria dos usuários. E também
34:54 quaisquer outras métricas de negócio que vocês tenham integrado ao caso de uso para, de fato, ajustar a relevância, o que poderia introduzir pesos diferentes para a combinação linear. Isso poderia alternar entre RF e combinação linear com pesos específicos, dependendo do tipo de consulta recebida, ou usar vários outros tipos de técnicas. A que acho mais comum, até mais do que essas duas, é criar conjuntos diferentes de filtros com base na consulta recebida. Sunnil criou a arquitetura original para isso. Nós
35:28 a chamamos de camada de busca inteligente. É algo que o Azure Search tentou integrar ao produto. Também é algo que vocês podem fazer hoje com o Elastic usando a estrutura do agent builder, abordada no último laboratório. Mas essa é uma técnica um pouco diferente de simplesmente ajustar os pesos em tempo real com base no que estamos observando. Nesse caso, vocês fariam o LLM analisar a consulta e, em seguida, executariam buscas com filtros diferentes com base nessa análise, o que eu
35:59 adoro. Acho essa técnica fantástica e fico feliz por termos uma estrutura para ela no Elastic. E é justamente para resolver esse tipo de problema que o agent builder foi criado. Sim. >> Exatamente. E é nisso que espero que trabalhemos. Ainda não anunciamos que vamos fazer isso, mas espero que, em algum momento, vocês vejam o conceito de relevância com ajuste automático como algo que possam ativar
36:31 e que possam especificar atributos ou configurações para ativá-lo e talvez até aumentar sua intensidade, dependendo do caso de uso e do que vocês observarem no uso real do sistema. E, só para deixar claro para todos na sala, ainda não lançamos nenhuma tecnologia que faça isso, mas o assunto surge com frequência suficiente no trabalho de campo com clientes que, se tivéssemos essa tecnologia, ela faria uma grande diferença e facilitaria muito a vida dos desenvolvedores. Você concorda?
37:01 >> Certo, vou mencionar isso de novo ao nosso CTO e fazê-lo dizer não mais uma vez. >> Certo. Então, vamos passar por este exemplo. A maioria de vocês provavelmente já passou por isso. Se não, tudo bem. Estamos tentando combinar aqui as duas metodologias diferentes, e o cerne do problema é — está em algum lugar por aqui — que o BM25 tem uma escala: ele dá notas aos documentos de zero até, mais ou menos, qualquer valor, enquanto a busca vetorial
37:35 normalmente vai de zero a um. Então, quando essas escalas não são iguais, obviamente um resultado ruim numa busca lexical BM25 quase sempre vai superar um bom resultado de busca semântica, se olharmos apenas para os valores numéricos. Aí começa a brincadeira de descobrir como combiná-las. Existem algumas maneiras diferentes. Não vamos abordar aqui como escolher uma delas
38:08 na hora, mas há diferentes formas de fazer isso. Vamos ver o básico. O RF foi projetado para funcionar razoavelmente bem logo de início, até deixar de funcionar. Mas é um bom ponto de partida. Não é preciso saber como ajustar, nem conhecer de fato os detalhes dos dados. A ideia é que, essencialmente, para o RF — há uma tabela aqui — vocês descartam
38:38 as pontuações. Então, executam as duas buscas em paralelo e usam a ordem. Há uma constante de posição no ranking aí, mas, essencialmente, se o documento do resultado aparece em uma posição alta nas duas listas, provavelmente é uma boa correspondência. Quando isso não acontece, é aí que a combinação entra em jogo. E há essa forma bem simples de pontuar aqui. Onde está? Passei por ela. E então há uma tabela. Portanto, o que vocês retornam não é uma lista de documentos com pontuações ordenadas por nota. É só a ordem no ranking.
39:11 E é por isso que há uma constante de posição no ranking: vocês estão obtendo apenas a posição dos documentos. Dá para ver aqui — onde isso está funcionando? Sim. A tabela explica que os documentos aparecem em ordens diferentes, mas, ao classificá-los, vocês esperam obter a melhor resposta. Mas isso nem sempre funciona.
39:44 E, na verdade, James mencionou isso há pouco: filtrar é uma maneira muito poderosa e eficaz de ajudar. Então, se vocês puderem filtrar os dados por palavra-chave, localização geográfica, data — qualquer coisa que reduza esse conjunto de dados a um grupo menor de candidatos —, normalmente vão obter resultados melhores. E, como o conjunto é menor, vocês não estão simplesmente lançando uma rede sobre tudo. Estão filtrando e restringindo os resultados, certo? É como se eu quisesse pizza hoje à noite: não iria simplesmente
40:17 pesquisar por comida, talvez. Mas, se pesquisasse por comida, poderia filtrar por pizza e pelo menos obteria resultados de pizza, coisas desse tipo. É aí que entra a filtragem. O Elastic Search faz isso muito, muito bem e muito rapidamente, e temos várias maneiras diferentes de fazê-lo. Mas aí chegamos ao fato de que isso nem sempre funciona. Então, vocês podem usar uma combinação linear. Falamos aqui sobre minmax. Há várias coisas que vocês podem fazer. Mas é aqui que vocês
40:48 normalizam as pontuações. Em vez de usar a ordem, vocês normalizam as pontuações. Assim, tudo passa a ter a mesma faixa de pontuação, de zero a um, e vocês podem combinar os valores. Há alguns exemplos de ajuste aqui. É, com certeza, uma introdução ao ajuste, mas vocês podem ajustar os pesos e ver qual funciona melhor. É aqui que entram os conjuntos de julgamento. E é aqui que coisas como — temos vários workshops e coisas do tipo —
41:23 a camada de consulta inteligente e outras ferramentas fazem isso de maneira mais automática, embora não sofisticada. Mas, essencialmente, vocês têm os julgamentos que, hoje em dia, uma pessoa define — dá para pedir ajuda a um LLM — com base nesta consulta: “estes são exatamente os documentos que quero”. Depois, executam os experimentos e veem quais pesos funcionam melhor para obter esses resultados com a maior precisão possível. Quer acrescentar algo?
41:54 Desculpe. E vou acrescentar mais um item, porque essa é, na verdade, uma técnica que usamos na arquitetura de camada de consulta inteligente sobre a qual falamos bastante no ano passado e no ano anterior. A Elastic oferece o conceito de search templates. Então, tecnicamente, você poderia ter três estratégias de busca diferentes: uma que usa RF, uma que usa busca linear e talvez outra que usa uma combinação de busca linear ou RF
42:27 com um reranker. E, se você tiver uma camada por cima — vamos chamá-la de LLM — com um prompt simples que diz: “Com base neste tipo de consulta, quero que você encaminhe para este search template. Com base neste outro tipo de consulta, quero que você encaminhe para este search template”, você pode literalmente ter o equivalente ao que vou chamar de ajuste automático improvisado, alternando entre diferentes estratégias de busca com base na aparência da consulta recebida. E você tem algo — não precisa ser um LLM, mas você
42:57 tem alguma forma de analisar essa consulta para decidir qual search template invocar. A maioria dos desenvolvedores que está criando um caso de uso avançado, sem uma única estratégia que possa usar para todas as consultas, vai acabar com algo assim por baixo dos panos. A questão é apenas o quanto é difícil programar isso. E, no caso da Elastic, muita gente não conhece os search templates, mas esse é um mecanismo poderoso que pode ser usado para reduzir a quantidade de código repetitivo que você precisa escrever para esse tipo de arquitetura. Não foi abordado nos labs, mas vale a pena saber
43:27 ao menos que esse conceito existe na Elastic. Então, a tabela no final, mais uma vez, deve ser considerada com cautela, mas é uma boa maneira de começar, certo? Se você não conhece muito bem seus dados, ou se a combinação de consultas é meio desconhecida, pode começar com RF. Funciona muito bem. Não fomos nós que inventamos RF, mas usamos, assim como outros também usam. E, além disso, você pode começar a explorar outras maneiras de combinar os dados. Mas nem sempre é necessário usar
44:00 busca híbrida. Às vezes, a busca semântica é suficiente; às vezes, BM25. Mas geralmente descobrimos que alguma combinação de busca semântica e lexical ajuda a recuperação a funcionar da maneira mais eficaz. E no lab quatro, apesar do título, você vai colocar isso em um modelo, mas vamos mostrar como
44:32 Mais uma vez, como eu disse no começo, os LLMs são extremamente — “inteligentes” talvez não seja a melhor palavra —, mas são eficazes em fornecer respostas. Só que, sempre que você precisa fornecer a eles dados que estão fora do conhecimento de treinamento, ou qualquer outra coisa, pode fazê-los dar uma resposta errada com bastante facilidade: basta fornecer um conjunto de dados e dizer que o céu é laranja, e normalmente eles vão dizer que o céu é laranja. Há maneiras de contornar isso, mas é aqui que mostramos que a recuperação continua sendo importante para
45:05 respostas agênticas. Uma rápida contagem de mãos: há alguém que ainda não chegou ao lab três? Certo, ótimo. O pessoal está avançando bem. Excelente.
45:42 E vale a pena mencionar também que é aqui que entramos no Agent Builder, a plataforma agêntica da Elastic, que permite, é claro, executar agents, ferramentas e skills. Você pode se conectar a muitos LLMs. O serviço de inference da Elastic disponibiliza todos os seus LLMs favoritos. Mas você também pode trazer seu próprio LLM, e ele consegue executar essas ferramentas diretamente nos dados dentro da Elastic. E, na verdade, isso agora não está
46:15 incluído no workshop, mas temos workflows. Basicamente, sempre que você tiver um conjunto ordenado de tarefas que quer concluir, pode incluir árvores de decisão e coisas assim. Os agents podem chamar esses workflows e também podem acessar outros sistemas. Você pode chamar ferramentas MCP, APIs, qualquer coisa que quiser. Mas, novamente, isso está fora do escopo deste workshop. Como temos um pouco de tempo, este é o ponto em que o agent pode começar a executar ações. Ou seja, não apenas recuperar respostas para você, mas há um
46:50 workshop inteiro que você poderia fazer em que, por exemplo, com base em um incidente e nos dados de rastreamento do hotel no sistema de observabilidade que você traz, o agent pode decidir: “Sim, o sistema está ficando sem recursos. Precisa escalar.” Então, por exemplo, você pode chamar um workflow para escalar automaticamente seu ambiente Kubernetes. É apenas um exemplo, mas é aqui que entramos no Agent Builder, que apresenta algumas das funcionalidades.
47:31 E uma das coisas mais interessantes sobre o Agent Builder para quem desenvolve software é que tudo o que você vê na interface de usuário do Kibana no Agent Builder é programável por meio de API. Então, se você decidir que quer fazer um protótipo rápido usando nosso mecanismo do Agent Builder na Elastic e pensar: “Ah, agora tenho que reescrever todo esse código do zero e criar um aplicativo de verdade”, não precisa fazer isso. Você pode reutilizar esses mesmos endpoints no seu aplicativo e fazer as mesmas
48:04 chamadas em uma experiência de usuário personalizada que você controla. E, além disso, se decidir que quer remover esses componentes do Agent Builder e conectá-los a outro framework ou a outro conjunto de APIs que você desenvolveu ou usar com um framework diferente, também seremos compatíveis com isso. Nosso objetivo é oferecer uma experiência pronta para uso tão completa quanto possível, mas sem prender você nem forçá-lo a criar aplicações da maneira que queremos. Somos muito flexíveis, quase até demais. Então, quando você nos faz uma pergunta, muitas vezes a resposta começa
48:36 com “depende”. Alguém chegou há pouco e não tem a URL? Desculpe. Imaginei que sim, mas comece ali. Fica no canto superior direito. É aquela URL curta que começa com ELD. E, caso alguém tenha chegado mais tarde e não tenha me ouvido dizer, o workshop em si ficará disponível por uma semana. E o link azul do James é o repo que contém todos os notebooks
49:08 e todo o restante do código. Mas o material relevante que você vai usar sem o Instruct são os notebooks. Você pode conectá-los a qualquer cluster do Elasticsearch que tenha — há um gratuito. Bem, mais ou menos, se você conectar outro serviço. Mas ele vai carregar os dados e você poderá acompanhar tudo. Então, isso ficará disponível até alguém apagar. Me apaguem. >> A propósito, obrigado ao nosso distinto arquiteto aqui, Sunnil. Nós
49:41 queríamos garantir que vocês recebessem conteúdo extra, materiais extras do workshop. Há outros workshops disponíveis online no mesmo formato que usamos aqui hoje. Eles têm basicamente um ambiente do Instruct pré-configurado, para que você possa acompanhar os conceitos e aprender mais sobre como a Elastic funciona por baixo dos panos. Recomendamos muito que acesse essa URL e faça os workshops. É basicamente um treinamento gratuito e, quando terminar esses workshops, provavelmente seu valor no mercado vai aumentar em, sei lá, US$ 100
50:12 mil ou US$ 200 mil por ano. É um aumento garantido de salário. >> Certo. Enquanto o pessoal trabalha nisso, vou fazer duas coisas. Uma delas… Desculpem, eu mencionei algumas vezes que podemos fornecer informações novas, atualizadas, recentes e também informações proprietárias para esses LLMs como forma de ampliar… é daí que vem o “a” de RAG, de aumentar o conhecimento deles. A outra coisa que
50:43 Isso surge bastante, e cada vez mais, em… bem, em todos os lugares, especialmente à medida que os agents começam a circular e a fazer coisas cada vez mais rápido: poder citar as fontes. Os modelos são muito bons em apresentar informações e, muitas vezes, elas estão corretas. Mas também são ótimos em mentir para você — não porque tenham sido treinados especificamente para isso. O que acontece é que, se houver uma linha muito tênue entre, digamos, duas outras linhas sobre as quais você faz uma pergunta, e o modelo não souber a resposta específica, mas
51:15 souber bastante coisa em torno da resposta e sobre outros tópicos relacionados, ele pode produzir uma resposta extremamente convincente que, a menos que você seja especialista ou conheça de fato a resposta, pode enganar as pessoas. Então, tudo isso para dizer que uma das coisas incluídas neste laboratório, mais ou menos no meio, e que está na tela agora, é a capacidade de fazer um LLM citar fontes. A maioria dos modelos não consegue citar as fontes porque não é um banco de dados.
51:46 Esses modelos não fazem uma consulta a uma tabela para buscar informações. Eles geram tokens com base no treinamento. Enfim, ao fornecer as respostas reais ao LLM e fazer com que ele as analise e monte uma resposta compreensível para as pessoas, ou no formato que você quiser, ele também pode citar as fontes. Isso é extremamente importante em áreas como a jurídica. Provavelmente vocês viram muitas notícias sobre advogados que se metem em encrenca porque, em processos, inventam respostas, citam casos que não existem ou distorcem as respostas. Então, se você conseguir fazer o modelo
52:20 processar grandes volumes de dados — dados complexos — e ainda assim citar a resposta, isso o torna muito mais útil e confiável, até certo ponto. Então, quando vocês acessarem isso, como James mencionou, uma das coisas legais da plataforma Agent Builder é que ela também funciona inteiramente por API. Por isso, o laboratório desta apresentação foi um pouco diferente: para mostrar que dá para criar tudo isso
52:55 programaticamente. Assim, você pode criar skills, ferramentas e agents; eu criei tudo isso programaticamente. Desse modo, você pode criar, remover, escalar e alterar tudo conforme necessário, mas ainda usar todos os recursos integrados à stack e coisas do tipo. Então, vamos entrar aqui. Aí você pode fazer uma pergunta. Se formos à visão geral, temos muitas skills prontas para uso. Estas são as skills, e tenho certeza de que todos aqui sabem o que são, já que vocês estão numa conferência de IA, certo? Mas uma skill
53:30 inclui várias coisas, mas, essencialmente, explica a um modelo ou a um agent como realizar uma tarefa de determinada maneira: quando usar ferramentas, como criar apresentações, como criar outros serviços. Pode ser qualquer coisa que você escreva para ajudá-lo. Assim, ele não precisa descobrir tudo sozinho. Algumas coisas são apenas maneiras de torná-lo mais rápido. Outras servem para quando você precisa de resultados muito específicos. Se quiser fornecer instruções centrais, como as mostradas aqui. E nós oferecemos
54:03 muitas coisas prontas para uso, como skills para criar gráficos, visualizações e fazer buscas, mas também criamos ferramentas. A diferença é que uma ferramenta executa uma ação. As ferramentas que oferecemos prontas para uso incluem, por exemplo, executar buscas e listar workflows. Falei sobre workflows: são uma maneira de acessar outros sistemas e consultar serviços externos ou executar tarefas de forma bem determinística. Mas você também pode criar suas próprias ferramentas. Então, se formos
54:35 ao agent que você criou, por exemplo, e olharmos a visão geral, ele é bem simples — novamente, para os fins de hoje, tem uma skill. Ela explica como diagnosticar um problema que você está investigando. Então, é bem, bem curta em comparação com as que vêm prontas para uso, mas aqui você pode fornecer o máximo de informações que quiser para ajudá-lo. Isso ajuda a encontrar a cláusula, encontrar a solução e fala sobre analisar
55:06 os códigos de erro. Outra coisa que ele pode fazer — acho que tem uma ferramenta. Sim. Aqui temos uma ferramenta de busca, mas, se eu adicionar outras ferramentas, só para mostrar: criar uma ferramenta, criar uma ferramenta nova. Esta é sempre uma pergunta divertida que gosto de fazer: quem aqui conhece ou já ouviu falar de ESQL na Elastic? Certo, temos uma pessoa. Ótimo. É mais ou menos o que
55:38 eu esperava. Mas fiquei feliz em saber que muitos de vocês conhecem a Elastic e o Elasticsearch. Isso é bom. ESQL é uma linguagem de consulta mais recente na Elastic. É a ES|QL. É uma linguagem semelhante ao SQL. Então, você tem uma sintaxe parecida com SQL e, essencialmente, o pipe está ali para encadear comandos. Você executa uma operação, o resultado passa para o próximo pipe, e assim por diante. É isso. Assim, você pode ter ferramentas de ES|QL para consultar documentos no Elasticsearch. A busca de índices é
56:12 uma ferramenta interessante, ou melhor, é uma ferramenta. Com ESQL, você executa uma consulta específica: escreve a consulta e recebe campos específicos de volta. Já a busca de índices é algo que eu quase considero uma ferramenta de documentação. Você informa para um índice ou conjunto de índices para que serve o índice, qual é o mapeamento dos campos e quais são os campos. Se você tiver, por exemplo, um índice de produtos e um índice de preços e estoque, ela informa como combiná-los. Com ESQL, você pode fazer joins entre
56:46 índices. Ela fala sobre isso e sobre agents: como eles podem fazer várias interações e explorar, em geral conseguem descobrir os índices do seu cluster. Então, se você simplesmente fizer uma pergunta e o agent não souber nada, ele vai usar a ferramenta de busca por consulta e analisar os mapeamentos — ou a ferramenta de mapeamento —, encontrar todos os índices e depois os mapeamentos. Vai tentar adivinhar qual deles parece ser de produtos e, então, tentar combiná-los. Enfim, vai ficar repetindo esse processo por um tempo, e isso consome tokens, e todos nós
57:19 adoramos gastar tokens. Então, esta é uma ferramenta que ajuda a acelerar bastante esse processo e a apontar o agent na direção certa. Workflows. Acho que já falei disso algumas vezes, mas podemos executar tarefas de maneira ordenada e acessar outros sistemas. E, se quiser chamar um servidor MCP externo, você pode fazer isso. Também vou mencionar que as ferramentas do Agent Builder — tanto as que vêm prontas para uso quanto as ferramentas personalizadas — são expostas como MCP. Então, o Kibana expõe um servidor MCP. Assim, você pode usar qualquer uma das ferramentas disponíveis nele se o seu agent quiser se conectar via MCP. E a última coisa: vocês vão fazer isso no laboratório, mas aqui mostramos basicamente como o agent pode executar vários ciclos. Primeiro, ele carrega a skill para descobrir como responder à pergunta sobre o motivo de continuar parando com o código 137
57:50 e por que isso acontece. Essa é uma pergunta com duas partes, certo? Por que isso acontece? Por que meu cluster está parando com o código de saída 137? Ele precisa descobrir a resposta para isso e, depois, como alterar minhas configurações para evitar que aconteça. Então, é uma pergunta com duas partes. Novamente, ele executa essa skill e começa a buscar a resposta. Ele passa por alguns ciclos e diagnostica o problema, explicando por que esse código 137 está ocorrendo. Na verdade,
58:20 Por que isso acontece e como? Então, esta é uma pergunta em duas partes, certo? Por que isso acontece? Por que meu cluster está morrendo com, sabe, o código de saída 137? Então, ele precisa descobrir a resposta para isso e, depois, como altero minhas configurações para evitar que isso aconteça. Então, é uma pergunta em duas partes e, de novo, ele executa essa skill e começa a encontrar a resposta. Então, ele faz algumas iterações e diagnostica o seu problema, sabe, explica por que esse código 137 está aparecendo. Na verdade, isso…
58:53 É o gerenciador de memória que está rodando e encerrando o processo. Depois, ele fala sobre como ajustar as opções da sua JVM para corrigir isso, mas também fala sobre prevenção. Então, como a resposta estava dentro do Elastic e ele tinha a capacidade de, sabe, consultá-lo e depois executar várias ferramentas e coisas assim, conseguiu meio que dar essa resposta e colocar você no caminho certo. >> Sim. E uma coisa que vou acrescentar é que, se você está em modo de prototipagem ativa e tentando chegar a uma…
59:26 lógica de busca ou lógica de linguagem de consulta que realmente resolva seu caso de uso, esta é uma ferramenta de desenvolvimento e depuração bem legal para descobrir quais buscas vão funcionar para recuperar os dados de que você precisa. E a última coisa que vou dizer sobre isso é que sou um grande fã de ESQL. No começo, eu estava um pouco cético, porque havia alguns recursos na linguagem de consulta do Elastic que não existiam no ESQL. Acho que ele tem recursos suficientes para que você pelo menos…
59:56 dê uma olhada, especialmente se estiver criando casos de uso de busca agêntica, porque há conceitos muito legais no ESQL que se prestam bem a resolver certas tarefas de busca melhor do que a linguagem de consulta do Elastic, que você deve considerar um superconjunto do que o ESQL é hoje. E outra coisa que torna o ESQL fantástico é a capacidade de ter parametrização integrada à cadeia de tool calling do MCP e conectada ao agent builder, o que é uma adição fantástica que, tecnicamente, é…
1:00:31 possível fora do ESQL, mas, pela forma como arquitetamos o ESQL, nosso agent builder e nosso endpoint do MCP, esse é o caminho mais fácil para muitos dos casos de uso de busca agêntica que você pode ter. Então, se ainda não deu uma olhada no ESQL, recomendo muito que faça isso. E, se estiver tentando acompanhar algumas das coisas inovadoras que estamos fazendo em busca, o primeiro lugar para procurar são, na verdade, os documentos do ESQL, para ver quais mecanismos novos e inovadores de recuperação estamos criando, porque estamos fazendo coisas muito…
1:01:04 interessantes com busca federada e, potencialmente, consultando os diferentes sistemas dentro de uma consulta em linguagem de consulta do Elastic que não é considerada tradicional do Elastic. Isso está em desenvolvimento agora, mas você vai ver isso chegar ao produto. E, quando chegar, o ESQL será sua porta de entrada para isso. Estou falando de coisas como poder fazer consultas em arquivos Parquet externos ao Elastic com uma chamada SQL, o que pode ser…
1:01:35 incrivelmente poderoso se você também combinar isso com dados provenientes do Elastic. Você pode ver que o agent usou ESQL para esta chamada. Então, é assim que fica. Ele pode fazer coisas como ramificar e, então, combinar duas das linhas de busca. É isso que a fusão ali embaixo faz. Assim, ele consegue fazer essas perguntas e depois retornar a resposta. Você pode ver que há os pipes, que podem…
1:02:08 mais uma vez, você executa uma consulta, executa uma etapa dela, essencialmente obtém a resposta e passa para o próximo pipe, e depois para o seguinte, em uma linguagem como essa. Então, ela é muito parametrizável. >> Parametrizável, e está tentando realizar tudo o que a linguagem de consulta do Splunk tentou fazer com o Splunk no auge. E também combinar isso com conceitos de SQL, que obviamente já foram testados e comprovados, e acho que…
1:02:39 a última coisa que você vai notar no ESQL é que as consultas são mais diretas; elas não têm tanta marcação para obter a recuperação correta, o que é um benefício adicional dessa estrutura em pipes. E há outras empresas que usam a mesma técnica para desenvolver busca, geralmente para conjuntos de dados não estruturados, como logs. E eu diria que o principal motivo pelo qual começamos a criar o ESQL foi construir a melhor experiência de busca da categoria…
1:03:10 para que as pessoas pudessem se livrar de tudo o que tinham no Splunk. E agora mudamos de rumo: essa estrutura é tão útil que deveria estar disponível em todos os pilares do Elastic: busca, segurança e observabilidade. Daqui para a frente, ela será uma estrutura de primeira classe nos três pilares, e será o principal mecanismo de inovação. >> E você pode ver que, quando ele executa uma das consultas de busca híbrida, ele responde. Ele mostra o registro de auditoria…
1:03:41 de como chegou a essas respostas. Então, além de citar as respostas lá embaixo, você pode clicar nelas e, se quiser se aprofundar no divertido mundo das configurações da JVM, pode fazer isso. Nunca mais vou fazer isso. Mas estou brincando. Outra coisa legal é que ele também mostra: estamos limitando a cinco e ele retorna cinco. Ele informa que encontrou cinco resultados, sem deixar a interface cheia de informações. Mas você pode clicar nisso e ir para o Discover. É meio que onde nós…
1:04:14 descobrimos documentos. É a interface normal de busca do Cabana. Ela mudou um pouco ao longo dos anos, se você não a usa há algum tempo, mas agora dá para fazer ESQL nela. E você pode ver aqui os cinco documentos que ela retornou. Se eu fechar alguns desses painéis, ela monta um gráfico bacana para você. Não sei se esse gráfico é muito útil, mas você pode ver que, com a consulta no topo, aparecem os documentos. E pode abrir para ver tudo. Aqui está o corpo do documento. E estávamos…
1:04:51 buscando parte disso. Ah, aqui está. Procurando a URL. Então, como incluímos a URL como parte do documento, conseguimos fornecer, essencialmente, um link para mais informações, sem precisar simplesmente adivinhar. >> Acho que esta sala fecha aos 420. Está certo? >> Sim. O cronômetro diz que faltam 18 minutos. >> 18 minutos, o que significa que vocês têm… >> Deixem o martelo vir nos acertar. >> Sim. O que significa que vocês ainda têm um tempinho para fazer perguntas. >> Sim. E tem… isso, fiquem à vontade…
1:05:24 para fazer perguntas. Desculpem. Há o laboratório cinco sobre rerankers. As luzes estão fritando meu cérebro. O reranking é uma coisa interessante que acho que muita gente não entende completamente por que deveria usar. Por isso adicionamos isso, para explicar por que você gostaria de usá-lo. E, se isto carregar…
1:06:03 vamos ver se aparece. Talvez seja problema do meu computador. Reranking é o seguinte: se as consultas que fizemos aqui e tudo mais são a primeira fase, ou seja, da recuperação, na segunda fase você pode fazer reranking. Então, se estiver executando busca vetorial, busca semântica ou busca híbrida na primeira fase e receber um grande conjunto de dados, poderá pegar esses dados e reordená-los. E o reranking tem…
1:06:35 Queria que isto estivesse funcionando. Acho que o problema é meu. O reranking combina a consulta e o documento na hora de pontuá-los. Normalmente, com vetores, você ingere todos os seus dados quando for e, na hora da consulta, consulta esses dados; então, ele executa HSW ou um dos algoritmos em disco e retorna um conjunto de documentos, mas…
1:07:07 a consulta e os documentos não são realmente pontuados juntos. O reranking os combina, mas, como eles são processados juntos nessa segunda fase, na hora da consulta, não é possível gerar embeddings antecipadamente. Então, você paga o custo de executar inference na hora da consulta. Para ajudar com isso, você não reordena todo o seu corpus de dados. Executa a primeira fase para obter um conjunto menor de dados e, depois, faz o reranking com…
1:07:41 um modelo para então, sabe, reclassificar esse pequeno conjunto de dados. Desculpem, lá vamos nós. Tentando mostrar um exemplo em vez de só falar. Aqui vamos nós. Meu laboratório estava travando.
1:08:18 Então, se vocês chegarem até esta parte aqui, poderão ver que, no final, há novamente alguns pontos sobre quando adicionar um classificador, caso vocês tenham essa margem de latência. Se não tiverem, se puderem gastar um pouco mais de tempo para deixar esta segunda fase rodar e gerar embeddings, porque essa precisão — sabe, se é a resposta um ou a resposta dois —, se isso for uma etapa crítica, é aí que vale pagar a pequena penalidade de latência.
1:08:50 Isso entra em jogo. Se vocês deixarem os documentos bons o bastante na primeira fase e deixarem o agent ir atrás deles, provavelmente não precisam de um reclassificador. Mas é quando precisam que essa ordem específica entre em jogo. E vemos isso bastante em casos de uso de busca agêntica. Estamos vendo muitas situações em que as pessoas testam a avaliação com base no primeiro, segundo e terceiro trechos de documento que retornam, o que dá uma janela de oportunidade muito pequena para acertar a resposta. Se vocês estiverem passando um
1:09:23 pequeno conjunto de candidatos para o LLM responder à pergunta, em vez de um conjunto maior de candidatos e, então, pedindo ao modelo que acerte, é aí que surgem muitos problemas de relevância. Vocês estão passando contexto demais. É uma questão de múltipla escolha em que duas ou três respostas parecem igualmente corretas para o LLM, e ele simplesmente escolhe uma. Se escolher a errada, seus usuários e os testadores beta do novo sistema de busca agêntica vão reclamar que a busca não funciona. Isso é muito comum, muito
1:09:53 muito comum. E, muitas vezes, um reclassificador como este será realmente muito útil. Há dois tipos de reclassificadores que oferecemos. O primeiro é por ponto, que é o tipo usado pela maioria dos reclassificadores hoje, e é o que o modelo V2 faz. O reclassificador por ponto ainda combina a consulta e o documento, mas dá uma pontuação a cada um de forma independente. Ele só analisa a
1:10:26 consulta e o documento, nada mais. O reclassificador por lista, que é o que está no modelo Jina V3, recebe o conjunto de candidatos e, por exemplo, acho que atualmente aceita até 64 documentos ou 64 candidatos, e analisa todos juntos. Assim, se as respostas ou os candidatos em potencial forem muito parecidos — se todos estiverem falando praticamente da mesma coisa —, é aí que o reclassificador por lista pode levar vantagem sobre o por ponto, porque
1:10:58 consegue perceber as nuances dentro da lista, já que vê vários documentos juntos. Ele exige um pouco mais de memória ou de tempo, porque, mais uma vez, precisa gerar embeddings para todos esses candidatos de uma vez, mantê-los juntos na memória e executar a avaliação sobre eles, em vez de processá-los um de cada vez. Então, se os seus dados forem bem diversificados e as respostas que retornam
1:11:34 formarem um conjunto de candidatos bem distinto, em que o primeiro, o segundo, o terceiro, o quarto e o quinto sejam todos diferentes o bastante para o reclassificador por ponto funcionar, desculpem. Lá vamos nós. Então, normalmente, o reclassificador por ponto costuma funcionar bem. Mas, de novo, se vocês tiverem um conjunto em que os candidatos em potencial sejam extremamente parecidos, provavelmente o reclassificador por lista vai ajudar mais.
1:12:08 E, em algum lugar aqui — porque queremos ser úteis —, vocês não precisam executar as duas etapas separadamente. Mesmo sendo um processo de duas fases, em que a fase um é a consulta e a fase dois é a classificação, não precisam fazer chamadas separadas à API manualmente. Podemos fazer tudo de uma vez. No laboratório, isso fica no retriever; dá para fazer por lá. >> Dá para reclassificar qualquer SQL? >> Sim. >> É, certo. [risos]
1:12:39 Então, também dá para fazer isso em SQL. Basicamente, vocês indicam qual reclassificador querem usar, o modelo e a consulta, e ele executa as duas fases para vocês. Assim, mais uma vez, vocês não precisam gerenciar as configurações de inference separadamente, nem chamar a API de inference, depois fazer a consulta e então reclassificar. Podem executar tudo de uma vez, e nós cuidamos disso para vocês. Vou mostrar de novo aquele slide com alguns links.
1:13:12 No canto superior direito está o que fizemos hoje. Ele fica disponível por uma semana. O repositório de referência azul, na parte de baixo, é onde está o código, os notebooks e coisas assim. E há dois links vermelhos no meio. O ambiente secreto da Elastic do Sunil. Ah, não, tem até um erro de digitação. Todo mundo vai tirar uma foto. E o outro… >> Isso só prova que estamos numa sessão ao vivo. >> Vou culpar as luzes. >> E que estamos, sabe,
1:13:45 fazendo as coisas na hora. >> Ainda tenho que executar. Certo. E os outros workshops estão online. Temos vários outros workshops online totalmente gratuitos. Por exemplo, sobre trabalhar com streams; se vocês recebem streams de dados, essa é uma maneira extremamente eficiente de lidar com esses dados. Também temos outro sobre RAG, busca lexical e tutoriais de busca vetorial.
1:14:17 Se alguém estiver trabalhando com observabilidade, por exemplo, com dados do OpenTelemetry ou buscando análise de causa raiz e coisas assim, temos laboratórios sobre isso. Alguns laboratórios de observabilidade. Deve haver alguns sobre segurança aqui. Segurança é uma grande área da nossa plataforma, uma parte importante dela. Há desde descoberta de ataques até regras de detecção. Sei que também estão saindo novos. À medida que adicionamos cada vez mais recursos de agent à stack.
1:14:56 Alguma pergunta? Certo. Então, deixa eu perguntar uma coisa rapidinho. Se vocês ficarem aqui, ganham automaticamente uma vaga no próximo workshop? Só estou curioso para saber se é por isso que as pessoas ficam. Certo. Estou tentando entender quem ainda está trabalhando e quem está só ficando por aqui, o que é totalmente normal. Eu posso ir embora de qualquer forma. Vamos presumir que a maioria de vocês está só ficando por aqui e não está esperando ajuda com nada. Mas
1:15:27 se estiverem, ainda têm mais 7 minutos e 57 segundos. Sil, quer demonstrar alguma coisa por sete minutos? Espero que isso tenha sido um bom uso do tempo para quem ainda está na sala. Adoraríamos receber o feedback de vocês. Não contamos isso, mas há um campo para enviar feedback no final do workshop. Então, quando terminarem, vocês poderão nos dizer o quanto o workshop foi incrível ou o quanto não gostaram dele. E, se disserem coisas ruins, isso vai
1:15:58 magoar nossos sentimentos. Mas vamos melhorar o workshop para as próximas pessoas.
Transcrição original
[00:12] Thank you for coming. Uh my name is Jeff Estle. I work at Elastic. I am a AI architect. We picked a new title this year so make it relevant. This is James. You want to introd yourself? >> Yeah, I’m James Williams. I’m a uh solutions architect focused on search. So, I help customers with all the technical stuff you’re about to walk through today. >> So, this is a very hands-on, as in I do not intend to talk much. I’ve been talking a lot lately on the road, so we’re going to have me not talk a lot.
[00:43] Um, you’re going to go through hands-on stuff. I will say in the upper right corner, you’ll see that short URL. Um, it’s a ELA elastic. This is the workshop environment. Um, quick note. So, they never told me how many people were coming. So, I took a random guess of 75. Looks like I undersshot a bit. So, there um 75 of you will start up pretty quickly. The other handful that are a little slower on the on the trigger here. It’s just a few extra minutes to start up. Um but basically, this is going to take you to
[01:14] an instruct environment. And then I’ll give a little intro. I’m just giving this spiel while it goes. Um we’ll go to this. You’re going to go here and then you’ll hit start and that’s going to spin up an environment for you. So while that’s doing it, um, so how many people are familiar with Elastic, the company, Elastic, Elastic Search. All right, pretty good. It’s good turnout. Um, and how many of you have used Elastic to build a like a a ragbacked application, retrieval, augmented
[01:47] generation? Great. How many of you are sick of hearing the term rag from the past two three years? Fantastic. I know I said it about a thousand times at many conferences and um my boss who no longer works here actually used to get really mad when we keep bringing up rag. Now the thing is um return a meant generation didn’t actually go away. Luckily it just kind of fell to the background. But as agents got more and more uh capable and you know effective they just kind of took over the management of being able to you know
[02:20] retrieve data and and analyze it. So the models are getting certainly smarter and smarter. Um you know Fable came out for a minute and teased us and then ran away. But um there’s still a a need for pulling in information into these models be it you know things that are time based that change proprietary information um price data anything out there that the model hopefully hasn’t been trained on whether they tell us or not. Um but there’s a need for that and so that’s where things like elastic search come in. It’s the retrieval layer
[02:51] that helps make these these agents very capable. And the the trick or the catch, I guess, is if you feed these models, no matter how smart they are, garbage data and you confidently tell them this is the answer, pretty much they’re going to believe you because that’s what you’re telling them. So, we want to be able to give accurate information and and give it. So, this is kind of what this workshop is about. I’m sure there’s 20 other workshops that explain how to build agents and I we actually have some too if you want to go to our website but
[03:22] this one’s going to talk to you kind of remind about um vector search semantic search why it’s important where it’s useful but also where it breaks down and then we’ll go into um the kind of lexical search BM25 so that’s that keyword search we’ve been doing for for decades um where it’s still relevant today and useful and then also again where that kind of breaks down and then putting bring them together into hybrid search. So, being able to kind of get the best of both. We’ll do combinations with uh RF, which is an out of the box
[03:54] combination. And then we’ll do some a little bit more advanced um linear combination where you can tweak those balances a little bit. And then should you have time, we’ll actually put it into um a little bit of Elastic’s agent builder platform where you can see what happens if you retrieve bad information and tell the agent it’s it’s good, it’ll doesn’t work. I mean, it works, but it gives you a bad answer. And if you give it the correct answers and things like that, um should you be very quick and get all the way to the end, there is a
[04:24] bonus um one about um sorry, rerankers. So reranking where it comes in useful that um the workshop is kind of basically four plus a bonus um chapters challenges. Each one has two parts. There’s the part in the dev tools console where you just run API commands within Elastic Search. Um each one of these environments if you’re in it and hit start and everything, what’s happening is a serverless instance is being spun up for you. Um and then you’ll load some data. It’s a small data set, you know, it’s a workshop, so
[04:56] nothing crazy. And um you’ll run the kind of the the short version of each one of these in the dev tools console and then you’ll hop over to a Python notebook tab and you’ll run the more in-depth one. What I would say is I’m going to stop talking in a minute and let you work on the workshop and then every 20 25 minutes we’ll kind of check in and see where people are at. I’ll tell a little summary about the the cha the chapter challenge you’re at. Um, to get the most out of this workshop, I would definitely spend time reading through what’s in the the Jupyter notebook, especially it kind of talks
[05:29] about why the documents come up in the orders they are and how to tweak it and how to tune and why it’s important. Um, if you just blindly hit run all in the notebook and fire through, you’ll be you’ll be done 10 minutes. But if you actually spend through it, it’s going to probably take longer than this workshop session. So, um, with that, I’ll let you get started. So, some of you should start up right away. Some of you will take a few more minutes in the meantime. Is anyone actually started? Sometimes you take a few minutes. That’s the thing. Yeah, >> we got it. >> Okay. >> And if you get stuck, raise your hand.
[06:01] I’m basically the runner. So, I’ll check out what you’ve got going on on your on your system and and and potentially help unstick you if if it’s something trivial. And if you have any questions, feel free to raise your hand. happy to provide a little bit more detail about what’s going on in the exercise if um you’re looking at something and you’re you’re a little bit confused and want won’t want won’t want won’t want won’t want won’t want won’t want won’t want won’t want won’t want won’t want to ask a question there and this is all also available um in a repo that should be public yeah I made
[06:35] it public um so you can run the notebooks um outside of instruct either after or or whenever if you want >> kind of glossed over this But the one big thing that I think has changed with rag over the last year year and a half is some of the data providers for vector database and we’re in that in that bucket have brought inference into the vector database. So you will see embedding generation happen within elastic search serverless. We have an inference service called Elastic
[07:09] Inference Service. Very um creative name that powers the models that are being used for these workshops. So we’ve got GINA models from from an acquisition that we made. So we actually do our own model development now. And um and it’s focused mostly on dense vector models and re-ranking models. So you’re going to get insight into some new tech that wasn’t part of Elastic Search a year ago. That’s that’s all I have to add there. >> We’ve heard of chunking. >> We do we do we do help with chunking. So
[07:43] yeah, we can answer this and feel free to jump jump in. He’s the manager of the search specialist team. I just wander around. Um so as James mentioned the we have you know the text field semantic text in elastic search. So there’s a couple ways to do this. Semantic text is kind of the automatic easy way on road. Um, so by default we will chunk on sentence boundaries and break into a certain amount. I can’t remember off hand what the number is >> 250. >> There you go. And so that’s you know configurable. So by default breaks on sentence you can break on word
[08:16] boundaries. You can change it. Um the the Gina model that James mentioned we you know part of Gina now or Gina is part of us whatever. Um it has a very very large context window but you’re not always going to want to fill that for various reasons. Um, and so you can configure chunking down to the word to paragraph, page boundary, things like that. >> We have a semantic mapping field in elastic which basically takes a piece of text and chunks it. So if you send us five pages of text, we’re going to chunk
[08:48] that into 250 token chunks with one sentence overlap and store that in the in the system for retrieval. There are frameworks that talk about semantic chunking and there are other labels for what I will call um large context window chunking. We actually and and this is talked about in the lab in the later sections. We do have a technique that we use called late chunking that can work on large context windows that is not exposed via elastic
[09:20] inference service yet but it is something that the GINA models do support. That’s the closest thing that I would say we would have to semantic chunking. But we don’t really have a need for that construct because the semantic text field itself uh allows us to deliver the same thing you would get with semantic chunking just by chunking the data and then and then running searches across it um in a you know in a semantic flavor and you you’ll get exposed to that in a lab. So we would we would solve the problem with traditional
[09:50] chunking and hybrid search, not any exotic semantic chunking scheme. >> You’re welcome. >> All right. Yeah. >> Yes. So I made it available for a week because I know how things go. Um so it is available for a week there. Um, and this isn’t a this isn’t anywhere. Um, I the workshop is in my repo for better
[10:23] or worse. Um, and so the the notebooks are all in here. So if you if you want to run just the notebooks, um, you know, you can hook it up to your serverless cluster or any kind of cluster should should work that has semantic text in there. But yeah, the the workshop itself is good for a week. And where was I?
[10:54] And yeah, so like I mentioned, the the first part the first half of each lab is this dev tools where you run a mapping. The left side is the input for your API. The right side is the output. And then you’ll get down to part two where you pop into the Python notebook and it’ll automatically connect to the um the Elastic Search environment that spun up for you. I see they’re letting folks in as as folks kind of go out to make sure the
[11:27] room is still full. Um the top right hand corner is really the URL that you want to hit. That’s where all the workshop content is. And then there’s a second URL that is the source code repo for all the notebooks for the workshop today. Those are the two most useful resources. So if you’re coming in and you haven’t fired up the workshop yet, top right hand corner and then the bottom right hand corner if you’re interested in the Python notebooks that power the content that you’re walking through today.
[12:00] I’ll probably repeat that message every time I see someone walk in. That is a really good question and I’ll repeat it so the other folks can hear it but is is a major point of this um lab sequence to let you know that VM25based search which is traditional lexical search we’ve been doing for a long time and dense vector semantic search do those two things need to be put together
[12:31] to form hybrid search that is the core thesis right now that we have as a company and the only thing that we add to that well obviously that that’s of value is the option of adding rerankers on top of that but yes that is a core thesis we’re firm believers in that approach and that’s in line with everything that I’ve seen since before even joining elastic even if you’re using a dedicated just pure vector database you often have to pair that with some other retrieval system and do the equivalent of hybrid search. The
[13:06] advantage to elastic is and you’re seeing this in the labs. It’s one API call. We handle all the inference that happens from ingest chunking to real-time search where the query gets translated into a query vector and we do all the work for you under the hood. And that’s what we we consider that of high value especially when you’re talking about largecale use cases where latency, accuracy, tunability matter.
[13:40] They are configurable. The chunking settings, are they configurable? They are. The documentation has insight into how you can change them and what chunk settings can be changed. So, we’ve got very detailed um API docs that walk through that. Uh they’re not described in detail in the workshop, but if you go to the elastic docs, you’ll see what the what the configuration settings are for chunking. And some of our customers do bring their own vectors and chunk on their own. We support that through standard um SDKs. So if you’re using Python, Java, Net Core, like pretty much any TypeScript, any modern programming
[14:16] language, um you could still use Elastic in the format for these workshops. You’re just doing more work as a developer. >> And so I’m sure people are moving along and you can continue on as at your own pace. Um, like I said, I’m going to check in every once in a while and kind of talk about the the labs a little bit. So, the the first one, right, the the whole point is essentially this little chart right here talking about how vector search works and and semantic search and what you’re getting it. And so, when when you use an embedding model that’s,
[14:47] you know, hooked up to Elastic and you know, we talk about Gina as the out of the box one, but you can certainly bring your own. You can hook up to other inference services. um we just make it easy for you to get started with Gina, but certainly bring your own and use semantic searches or semantic text as well. But the the nice thing about this particular way it sets up is you know when you create an an embedding at query you know at inest time you create the embedding from your your document but then at query time you need to use the same embedding model to do the query time otherwise it’s you know like me
[15:18] trying to speak Portuguese it would not go well. Um so by when when I started when we started doing this a few years ago um in the early days early um you know you had to keep track of the inference ID you had to keep track of the model and then the model you know then you have developers all and you have to like make sure everyone’s using the right one and there’s all this things. So by embedding it in the ID in the uh field itself it helps on two ways. one, you only have to set it once and as the person who’s setting up the index, um, you know, there might be other people using that same index to
[15:50] ingest their own data or query it, right? So, you can set that up once again, whether it’s the Gina model or or some other model. Um, anytime you use that field, it just becomes like another field. You just either send data in or you query it. So then at query time, what you’re seeing up here is um the text comes in. It may or may not get chunked up depending on the the size and settings. It goes to the um maybe the elastic inference service which is default out of the box. Maybe goes to another inference service. That’s fine.
[16:21] And then we generate the embeddings and we then pass it back to elastic to do the um HSW&N. We do have other discount. We have disk ANN but by default we’re using HSW the hierarchical navigable small worlds graph. um basically just allows quick traversal to find nearest neighbors of of relevant documents and then you get back your top k five 10 whatever you want documents and that allows you to ideally if everything’s working well find documents or you know
[16:52] chunks that are semantically similar to what you’re asking and as you learned in the lab it’s not the exact keywords it’s the idea of what you’re asking so if if all of us in this room ask you know how to set up security on, you know, TLS on elastic search or something. We’re all going to phrase a little differently, but the idea is all the same. And so hopefully you get back the same documents. And you kind of saw where sometimes that breaks down. Um, one of the key places is if you have a very specific keyword, um, certainly if you have a keyword that is not a word
[17:27] like a product ID that has makes no sense, it’s very specific, um, semantic search then kind of falls apart because it doesn’t really need that. And that’s what the second lab is where bringing in um, BM25, lexical, keyword filtering, and all the other traditional so-called search uh, methodologies we’ve been doing for a long time help can augment that. And so I’ll give you I’m sure some of you are progressed past that one, but I’ll check in in a few minutes and review lab two. And again, if there’s any questions, feel free to ask,
[18:06] >> right? Page. Yeah. Paging. So if you have like a hundred results, you want to get back 10 at a time. Is that is that what you’re asking for or Oh yeah. So you can do that. There’s um I forgot the the exact thing, but there’s a basically essentially a checkpoint ID. And so then it it continues on. And so yeah, you’re not researching again. You’re not rerunning the search for that part. It goes on. So you can that’s what our pageionation API
[18:39] part does. So if you know that’s a possibility, you use that and then we send you that key and it’s basically like this is where you start and continue on. >> I think the official label for it is point in time. There you go. If you’re looking in Elastic Docs, uh just you search for point in time and it shows you how to use point in time to do to do just that. >> Oh, good question. Um so the the summary field is generated just for this workshop and it was generated by an LM. It it’s not exactly part of it. The real reason is when I first ran through this
[19:10] and you print out the whole body field, it was way too long and it was cluttering everything up. So just having this little summary field. Now that said, you can use like for example an ingest pipeline in elastic search and make an inference call and say I do want to generate a summary of of this you know document or I do want to pull out the possible queries that could do that. So you can do that on uh ingest. It’s just for this particular thing it was just to make it easier. But so the the vector field you’re searching is is the title. Yeah. >> And as we get deeper into the labs, we
[19:42] don’t use that that construct, but there is LLM completion API calls in in the later labs that it would be the exact same thing. You just wired in your ingest pipeline >> question. >> It’s a great question. So when it comes to work that we’ve done to make HNSW more efficient, um that started two years ago actually two plus years ago where we introduced int 8 quantization which I still I think is still the default. So by default we’re going to take float 32 vectors and quantize them
[20:14] before we store them in memory. We still we still keep the full vector um but we’re only storing the quantized vector in memory. We also have uh BBQ which is yeah and we got a blog that talks about BBQ. This is a little over a year old maybe even a little bit longer than a year old where we’ve compressed the HNSW um graph vector that we use even more all the way down to uh basically a bit and and there’s sophisticated stuff under the hood that supports that and
[20:46] still keeps the recall high. And then we just introduced disk BBQ which pretty much eliminates the memory overhead for um for vector search. The only uh difference I would say between disbel as the underlying mechanism for search. Um and then and the newest form of that is disbrietary to elastic. No one else implements that
[21:16] [clears throat] graph-based search. You want to take that one? [laughter] So, graph based search. Uh, so to be fully clear, we are not a graph database. There are some very specific graph databases. Um, graph has its place. It usually has a lot of overhead to keep and maintained. If you do that, great. Um for the vast majority of the people though it’s we find that it’s not really needed where the ability to especially with quantization where you can search across large amount of
[21:48] documents quickly. Um now especially with the agent world too where you can do multiple queries in. So you can one of the labs later on it does a couple round trips I think just two as an example but you can go in get your kind of first phase get a sample of documents and then see oh okay so they’re all related to this tag and then go searching. So that’s where things like filtering and um some of our other search methodologies help. Um and so yeah, I mean I just it comes up, but we haven’t seen it, you know, too often as
[22:18] an actual blocker where you have to set it up. >> And and the last thing I’ll say about that is what we see is far more common is um machine learning models that do classification on the fly, which is another way to solve that graph challenge. works in some situations, not not in all, but Neo Forj and other graph databases have been around for a long time. I don’t know of any that scale really well, and we’re trying to target multi-billion vector data sets, which means that um we’re very careful not to
[22:49] not to intro introduce a construct that keeps us from being able to scale at that level. And we we we haven’t found the need to go there yet, although it comes up a lot. It was a big theme last year at this conference. I remember being here and seeing graph rag was was heavily talked about, probably will continue to be. Um, I haven’t seen a technology nail that yet. And maybe there’s a Neo Forj person in here that would contest me on that and say, “No, no, no. We have it figured
[23:20] out.” I think they do, but not at not at the scale that we operate at. >> Yeah. Oh, so you came from their session. Nice. Okay. in the back. I think the question was we can use classification models to uh um to achieve some of the same results you might get with with a with a graph traversal. Um so we have the concept in elastic of running uh machine learning models in in elastic on what we call ML
[23:53] nodes. um you could basically upload whatever classification model that you’ve identified that works and wire it into elastic that way. The other model the other option would be to create your own model that you have your own external inference to and and potentially use that um in place of uh of our ML technology and I’m hoping that we’ll introduce more sophistication down the road in that area. But we don’t have anything noteworthy to announce right now. We’re focused on taking the genome models that we have and pushing the limit to what we can do with handling unstructured data and and dense vector
[24:27] embeddings and rerankers. We’ll probably end up pivoting off of off of that once we nail the um the reranking piece and and the and the dense vector models that are that are in development and you know doing quite well in the market. I’ll add in too that along with that so there’s classification models and you can also run things like NE models name entity recognition so you know if you pull out the entities if you’re trying to identify person location um business
[25:00] names things like that or product names you can run those on the fly as part of a you know part of the query where you as the the query comes in you run it through the ne model and ne models are very fast because they’re they’re small. They’re really small models and you pull out these entities and then you know again now with agents and things like this you don’t have to wire up crazy um painless scripts the agent can take those and then create a query that’s more tuned for that. So there’s a lot of ML capabilities that we don’t talk about as much as we used to because again like Jim said we kind of pivoted to focus on
[25:32] other things but they’re still there in the stack and very capable filtering in that’s great. What’s up man? Um one of our distinguished essays over in the corner can ask him all our questions. I’m gonna now redirect. Um for the people who came in aside from Sneil, the upper right corner is the short URL for the workshop and you can spin that up. It opens up a kind of lab for you lab environment and also spins up a um elastic search serverless cluster all set up for you.
[26:07] So feel free to run through there. So, there’s um there’s one main knob for reciprocal uh uh RF and it is and I’m I’m spacing out here off the top of my head. I do not know. You’re you’re pulling it up. >> I don’t know if we expose it in the in the RF um attributes for the retriever.
[26:43] What’s the default constant >> constant? The rank constant. I It is something that you can configure. Um I don’t know what the range is. >> That’s what lab five is the optional one. It’s all about well lab five is rebranking. RF is in there somewhere. Um sorry brain melted for a sec. Um it’s in there somewhere about talks about what what Sil’s talking about a little bit more example and you can change things like that. So
[27:14] >> So I don’t know did that answer your question? >> Okay cool >> fire away. That’s a great question. There’s actually a table that kind of explains some of those decision trees in the later workshop. I want to say workshop
[27:48] number four. But the short answer is for a small document corpus and and and my rule of thumb is always see what you can accomplish with a combination of BM25 and semantic search. If that gets you the recall or precision uh target that you’re looking for, whatever relevance targets you have, stop. Anytime you add anything on top of that, you’re going to be taking on an additional latency hit. Only do that if you need to. And the next uh you know extension point would
[28:18] be to um to use a rebanker model and um and then it’s just a matter of picking one that that you think is going to work best for your corpus and doing some testing and validating that it moves the needle enough. Um that would be kind of the standard happy path approach. There are some folks that would change that uh recommendation slightly and and say look just do BM25 just regular search um and and then and then add semantic search if it’s not um relevant enough but I’m a
[28:50] big fan of dense vectors so I would just go ahead and wire them into the architecture right out of the gate and uh that way I don’t have to worry about things like you know you you you get into these weird situations with lexical where you’re starting to add synonyms or get into advanced um lexical tuning techniques that you might not need if the semantic search is able to to pair well with a lexical search. >> Welcome. All right, so I know people are moving along which is great. Um just give a little wrap up on lab two which again was about your favorite be lexical
[29:23] search. Uh but hopefully you did learn uh you know get across the point that it does it does have its its points. Um, we just barely touched the surface on Lexical because, you know, for 15 years or so, you know, a dozen years at Elastic, that’s what we had. So, if you’ve ever been on the Elastic Search doc sites and you go to the search part and you click on the search API, there’s an insane amount of ways to change and tune and tweak lexical search. Because
[29:56] to James’s point, before we could do semantic search, we had to do all these uh crazy things to get relevant search. Um luckily now we don’t have to do quite as much, at least usually once in a while still. Um but with lexical search, you do it does have a it’s its point. Um but it does tend to break down um anytime you break out of looking for very specific keywords or a very specific phrase. Um the upside of it is it’s I mean I don’t even want to say I was going to say it’s generally faster. Although now with quantization things
[30:27] like that that’s not always the case but um by default it’s kind of faster. So um in lab three most people are probably along there but you move on to combining them. And I will say that even though I’m a big fan of dense vector search that lexical search usually does have lower latency profiles in almost all use cases and that’s because there is no ML inference happening. So anytime you go semantic search with with dense vectors you’re introducing um a call to um you know an inference endpoint and more
[31:00] often than not that inference endpoint is going to be more of a bottleneck than the rest of the system. And that’s another reason why we wired um the inference into the into the data platform because when you’re doing endtoend testing, it doesn’t matter if your vector database returns vectors, you know, really fast. If the inference that you’re depending on is slow, then your search is going to be slow. I think that’s a question that is shapeshifting as the data platforms wire more capability into the systems and these models improve the um and every vendor is going to have their own
[31:34] specific take. Our take is that everything starts with traditional search which makes a lot of sense given our heritage and then you add semantic capabilities on top of that and and then you layer in re-ranking if you if you need to in terms of where that stuff happens. That’s where the devil’s in the details. As as a developer trying to build an architecture around this stuff, your options are are quite vast. And depending on the stack you start with, you’re going to have perceptions of what you should be doing in the data platform
[32:08] versus what you might have some sort of middleware around it that that is that is wired up. And and I’m using the word middleware kind of loosely, but there’s a whole application runtime construct that’s went away ever since this this AI boom started. that is going to have to come back and it’s either going to land in the data platform itself where we’re doing inference and some of these other things you would normally have to coordinate with these external services or um there’s going to be you know platforms to try to try to accomplish um
[32:41] that and then use the data platform as just kind of this thing that you plug in and I’m thinking about like old school stuff like back in the old days when I started my my tech career we were doing object relational mapping and and the database was, you know, supposedly pluggable. You swap out your credentials and it doesn’t matter because you’re not using SQL anymore. Um, I think that we’re in the very early days of AI where for retrieval purposes as soon as you um soon as you start writing code, you’re locked into whatever stack you’ve
[33:13] picked. and and that dictates a lot of different design decisions that that you have to make especially as you start to scale. And where we kick in and have an advantage against let’s call it a simpler stack would be when the the data volumes get larger and the latency requirements become more um you know more I don’t want to say severe but the SLAs’s are really tight. That’s when we’re going to shine because we can do things that the other platforms can’t do and we’ve got a level of tunability especially on the relevance side that that can’t be accomplished with other
[33:46] data platforms. That’s a very good question that we do talk about in the lab but I don’t think we provide that authoritative answer key of here’s how you construct your weights based on you know things that you can tell from the shape of your data or the shape of the searches that you know users are going to execute. The um the short answer to that is today that’s actually hard to do. Um the longer answer is and and this is something that I think you’ll see come from us is um there’s a missing element to relevance
[34:22] tuning that hasn’t been um addressed in a way that makes this turnkey yet. And um I’ve actually got a reference architecture that I put out a year ago. It needs to be refined. It’s based on Mashra about auto that covers autotuning and that concept. Um, but in a perfect world, you would actually be able to take the searches that are coming through the system and the telemetry from those user experiences and things like click-through traffic and and and thumbs up, thumbs down, basically telemetry from the users. And then also
[34:54] um any other business metrics that you have wired into your use case to uh to actually tune the relevance which might introduce different weights for linear. Um it might um toggle between RF and linear with specific weights depending on the type of query coming in or um you have all sorts of other types of techniques. The one that I think is more common than even those two is just coming up with different sets of of filters um based on the the query that’s coming in. So um Sunnil built out the original architecture for this. We
[35:28] called it an intelligent search layer. Um and it’s something that Azure search has tried to kind of wire into their product. It is something that you can actually do today with elastic using the agent builder construct which is covered in the last lab. Um, but that’s that’s a little bit different technique than just tweaking the weights on the fly based on what we’re seeing. You you would actually have um the um the LLM interrogate the query and then and then execute searches with different filters based on that interrogation, which I
[35:59] actually love that technique. I think it’s fantastic and I’m glad that we have a construct for it with with Elastic. And that’s that’s all, you know, stuff that agent builder designed to solve for. Yep. >> Exactly. And that’s where I’m hoping and and this isn’t something that that we’ve announced that we’re going to do yet, but I’m hoping that at some point you’re going to see uh the concept of autotuned relevance um be something you can enable
[36:31] and and have attributes or settings that you specify to to turn that on and maybe even turn it up depending on the uh the use case and and what you’re seeing with actual usage of the system. And and just to be clear with everybody in the room, we have not released any technology that does that yet, but it comes up often enough in the field when where I’m working with customers that it’s something that if we had it, it would move the needle big time and make developers lives a lot easier. Would you agree?
[37:01] >> Okay, I’m gonna I’m gonna bring it up again to our CTO and make him make him say no again. >> Right. So, we’re gonna just walk through this one. Most of you are probably along with that past it. If not, it’s all right. Um so right so we’re trying to combine the two the two different methodologies here and the the crux of the problem is and it’s in here somewhere right like BM25 has a scale it scores documents from zero to kind of whatever whereas vector search
[37:35] normally it’s zero to one and so when you have these scales that do not that aren’t the same obviously A poor result in a lexical BM25 search is almost always going to beat out from a pure number perspective a good semantic search. So then it’s the fun game of how do you combine them? And so there’s a couple of different ways. Um we don’t get into the kind of choosing one on the
[38:08] fly here but there are you know different ways to get into that. Kind of getting the basics here. So RF is kind of designed to be the out of the box works pretty well um until it doesn’t. But it’s the it’s a good first start. You don’t have to know how to tune. You don’t have to really know um the details of your data. But the idea then is that essentially forot there’s a table in here. You you throw
[38:38] out the scores. So you you run the two searches in parallel. you take the order. There’s a little bit of that rank constant in there, but essentially if you’re high, if your result document is high in both, it’s probably a good m it’s probably a good match. When they’re not, that’s where the kind of combination gets into play. And you have this pretty simple, where is that? I scroll past it. Um, scoring in here. And then you have a table. And so essentially what you’re returning is not a a uh list of
[39:11] uh score documents scored order. It’s just the rank order. And so that’s why there’s a rank constant in there. Um because you’re just getting the rank of the documents. And you can see in here, where is it working? Yeah. Um it talks about it in this table where the the documents come in in different um different orders, but by ranking them then you hopefully get the best answer for you. But that doesn’t always work.
[39:44] And actually James mentioned this a second ago, filtering is a really powerful and effective way to help along. So if you can filter your data by keyword, geoloccation, date, anything that gets that data set down to a smaller candidate pool, you’re going to have better results usually. And because you have a smaller thing, you’re not just casting a net over everything. You’re filtering it down and you’re narrowing it down, right? It’s like if if I want pizza tonight, you know, I’m not just
[40:17] going to search for food maybe, but I can if I did search for food, I can then filter by pizza and at least I’ll just get pizza results or you know, things like that. So, um that’s where filtering comes into play and it’s it’s something elastic search does very very well and and very quickly and we have a lot of different ways to do it. But then it gets into that doesn’t always work. And so you can get into linear combination and there’s we talk about minmax in here. There’s different things you can do. Um but this is where you’re
[40:48] normalizing the scores. So instead of taking the order, you’re going to then instead just normalize the scores. So everything has the same scoring range from zero to one and you can put them together. And there’s a little bit of the the tuning examples in here. It’s a again it’s kind of the um intro level to tuning for sure, but you can tune the weights and you can see um which one works well. And this is where judgment sets comes in. And this is where things like um you know we have a lot of different workshops and things
[41:23] like that and the the intelligent query layer and things like this do this more automatically not in and sophisticated way but essentially you have your judgments that that a human these days you can get an LLM to help you but um is based on this query. these are the exact documents I want. And then you run your experiments and you see which weights work for you to give those results as as accurately as possible through here. Do you have something you want to add?
[41:54] Sorry. And I will add one more item because this is actually a technique that we used in the intelligent um intelligent query layer architecture that um that that we were talking about quite a bit. uh last year and the year before. Um, Elastic supports the concept of search templates. So, you could technically have three different search strategies. One that uses RF, one that uses linear and maybe another one that uses um a combination of linear or RF
[42:27] with a reranker. And um if you have a layer on top, let’s call it an LLM that’s got a simple prompt that says based on this type of query, I want you to route to this search template. Based on this other type of query, I want you to route to this search template. You can literally have the equivalent of a what I’ll call poor man’s um autotuning where you’re literally toggling between different search strategies based on what the search query that’s coming in looks like. and you have something and it doesn’t have to be an LLM, but you
[42:57] have some way of interrogating that search to decide which search template to invoke. Most developers that are building out an advanced use case where they don’t have a single strategy that they can use for all queries are going to end up with something like that under the hood. It’s just a matter of how hard it is to actually code that up. And in the case of elastic um a lot of folks don’t know about search templates but that is a powerful mechanism that can be used uh to reduce the amount of boilerplate code you have to write for that type of architecture. Not covered in the labs but noteworthy
[43:27] to at least have an understanding that that that concept exists in elastic. So the table at the end again is kind of the take it with a grain of salt but it’s a good way to get started right like if you don’t know your your data too well or it’s all you know kind of an unknown query mix you can start with RF it does work pretty well it’s not something we didn’t invent RF but we do use it other places uses it um and then beyond that you can start getting into um other ways to com to combine the data um but you don’t always have to do
[44:00] hybrid search sometimes semantic search is enough sometimes times BM25. Um, but usually we we find that there’s some combination of of semantic and lexical search that helps the um the retrieval work most effectively. And then lab four is where you um despite the title you do put it into a model but we’re going to show you how
[44:32] again as I said at the top of this LLMs are extremely you know smart’s not their best word but you know they are effective at giving you answers um but you anytime you have to feed them data of that they’re outside their training knowledge or anything, you can pretty confidently get them to give you the wrong answer by providing them the the set of data and say the sky is orange and then usually it’ll tell you the sky is orange. Um there’s ways around that, but this is where we kind of show you that retrieval is still important to
[45:05] agentic um answers. Quick show of hands. Are there any folks that are not [snorts] actually past lab three yet? Okay, good. People are cruising along. Awesome.
[45:42] And so it’s worth mentioning too, this is where we actually get into agent builder um elastic’s agentic platform which has um the ability to obviously to run agents to run tools and skills. Um you can hook into lots of LLMs. The elastic infrance service has you know all your favorite LLMs available to it. Um but you can again bring your own um your LLM and and it’s able to then run these tools directly against uh the data within elastic and actually now it’s not
[46:15] covered in the work in the the workshop but we have uh workflows and workflows essentially are anytime you have a an ordered set of tasks you want completed can have decision trees and things like that. Um the agents can call these workflows and they can also reach out. So you can call out to other systems, you can call MCP tools, you can call APIs, call anything to your heart’s content. Um, but again outside the scope of this workshop, but since we have a little time here, this is where the agent has the ability then to start doing things. So not just retrieving your answers for you, but there’s a
[46:50] whole other workshop that you could go to where because of you know an incident for example the the observability the hotel trace data you bring in it can decide yeah the system is not is running out of of resources it needs to scale. So you can call a workflow for example to autoscale your Kubernetes environment. It’s just one example, but this is where we actually get into agent builder and it walks you through a little bit of the um the capabilities.
[47:31] and one of the more interesting things about agent builder for folks that are software developers is the fact that everything that you see in a cabana user interface in agent builder is is programmable programmable via API. So if you decided that you wanted to do a quick prototype and you’re using our agent builder mechanism within Elastic and you think, “Oh, I have to rewrite all this code from scratch now and build out a real app.” You don’t have to do that. You can reuse those same endpoints in your application and make the same
[48:04] calls in a custom user experience that um that you control. And then you have the added benefit if you decide that you wanted to pull those agent builder components out and wire in another framework or another, you know, another set of APIs that you either build or use a different framework for, uh, we would be compatible with that as well. So the goal for us is to provide as much turnkey experience as possible, but not lock you in so that you’re forced to build applications the way that we want you to build them. We’re very flexible, almost to a fault. So when you ask us a question, oftentimes the answer starts
[48:36] with it, it depends. Did anybody come in recently that doesn’t have the URL? Sorry. Thought so, but start up there. Um, so it’s in the upper right. It’s that short ELD one. And in case anyone um came in later and didn’t catch me say it, this will be available for a week, the actual workshop itself. And then the blue by James um link is the the repo that has it has all the the notebooks in
[49:08] there. It has all the other code in there, but the relevant stuff you’ll use without instruct is the notebooks. You can hook it up to any elastic search cluster you have free one. Well, sort of if you hook up a different service. Um but it’ll load the data and you can run through it all. So that that’ll be available until someone deletes it. delete me. >> By the way, thanks to our distinguished architect over here, Sunnil, we uh
[49:41] wanted to make sure that we give you bonus content, bonus workshop materials. There are additional workshops available online that have the same format that we used here today where there basically is an instruct environment. It’s pre pre-built so that you can walk through the concepts and learn more about how Elastic works under the hood. We highly recommend that you hit that URL and and use the workshops. It’s essentially free training and once you complete those workshops, you’ll probably increase your market value by I don’t know$100
[50:12] $200,000 a year. It’s a guaranteed pay raise. >> Okay. So, while people are working on that, I’m going to do two things. So, one of the So, sorry [clears throat] I kept talking a couple times about um you know providing new information and up-to-date and um fresh and whatever proprietary information to the these LLMs as a way to augment it’s where the augment the a and rag comes in augment their knowledge. The other thing that
[50:43] comes up a lot and this is coming up more and more in the in well everywhere especially as agents start running around and and doing things even faster is being able to site the sources. So models are really good at coming up with information and oftentimes it is correct. But what they’re also great at is lying to you because not because they’re specifically trained for it. But what happens is if there’s a very thin line line between say two other lines that you ask a question about and it doesn’t know that specific answer but it
[51:15] knows enough other information around the answer and about other topics and related it can come up with a extremely convincing um you know response that unless you’re an expert or really know the actual answer can can trick people. So, all that [clears throat] to say, one of the things that’s in this lab, it’s kind of in the middle, and it’s up on the screen right now, is the ability to have an LLM site sources. Most models do not have the ability to site their sources because it’s not a database.
[51:46] It’s it’s these models are not doing a table lookup and pulling information. It’s generating tokens based on his training. Anyways, so by providing the actual answers to the LM and having it parse it out and put together a human-friendly answer or whatever format you want it in, it can also then cite its sources. This is extremely important in things like legal, which is you’ve probably seen in the news come up a lot of times where lawyers are getting in trouble because they’re having cases and then they’re making up answers, citing cases that don’t exist or twisting the answers. So if you can have the model
[52:20] process you know large amounts of data complex data but still site the answer um it makes them a lot more useful and trustworthy to a point. So when you go into this as James mentioned um one of the nice things about the agent builder platform is that it is all also API driven. So that’s kind of why the the lab in this one was a little bit reversed to show that where you can build all this
[52:55] programmatically. So you can build skills and tools and agents and you know through I built this all programmatically and that way you can create it, tear it down, scale it, change it as you need um but still use all the capabilities built into the stack and things like that. Um so we’ll go in here and then you can um ask a question you know we go into overview we have a lot of skills out of the box. So these are the skills and I’m sure everyone here knows this because you’re an AI conference right but a skill
[53:30] has a lot of different things but essentially it’s explaining to um you know a model or an agent how to perform a task in a certain way. um when when tools should be used, how to create presentations, how to create other services. Um but it’s anything you can write down to kind of help it out. So it doesn’t have to just figure it out by itself. Um some things is just ways to make it faster. Some things is when you run very specific outcomes. Um if you want to give it core instructions as as shown in here. Um and so we provide a
[54:03] lot of out of the box things um skills for you like if you want to create graphs, visualizations, searching um but we also create tools. So the difference then is a tool is performing an action. So a tool that we pro you know provide here out of the box are things like running searches, listing workflows. I talked about workflows. There’s the way to actually reach out and you know query external services or run things in a very specific um deterministic manner but you can create your own tools. So if we go
[54:35] into the the agent that you created for example and you look at the overview um it’s a very you know simple agent again for the purposes of today it has one skill. It talks about how to diagnose and and um an issue that you’re looking for. So, it’s pretty pretty um pretty short here compared to the out of the box ones, but this is where you can provide as much information to to help it out. So, it helps to find the clause, find the fix, talks about um looking at
[55:06] the error codes. The other things that it can do is I think it has one tool. Yeah. So here we’re um we have a search tool but if I add other tools just to show create a tool create a new tool. Um [clears throat] this is always a fun question I like to ask. Who here knows or has heard of ESQL within Elastic? Okay, >> we got one. Nice. It’s about what I
[55:38] expect. I was happy to hear though that a a lot of you are familiar with elastic in elastic search. So that that’s good. Um ESQL is a newer u query language within elastic. It’s the ES pipeQL. So it’s a uh SQL near SQL like um language. So you have a SQL like syntax and then essentially the pipe is in there to you pipe commands together. You you run the thing, it passes it to the next pipe and so on and so on. Um do that. So you can have VSQL tools to query um you know documents in elastic search. Index search is [clears throat]
[56:12] kind of an interesting tool or yeah tool. So ESQL is you’re running a specific query. You’re you’re querying you write down the query you get back specific fields. Index search is kind of this I almost think of it as a documentation tool. So you’re you’re telling it for a specific index or set of indices this is what the index is for. This is what the field mapping is. These are what the fields are. If you have say a product index and a pricing inventory index, it tells how to combine them. Like with ESQL, you can join uh
[56:46] indices together. So it talks about that and agents because they can do round trips and do exploration. They will generally be able to figure out um you know the indexes in your in your index in your cluster. So if you just ask a question and it doesn’t know anything, it’s going to do this query search tool and it’s going to look at the mappings or it’s a mapping tool. It’s going to find all the indices and then the mappings. It’s going to try to guess like what sounds like a product thing and then it’s going to try to put them together. Anyways, it’ll roundroin for a while and that costs tokens and we all
[57:19] love token spending. So this is a tool that helps speed up that dramatically and kind of help point the agent in the right direction. Workflows. I think I talked about this a few times, but we can run things in a uh orderly fashion and reach out to other systems. And then MCP, if you want to call out to an external MCP server, you can [clears throat] do that. I will mention at this point also that the tools in agent builder, both the out of the boxes one and custom tools are exposed as an MCP. So, Kabana exposes an
[57:50] MCP uh server. So any of the tools in there you can use you know if your agent has um wants to connect via MCP and the last one. So you do this in the lab but this shows basically how the agent can then do multiple um multiple loops. So it has to do first it loads the skill to see how to answer the question about um keeps dying with a 137
[58:20] why does it happen and how so this is a two-part question right why does this happen why is my cluster dying with you know the 137 uh exit code so it has to figure out the answer to that and then how do I change my settings to to prevent it so it’s a two-part question and again so runs that skill and then it starts to find the answer. So goes a couple loops and it diagnoses your problem of you know tells you why this 137 is happening. It’s actually
[58:53] it’s the o the fun out of memory manager running and killing you. Um then it talks about how to uh tune your JVM options to to fix it but talks about preventing. So because the answer within was within elastic and it had the ability to you know query it and then run multiple tools and things like this it’s able to kind of get you that answer and uh get you get you on your way. >> Yeah. And the one thing I’ll add is that if you’re if you’re in active prototype mode and you’re trying to to get to um
[59:26] search logic or query language um logic that that actually solves for your use case. This is actually a a pretty nice developer tool and debugging tool to find out what um what searches will work to retrieve uh the data that you need. And the last thing I’ll say about uh I’m a big fan of ESQL. I started out a little bit skeptical because there were some features in Elastic Query language that weren’t in ESQL. I think that it’s feature complete enough uh for you to to
[59:56] at least take a look at it, especially if you’re building a gentic search use cases because there’s some really cool concepts in ESQL uh that lend themselves well to um to solving for for certain search um tasks better than elastic query language, which you should consider a superset of what ESQL is today. Um, and the other thing about ESQL that makes it fantastic is uh the ability to have parameterization wired into the MCP tool calling chain and and wired up with agent builder, which is um a fantastic ad that technically is
[1:00:31] doable outside of ESQL, but the way that we have architected ESQL and our agent builder and our MCP endpoint, it is the happy path to a lot of the um let’s call them agentic search use cases. that you might have. So if you have not looked at ESQL yet, highly recommend you do that. And if you were trying to pay attention to some of the innovative stuff that we’re doing around search, first place to to look is actually going through the ESQL docs and seeing what new novel um retrieval mechanisms we’re coming up with because we’re doing some very
[1:01:04] interesting things with federated search and potentially calling out the different systems within an elastic query language um you know query that that is not considered traditional elastic. Um, and that’s stuff that’s in development now, but you’re going to see that hit hit the product. And when it does, ESQL is going to be your gateway into that. And I’m talking about things like being able to do like parquet queries on things that are external to Elastic with with an SQL call, which could be
[1:01:35] incredibly powerful if you’re also joining that with data that comes from Elastic. You can actually see that the the agent used ESQL for this uh this call. So this is what it looks like. Um so it can do things like fork off and then so this is where it’s combining uh two of the two of the search threads. That’s what the fuse is down there. And um so it’s able to ask these questions and then return the answer. So you can see it’s you know there’s the pipes that can um
[1:02:08] again you run a query you run a phase of it essentially get the answer and it moves on to the next and next pipe language like that. So it’s um yeah it’s very parameterizable is >> parameterizable and it’s it’s trying to accomplish all the things that the Splunk query language tried to you know to do with with Splunk in its heyday. uh and then um and then also marry that with SQL concepts which are obviously tried and true and I think that the uh
[1:02:39] the last thing that you’ll see with ESQL is the queries are are more tur they don’t have as much markup in them uh to actually get to get the retrieval right which is one one added benefit to that piped uh construct and there are other other companies that that leverage the same technique in order to build out um you know search usually it’s for unstructured data sets logs Um, and you know, and I’d say that that was the primary reason we started building ESQL was to build, you know, the best best-in-class search experience
[1:03:10] so people could get rid of all their Splunk stuff. And and now we’ve pivoted to where this construct is so useful that it should be available in all the pillars of elastic, search, security, and observability. It’s a first class citizen construct for for for all three pillars going forward with a primary it being the primary mechanism for where we’re going to innovate. >> And so you can see when it’s doing its one of the the hybrid search query, it [clears throat] responds. It shows you so you have the you have the audit trail
[1:03:41] essentially of how it got to these answers. So, not only citing the answers all the way at the bottom and you can click on them and if you want to deep dive into the fun world of JVM settings, you can do that. Um, never doing that again. But, um, just kidding. One of the nice things too is then it’ll show you. So, we’re limiting five and it it does five. It tells you it found five results. um doesn’t clutter it all up in in the UI here for you. But you can click on that and you can hop over to this is discover. It’s kind of where we
[1:04:14] discover documents. It’s the kind of normal searching around interface of Cabana. It’s changed a little bit over the years if you haven’t used it in a little while, but now you can do ESQL in there. And you can see here then it has the five documents that it came back with. And if I close like some of these panels, builds a nice little chart for you. I don’t know if that’s the most helpful chart, but you can see then with the query up at the top, you have the actual documents. And go in and see the full thing. And so here’s the body of it. And so we were
[1:04:51] searching part of this. Oh, here it is. Looking for the URL. So the URL again, this is because we provide the URL as part of the document, we’re able to, you know, provide essentially a link to more information without having to just guess. >> I think this room closes out at the 420 mark. Is that correct? >> Yeah. Timer says 18 minutes till >> 18 minutes, which means you have >> Let the hammer come and hit us. >> Yeah. Which means you you do have a little bit of time to ask questions. >> Yeah. And there is the Yeah, feel free
[1:05:24] to ask questions. Sorry. Um there is the lab five about um rerankers. Lights are like burning my brain. Um so reranking in there is is an interesting um thing that I think a lot of people don’t kind of fully understand why you want to use it. And so that’s why we added this on um to kind of explain why you want to use it. And if this spins,
[1:06:03] see if that comes up. Maybe it’s my thing. Reranking is taking the So if if [snorts] the queries that we’ve been doing here and everything is the first phase, call it of of retrieval. The second phase you can do retrie uh reranking. And so if you’re running vector search, semantic search, hybrid search across a first phase and get back a large set of data, then you can take that data and you can rerank it. And reranking has I
[1:06:35] wish this thing was working. I think it’s me. re-ranking combines the the query and the the document as scoring time together. So normally with with vectors you you know you ingest all your data whenever that is and then at query time you query it and it just does um HSW or or one of the disk algorithms and returns a set of documents but the
[1:07:07] the query and the the documents aren’t really scored together. Reranking combines those together, but because they’re running together at at that query that phase second phase time, you can’t pre-mbed. So you pay the penalty of having to run inference at, you know, at query time. Now the way you do this then to kind of help this along is by not reranking your entire corpus of data. You run the first phase to get a smaller set of data and then rerank with
[1:07:41] a model to then you know rerank that that small set of data. Sorry, there we go. Trying to show an example instead of just talk. Here we go. My lab was dying.
[1:08:18] So if you get to this in here, you can see toward at the end um again kind of the points on here about when you can add a ranker if you have that that the latency budget. If you don’t if you can spend a a little bit of extra time to let this second phase run and generating embeddings because that precision of the you know if it’s answer one versus answer two if that is a critical step that’s where paying you know the the slight um latency penalty
[1:08:50] comes into play. If you just get your documents good enough in the first phase and let the agent go after them, then you probably don’t need a reranker. But it’s when you need to have that or that specific order come into play um come in and um and we see that a lot with agentic search use cases. We’re seeing a lot of situations where folks are testing the evaluation based on the first, second, and third document chunk coming back, which gives you a very small window of opportunity to get the answer right. If you’re just handing a
[1:09:23] small set of candidates to the to the large language model to answer the question versus a larger candidate set and then and then asking the model to get it right. And and that’s where a lot of relevancy issues come in. You’re passing in too much context. It’s a multiple choice where two or three answers look equally right to the LLM and it just picks one and and if it picks the wrong one then your your users and their beta testers for your new agentic search system complain about the search not working. Very common, very
[1:09:53] very common. And um you know oftentimes a reranker like this will will actually be very very useful. And so there’s two points or two types of um reankers at least you know that we support. So there’s point-wise these are what most reankers are today and this is what that the V2 model is. And so the point-wise it it still combines the it takes the query and the document together but it just scores them independently. It’s only looking at the
[1:10:26] the query and the document, nothing else. Listwise, which is what is in the Gina V3 model, takes your candidate set and I think it right now, for example, up to 64 documents or 64 candidates and it looks at them all together. And so that way way if the if the answers essentially or the the potential candidates are all very similar like they’re all pretty much talking about the same thing. That’s where having the listwise can edge out pointwise because
[1:10:58] it can see the nuance see it can see the nuances um within that list because it sees the multiple documents together. Um it does take a little bit of extra u memory or or time because again it has to generate embeddings for all those candidates all at once and hold them together in memory and run um run its evaluation across them as opposed to just firing one at a time and do that. So if your if your data is pretty diverse and where the answers come back
[1:11:34] and it’s you know it’s a pretty distinct set of candidates where you know one two three four five are all pretty different enough that the pointwise is hitting it. Sorry. There we go. Um then point wise usually pretty much usually works out. But again, if you have that set where the the potential candidates are all extremely similar, listwise is probably going to help you out for the best.
[1:12:08] and somewhere in here because we want to be helpful. You don’t have to run um while it is a two step a two-phase um you know phase one is query phase two is your ranking you don’t have to manually um have those as separate separate API calls we can do it all in one shot um you do it in the lab it’s in the retriever you can you can do it >> can you rerank any SQL >> yes >> yeah okay [laughter]
[1:12:39] um so you can do it in SQL too but one dot basically you have the reranker you tell what reranker you want to use you know the model and the query and it runs both phases for you so that way again you’re not having to manage the inference setting separately you’re not having to call the inference API then query then rerank you can just fire it all in one shot and we’ll take care of it for you so I’m going to put up that slide again with few of the links again.
[1:13:12] So the upper right is what we’ve been doing today. That’s available for a week. The bottom blue reference repo is where the the code for this lives, the notebooks and things like that. And then there’s the two red ones in the middle. Um Sunnil’s secret elastic environment. Oh man, typo it too. Um everyone’s gonna take a picture of it. So, and then the other god >> just proves that we’re in a live session. >> I’m gonna blame the lights >> and that we’re just, you know, we’re
[1:13:45] doing stuff on the fly. >> Still got to run. Okay. Um, and then the other workshops online. So, we do have a bunch of other workshops that online that are completely free. And so things like working with streams, if you have streams of data coming in, it’s extremely um efficient way to handle that data. Another rag one, lexical search, vector search tutorials.
[1:14:17] If you have anyone’s doing uh observability work, so things with open telemetry data or looking for root cause analysis, things like that, we have a labs on that. So, a couple observability labs. Should be some security ones in here. So, security is a big platform, our big part of our platform. Um, doing anything from like attack discovery and detection rules. I know there’s new ones coming out too. Um, as we add in more and more agent capability into the stack.
[1:14:56] Any questions? All right. So, let me ask a question real quick. If you hang out in here, do you automatically get a seat in the next workshop? I’m just curious if that’s why people hang out. Okay. I’m trying to judge who’s still working and who’s just hanging out, which is totally fine. I Yeah, I get to leave either way. We’re going to assume that most of you all are hanging out and that you’re not, you know, waiting for help on anything. But
[1:15:27] if if you are, you’ve got another 7 minutes and 57 seconds. Sil, you want to demo anything for seven minutes? Hopefully this was a good use of your time for the folks that are still in the room. And we’d love to get your feedback. We didn’t tell you this, but there is a feedback um data entry point at the end of the workshop. So, when you finish it, you do have the ability to tell us how awesome the workshop is or or how much you didn’t like it. And if and if you say bad things, then it will
[1:15:58] hurt our feelings. But but we will make the workshop better for others after the fact.