Neo4j Embeddings, Vector Search, Retriever, LLM & RAG
From the publisher’s feed, collected in the ZeroLabs newsroom.
An LLM (Large Language Model) is trained on a large dataset. But over time, this data gets old, and the LLM lacks recent updates. Also, the training dataset only contains publicly available data and lacks organisational and user-specific information like the internal guidelines of a company, the admission process of a university, or the product catalog of an online store. Thus, an LLM alone can not respond to all user queries.To provide additional context to an LLM, it is used with a RAG system. The RAG system employs a Retriever to query relevant data from private data sources (storage, database, etc.). The Retriever creates embeddings for the user query, may use a vector index, and performs vector search to return a response. The RAG attaches this response to the user query before passing it to the LLM. Thus, the LLM gets the user query with some additional context, which it uses in combination with its training data to return the final response. ┌───────────────────────────────┐ │ User Query │ └───────────────┬───────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ RAG FRAMEWORK │ │ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ RETRIEVER │ │ │ │ │ │ │ │ 1. Convert User Query ──> [ Embedding Model ] │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ 2. Perform Vector Search ──> [ Vector Index ] │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ 3. Fetch Relevant Data ──> [ Data Sources ] │ │ │ │ from Storage/Databases │ │ │ │ │ └──────────┐ │ │ │ │ ▼ │ │ │ │ [ Relevant Context ] │ │ │ └─────────────────────────────────────────────┬───────────┘ │ │ │ │ │ ┌─────────────────────────────────────────────▼───────────┐ │ │ │ AUGMENTATION STEP │ │ │ │ │ │ │ │ Combine: [ User Query ] + [ Relevant Context ] │ │ │ └──────────────────────────────────────┬──────────────────┘ │ └──────────────────────────────────────────┼──────────────────────┘ │ ▼ ┌───────────────────────────────┐ │ LLM (Generator) │ │ Uses combined prompt + │ │ its training data │ └───────────────┬───────────────┘ │ ▼ ┌───────────────────────────────┐ │ Final Response │ └───────────────────────────────┘In this story, you’ll use Neo4j as the data source for the retriever, free and open-source SentenceTransformer as the embedding model, and Ollama for the LLM.If you are new to Neo4j and its implementation in Python, please read Neo4j in FastAPI to understand the essentials.Create and store embeddings in the Data Source (Neo4j)Embeddings are numerical representations of the context of the data (text, audio, video, image, etc.). The AI models use these embeddings to compare with the context of the query and retrieve a relevant response.In a RAG system, the Retriever makes the queries by comparing embeddings of the user query with those stored in the private data source. To enable this, the data source must have embeddings created and stored in it (generally complemented with a vector index). Here, you’ll create embeddings for the bio property of the Customer nodes in the Neo4j database instance and later use it to provide additional context to the LLM.i. You need an embedding model to create embeddings. Here, you’ll use the SentenceTransformer model ‘all-MiniLM-L6-v2’, which will create embeddings with 384 dimensions.model = SentenceTransformer('all-MiniLM-L6-v2')ii. Next, you need to provide the appropriate data field to create embeddings. Here, you will fetch all Customer nodes from Neo4j and create embeddings from their bio property (bio stores a short description of a customer).session.run('MATCH (c:Customer) RETURN c.bio AS bio')iii. Use the encode() method of SentenceTransformer to create embeddings, and you may store them in an array for the time being.(The recommended way is to commit the embeddings to the database in small batches to prevent data loss and avoid overwhelming the machine.)if bio is not None: customers_with_embeddings.append({ 'bio': bio, 'embedding': model.encode(f''' bio: {bio} '''), })iv. Lastly, you will use the Neo4j driver to call the db.create.setNodeVectorProperty() system procedure inside the database query to store the embeddings as a vector property of nodes/relationships. Here, a new vector property named embedding is created in the Customer nodes.driver.execute_query(''' UNWIND $customers as customer MATCH (c:Customer {bio: customer.bio}) CALL db.create.setNodeVectorProperty(c, 'embedding', customer.embedding) ''', customers=nodes_with_embeddings, database_=DATABASE)A full implementation to create and store embeddings for Neo4j is presented below-https://medium.com/media/b4494bd11047f928c1d1abc4e5c6b533/hrefYou can save the script file as embedding.py. To execute it, open a terminal and run python embedding.py.python embedding.pyCreate a Vector Index in Neo4jA vector index is required to efficiently perform a (vector) search on the embeddings. A properly configured index can immensely speed up the queries made by the Retriever. Without a vector index, a brute search will be performed, taking from minutes to hours.Use the Neo4j driver to execute the query. Provide the index name (customerBio) and the node/relationship property (embedding) for which you want to create the index.https://medium.com/media/dbb6da9e6a9580c0fdcca9acce40ac8d/hrefYou can save the script file as vector_index.py. To execute it, open a terminal and run python vector_index.py.python vector_index.pyPerform vector searchIn a RAG system, once the embeddings are in place, a retriever performs vector searches internally. To see how a vector search works, first create embeddings for the user prompt. Then compare these embeddings with the stored embeddings to return the closest matches.i. Initialize an embedding model (here, SentenceTransformer(‘all-MiniLM-L6-v2’) is used).model = SentenceTransformer('all-MiniLM-L6-v2')ii. Generate embeddings for the user prompt using theencode() method of the initialized model.query_embedding = model.encode(query_prompt)iii. Using the Neo4j driver, perform a query with the help of the SEARCH clause. It will need the vector index name (customerBio) and embeddings generated from the user prompt. Along with the matched records, it will also return a confidence/similarity score for each returned record.records, _, _ = driver.execute_query(''' MATCH (customer:Customer) SEARCH customer IN ( VECTOR INDEX customerBio FOR $queryEmbedding LIMIT 5 ) SCORE AS similarityScore RETURN customer.name AS name, customer.bio AS bio, similarityScore ''', queryEmbedding=query_embedding, database_=DATABASE)A full implementation of a vector search will look as below-https://medium.com/media/750e43eed1c0d0a50bf3a50a5f232fc7/hrefYou can save the script file as vector_search.py. To execute it, open a terminal and run python vector_search.py.python vector_search.pyRAG with LLM and RetrieverRAG (Retrieval-Augmented Generation) systems can be used to provide additional, domain-specific, latest information to an LLM (Large Language Model). A RAG uses a retriever to query the knowledge base or vector stores to fetch the information from internal storage or a database, and injects it as additional context along with the user prompt to the LLM.i. Create an embedding model that will be used to generate embeddings for the user prompt. Use the same model as used to generate the embeddings stored in the private data source.embedder = SentenceTransformerEmbeddings(model='all-MiniLM-L6-v2')ii. Create a retriever. Instead of creating it from scratch, you can use VectorRetriever, a Neo4j implementation of retrievers. This retriever will take the database driver, the embeddings generated from the user prompt, the vector index name, & the embedding model instance, and return records from the database that match the user's query prompt.retriever = VectorRetriever( driver, neo4j_database=DATABASE, index_name="customerBio", embedder=embedder, return_properties=["bio"],)iii. Create an LLM. Here you’ll use the Ollama model llama3.2:b. Ollama is freely available and can be run locally.You need to download and install Ollama. Then, in a separate terminal, pull the llama3.2:3b model and run it locally.# pull the llama modelollama pull llama3.2:3b# run the llama model locallyollama run llama3.2:3b# Initialize the LLM with llama modelllm = ChatOllama(model="llama3.2:3b")Read more about Ollama and running it locallyiv. Next, create a graph RAG by providing the already declared LLM and Retriever instances.rag = GraphRAG(retriever=retriever, llm=llm)v. You can use the search() method of the initialized RAG instance to provide the query prompt and get the response.The retriever will use this query prompt to fetch relevant data from the database (here, Neo4j) and attach it to the query prompt as additional context before passing it to the LLM. The LLM will then generate a response to the query prompt with the help of its own knowledge and the additional context provided by the retriever.def rag_query(query:str): response = rag.search(query_text=query, retriever_config={"top_k": 5}) return response.answerA full implementation of a RAG system will look as follows. (The comments contain the sample implementation of the Embedder and the LLM using OpenAI models.)https://medium.com/media/faa0d833e3eb8455aa2d6a621ed0482e/hrefYou can save the script file as rag.py. To execute it, open a terminal and run python rag.py.python rag.pyWith an understanding of embeddings, vector search, LLM, and RAG systems, you can develop several interesting projects. You can create customer chatbots, implement semantic search, a domain-specific query base, a personal assistant, etc.Read more about RAG systems in Neo4jNeo4j Embeddings, Vector Search, Retriever, LLM & RAG was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.