RAG precisa de um mapa: usando GraphRAG para recuperar contexto conectado — Nyah Macklin, Neo4j
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: RAG Needs a Map: Using GraphRAG to Retrieve Connected Context — Nyah Macklin, Neo4j · Canal: AI Engineer · 52:56 · Assistir no YouTube
Tópicos: Agentes de IA, Dados, bancos de dados e embeddings, RAG, busca e recuperação de informação
Nyah Macklin apresenta os fundamentos de GraphRAG e explica como incluir um grafo de conhecimento no caminho de recuperação pode ajudar a responder perguntas que exigem conexões entre informações. A palestra compara RAG baseado em vetores com GraphRAG e destaca que combinar os dois métodos costuma ser mais útil do que substituir um pelo outro. Em uma oficina prática, os participantes criam um grafo a partir de dados textuais e conectam um agent ao grafo usando busca por similaridade e consultas Cypher. A demonstração também aborda a construção do grafo, a configuração de ferramentas e o uso de um schema para orientar a extração de entidades e relações.
Pontos-chave
Seção intitulada “Pontos-chave”- GraphRAG inclui um grafo de conhecimento no caminho de recuperação de informações.
- RAG baseado em vetores pode ser suficiente para perguntas que se parecem com uma busca convencional.
- GraphRAG pode ajudar em perguntas que exigem múltiplos saltos entre entidades, agregação ou informações de documentos diferentes.
- Combinar busca vetorial e recuperação baseada em grafos permite aproveitar os pontos fortes de ambas.
- Grafos de conhecimento representam entidades e relações de forma legível tanto para pessoas quanto para máquinas.
- A oficina demonstra a extração de entidades e relações de textos com um LLM e a criação de um grafo no Neo4j Aura.
- O agent da demonstração usa busca por similaridade e uma consulta Cypher para recuperar conteúdo conectado.
- Um schema definido para o grafo orienta o LLM e limita os tipos de nós e relações que ele pode gerar.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:13 | Abertura e apresentação da palestrante | Nyah Macklin apresenta o tema, consulta a experiência da plateia com RAG e descreve seu trabalho na Neo4j. |
| 02:17 | Preparação para a oficina | A palestrante apresenta a equipe de apoio e orienta os participantes a acessar a Graph Academy e os materiais. |
| 06:54 | Grafos de conhecimento e explicabilidade | A palestra compara representações vetoriais e grafos e explica como as relações podem facilitar a rastreabilidade das respostas. |
| 11:41 | RAG baseado em vetores e GraphRAG | Nyah descreve os dois fluxos de recuperação e discute quando perguntas com múltiplos saltos podem se beneficiar de GraphRAG. |
| 15:23 | Retrievers e construção de grafos | A palestrante explica o papel dos retrievers, define grafos de conhecimento e apresenta as etapas para construí-los a partir de texto. |
| 23:12 | Configuração do ambiente e conexão com o banco | Os participantes abrem um ambiente no GitHub Codespaces e configuram as credenciais para conectar ao banco de dados. |
| 28:24 | Geração e consulta do grafo de conhecimento | A oficina executa o construtor do grafo e mostra como consultar e inspecionar os nós e as relações no Aura. |
| 32:09 | Criação e configuração do agent | Nyah demonstra como habilitar os recursos necessários e criar um agent vinculado ao grafo de conhecimento. |
| 37:00 | Busca por similaridade e consulta Cypher | A palestrante configura um índice vetorial e adiciona ao agent uma ferramenta de busca que retorna dados conectados do grafo. |
| 43:52 | Testes do agent e agregação de informações | O agent responde a perguntas sobre o conteúdo e demonstra tanto a recuperação de contexto quanto a contagem de aulas. |
| 47:30 | Código do construtor e encerramento | A equipe revisa o código que gera o grafo, explica como o schema orienta a extração e apresenta recursos para continuar aprendendo. |
Citações
Seção intitulada “Citações”GraphRAG é RAG, mas o caminho de recuperação inclui o grafo de conhecimento. — 12:45
Usar os dois é, na verdade, a chave aqui. Queremos usar tanto grafos quanto vetores. — 14:21
Usar um schema como esse vai orientar o LLM para que ele não invente novos tipos de nós e relações. — 50:05
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- GraphRAG (conceito): Abordagem de RAG em que a recuperação inclui um grafo de conhecimento para encontrar relações e contexto conectado.
- RAG (conceito): Método que recupera informações de fontes externas para fornecer contexto a um LLM na geração de uma resposta.
- Knowledge graph (conceito): Representação de entidades e das relações entre elas em forma de grafo.
- Vector Search (conceito): Técnica de busca que usa representações vetoriais para localizar informações semelhantes.
- Cypher (conceito): Linguagem de consulta otimizada para trabalhar com grafos.
- Nyah Macklin (pessoa): Engenheira de software sênior e developer advocate sênior na Neo4j, que apresenta a oficina.
- Neo4j (empresa): Empresa associada à plataforma de banco de dados de grafos usada na demonstração.
- Graph Academy (ferramenta): Plataforma de aprendizado online da Neo4j, usada como material e ambiente de oficina.
- Neo4j Aura (ferramenta): Plataforma hospedada na nuvem usada para criar e consultar o grafo de conhecimento.
- GitHub Codespaces (ferramenta): Ambiente de desenvolvimento usado pelos participantes para executar o código da oficina.
- OpenAI (empresa): Serviço cujas credenciais e modelos de embedding são usados na demonstração.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:13 Olá, pessoal. Muito obrigado por virem hoje e sejam bem-vindos a “RAG precisa de um mapa: usando GraphRAG para recuperar contexto conectado”. Antes de começarmos hoje — sei que ainda tem gente chegando —, queria fazer uma enquete rápida para saber quem já usa RAG nos pipelines, o RAG comum baseado em vetores. Beleza, ótimo. Tem alguém que já usa RAG baseado em grafos nos pipelines? Certo, entendi, ainda estão trabalhando nisso. Vejo
00:44 só algumas pessoas. E quem já usa RAG baseado em grafos nos pipelines poderia explicar o que é GraphRAG? Algumas pessoas mais ou menos. Certo. Tem gente dizendo “mais ou menos”; tudo bem. Para quem está conhecendo o conceito, vamos fazer uma espécie de introdução individual a GraphRAG. Se você já é especialista, provavelmente já sabe do que estamos falando. É só para nivelarmos o conhecimento. Mas,
01:15 no geral, quero garantir que todos saibam sobre o que vamos falar hoje. Para me apresentar brevemente, meu nome é Nyah Macklin e sou engenheira de software sênior e developer advocate sênior aqui na Neo4j. Minha pesquisa se concentra na teoria dos grafos, em algoritmos de grafos e também em engenharia de contexto, sempre tentando entender as muitas arquiteturas usadas para criar agents e também quais arquiteturas são mais adequadas para abrir essa caixa-preta
01:45 e conseguir decifrar, rastrear e explicar como os sistemas de inteligência artificial funcionam. Também dedico bastante tempo a pensar em governança e segurança de IA, o que acaba sendo muito importante ao pensar em como seu agent toma decisões e como ele é construído. Trabalho com isso há cerca de uma década e estou animada para trazer todos vocês — para voltarmos ao básico e tentarmos entender o GraphRAG. Então, este é um workshop do tipo “GraphRAG 101” para quem está começando a conhecer
02:17 o conceito. Hoje, tenho dois colegas de equipe incríveis que vão me acompanhar, além de mais um colega que também está aqui. Tenho meus colegas Jeremy Adams Castanas, que está aqui na frente. O Jeremy está acenando para todo mundo. Se tiverem qualquer dúvida, por favor, perguntem ao Jeremy. Também tenho meu colega Ryan Knight, que está aqui em algum lugar, acho. Ah, ótimo. Oi, Ryan, que bom ver você. O Ryan vai me acompanhar. E também temos um convidado especial, o palestrante da sessão anterior, Zach,
02:49 que está lá atrás. Ele é um engenheiro de pesquisa em IA incrível na equipe da Neo4j. Também está aqui para nos acompanhar e ajudar com qualquer dúvida que vocês tiverem. Então, se tiverem alguma pergunta, basta levantar a mão durante o workshop, e um dos meus colegas irá até a mesa de vocês e ajudará a resolver. Antes de começarmos, só alguns avisos. Hoje, vamos usar esta plataforma chamada Graph Academy para acompanhar o workshop. Alguém já se inscreveu,
03:19 usou ou ouviu falar da Graph Academy? Certo. Não? Tudo bem. A Graph Academy é nossa plataforma de aprendizado online totalmente gratuita para sempre, onde vocês podem aprender sobre todos os conceitos de que vou falar hoje. Ela ensina vocês a criar agents. Ensina sobre memória agentic e sobre grafos de contexto, caso já tenham ouvido essa expressão. Há muitos cursos diferentes disponíveis online, todos totalmente gratuitos. Eles não são cursos para ficar sentado ouvindo uma palestra.
03:50 São cursos práticos, para pôr a mão no teclado e começar a construir. Esse é o principal objetivo da Graph Academy, e ela é um recurso realmente excelente para vocês usarem. Mais uma vez, totalmente gratuita, a qualquer momento. Então, vamos usá-la hoje. Para começarmos, quero que criem uma conta na Graph Academy. Deve ser um processo rápido. Acessem graphacademy.neo4j.com
04:20 e comecem a criar a conta. E, mais uma vez, esses recursos são gratuitos. Vocês podem usar o material durante todo o tempo que estiverem aqui no AI Engineer ou enquanto continuarem aprendendo sobre grafos e RAG. Também tenho aqui um link com todos os links de que vamos falar hoje. Todas as anotações que temos. No final, também vou compartilhar com vocês os slides desta apresentação. Mas acessem dev.neo4j.com/workshop-genai
04:50 neo4j.com/workshop-genai-notes; lá estão todas as informações de que precisamos. Vou acessar agora mesmo. E vocês verão aqui — se eu conseguir, sempre tenho que lutar com essas coisas — que este é o documento que vocês acessam ao clicar no link com “-notes”. Aqui temos alguns links que vocês verão depois de se inscreverem na
05:20 Graph Academy. Também quero que criem uma instância do Neo4j Aura. Essa é nossa plataforma na nuvem hospedada. Vamos fazer tudo isso de graça. Então, por favor, não cliquem nas instâncias pagas. Quero que cliquem na instância gratuita. Mais uma vez, lembrem-se de que estamos fazendo tudo isso de graça. Cliquem na instância gratuita. Se quiserem mais ferramentas no futuro, podem escolher a instância profissional ou outra opção. Mas vamos criar uma instância gratuita, que vai permitir que vocês
05:51 se conectem ao que vamos explorar hoje: os agents do Aura também. Ou seja, criar agents dentro da plataforma Aura. E vocês podem ver aqui — sei que todo mundo gosta de uma boa API key gratuita. [risos] Não se preocupem, não revelei minha API key aqui. Mas temos uma API key da OpenAI que vai dar acesso a vocês para construir hoje. Queríamos facilitar ao máximo e deixar tudo fácil para começarem. Então, estamos dando a vocês uma API key gratuita
06:22 que podem usar para construir. Temos limites, então não dá para acumular uma conta enorme, mas, por favor, copiem essa API key ou salvem no computador. Mais uma vez, ela também estará neste documento quando vocês o acessarem, para que possam consultá-la depois. Só queria mostrar este documento para vocês. Há algumas maneiras diferentes de começar a usar a Neo4j, mas tudo bem. Enquanto vocês trabalham em
06:54 criar essas instâncias e essas contas, vamos começar com parte do material de que vamos falar hoje. Vou dar uma breve introdução e, em seguida, vamos explorar o que será abordado na Graph Academy. Primeiro, muitos de vocês já devem ter ouvido falar disso, porque já trabalham com RAG e RAG baseado em vetores. Mas, para superar o problema da caixa-preta da IA, muitas vezes precisamos tornar transparentes o próprio conhecimento
07:27 e os próprios dados. Aqui, vemos a representação de uma maçã para um ser humano, bem no centro. À direita, temos também a representação vetorial de uma maçã. Nessa representação vetorial, vocês veem esta sequência de números, certo? São números de ponto flutuante, para quem é da área de engenharia. Mas esses vetores não são necessariamente legíveis nem compreensíveis para as pessoas, a menos que vocês tenham memorizado a representação vetorial de uma maçã. Mas
07:59 Cada objeto pode ser representado como um vetor ou como dados propriamente ditos. Mas todo objeto que existe na Terra pode ser representado aqui. À esquerda, vemos uma representação de uma maçã em um grafo de conhecimento. Certo? Podemos ver que essa maçã vem de uma árvore, que tem um corpo específico e uma aparência específica. A maçã é redonda. Esta maçã em particular é vermelha. E uma maçã é
08:32 uma fruta. Não estamos falando da empresa. Então, os grafos de conhecimento podem fazer com que aquilo que os humanos entendem também seja entendido pelas máquinas, e muitas vezes criam uma fusão dos dois. Assim, é possível entender que esta é uma representação em grafo de uma maçã, legível tanto por máquinas quanto por humanos. Se você chegou atrasado e não tem acesso a estes materiais, Jeremy e Ryan estão passando por aí. Eles têm os QR codes. É só
09:04 levantar a mão, que eles vão até você e entregam o QR code dos materiais que acabei de mostrar no slide. Mas, neste momento, a maioria das pessoas tem os dados estruturados em tabelas e linhas ou, como mostrei antes, em vetores. Quando os dados estão estruturados em tabelas e linhas, muitas vezes é preciso fazer várias junções complexas nesses dados
09:35 para descobrir como essas linhas e tabelas estão relacionadas entre si. E sabemos que isso vai reduzir drasticamente o desempenho da nossa aplicação. Não podemos permitir isso, especialmente porque a maioria de nós lida com a mentalidade de São Francisco: mover-se rápido e quebrar coisas, certo? Fazer funcionar mais ou menos e depois colocar em produção. A gente resolve, sabe, resolve os problemas que surgirem. Então, essa é a maneira mais lenta de fazer as coisas. Não temos tempo para isso, certo? Temos que agir rápido. Temos que ser precisos e temos
10:07 que ser explicáveis. Se você estruturasse todos esses mesmos dados em um grafo de conhecimento, as relações, conexões e agrupamentos ficariam muito mais claros. Assim, seu agent pode literalmente saltar de um nó — e, quando digo nó, quero dizer um círculo — para o próximo círculo, por meio dessa relação que vemos, certo? A linha representa a relação. Podemos saltar de um nó para o próximo nó de informação e conseguir rastrear e
10:38 explicar o que aconteceu no passado. Isso é uma melhoria enorme, certo? Quando você consegue saltar entre nós usando coisas como a memória do agent — algo que, na verdade, não vou abordar nesta palestra. Tenho outra palestra inteira que explica a memória do agent. Mas, com esse conceito de memória do agent, você pode ter essa memória e esse contexto de como o agent chegou à decisão que tomou no passado. E isso é incrível para lidar com casos em domínios regulamentados, como
11:10 casos de uso financeiros. Vocês não querem um sistema bancário por vibe, certo? Ninguém quer um sistema bancário por vibe. Vocês não querem que seu agent tenha acesso ao seu dinheiro e depois gaste tudo. Já vi isso acontecer antes. O mesmo vale para áreas como a medicina, espaços regulamentados e áreas jurídicas. É aí que esse contexto, esse histórico e essa memória são muito, muito importantes. Mas, com uma representação em grafo de conhecimento, as possibilidades de seu agent dar respostas explicáveis, rastreáveis e precisas se tornam muito
11:41 maiores — e alguns diriam que são infinitas. Então, novamente, como esta é uma oficina introdutória, quero garantir que as pessoas entendam a arquitetura de um sistema RAG baseado em grafos. Em um pipeline RAG normal, não se usam grafos de conhecimento, certo? No pipeline RAG básico. Em um pipeline RAG normal, você pode pegar alguns PDFs, por exemplo, dividi-los em trechos e indexar esses trechos usando um modelo de embedding de texto. Quando chegar a hora de consultar esses trechos de texto, você usa o mesmo modelo de embedding. Depois, tenta
12:13 buscar os k principais, ou os x principais documentos relevantes, e passar isso para um LLM. Então, seu LLM vai gerar a resposta final com base nesses documentos. E esse é o aspecto do pipeline que as pessoas geralmente usam, certo? Mas, por outro lado, GraphRAG é fundamentalmente RAG, mas nele o caminho de recuperação inclui o grafo de conhecimento. GraphRAG é quando o caminho de recuperação inclui um grafo de conhecimento. Então, você vai
12:45 ver que a arquitetura é um pouco diferente. Na ilustração do pipeline RAG que mostrei antes, o pipeline RAG normal não usava um grafo de conhecimento. Mas aqui embaixo vemos que, na verdade, incorporamos um grafo de conhecimento. Quando as pessoas me perguntam quando usar RAG em vez de GraphRAG, geralmente digo que, se você está tentando responder a uma pergunta que pode ser resolvida com um mecanismo de busca — esse é o jeito mais simples de explicar —, então o RAG baseado em vetores costuma ser suficiente. No entanto, se você quiser fazer uma pergunta que inclua
13:17 o que chamamos de múltiplos saltos. Vimos antes o exemplo de um grafo de conhecimento e seus nós. Se você está tentando fazer esses múltiplos saltos, ou pelo menos três saltos, é aí que GraphRAG se torna essencial, porque você consegue ver e determinar por onde o agent precisou passar para chegar à resposta. Mas, se você está tentando fazer, por exemplo, análise de código-fonte, ou se quer responder a uma pergunta sobre a cadeia de suprimentos, ou qualquer coisa que exija
13:49 agregação ou concatenação de dados de documentos diferentes, é aí que o RAG com grafos pode ser muito útil. E não quero necessariamente desmerecer o RAG baseado em vetores. Acho que ele é incrivelmente poderoso para a maioria dos nossos casos de uso. Mas estes são alguns exemplos em que o RAG que usa apenas vetores e os bancos de dados que usam apenas vetores podem não dar conta: situações em que grafos, a capacidade de percorrer nós e o acesso a esse contexto histórico podem ser úteis. Não vou passar
14:21 por todos esses exemplos, mas queria que as pessoas pudessem ver onde podem estar as diferenças. Em suma, quando as pessoas perguntam: “Certo, devemos usar GraphRAG ou RAG baseado em vetores?”, digo que usar os dois é a chave. Queremos usar tanto grafos quanto vetores. Não estamos dizendo que os grafos vão substituir completamente sua camada vetorial. Estamos dizendo que, se você usar os dois, terá os benefícios de ambos. Então, vamos acrescentar isso, certo? Vamos garantir
14:51 que nossos agents sejam o mais úteis possível. Certo. Vou fazer uma pausa aqui e vamos acessar a Graphacademy. Na Graphacademy, vamos abrir o primeiro link, graphacademy.com, e acessar esta oficina. O que quero que façamos é pular as primeiras seções. Claro que já fiz o curso, mas posso reiniciá-lo. Então, vamos
15:23 continuar o curso e pular algumas partes mais introdutórias, como “O que é IA generativa?”. Não precisamos saber isso. Se você precisar saber, tudo bem também. Mas, para esta conversa, vamos avançar. Vamos direto para a seção sobre GraphRAG. Certo. Já vimos o processo de recuperação do GraphRAG e as diferenças entre o processo do RAG normal e o do GraphRAG. Primeiro, vemos aqui o processo típico, que eu já
15:54 passou por isso. Você tem seus retrievers, seu usuário, sua aplicação e seu LLM, e depois seu armazenamento de dados, que normalmente é um vector store. Mas, se descermos um pouco, também veremos algumas diferenças. E o que eu queria abordar aqui é o conceito de retrievers. Muitos de vocês já sabem o que são retrievers. Levantem a mão rapidinho, assim não preciso explicar. Certo, na verdade não são tantos quanto eu pensava. Tudo bem. Tudo bem mesmo. Então vamos explicar rapidinho. Um
16:24 retriever é um componente essencial do processo de RAG, certo? Uma recuperação é responsável por pesquisar e recuperar informações relevantes das suas fontes de dados externas. E o que eu gosto de dizer — vamos aumentar isso. Muito obrigada. O que eu costumo dizer, ou uma maneira simples de lembrar o que são retrievers, é que eles são como golden retrievers, certo? Todos nós conhecemos os golden retrievers; eles gostam de buscar bolas. Gostam de buscar coisas. Então, um retriever é… Se você
16:55 pensar nesse golden retriever, ele gosta de ir buscar as informações necessárias. O retriever geralmente recebe uma entrada não estruturada, como uma pergunta ou um prompt, como quando usamos chatbots, e então pesquisa os dados estruturados para fornecer o contexto da resposta. E isso é um pouco sobre o que o Neo4j especificamente oferece: busca de texto completo, busca vetorial e também retrievers de texto ou Cypher. E temos várias fontes de dados diferentes também. Essas fontes de dados, em pipelines e processos de RAG convencionais,
17:26 podem variar: documentos, APIs e também knowledge graphs. Mas, se usássemos, por exemplo, esse chatbot de uma agência de notícias, o processo seria assim, certo? Uma API de notícias seria usada para recuperar os artigos e as manchetes mais recentes. O knowledge graph seria então usado para entender as relações entre diferentes tópicos, como a maneira como se relacionam entre si em um contexto histórico. E o banco de dados de documentos armazenaria e recuperaria artigos, reportagens ou
17:58 informações textuais também. Esse é apenas um exemplo e uma arquitetura de como isso poderia ser. Mas vamos continuar, certo? Há muitos benefícios diferentes em usar GraphRAG. Vou falar disso bem rapidinho, mas um deles é ter um contexto mais rico e, especificamente, maior precisão e explicabilidade, como vimos naquele knowledge graph. Se você conseguir percorrer seu knowledge graph e
18:29 depois usar isso junto com coisas como a memória do agent, poderá obter esse contexto histórico rico, que é realmente necessário e muito benéfico para desenvolver seus agents. Então, vamos continuar. Ouvi algumas pessoas, e meu colega passou pelo corredor um pouco mais cedo para ver se alguém já tinha construído knowledge graphs. Algumas pessoas podem levantar a mão? Alguém já criou knowledge graphs? Só algumas pessoas. Certo. Só algumas. Certo. Um pouco. Sim. Certo. Certo. Olá, mundo. Está perfeitamente bem. Sem problema. É
19:00 por isso que estamos todos aqui: para aprender mais. Então, só para garantir que entendemos o que é um knowledge graph: vimos um pouco disso no exemplo, mas, em geral, um knowledge graph é uma representação organizada de entidades do mundo real e das relações entre elas. Então, se eu sou um node — certo, sou um círculo, sou um node —, e meu colega Jeremy também é um node. Sim, Jeremy, somos nodes. E temos uma relação: somos colegas e amigos. Então, temos duas relações diferentes aqui. Mas essa é a arquitetura mais simples
19:31 de um knowledge graph. E também podemos estar conectados a pessoas diferentes. Temos nosso colega Zach e outro colega, Ryan. Há muitas maneiras diferentes, mas isso é apenas uma representação de dados na sua forma mais simples. Então, o que é um knowledge graph? Aqui vocês podem ver outro exemplo desse knowledge graph. Para aproveitar o tempo, vou pular para baixo e vamos entrar na parte de construção do knowledge graph. Para quem está acompanhando, estamos na
20:03 seção de construção de knowledge graphs. Então, vamos construir um knowledge graph rapidinho. Construindo knowledge graphs. Nesta aula, vamos revisar o processo de construção de knowledge graphs a partir de textos não estruturados usando um LLM. O processo geral consiste em reunir fontes de dados e, em seguida, dividir essas informações e esses dados em chunks. É claro que também vamos transformar esses dados em vetores e, depois, extrair nodes e relações e, claro, gerar o graph. Então, neste
20:35 exemplo, se quiséssemos construir um knowledge graph com base na página da Wikipédia do Neo4j, que podemos ver aqui, reuniríamos o texto dessa página, certo? Pegaríamos todo o texto e depois o dividiríamos em chunks. Como podem ver aqui, geraríamos embeddings e vetores a partir de cada um desses chunks e, em seguida, extrairíamos as entidades e as relações usando um LLM. Agora, se quiserem, podem fazer essa extração manualmente. Mas achamos que usar um LLM pode reduzir o tempo necessário para fazer essa extração. Então,
21:08 enviaríamos ao LLM um prompt apropriado — aqui temos um exemplo de prompt: “Sua tarefa é identificar, em um texto fornecido, as entidades e as relações solicitadas pelo prompt. Em seguida, você deve gerar a saída em formato JSON, contendo uma lista com objetos JSON.” Depois, colaríamos — desculpem, analisaríamos — essas entidades e relações, inseriríamos a saída no LLM, colaríamos isso como JSON e, então, geraríamos o graph com tudo isso. Então, vemos aqui, vemos aqui
21:39 o Cypher, que é uma linguagem de consulta otimizada para graphs. Alguém já usou Cypher? Algumas pessoas. Certo. Algumas pessoas. Então, se você é especialista em Cypher, [risos] e responder a algumas das minhas perguntas, também tenho brindes para você. À medida que avançarmos neste workshop, quero que ele seja mais interativo do que um workshop normal. Vou fazer perguntas e, se você tiver coragem de responder a uma delas ao vivo — também estamos transmitindo ao vivo —, tenho brindes exclusivos
22:09 para você. Isso inclui camisetas, brindes especiais que você não encontra em nenhum outro lugar, meias etc., além de outros brindes especiais. Então, agradeço a todos por se disporem a se arriscar e responder a algumas perguntas que possamos ter. Mas, por fim, vocês verão aqui um exemplo de um graph gerado. Temos um banco de dados de graphs desenvolvido pela Neo4j, que é uma empresa. A Neo4j não desenvolveu todos os bancos de dados de graphs em geral, mas apenas…
22:41 O Neo4j é o banco de dados de graphs desenvolvido pela Neo4j, a empresa. E ele é implementado em Java. E uma observação rápida: o nome Neo4j vem de Neo, de Matrix. Certo, para quem conhece Matrix, e de “Neo for Java”. Então, quem souber esse pequeno detalhe vai entender essa observação sobre o Neo4j. Podemos continuar. >> Ah, sim. Sim. >> Pode falar.
23:12 >> Sim. Sim, vamos fazer isso. >> Certo. Como já passamos da metade da hora, queremos que vocês aproveitem ao máximo. E algumas pessoas queriam construir o knowledge graph. Na barra lateral à esquerda, há um link que diz “GraphRAG para Python”. >> Isso mesmo. >> Acessem esse link. Se rolarem a página para baixo, ele vai levar vocês até lá. Isso vai falar um pouco sobre o pacote GraphRAG para Python, um pacote open source oferecido pela Neo4j para construir e recuperar knowledge graphs e para trabalhos com agents.
23:43 E também nesta página estão todas as credenciais de que vocês vão precisar para todos os exemplos que vamos usar. E então, Nia, quer assumir e falar sobre as credenciais e o GitHub Codespaces? >> Com certeza. Então, vamos começar. Vamos começar. Como mencionamos, agora estamos na seção de Python do Graph, e queremos rolar a página para baixo e clicar em “Abrir no GitHub Codespaces”. Depois de abrir, vocês vão precisar entrar no GitHub, caso ainda não tenham feito isso. Depois de abrir, vamos deixar
24:14 todos esses system prompts como estão. E então vamos criar o Codespace. Isso vai levar um tempinho. Enquanto ele é criado, vamos adiantar algumas coisas — não exatamente adiantar, mas fazer enquanto ele está sendo gerado. Então, enquanto isso acontece, quero mostrar a vocês que vamos criar este ambiente de configuração. Vamos criar uma cópia deste m.example. Basta clicar em “Copiar” aqui. E vamos criar isso dentro da nossa seção de Codespaces
24:44 . E o processo vai continuar. É claro que o Wi-Fi nem sempre ajuda, mas isso vai continuar. Por fim, ele vai configurar toda a estrutura de pastas e terá uma pasta M.ample. Então, em vez disso, vamos criar um arquivo M e colar todas essas credenciais nele. Na verdade, não vamos colar exatamente essas credenciais, porque o que queremos fazer especificamente — e eu coloquei isso nas
25:17 anotações — é criar uma instância Neo4j Aura. E eu coloquei isso nas anotações para começarmos. Então, criem uma instância Neo4j Aura. Como mencionei, devemos criar uma instância gratuita especificamente para este workshop. Vocês também podem criar uma instância profissional. Mas eu já tenho uma configurada. Esta instância é a número três aqui. A de vocês deve mostrar o tipo Aura, acho, ou gratuita. Mas o que vamos fazer é nos conectar a essa instância
25:48 . E, depois que vocês criarem a instância, os detalhes da conexão serão baixados diretamente para o computador de vocês, para que não os percam. E então vamos nos conectar a ela aqui. >> Sim. E há uma bifurcação no caminho aqui. Não se preocupem se, por algum motivo, não conseguirem criar a instância Aura a tempo. Seria ótimo se conseguissem até a última parte do
26:18 exercício. Mas aquelas outras credenciais que vimos no Graph Academy estão em uma pequena instância gratuita dentro do próprio Graph Academy. Então, vocês podem usá-las. De qualquer forma, precisamos dos detalhes de conexão com um banco de dados Neo4j, porque é lá que vamos construir o grafo de conhecimento. >> Isso mesmo. >> Perfeito. Então, o que estou fazendo agora é pegar as informações da minha instância e colá-las aqui no nosso grafo. Perfeito. Vamos
26:52 ver isso aqui. Também vou pegar a chave da OpenAI. Sim. E vou aumentar a janela também. Vou mover este terminal para baixo. Vou tirar isto do caminho. Perfeito. Também precisamos daquela chave da OpenAI que tínhamos pegado; vamos copiá-la diretamente das anotações.
27:23 Então, é só copiar e colar a chave aqui. Boa. Certo. Isso será salvo automaticamente se o salvamento automático estiver ativado; caso contrário, vocês terão que salvar manualmente. Agora temos isto. Depois de termos esse arquivo M, vamos testar rapidamente o ambiente. Vamos até test environment.py e executar este teste. Se estiverem usando o VS Code, vocês podem executá-lo por aqui ou usar o comando “run”
27:53 no ambiente virtual do Python, esperamos. Mas vamos executar. Certo. Aqui embaixo, dá para ver que está tentando se conectar. Perfeito. Foram executados cinco testes, e o resultado é positivo. Está tudo certo. Então, >> alguém está tendo algum problema? Se estiver, confira se criou um arquivo .env e se não está usando apenas o arquivo de exemplo. >> Isso mesmo. >> Vocês podem renomear o arquivo ou criar um novo. E isso vai
28:24 nos mostrar que estamos nos conectando ao banco de dados Neo4j e que a nossa chave da OpenAI está funcionando. >> Perfeito. Agora que o teste do ambiente foi executado com sucesso, podemos dar uma olhada. Se vocês forem até workshop.jai, verão que temos várias soluções diferentes. Temos os dados brutos. Temos
28:54 as soluções, o agent, o construtor de grafo de conhecimento e também o construtor estruturado de grafo de conhecimento. Então, vamos clicar neste construtor estruturado de grafo de conhecimento, que vai criar este grafo de conhecimento diretamente na nossa instância Aura. Se vocês também estiverem no VS Code, podemos simplesmente executá-lo. Esse processo vai levar um tempinho, mas vai gerar o grafo de conhecimento, e podemos vê-lo sendo preenchido ao vivo na instância Aura do Neo4j. Então, vamos
29:24 voltar para o Aura. Também fiz isto aqui: vou me conectar e acessar “Query”. Como podem ver, eu já fiz isso. Já o preenchi antes, porque o processo pode demorar um pouco. Então, provavelmente haverá alguma duplicação, já que eu já o executei. Mas todas essas informações serão preenchidas aqui. Depois, podemos consultar isso e ver o que existe
29:57 na instância. E podemos ver que este grafo de conhecimento vai continuar sendo preenchido conforme vocês fizerem mais consultas. Por enquanto, vamos apenas ver quais relacionamentos e nós já estão aqui. Então, temos P e, depois, “match P”
30:37 . Cometi um pequeno erro de sintaxe aqui. Ah, obrigado. “Match P equals”. Isso mesmo. Ótimo. Agora podemos ver — vou ampliar para conseguirmos enxergar o que está acontecendo — todos esses nós e relacionamentos diferentes, apenas
31:08 com base nos dados que ingerimos no grafo de conhecimento. Vocês podem clicar nesses dados e inspecioná-los também. Esta não é apenas uma ferramenta de visualização, mas também uma ferramenta de consulta, uma forma de consultar os próprios dados. Este é o grafo de conhecimento concluído. O grafo de vocês será bem menor. E, quanto mais vezes executarem esta consulta específica, “match p equals empty”, como um nó, na verdade. Então, “empty
31:39 node”, depois “return that p”. Quanto mais vezes executarem isso, mais o grafo de conhecimento vai crescer. A consulta, em geral, está apenas dizendo: mostre todos os nós, certo? Mostre todos os nós e relacionamentos. Ótimo. Então, depois de termos esses nós e relacionamentos, para quem
32:09 estiver com problemas nesse processo, podem levantar a mão. Temos colegas que vão ajudar vocês. Mas, quando o grafo de conhecimento começar a ser gerado, queremos entrar e criar um agent. Ah, estou vendo algumas mãos bem ali atrás. Talvez vocês ainda não estejam vendo a seção “Agents”. Se não estiverem, levantem a mão aí. Certo? Mas sei que algumas pessoas provavelmente ainda não chegaram a essa etapa. Mas, se
32:42 Se você não estiver vendo esta seção de agent, o que quero que faça é acessar sua organização, sua organização NearJ. Depois, vamos clicar em todas as organizações. O que vamos fazer é habilitar os recursos Jedi nesta organização. Estamos nesta nova organização. Em seguida, vamos acessar as configurações. Eu já habilitei isso, mas, para quem não sabe como habilitar ou nunca usou o Neo4j Aura antes, aqui temos…
33:13 Você vai clicar nestas duas opções. Elas estarão esmaecidas, mas quero que clique nelas para habilitá-las. Então, assistência de IA generativa e, especificamente, o Aura agent, porque hoje vamos criar um agent. Ah, temos algumas mãos levantadas. Perfeito. Depois que tivermos essa organização, vamos voltar à nossa organização específica. Vamos voltar à nossa instância.
33:44 Vamos abrir nossa instância no modo de consulta. Veremos nosso agent… veremos nosso grafo de conhecimento sendo preenchido. Em seguida, vamos clicar aqui, em agents, e neste agent aqui. Eu já tenho um agent aqui, mas o que vamos fazer é criar um agent. Então, vou criar um agent do zero e vinculá-lo a esta instância específica. Ele deve ser preenchido automaticamente com base na instância mais recente que você criou
34:17 e vamos configurá-lo. O que queremos que este agent faça… vamos chamar este agent de… fundamentos de GenAI. Na verdade, vamos chamá-lo de Fundamentos de GraphRAG. Agent de Fundamentos de GraphRAG.
34:51 Perfeito. E, para a descrição deste agent, vamos dizer que ele fornece informações sobre GraphRAG do Neo4j, fundamentadas neste curso específico da GraphAcademy que temos.
35:25 Então, temos este agent e, mais uma vez, para quem está acompanhando, ele vai fornecer informações sobre o grafo do Neo4j, fundamentadas neste curso específico da GraphAcademy. Por fim, vamos fornecer aqui as instruções para esse agent. Essa instrução será… e podemos simplesmente copiar e colar. Também vou incluir isso na seção de notas do GenAI, para que todos possam ver.
35:57 Vou acessar as notas. Esta é uma maneira fácil de criar a descrição do agent para vocês, para que possam copiá-la e colá-la e fazer com que seu agent trabalhe conosco aqui. Se tiverem dúvidas, fiquem à vontade para levantar a mão. Certo. Também vamos copiar isso para o nosso agent. Temos a instrução e
36:28 depois vamos deixar quase tudo como está: também o local da instância e do agent, e então, interno, e o que queremos fazer. Perfeito. É… criar esse agent. Mas, na verdade, queremos…? Sim. Certo. Antes de criar esse agent, vamos tentar adicionar uma busca por similaridade a ele. Se você ainda não
37:00 tiver adicionado uma busca por similaridade ao seu agent, ou uma busca vetorial — especificamente, um índice vetorial —, precisamos fazer isso para que este prompt apareça. Você receberá um prompt separado dizendo que a busca vetorial é necessária para fazer isso. Um bom lugar para encontrar essas informações… vamos fechar isto. Ah, podemos deixar aberto. O que vamos fazer é acessar a seção de Python…
37:30 A seção de Python. Há outra… vamos ver, na seção de Python do Graph… aqui está. Também vou colar isso nas notas para vocês. Adoro usar o modo de tela cheia. Vamos lá. Vou sair do modo de tela cheia. Certo, deixem-me colar isso para vocês. Vamos criar um índice vetorial. Então, queremos acessar este link aqui.
38:03 Criar índice vetorial. Legal. É isso que vocês vão fazer. Cliquem nesse link, que fornece um código de exemplo para criar o índice vetorial. E vou mostrar agora onde vamos inserir essas informações. Temos aqui a opção de criar um índice vetorial. Basta copiar isso e depois vamos incluí-lo.
38:35 Então, sobre o índice vetorial, vou perguntar ao Jeremy: você se lembra onde colocamos nosso índice vetorial? >> Sim. Bem aqui, na janela de consulta Cypher. >> Sim, você tem razão. Está absolutamente certo. Certo, vamos voltar. Vamos sair daqui. Isso depende da instância que você está usando. Se estiver usando uma instância Aura, acesse a interface de consulta no console do Aura. Então, talvez você queira…
39:07 abrir outra janela. >> Isso. >> Assim, você pode deixar seu agent aberto, ou vai precisar fechá-lo por um minuto e acessar a consulta. >> Certo. E então você pode criar esse índice vetorial. >> Então, como o Jeremy mencionou, vamos colar esse índice vetorial aqui mesmo na janela de consulta Cypher. Você vai executá-lo e verá que vamos… ampliar isto. Certo, este comando… Acho que isso aconteceu porque eu já tinha… Ah, sim, ele já existe. Exatamente. Porque eu já tinha
39:37 executado isso. O que você vai fazer é executar esse comando e ele vai mostrar o índice vetorial que foi criado. Depois que o índice vetorial estiver criado, você poderá acessar a seção de agents e abrir o prompt que vimos. Vou fazer a mesma coisa de novo: criar do zero, configurar e fazer a mesma coisa. GraphRAG. Ótimo. Preenchimento automático.
40:10 Ótimo, descrição. Isso mesmo. E temos o mesmo prompt. Beleza. Em seguida, vamos à seção de adicionar ferramenta. Agora, busca por similaridade. Agora você deve conseguir ver o mesmo prompt. Para esta ferramenta de busca por similaridade, vamos criar uma ferramenta que vai pesquisar o conteúdo desta aula e nos permitir
40:40 obter insights desta aula sem precisar fazê-la. Pesquisar conteúdo da aula. E temos uma descrição que também vou colar. Vou colá-la. Certifiquem-se de que todos tenham essa descrição também. Descrição da busca por similaridade.
41:12 Perfeito. Agora está nas notas, para que vocês também possam usar. Em seguida, vamos selecionar especificamente o índice vetorial que acabamos de criar, chamado chunk embedding. Vamos escolher cerca de cinco resultados do topo. Depois, vamos selecionar nosso provedor de embedding, que é a OpenAI. Para o modelo de embedding, vamos usar o text-embedding-3-small. Serve perfeitamente. As dimensões padrão são 1536. E precisamos garantir que vamos retornar estes dados do grafo conectado
41:44 o que é muito, muito importante, especialmente porque estamos usando esta interface de grafo. Vamos retornar esses dados do grafo. Para isso, podemos usar linguagem natural aqui, mas também podemos usar Cypher especificamente. Para esta consulta Cypher, já temos uma consulta pronta. Estou tentando lembrar onde ela está. Ah, tem um modo claro? Ótima pergunta. É muito difícil de enxergar. Sim, vamos aumentar.
42:18 Ótimo. Para esta consulta Cypher, vamos usar este Cypher aqui, e vou colá-lo para vocês. Esta é a consulta Cypher que vamos usar. Então, ela é… Ah, na verdade, eu deveria…
42:50 colar a consulta Cypher em si, não apenas um link para ela. Legal. Certo. Aqui está o Cypher que vamos incluir no nosso agent. Vamos colá-lo aqui no nosso Aura agent. É a mesma consulta Cypher; não alterem nada. O importante é que, se vocês olharem para a consulta Cypher, precisamos que ela inclua nós. Dá para ver aqui: nós e também pontuações. Então, nós e depois pontuações, ou
43:21 similaridade, e assim podemos ver que essa consulta Cypher específica usa nós e pontuações dentro da consulta. Mas essa é uma consulta muito útil, e também vou me certificar de incluir o link de onde a obtivemos, para que você possa consultá-la depois. Perfeito. Certo. Agora, podemos criar esse agent, certo? Ou podemos adicionar essa ferramenta específica. Certo. Então, temos tudo aqui. Vamos usar a opção interna, que é gratuita, para
43:52 ter acesso. Temos essas duas ferramentas: busca pelo conteúdo das aulas e busca por similaridade, além da ferramenta de linguagem natural para Cypher. E vamos criar o agent. Podemos ver o Graph Fundamentals Agent bem aqui. Então, não precisamos mais configurá-lo. Mas, se precisar, enquanto estivermos criando esse knowledge graph, você pode atualizar esse agent. Basta clicar em “Atualizar agent”, e ele incorporará todas as informações do knowledge graph. Agora podemos conversar com
44:22 esse agent específico e fazer diferentes perguntas a respeito dele. Eu queria poder mover isso para o lado, mas não consigo; tudo bem. Podemos fazer muitas perguntas diferentes e agora você pode aprender qualquer coisa que esteja de fato no curso da Graph Academy. Por exemplo, temos informações sobre como a temperatura afeta um LLM.
44:53 E ele vai usar todas as informações do knowledge graph que criamos no Neo4j, e somente as informações desse knowledge graph, para dar uma resposta. E vou me certificar de que… >> Aqui está. >> O interessante é que, para quem voltar mais tarde e olhar aquele diretório de dados, todos aqueles arquivos PDF eram de um curso introdutório sobre GenAI da Graph Academy. Isso mesmo. >> Então, treinamos isso com a Graph Academy, na Graph Academy. Meio metalinguístico, mas… >> Exatamente, funciona. >> Não, perfeito. E, como Jeremy mencionou,
45:25 todas essas informações foram treinadas com a Graph Academy. Então, você tem todas as informações da Graph Academy ao alcance dos dedos, aqui dentro do próprio agent. E ele respondeu que a temperatura é um parâmetro que controla a quantidade de aleatoriedade no texto gerado. Certo? Você tem temperatura alta, temperatura baixa e uma explicação do que isso depende, além das fontes de informação onde pode aprender mais, também dentro da Graph Academy. Mas não só é possível perguntar sobre o conteúdo da Graph Academy: você também pode pedir informações agregadas com base na Graph Academy,
45:57 também. Então, podemos fazer perguntas como: quantas aulas há neste curso? Geralmente, quando você está criando agents ou pipelines de RAG, eles costumam ser bem ruins nisso, como mencionei: nessa parte de agregação e concatenação. Mas vamos ver. Podemos observar que, neste curso específico, há 30 aulas diferentes. Na verdade, são 15 aulas, mas agora ele está contando 30 porque executei novamente o construtor do knowledge graph, que tinha as 15 aulas iniciais, e depois executei de novo o
46:28 construtor do knowledge graph, que criou as 30 aulas diferentes. Então, se voltarmos ao Aura para conferir onde estamos… Ah, sim. Se voltássemos e simplesmente fizéssemos uma consulta, fora daqui, para descobrir quantas aulas há, veríamos que ele nos daria o número correto.
46:59 >> Você também pode clicar no tipo de nó da aula à esquerda. >> Isso mesmo. >> Para usar o código secreto. >> Então, veremos a resposta correta, que é 15 aulas neste espaço. E, como eu executei isso de novo, mas não repopulei aquilo lá dentro, ele diz 15 aulas, que é o número de aulas neste curso da Graph Academy. >> Então, Nia, algumas pessoas estavam se perguntando, agora que percorremos todo o processo,
47:30 criamos um knowledge graph a partir de alguns dados brutos e conectamos um agent que pode usá-lo, com uma combinação de GraphRAG, consultas vetoriais e consultas Cypher. Elas queriam saber se poderíamos dar uma olhada rápida no código que faz isso. >> Então, poderíamos ver o código do arquivo do construtor estruturado do knowledge graph e fazer uma breve apresentação, só para vermos seus componentes? >> Claro. Vamos abrir nosso
48:01 construtor estruturado do knowledge graph. Perfeito. Aqui está todo o código que cria e gera o próprio knowledge graph. Vou tentar aumentar o máximo possível sem cortar nada. Eu gostaria de ativar a quebra de linha. >> Acho que você pode ocultar o painel à esquerda. >> Ah, sim, claro. Perfeito. Certo. Podemos ver aqui que estamos importando todas as partes necessárias: o LLM da OpenAI, os embeddings da OpenAI, o pipeline simples de KG, que é nosso pipeline simples de knowledge graph,
48:31 e também o separador de tamanho fixo. Aqui temos o driver do Neo4j, que é basicamente o núcleo. E, quando dizemos “driver”, queremos dizer literalmente um driver, a coisa que gera tudo isso, certo? Então, estamos nos conectando ao nosso banco de dados de grafos usando esse driver do Neo4j. É a maneira mais simples de se conectar. Depois, vemos aqui o LLM. Estamos especificando que esse LLM é o LLM da OpenAI que temos aqui. Também temos nossos embedders, que são aqueles embeddings da OpenAI.
49:02 E, claro, vamos usar esse separador de texto de tamanho fixo. Definimos o tamanho dos chunks como 500 e também uma sobreposição entre chunks, para o caso de alguma coisa se perder nesses chunks específicos. Depois, temos alguns tipos de nós de exemplo. Lembre-se: os nós são os círculos. Também temos relacionamentos, mas os tipos de nós aqui são tecnologia, conceito, exemplo, processo, desafio e benefício. E temos tipos de relacionamento que consideramos muito importantes para este
49:33 knowledge graph. Vamos preencher os tipos de relacionamento, mas queremos que eles se concentrem em relações como “relacionado a”, “parte de”, “usado em” etc. Depois, podemos ver esses padrões, que são os padrões de nó-relacionamento-nó que estamos vendo aqui. Por exemplo, uma tecnologia relacionada a uma tecnologia específica, ou um exemplo usado em uma tecnologia específica. Então, depois de inserirmos todas essas informações de exemplo,
50:05 podemos ver que este construtor de knowledge graph recebe esse pipeline de knowledge graph e todas as informações para gerar o próprio knowledge graph. E essa é uma parte muito legal: claro, usamos dados da Graph Academy e um schema apropriado para eles, mas a maioria de vocês vai usar vários documentos da sua empresa ou algo assim. E pode usar o LLM para ajudar a descobrir o schema certo. Mas, depois de defini-lo, usar esse schema vai orientar o LLM, para que ele não invente novos tipos de nós e relacionamentos. Ele vai
50:37 seguir esse schema. >> Isso mesmo. Excelente. Então, podemos ver que estamos recebendo esses arquivos CSV. Também temos vários arquivos CSV nos nossos dados, dentro do diretório data, além de todos os PDFs gerais desta aula. Em seguida, ele vai analisar o CSV e criar e gerar o knowledge graph. Essa é, em linhas gerais, a explicação por trás deste construtor de knowledge graph, que usa GraphRAG no backend para criar o knowledge graph que vimos no Aura.
51:08 Perfeito. Certo. É. Então, era isso que queríamos mostrar a vocês hoje sobre GenAI. Vou terminar com mais alguns slides e alguns convites à ação também. Estes são alguns dos últimos benefícios de usar RAG com grafos. Como mencionei, maior precisão, desenvolvimento mais fácil e explicabilidade. Mas, em geral, os melhores lugares para aprender mais sobre grafos e RAG com grafos são a Graph Academy, onde vocês encontram todos esses recursos e cursos práticos, totalmente gratuitos. Fundamentos de Cypher, se você quiser
51:40 se tornar especialista em Cypher e em construir grafos de conhecimento e grafos de contexto. E, na terça-feira — ou, sim, na terça-feira desta semana —, na verdade, vamos estar… ou na quarta-feira. Em 1º de julho, vamos fazer um encontro no Digital Garage, em São Francisco, das 17h às 20h. Fiquem à vontade para participar e se inscrever. Se quiserem se inscrever nesse encontro, é só passar no nosso estande. Teremos alguns especialistas incríveis da área de grafos e grafos de conhecimento, incluindo nosso fundador e CEO, Emil Efim, que estará
52:11 lá, e vocês poderão fazer perguntas a ele sobre como construir grafos de conhecimento. A equipe técnica também estará lá: eu, Jeremy e Zach. Estaremos todos lá para responder às perguntas de vocês sobre seus casos de uso. Mas esta palestra específica é sobre ensinar o porquê por trás das decisões. Ou seja, as decisões tomadas em grafos de contexto. E fiquem à vontade para passar no nosso estande, o P3, que fica bem ao lado do estande da Microsoft. Estaremos lá para responder a todas as perguntas de vocês. Muito obrigado por terem vindo hoje. Agradecemos. [aplausos] Obrigado.
52:56 >> [música]
Transcrição original
[00:13] Hello everyone. Thank you so much for coming today and welcome to rag needs a map using graph rag to retrieve connected context. So before we get started today and I know there are people who are trickling in but before we get started today I just wanted to do a quick little poll to see who is already using rag in their pipelines regular vector-based rag. Okay cool perfect are there people who are already using graphbased rag in their pipelines. Okay >> got it still working on it. So I see
[00:44] just a few people. Um and for those who um are already using graph-based rag in their pipelines, could you explain what graph rag is? A couple sort of. Okay. People are like sort of that’s perfectly okay. Um what we’re going to do is for those who are new to the concept um this will be a sort of one-on-one graph rag um talk. So, if you’re already an expert, this you’ll already know what we’re talking about just so that you can um level set. But,
[01:15] um all in all, I want to make sure that people know what we’re going to be talking about today. So, just to shortly introduce myself, my name is Ny Mlin and I’m a senior software engineer and senior developer advocate here at Neo4j. Um my research focuses on graph theory, graph algorithms as well as uh context engineering while all trying to understand um the many architectures that are in place um to build out agents but also which architectures are best suited to break open this blackbox
[01:45] phenomenon um to be able to decipher and trace and explain how artificial intelligence systems work. So I um spend a lot of time thinking about AI governance and safety as well which also turns out to matter a lot when uh thinking about how your agent is making its decisions and how your agent is built. Um but I’ve been doing this work for about a decade now and I’m excited to bring you all bring us all back to basics to try and understand uh graph rag and so this is a graph rag 101 type of workshop for those who are newer to
[02:17] the concept. So today I have two incredible team members who are joining me as well as another team member who’s joining me today. I have my colleagues uh Jeremy Adams Castanas who is here in the front. Jeremy’s waving to everyone. If you have any questions whatsoever, please ask Jeremy. Um I also have my colleague Ryan Knight who is here I think somewhere. Oh great. Hey Ryan, great to see you. So Ryan’s going to be joining me and I also have a special guest, the uh the speaker for the previous session as well, Zach,
[02:49] who is in the back. He’s an incredible AI research engineer on the Neo Forj team. He is also here to join us and to help out with any questions that you need. So if you have any questions, just raise your hand during the uh the workshop and one of my colleagues will um will join you at your table and help you work through this. So, just a couple um uh housekeeping notes before we even get started. Today, we’re going to be using this platform called Graph Academy in order to proceed through this workshop. Has anyone signed
[03:19] up or used Graph Academy before or even heard of Graph Academy? Okay. No, not at all. That’s perfectly fine. So, Graph Academy is our completely free forever free online learning platform where you can learn about all the concepts that I’m going to be talking about today. It takes you through building out agents. It takes you through learning about agentic memory, about context graphs, if you’ve all heard of that phrase as well. Um, there are lots of different free courses that are online and completely available. These are not sit back and
[03:50] listen to a lecturer speak courses. These are handson keyboard start building type of courses. So, that’s the main goal for Graph Academy and it’s an absolutely excellent resource for you to use. Again, completely free at any time. So, we’re going to be using that today. And what I want you all to do just so that we can start off is because we’re using Graphacademy, I want you to create a Graphacademy account for me. And so, it should be a quick process. You’re going to go to graphacademy.ne4j.com
[04:20] and then you can start to create this account. Um, and again, these are free resources. So you can take this and go um throughout your time either here at AI engineer or as you continue to learn about graph and rag. I also have a link here for all of the links that we are going to be talking about today. All of the um all of the notes that we have. I will also at the end be able to present with you all the slides from this deck. Um but um you’ll go to dev.neforj.comworkshop-genai
[04:50] neo4j.comworkshop-genai-notes and that has all of the information that we need. I’m going to go to it right now actually. And you’ll see here if I can I always have to fight with these things. So you’ll see here this is what uh the document that you go to um if you actually click that link the dash notes. So here we have um a couple links that you’ll see after you sign up for
[05:20] graphacademy.com. I also want you to create a Neo Forj Aura instance. This is our hosted cloud platform. We’re doing this all for free. So please do not um uh click the instances that you’re paying for. I want you to click the free instance. Um and so again remember that we’re trying to do all this all for free. Click the free instance. If you want to have more um more tools in the future, then you can feel free to click the uh the professional instance or or what have you. But um we’re going to create a free instance um and this will allow you to
[05:51] to hook up to what we are going to be diving in today, Aura agents as well. So building out or building out agents within the Aura platform. But you can see here now I know people love a good free API key. [laughter] Don’t worry, I did not leak my leak leak my API key here. But we do have a um OpenAI API key that’s going to give you access to be able to build today. So, we wanted to make this as simple as possible for you all and is easy to get started. So, we’re giving you a free API
[06:22] key that you can use um in order to build. And um we do have limits on that. You can’t just run up run up the bill, but um please do copy down that API key or save it on your computer. again it’ll be here on this document as you view it um so that you can have access to it later but I just wanted to show off this uh this document for you all um there’s some different ways in order to get started with Neoforj but that’s all okay so while you all are working on um
[06:54] creating those instances and creating those accounts what we will do is just get started with some of the material that we’re going to be talking about today and I’m just going to give you a a short primer and then we’ll actually dive into what we’ll be talking about in graph academy. So first of all and this will be uh something that many of you have already heard of because you’re already working within uh rag and within vectorbased rag but to overcome this AI’s blackbox problem right we often need knowledge
[07:27] itself and data itself to actually be transparent. So we can see here that we have a human view of an apple right in the center. And then we also have to the right the vectorzed view of an apple. And so for the vectorzed view of an apple you see this series of numbers here, right? It’s floats for those who are engineers themselves. Um but these are not necessarily human readable and human understandable um uh vectors uh unless you’ve actually memorized the vector view of an apple yourself. Um but
[07:59] every single object you can represent both as a vector or or as data itself. Um but every single object that exists on earth can be represented here. But then on the left we see a knowledge graph view of an apple. Right? So this apple we can see that the apple itself it comes from a tree that the apple um has a specific body and a specific look. The apple is round. um this particular apple is red. Um and an apple itself is
[08:32] a fruit. We’re not talking about the company. So knowledge graphs can make what is understood by humans also understood by machines and it creates knowledge graphs oftentimes create a fusion of both. So you’re able to understand both this is both machine readable and human readable graph a view of an apple. And if you’re coming in late and you don’t have access to these uh the materials, Jeremy and Ryan are coming around. They have the QR codes. Um just
[09:04] raise your hand and they’ll come around and give you the QR code for the materials that I had just had up on the slide. But most people right now you can either you’ll either have your data structured as a um uh actually in structured as tables and rows or you might have your data structured in vectors like I had shown before. But if you’re structuring your data in tables and rows, then you have to oftent times do a number of different complex joins on that data um
[09:35] in order to figure out how these rows and these tables are all related to and then we often understand that that is going to drastically slow down the performance of our application. And we can’t have that especially mo most of us um deal with the uh the San Francisco mentality move fast and break things, right? just get it working halfway and then push it to production. We’ll figure out, you know, we’ll figure out any issues going forward. So, this is the slowest way to do things. We don’t have time for that, right? We have to move fast. We have to be accurate and we have
[10:07] to be explainable. So, if you were to structure all of that same data in a knowledge graph, then the relationships and the connections and the groupings actually become much more clear. So now your agent can physically hop right from one node and when I say node I mean one circle to the next circle through this relationship that we see right and the line is the relationship. We can hop from one node to the next node um of information and be able to trace and
[10:38] explain what happened in the past. That’s a massive improvement, right? Once you’re being able to hop through nodes through things like agent memory, which I’m actually not going to get into in this talk. I have a whole another talk that talks that breaks down agent memory. But through this this concept of agent memory, you can now have this memory and have this context of how did that agent come to create the decision that it made in the past. And so that’s that’s incredible for dealing like uh dealing in regulated domains um like
[11:10] financial use cases. Um, y’all don’t want Vibe Vibe banking, right? Nobody wants Vibe banking. You don’t want your agent just having access to your money and then spending all of your money. I’ve seen those things happen before. But things like medicine as well, regulated spaces, legal spaces, this is where that um that uh context and that history and that memory is actually very very important. But once you have a knowledge graph representation, your possibilities for your agent to give you that explainable, traceable, and accurate responses actually become much
[11:41] more improved and some might say endless. So again, because this is a one-on-one workshop, I wanted to make sure that people understand the architecture of a graph-based rag system. So in a normal rack pipeline, you are not using knowledge graphs, right? in in the basic rag pipeline. Um in a normal rag pipeline, you could take a few PDFs, for example, and then chunk them and then index those chunks using a text embedding model. Um and then when it’s time to query those text chunks, you get that same embedding model. Then you try
[12:13] to fetch the top k or top x number of relevant documents and you pass that in to an LLM. And then your LLM is going to give you back the final answer from those documents. and and that’s what the pipeline looks like for that poker usually um most likely used to right but graph rag on the other hand is fundamentally it is rag but it’s where the retrieval path actually includes the knowledge graph so graph rag is where the retrieval path actually includes a knowledge graph and so you’ll
[12:45] see here the architecture is just slightly different so in the rag pipeline illustration that I showed before the normal rag pipeline did not use a knowledge graph But you see here down here, we actually have a knowledge graph incorporated into that space. So when people ask me when to use rag versus graph rag, usually I like to say that we’re if you’re trying to answer a question that can be solved um with a either a search engine, then uh for and that’s the simplest term, right? Then vector-based rag is actually usually sufficient. However, if you want to ask
[13:17] a question that includes what we call these multiple hops. So we saw the act the example of a knowledge graph before we saw the nodes. If you’re trying to do these multiple hops or at least three hops, then that’s when graph rag actually becomes imperative because you’re able to then see and able to then decipher where the agent had to um had to hop in order to get to its answer. But um if you’re trying to do something for example source code analysis or if you’re trying to have a supply chain question or anything that requires
[13:49] aggregation or concatenation of data then uh from different documents then that’s when this graph rack actually be really helpful and I’m not going to necessarily knock vectorbased rag. think it is incredibly powerful for most of our use cases. But here are some of the examples where vector only um rag and vector only databases they might fall short with when it comes to these things where graph and being able to traverse nodes and get that that historical context um can be beneficial. I’m not going to go
[14:21] through all of these but I wanted people to be able to see where um where the differences might lie. And so all in all, when you’re going to be when people ask, okay, should we use graph rag versus vector-based rag? I say that using both is actually the key here. We want to use both graph and vector. Um and uh graph we we’re not saying that graph is going to completely um uh completely replace your vector layer. We’re saying that if you use both, then you the benefits of both. So let’s add on, right? Let’s make sure
[14:51] that our agents are being as uh beneficial as possible. Okay. So, I’m going to pause there and we are going to go into uh Graphacademy. So, for Graphacademy, the first link, graphacademy.com, we’re going to go into this workshop um.ji and what I want us to do is to we’re going to skip the first few sections of this. So, um I have of course already done the course, but I can reset it. So, we’re going to
[15:23] continue that course and what we’re going to do is we’re going to skip over some of this um more introductory stuff like what is generative AI. We don’t need to know that. If you do need to know that, that’s perfectly fine as well. Um but uh for this conversation, we’re just going to skip down. We’re going to skip down to the to the graph rag section. All right. So, we already went through the graph rag um the retrieval process and the differences between normal rag versus graph rag process. We’re seeing that we’re first of all we we see the typical process here which I already
[15:54] went through. You have your retrievers, your user, your application and your LLM and then your data store which is normally um a vector store. Um but then if we go down then we see a little bit of the difference um as well. And what I did want to touch upon here is this concept of retrievers. Many of you already know what retrievers are. Just get a quick hand so I don’t have to go over it. Okay, well actually not as many as I thought. So that’s okay. That’s that’s totally okay. Let’s actually go over it then quickly. So a
[16:24] retriever is a key component of the rag process, right? A retrieval is actually responsible for searching and retrieving relevant information from your external data sources. And what I like to say, okay, let’s let’s make this um bigger. Thank you so much. Um what I like to say often or ways that I like to remember what retrievers are um the simple way um is that retrievers are the golden retriever, right? We we all know about golden retrievers, they like to catch balls. They like to catch things. So a retriever is some is uh if you would
[16:55] think of this golden retriever likes to go and fetch the necessary information. Um, and so the retriever usually takes in unstructured input like a question or a prompt like when we’re using chat bots and then it searches the structured data to provide the context for the answer. And so this is just a little bit about what Neoforj specifically report supports full text search vector search and then uh text or cipher retrievers as well. And then we have a number of different data sources as well. So those data sources in uh regular rag pipelines
[17:26] and processes can vary um documents, APIs, knowledge graphs as well. Um but um if we were to use uh this uh this news agency chatbot for example, then the process would look like this, right? A news API is going to be used to retrieve the latest articles and headlines. The knowledge graph is then going to be used to understand the relationships between different topics um such as how they relate to each other in a historical context. And then the document database is going to store and retrieve uh articles or reports or
[17:58] textual information as well. So we that’s just an example and a um architecture of what that could look like. But let’s keep going, right? There’s lots of different benefits to using graph rag. I’ll touch upon this really quickly, but one of those is um having uh richer context specifically and then improved accuracy, explanability like we had actually seen within that knowledge graph. If you’re able to actually um if you’re able to traverse your knowledge graph um and
[18:29] then use that plus things like agent memory, then you can get this rich historical context that’s really necessary and really beneficial for building out your agents. So, let’s keep going. And then I heard a couple people um and my colleague had went through the line a little bit earlier to see like have people built knowledge graphs before. Can I get a couple hands to see has anyone built out knowledge graphs? Just a few. Okay. Just a few. Okay. A little bit. Yeah. Okay. Okay. Hello world. That’s perfectly fine. No problem. This
[19:00] is why we’re all here to learn more. Um so, uh just um making sure that we understand what is a knowledge graph. We went through this a little bit in the in the example, but a knowledge graph in general is a um organized representation of real world entities and their relationships. So if I am a node, right, I’m a circle, I’m a node, and then my colleague Jeremy is a node as well. Yes, Jeremy, we are nodes. And then we actually have relationship that we are colleagues and we are friends. So we have two different relationships here. Um but um that is that’s the simplest
[19:31] architecture of a um of a knowledge graph. And then we can be connected to different people as well. We have our colleague Zach and then another colleague Ryan. There’s so many different um ways, but that’s just a represent. It’s just a representation of data in its most simplest form. Um so uh what is a knowledge graph? You can see here another example of that knowledge graph. And so in the interest of time, I’m just going to skip down and we’re going to get into this knowledge graph construction piece. So for everyone who’s following um we’re in
[20:03] the um knowledge graph construction section. So let’s build out a knowledge graph quickly. So constructing knowledge graphs. In this lesson we’ll review the process of constructing knowledge graphs from unstructured tests using an LLM. So the overall process is making sure that we’re gathering data sources and then we’re chunking that information and chunking that data. We’re of course going to vectorize that data as well and then um extracting nodes and relationships from that and then generating the graph of course. So in
[20:35] this example, if we wanted to construct a knowledge graph based on the Neo Forj Wikipedia page, which we can see here, we’re going to gather text from that page, right? Take all the text and then we’re going to split that text into chunks. As you can see here, we would generate embeddings and vectors from each of those chunks and then extracting the entities and the relationships using an in LLM. Now, you can do that manual extraction if you wish. Um but we think that um using it in an LLM can cut down on the amount of time that it takes in order to do that extraction. Um and so
[21:08] we would send the LLM to with an appropriate prompt um a prompt example here. Your task is to identify the entities and the relationships requested with the prompt from a given text. And then you must generate the output um in a JSON format containing a list with JSON objects. And then we would paste oh sorry parse those um entities and relationships. the output into the LLM, paste that into as JSON, and then we would generate the graph from all of that. So, we see here we see here
[21:39] Cipher, which is a query language that’s optimized for graphs. Has anyone used Cipher before? A couple. Okay. All right. A couple people. Um, so if you’re a cipher expert, [laughter] then I have um uh if you answer some of my questions here, I have swag as well. So people as um as you are going through this workshop I want it to be more interactive than a normal workshop. So I’ll be asking questions and if you’re brave enough to answer one of my questions live it’s also being live streamed but live then I have free uh
[22:09] unique swag for you. So that includes t-shirts that includes um uh special swag that you cannot get anywhere else as well socks etc but um special swag on top of that. So, um, thank you all for, uh, being willing to put yourself out on a limb and answer some questions that we might have. But you’ll see here, uh, lastly, an example of a generated graph. So, we have a graph database was, uh, developed by Neo Forj, which is a company. Um, and, uh, Neo Forj didn’t, uh, develop graph databases all in general, but just
[22:41] Neo Forj is the graph database that was developed by Neo Forj with the company. And then that’s implemented in Java. And quick side note, Neo for J the name comes from Neo who is matrix. All right, those who know the matrix and then Neo for Java. So for those who have that quick little piece, you’ll know that that note about Neo forj. So we can continue. >> Ah yes. Yes. >> Go for it.
[23:12] >> Yeah. Yeah, let’s do it. >> Okay. So um because we’re at half past the hour, we want you to get the most out of this. And people wanted to do building of the knowledge graph. There is a on your left sidebar it says graph rag for Python. >> That’s right. >> That link there. So kind of navigate to that. That will take you if you scroll down. Um this is going to talk a little bit about the the graph rag for Python package an open source package that Neo4j provides for knowledge graph building and retrieval and agentic work
[23:43] and also on this page are all the credentials you’ll need for all the examples we’ll be using and then um Nia you want to take it away and talk about the credentials and the GitHub code space. >> Absolutely. So let’s start off uh for let’s start off. So, we had mentioned we’re in the graph for Python section now and we want to um go scroll down and then click open in GitHub code spaces. Once we open that, we’re um you you’re going to have to sign into GitHub if you’re not already, but once we open that, we’re just we’re going to leave
[24:14] all of these um uh system prompts the same. And then we’re going to create the code space. It’s going to take a little bit of time. So, we’re going to do a little bit a couple of things ahead of um not necessarily ahead of time, but while this is generating. And so while this is generating, I just wanted to show you all that we’re going to be creating this setup environment. And so we’re going to create a copy of this m.example. And you can just click copy here. And we’re going to actually create that um within our um code spaces
[24:44] section. And so this will continue. Of course, Wi-Fi is not always fun, but this will continue. Eventually, it’s going to have an entire setup for the um uh for the folder structure, and it’ll have a uh M.ample folder. So, we’re going to instead create a M file, and we’re going to paste all of these um uh um all these credentials in. And actually what we’re going to do, we’re not going to paste those exact credentials because what we want to do specifically is to and I had this in the
[25:17] notes is to create a Neo Forj Aura instance. And so I had that in the notes for us to get started on. So create a Neo Forj Aura instance. And again I mentioned we should be creating a free instance specifically for this workshop. You can create a professional instance as well. Um, but I already have one that’s set up. And so this instance is um instance number three here. Um, yours should say type um aura I think or free. Um, but what we will do is that we’re going to actually connect to set
[25:48] instance. And so um once you do create that instance actually you’ll um have a the connection details that you’ll be download directly to your computer so you don’t lose it. And um uh what we’ll do is then um connect that here. >> Yeah. And um so really there’s a a fork in the road here. Don’t feel bad if for whatever reason uh you aren’t able to create the Aura instance in time. Um it’ll be ideal for the last part of the
[26:18] exercise if you can. But those other credentials we saw in Graph Academy, they’re in a a small uh free instance that’s within Graph Academy itself. So you can use those. Either way, we want to have the connection details to a Neo4j database because that’s where we’re going to build that knowledge graph. >> That’s right. >> Perfect. So, what I’m doing right now is I’m grabbing my um instance information and then I’m just going to paste that here into our um our graph. So, perfect. We
[26:52] see that there. And then I will also grab the open AI key. Yeah. And I’ll make this bigger as well. Move this terminal down. Move this out the way. Perfect. So, we want that OpenAI key as well that we had C that we had grabbed and we’ll grab that directly from the notes.
[27:23] So, just copy and paste the key and place it. Dope. All right. So, this will save uh if you have autosave or you have to save it yourself. And now we have this. And so once we have that M file, then we’re actually going to want to test our environment really quickly. So we’ll go down to um test environment. py and we’ll just run this environment. You can actually if you’re using VS Code and you can run it using this or you’ll use run
[27:53] it using your um uh hopefully a Python virtual environment as well. But let’s make sure we do it. Okay. So we can see down here it’s trying to connect. Perfect. It ran five tests and it’s positive. We’re okay. So, >> anyone hitting a snag there? If you do, make sure you’re actually you’ve actually created av file and you’re not still just in the example. >> That’s right. >> And uh you can rename the file or create a new one. And um that will essentially
[28:24] now we know we’re connecting to the Neo4j database and our open AI key uh is successful. >> Perfect. So, Now um that the test environment is run. This is successful. Now we can take a look and we can see here um if you go under workshop.jai you can see here that we have a number of different solutions. So we have the d the raw data itself. We
[28:54] have solutions itself and then the agent and then the knowledgeraph builder and knowledger graph structured builder as well. So we’re going to click on this knowledge graph structured uh builder and it’s going to build out this knowledge graph right in our Aura instance. And so if you’re again in VS code then we can just um p uh play that and then this process is going to take a little bit but it’s actually going to generate the knowledge graph and we can see it populating live within the doj aura um aura instance and so let’s go
[29:24] over back to aura and what I’ve done as well as um within here so again I’m going to connect we’re going to go to query And we can see I’ve already done this. So I’ve already pre-populated it just because it’ll take some while. So it’s going to probably do some dduplication um based on the fact that I’ve already run it. Um however um all of that information is going to u populate within here. And then we can query this um and see what’s uh what exists within
[29:57] the um within the instance. And we can see that this knowledge graph it will the more times you query you’ll see um that it actually will uh continue to populate. So just right now we’re just going to see what um relationships and um uh u and nodes are actually here already. So we have P and then so match P
[30:37] done a little syntax here. Oh, thank you. Match P equals. There we go. Beautiful. So now we can see and I’ll sc I’ll zoom in so that we can actually see what’s going on here. But now we can see all of these different nodes and relationships just
[31:08] based on the data that we had um that we had ingested into the knowledge graph. And you can click on this data and you can inspect the data as well. This is not just a visualization tool, but it’s also specifically a query tool, a way that you can um query your data itself. But this is the finished um knowledge graph. Your knowledge graph will be much smaller. And then the more times you run this particular query, match p equals um empty like a node actually. So empty
[31:39] node uh d-mpt node then return that p. Um you’ll if the more times you run that, the more times you’ll see that that knowledge graph grow. It’s just uh in the query in general is just saying like show us all the nodes, right? Show us all the nodes and relationships. Wonderful. Okay. So once we’ve got that um those nodes and relationships and and uh for anyone
[32:09] who’s having problems with that process um uh feel free to throw up your hand and we have colleagues who are who will come in and help you. Um but once you got that um that knowledge graph beginning to generate then what we want to do is actually go in and create an agent. Oh I see a couple hands right behind. Um, so you might not already see this agents um section. If you do not, let me see your hand in your um thing. Okay? But I do know a couple people probably are not there yet. Um, but if
[32:42] you don’t see this agent section, what I want you to do is to go to your organization, your NearJ organization. Um, and then we’re going to click all organizations. And what we’re going to do is we’re just going to enable um, Jedi um, capabilities onto this organization here. And so we’re in this new organization. Then we’ll go to settings. I already have it enabled, but for those who don’t know how to enable it or have never used Neo forj A or before, um here we have um
[33:13] you’re going to click these two. They’ll be um they’ll be grayed out, but I want you to click them in order to enable them. So generate AI assistance, generative AI assistance, and then Aura agent specifically because we’re going to be building out an agent today. So, oh, got a couple hands. Perfect. So, once we have that organization, we’re going to go back to our specific organization. We’re going to go back to our instance.
[33:44] We’re going to open our instance within query mode. See our agent um see our knowledge graph populating. And then we’re going to click here, agents. and this agent here. So, I already have an agent here, but what we’re going to do is you are going to create an agent. So, I’m going to create an agent from scratch and we’re going to tie that agent to this specific instance. It should autoop populate based on the latest instance that you had created
[34:17] and we will configure. And so what we want this agent to do, uh, we’re going to call this agent, we’re going to call it a, um, uh, genai fundamentals. Um, actually, we’ll call it graph rag fundamentals. Graph rag fundamentals agent.
[34:51] Perfect. And then for the description uh to describe this agent, we’re going to say that this agent provides um forj graph rag information grounded in this specific graph academy course that we have.
[35:25] So we have this agent and again for those who are following along it’s going to uh provide neo forj graph information grounded in this specific graph academy course and then lastly we’re going to um provide the instruction for that agent here. So um that instruction will be that um and we can really just copy paste and what I’ll do is I’ll also include this in the geni notes section so that you can all see it.
[35:57] I’ll go over to the notes. But this is an easy way to um create your agent agent description for you all so that you can copy and paste it and have your agent actually be working with us here. And if you have questions, please feel free to put up your hands. Okay. So, we’ll just copy that over to our agent as well. We have the um instruction and
[36:28] then we’re going to keep everything pretty much the same. the instance um agent location as well and then internal and what we want to do. Perfect. Is um create that agent. But actually, do we want to Yeah. Okay. So, before we create that agent, we’re actually going to try and um add similarity search to it. So if you don’t
[37:00] already have um um similarity search added to your agent or vector search or vector insects is specifically added to your agent then we actually have to do that in order for this u this prompt to come up. So you’ll get a separate prompt that says um vector search is necessary in order to um to do that. So, where we get a good a good place to get that information, we’re going to close out this. Oh, we can keep it open. But what we’re going to do is we’re going to go to um the Python
[37:30] um Python section. There is another let’s see in the graph for Python section. Here we go. And I’m going to paste this into the uh notes for you all as well. I gotta love being in full screen mode. Come on. Come on. I’mma just I might just exit out full screen. Okay. And let me paste this for you all. So, we’re going to create a vector index. So, we want to go to this link here.
[38:03] Create vector index. Cool. And that’s what you’re going to do. You want to click that link and that allows you to um that just gives you a sample code um in order to create the vector index. And I’ll show you where we’re going to put that information right now. So we have this create a vector index here. You’re just going to copy that and then we’re going to include that.
[38:35] So for the vector index and I’m going to ask Jeremy, do you remember where oh where we put our um vector index? >> Yes. Right. Right in as the cipher query window. >> Yes, you’re right. You’re absolutely right. Okay. So, let’s go back. So, we’ll go out of here. So, this will depend on which instance you’re using. If you’re using an Aura instance, you’re going to go in your Aura console into the query interface. So, you might want
[39:07] to either open another window. >> Yep. >> So, you can leave your agent or you’ll have to close your agent for a minute and go to query, >> right? And then you can create that vector index. >> So just like Jeremy had mentioned, we’re going to actually paste that vector index right here in the cypher query window. And so you’ll run that and then you will see that we’ll um extend this. Okay, this command and this I think it’s this is specifically because I had already no successful. Oh yeah, it already exists. Exactly. Because I had
[39:37] already run this. What you’re going to do, you’re going to create, you’re going to run that command and then it will actually show you the vector index that has been created. So once you have that vector index already created, then you can then go into the um agent section and then uh access that prompt that we saw there. So I’m going to do the same thing again. Create from scratch, configure, and we’re going to do the same thing. Graph rag. Great. Autopop populate.
[40:10] Beautiful description. Yep. Beautiful. And then we have that same prompt. Sweet. And then we’re going to do the add tool section. Now, similarity search. Now you should be able to see this uh the same prompt. But for this similarity search tool, we’re going to create this tool which will say we’re going to search this lesson content and be able to actually
[40:40] gather insights from this lesson without having to take the lesson. Search lesson content. Um and then we have a description that I’ll also paste as well. And I’ll paste that. Make sure that you all have that description as well. Similarity search description.
[41:12] Perfect. So now it’s in the notes so that you can also use it. And then we’re going to select the V vector index specifically that we had just created that is chunk embedding. We’re going to say we’re going to use about the top five um uh as well. And then we’re going to select our embedding provider that’s open AI. The embedding model we’re just going to use text embedding three small. It’s perfectly fine. And then the default dimensions is 1536. And then we want to make sure that we are uh returning this connected graph
[41:44] data which is very very important especially because we’re using this uh graph interface. So we’re going to return this graph data and what you want to do we can use natural language here but you can also use cipher specifically but um cipher for this cipher query um we have there’s a cipher query that we already have. I’m trying to remember where it is. Oh is there a light mode? That’s a great question. Oh, because it is so hard to see. Yeah, let make it bigger.
[42:18] Awesome. So, for this cipher query, we’re going to take this cipher here, and I’ll make sure to paste it for you all. This is the cipher query that we’re going to use. So, it’s it’s um Oh, actually, I should
[42:50] just paste the actual cipher query itself, not just a link to the cipher query. Cool. All right. So, here’s the cipher that we’re going to include in our agent. And what we’re going to do is we’re going to paste that in our Aura agent here. same cipher query don’t change anything but the the point here is if you look at the cipher query we need that cipher query to include nodes you can see here nodes and then scores as well so nodes and then scores or
[43:21] similarity and so we can see that this cipher query specifically uses nodes and scores within its query um but this is a very helpful query and I’ll also make sure that I link where we got that query as well for you small just so you can have it for later. Perfect. All right. Now, we can create this agent, right? Or we can add this specific tool. All right. So, we have everything here. We’re going to use internal which is for
[43:52] free. Um, we have these two tools, search lesson content, and then the similarity search and then the natural language for cipher tool. And we’re going to create the agent. So we can see graph fundamentals agent right here. So we no longer have to configure it. But if you need to um as we were building out that knowledge graph, you can update that agent. You can press that update agent which will take in all the information from the knowledge graph. So now we can have a chat with
[44:22] that specific agent and we can ask different uh questions with regard to um that agent. And I wish I can slide this over but I can’t but that’s okay. So these particular questions we can ask lots of different questions um and um you can now learn anything that is actually in the graph academy course. So for example, we have information about um how does um temperature for example uh affect a LLM
[44:53] and this will take in all the information based on the knowledge graph that we had created within Neo4j and only that information within the knowledge graph in order to um give you an answer. And I’ll make sure that I >> Here we go. >> The fun thing is uh for folks that go back later and look in that data directory, you’ll notice that all those PDF files were from an intro to Genai course in Graph Academy. That’s right. >> So we trained this on Graph Academy in Graph Academy. Kind of meta but >> exactly it works. >> No, that’s perfect. And like like Jeremy
[45:25] had mentioned, all this information is trained on Graph Academy. So you have all the information within graph academy at your fingertips here within this agent itself. But it answered that um temperature is a parameter that controls the amount of randomness in the generated text. Right? You have tire temperature, lower temperature and what that um is based on and then as well as the sources of information where you can learn more um within graph academy as well. But you don’t you not only are able to ask about the content of the graph academy but you’re able to do things like get that aggregated information um based on graph academy as
[45:57] well. Um, so we can ask questions um like how many lessons are there in this course and so usually when you’re building out agents they or when you’re building out rag pipelines they’re often pretty bad at doing this like I had mentioned this aggregation and concatenation piece but um let’s see we can see that within this specific course there are 30 different lessons and it’s actually 15 lessons but it’s counting 30 right now because I had rerun run the um
[46:28] uh the knowledge graph builder which had the initial 15 lessons and then I reran that builder which created the 30 different lessons. So if we were to um then check within Aura make sure where we are. Oh yeah. So, if we were to go back and just uh query, right, we’re outside of this and we were to just like figure out how many lessons, then we could see that it would actually give us the correct number.
[46:59] >> And you can even just click on the lesson no type on the left as well. >> That’s right, >> for the cheat code. >> So, we’ll see the correct answer, which is the 15 lessons here within this space. And then the um uh the because I had reran that but I did not repopulate that within the within the thing. So it says 15 lessons which is how many lessons are in the um or within this graph academy course. >> So Nia I had some folks that were wondering now that we’ve gone kind of
[47:30] end to end we built a knowledge graph from some raw data. We were hooked up an agent that can use this now using graph rag combination of vector and cipher queries. They were wondering could we look at the code that does this really quick >> and so um could we look at the code of that knowledger graph structured builder file >> and just just do a quick walk through just so we see the elements of it. >> Absolutely. So let’s go into our um
[48:01] knowledge graph structured builder. Perfect. So here is all the code that’s that’s creating and generating this knowledge graph in itself. So we’re seeing and I’ll try to make it as big as possible without also cutting. I would like to do a word wrap. Um >> I think you can hide the uh the left hand. >> Oh yes, absolutely. Perfect. All right. So we can see that here um that we are importing all of our necessary um uh portions. So OpenAI LLM, the OpenAI embeddings, the simple KG pipeline which is our simple knowledge
[48:31] graph pipeline. um as well as fixed size splitter. But we have here which is our Neo Forj driver which is pretty much your um your core and when we say driver we really do mean driver the thing that’s generating all of this right. So we’re connecting to our um our graph database using that Neoraj driver. It’s the simplest way in order to get connected. But then we see here that we have the LLM. We’re stating that that LLM is actually the OpenAI LLM that we have here. We have our embedders here as well which is those open AI embeddings.
[49:02] And then we are of course going to use that text splitter fix um fixed size um splitter and we have that chunk size being um 500 and then a choke overlap just in case we miss anything from those specific chunks. And then we have some sample node types. So those node types here remember nodes are the circles um and then we have relationships but the nodes here are technology concept example process um challenge and benefit. And then we have relationship types that we think are really important to this uh
[49:33] this knowledge graph. So these relationship types we are populating but we want those relationships to focus on this related to piece the part of used in etc. And then we can see that these patterns these patterns um which is this node relationship node pattern that we’re seeing here. Um and so we have for example technology related to specific technology right or example used in specific uh technology. So then after we we’ve put all of that sample information
[50:05] we can see that this knowledge graph builder is taking in this knowledge graph pipeline and all the information in order to generate the knowledge graph itself. I mean, and that’s re really a cool part here is that of course we we did Graph Academy data here and a schema appropriate for that, but most of you will be using like a bunch of documents from your business or whatever. And you can use the LLM to help you figure out the right schema. But once you got it, that using that schema like that will guide the LLM so it won’t just make up new node and relationship types. It’ll
[50:37] stick to that. >> That’s right. Excellent. So then we can see that we’re taking in those uh CS we have different CSV files within our data as well right under data a different CSV file as well as all the general PDFs from um this lesson and then it’s going to parse that CSV um and then create and generate that knowledge graph all in all. So that’s the background behind this builder this knowledge graph builder that’s using graph rag on the back end in order to create the knowledge graph that we saw within um Aura.
[51:08] Perfect. All right. Yeah. Um, so that is what we wanted to show you all today um, for Genai. I’ll finish off with a couple last slides and a couple calls to action as well. These are some last some benefits of using graph rag. Again, I had mentioned higher accuracy, easier development, and then explanability. But all in all, the best places to learn more about graph and graph rag is Graph Academy where you’ll see all of these different um, resources completely free and hands-on courses. um cipher fundamentals if you want to
[51:40] become an expert at cipher um and uh building out knowledge graphs and context graphs. And then on Tuesday or yes on Tuesday of this week um we are actually going to be or Wednesday um but on July 1st we’re going to be having a meetup down at the digital garage in San Francisco from 5 to 8. Please feel free to join us and please feel free to register. Just make sure you come by our booth if you want to register for that meetup. We’re going to have some incredible experts within the graph and knowledge graph space including our founder and CEO Emil Efim who is going
[52:11] to be there and you can ask him different questions about building knowledge graphs as well as the technical team myself Jeremy Zach um we’re all going to be there to answer your questions about your use cases. Um but this specific talk is about teaching the why behind decisions. So context graph decisions that are being made. And then please feel free to come by and see us at booth um P3 which is right by the Microsoft booth. Um we’ll be there to answer any questions that you have. And thank you so much for coming today. We appreciate it. [applause] Thank you.
[52:56] >> [music]