Skip to content
ImagineWorld

GraphML and LLMs

node_idnode-book_graph-machine-learning_chapter-12-graphml-and-llms
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleGraphML and LLMs
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

LLM-GNN integration — LLMs as predictors, LLMs as encoders, LLMs as aligners, building knowledge graphs from text, GraphRAG with Neo4j, challenges and future directions.

In the rapidly evolving field of artificial intelligence, the convergence of Graph Machine Learning (GraphML) and Large Language Models (LLMs) represents a frontier rich with possibilities. This chapter explores how these two powerful technologies can be combined to unlock new insights and applications. From understanding context-rich relationships in text to enabling enhanced reasoning capabilities, this chapter aims to provide a comprehensive overview of state-of-the-art advancements in integrating GraphML and LLMs, before delving into theoretical insights and practical examples to illustrate their synergy.

In this chapter, we will:

  • Provide an overview of the synergies between GraphML and LLMs.
  • Illustrate the benefits of combining LLMs with graph-based approaches.
  • Offer hands-on practical examples and code snippets to demonstrate these integrations.
  • Highlight the challenges and opportunities in this emerging field.

In the rapidly evolving field of artificial intelligence, LLMs have significantly advanced natural language processing (NLP) and understanding. These models, characterized by their extensive number of parameters and trained on large datasets, have demonstrated remarkable capabilities across a wide set of language-related tasks.

The journey of language models began with statistical approaches that relied on probabilistic methods to predict word sequences. These early models, while creating the foundations, were limited by their reliance on fixed-size context windows and the inability to capture long-range dependencies. However, as we also discussed in Chapter 4, Unsupervised Graph Learning, with the advent of neural networks, the field has undergone a significant shift, introducing models capable of learning word embeddings. In order to improve the ability to capture long-range dependencies, the initial neural network models were based on the Long-Short Term Memory (LSTM) and Gate-Recurrent Unit (GRU) architecture, which are forms of Recurrent Neural Networks (RNNs). However, a pivotal moment occurred with the introduction of the Transformer architecture by Vaswani et al. in 2017. Unlike its predecessors, the Transformer model utilized self-attention mechanisms, enabling it to consider the entire context of a sentence without the sequential constraints inherent in RNNs. This innovation facilitated the development of models capable of processing and generating text in a more coherent and fluent way.

Building upon the Transformer architecture, researchers scaled models to unprecedented sizes, leading to the emergence of LLMs such as OpenAI’s GPT series, Google’s BERT and T5, and more recently, models such as GPT-3 and GPT-4.

In a nutshell, training LLMs involves optimizing a large number of parameters on very large datasets. This process, known as pretraining, typically employs unsupervised learning objectives, such as predicting missing words in a sentence (masked language modeling) or forecasting subsequent words (causal language modeling). As a side effect, the pre-training phase lets the model learn and “understand” a language, resulting in a remarkable ability to generalize across various tasks, often achieving state-of-the-art performance. LLMs have demonstrated proficiency in a diverse array of applications, reflecting their versatility and depth of language understanding. Key areas include text generation, language translation, question answering, and summarization, among many others.

Given the strengths of LLMs in unstructured text processing and generative tasks, an exciting frontier emerges when we consider their integration with graphs. While LLMs excel in understanding and generating natural language, graphs are particularly powerful for representing and analyzing structured relationships between entities. In the rest of the book, we will see examples of how we can take advantage of both.

As we have learned throughout this book, GraphML excels at representing and analyzing structured data such as knowledge graphs, social networks, chemical structures, and so on. It is extremely useful for situations where exploiting relationships between entities is crucial for achieving good performances. However, LLMs are particularly good at interpreting unstructured text, offering generative skills, reasoning, and profound contextual awareness. When it comes to language-based activities such as content creation, question answering, and summarization, they excel.

Despite their impressive capabilities, LLMs are not without limitations. One of the most significant challenges is the problem of hallucination, where an LLM generates factually incorrect or misleading information that appears plausible. This is particularly problematic in domains requiring high factual accuracy, such as healthcare, finance, and legal applications. To mitigate hallucinations and enhance the reliability of LLM outputs, Retrieval-Augmented Generation (RAG) has emerged as a powerful technique. RAG works by dynamically retrieving relevant information from an external knowledge source (such as a knowledge graph) at inference time, rather than just relying on pre-trained knowledge. This approach ensures that the model has access to up-to-date and accurate data, grounding answers in verified information rather than generating content purely from its internal representations.

Recent advancements highlight how integrating GraphML with LLMs can drive significant innovation, enabling the development of applications that require both rich semantic understanding and relational analysis. For instance:

  • Graph-Augmented Question Answering: LLMs can leverage knowledge graphs to answer domain-specific questions with factual accuracy.
  • Node Embedding Generation: State-of-the-art frameworks such as GraphGPT use LLMs to generate node embeddings directly from textual data, enabling seamless integration with graph structures.
  • Knowledge Graph Construction and Enhancement: Recent applications have shown how LLMs can be used to enrich knowledge graphs, where LLMs are used to extract semantic relationships and entities from text to enhance existing graph data.

Therefore, by bridging the gap between structured knowledge and natural language understanding, the synergy between GraphML and LLMs paves the way for more accurate, explainable, and intelligent systems.

In the next section, we will explore the state-of-the-art trends in combining GraphML and LLMs, as well as the current challenges.

Before diving into specific examples, it is crucial to understand the current landscape of GraphML and LLM integration. According to a recent survey by Jin et al. (https://arxiv.org/abs/2312.02783, 2024), the application scenario can be categorized into three main scenarios:

  • Pure Graphs: These are graphs that lack associated textual information. Examples include social networks, traffic networks, and protein interaction networks. In such cases, the focus is on leveraging LLMs to process and analyze the structural aspects of the graph data.
  • Text-Attributed Graphs: In these graphs, nodes or edges are enriched with textual attributes. For instance, in academic networks, papers (nodes) come with titles and abstracts, while authors (nodes) have profiles. E-commerce networks also fall into this category, where products (nodes) have descriptions, and user interactions (edges) may include reviews. The challenge here is to effectively combine the textual content with the graph’s structural information.
  • Text-Paired Graphs: This scenario involves graphs that are paired with separate textual descriptions or documents. Unlike text-attributed graphs, where text is embedded within the graph as attributes, text-paired graphs treat the graph and text as distinct but related entities. A pertinent example is molecular graphs accompanied by detailed textual descriptions of their properties. The objective is to align and integrate the information from both the graph structure and the associated text to enhance understanding and analysis.

To effectively utilize LLMs in these scenarios, three primary techniques can be used: LLMs as predictors, LLMs as encoders, and LLMs as aligners. Let’s see these approaches one by one.

The simplest and most direct approach is to use LLMs as predictors. In this paradigm, the LLM operates as a tool to infer outcomes directly from graph data. Imagine a scenario where textual information is either minimal or entirely absent (pure graphs). In this case, you can transform the graph data into a format that the LLM can process, such as converting graph structures into sequences or textual descriptions.

For instance, consider a simple social network graph where nodes represent people and edges indicate friendships (Figure 12.1). These features can be converted into a textual narrative, such as Alice is linked with Bob. An LLM can then process this narrative to predict new relationships or infer additional attributes about the nodes, such as professional interests or potential connections.

Figure 12.1: Examples of how graphs can be converted to text narratives

Figure 12.1: Examples of how graphs can be converted to text narratives

Once the data is prepared, the LLM can be fine-tuned or prompted to perform specific tasks. These might include predicting node classifications, such as identifying the role of individuals in a social network, or link predictions, such as forecasting interactions between entities. In molecular research, LLMs as predictors can help determine the properties of chemical compounds based solely on their structural representations.

One advantage of this approach is its simplicity: LLMs can be applied directly to graph data without requiring extensive preprocessing or specialized models. However, this simplicity can also be a limitation. Purely structural information might not always be sufficient for complex tasks, particularly when additional contextual or textual data is available but not leveraged. Moreover, scalability and cost must be considered: encoding entire graphs as text can lead to an explosion of sentences, making inference expensive, potentially inefficient, and sometimes impossible (for example, if the maximum number of words an LLM can process at once is too small to contain the whole graph). Performance may also be limited, as this approach is similar to providing an LLM with a structured dataset and expecting accurate predictions without tailored adaptations. For this reason, more complex graph2text formalisms can be designed, incorporating node/edge descriptions into textual narratives while balancing efficiency and accuracy.

When graphs are enriched with textual attributes, the LLM as encoder approach becomes particularly powerful. Here, the LLM is tasked with processing and encoding the textual information associated with nodes or edges, producing meaningful representations that can be integrated with the graph’s structural features. These embeddings are then integrated into the graph through proper algorithms such as graph neural networks, which process the combined representation to perform downstream tasks.

This hybrid representation combines the strengths of both modalities, capturing the nuances of text alongside the relationships encoded in the graph. As depicted in Figure 12.2, each node could have attributes, such as a name and a brief bio for a node representing a person, while the edges might be annotated with information about the nature of the relation, e.g., close friend or colleague for a graph representing social networks. These features can be converted into a textual narrative, such as Alice, a software engineer, is close friends with Bob, a data scientist.

Figure 12.2: Examples of how LMMs can be used as encoders for node attributes

Figure 12.2: Examples of how LMMs can be used as encoders for node attributes

Other examples include academic citation networks, where papers (nodes) come with titles, abstracts, and keywords. An LLM can process these textual attributes to generate embeddings that encapsulate their semantic content. These embeddings are then combined with graph-specific features, such as the citation relationships between papers, to create a unified representation. Similarly, in e-commerce platforms, product descriptions and user reviews can be encoded by LLMs to enhance product similarity graphs or user behavior analysis.

It is worth noticing that the process of using LLMs as encoders typically involves fine-tuning the LLM on domain-specific textual data to ensure that the embeddings accurately reflect the requirements of the task.

This encoder approach offers significant benefits. By leveraging textual data, it captures context and nuances that purely structural methods might miss. It is particularly effective in scenarios where textual attributes can provide critical insights, such as identifying the themes of academic papers or understanding user preferences in recommendation systems.

The goal here is to align and integrate the information from both structure and textual descriptions (or accompanying documents, in the case of text-paired graphs), enabling a comprehensive analysis that leverages the strengths of each. This can be achieved, for example, by finding a shared latent space or a semantic mapping that connects the two modalities. Such an approach might involve designing models that jointly optimize both modalities or using attention mechanisms to focus on the most relevant parts of each input.

In more detail, the synergy between textual encoding (handled by the LLM) and graph structure encoding (handled by, for example, a GNN), can be typically in two ways:

  1. Prediction Alignment: Iterative training where LLMs and GNNs generate pseudo-labels to guide each other’s learning
  2. Latent Space Alignment: Contrastive learning to align the latent representation of the text and the graph structure in a shared space (e.g., Figure 12.3)

Figure 12.3: Graphs and associated texts can be embedded in a shared latent space

Figure 12.3: Graphs and associated texts can be embedded in a shared latent space

For example, in molecular research, a molecular graph might represent the structure of a compound, while a textual description provides information about its properties, synthesis, or applications. In this context, an LLM can be used to process the text to extract relevant features and align these with the structural characteristics of the graph, enabling tasks such as property prediction or drug discovery.

As you can imagine, this approach is particularly powerful in interdisciplinary fields where graphs and text provide complementary points of view. In computational social science, for instance, social graphs representing interactions between individuals can be aligned with news articles, social media posts, or other textual data to study the spread of information or public sentiment. Similarly, in e-commerce, user behavior graphs can be integrated with textual reviews to improve personalized recommendations.

Now that we have a clearer understanding of the LLM and graph landscape, let’s dive into a practical example of how this integration works. We will explore this in the next section.

Based on the previous characterization, the following sections present hands-on examples that showcase how GraphML and LLMs can be integrated.

First of all, let’s define a simple social network using NetworkX. We have three nodes (Alice, Bob, and Carl), each coming with a short description of their job and what they like:

import networkx as nx
# Create a directed graph
G = nx.DiGraph()
G.add_node(1, name="Alice", description="she is a software engineer and she likes reading.")
G.add_node(2, name="Bob", description="he is a data scientist and he likes writing books.")
G.add_node(3, name="Carl", description="he is a data scientist and he likes swimming.")
G.add_edge(1, 3, relationship="is friend with")

Now that we have created the graph, let’s define a function to encode it as a narrative text. We will be using a simple formalism in which we first declare each node and then we describe each connection. Notice that more complicated formalisms can be used to describe more complex scenarios, despite there being no standard way to do this:

# Function to convert network to text
def graph_to_text(graph, edge_type):
descriptions = []
# 1. describe the graph structure
descriptions.append(f"Num nodes: {graph.number_of_nodes()}.\n")
for n in graph:
descriptions.append(f"Node {n}: {graph.nodes[n]['name']}\n")
for u, v, data in graph.edges(data=True):
node_u = graph.nodes[u]
node_v = graph.nodes[v]
descriptions.append(f"The person named '{node_u['name']}' ({node_u['description']}) {edge_type} '{node_v['name']}' ({node_v['description']}).")
return " ".join(descriptions)
text_input = graph_to_text(G, "is friend with")
print("Social Network as text:\n", text_input)

The output should be as follows:

Social Network as text: Num nodes: 3. Node 1: Alice Node 2: Bob Node 3: Carl The person named 'Alice' (she is a software engineer and she likes reading.) is friend with 'Carl' (he is a data scientist and he likes swimming.).

We will now declare a prompt, which is a simple instruction describing the task to the LLM:

# Create a prompt
prompt = f"Here is a social network: {text_input}\nBased on the above, suggest any missing link and explain why they might be relevant."

It is now time to send the prompt to the LLM server and wait for a response. To achieve this aim, we will be using the OpenAI API to create a client instance. The client will connect to the LLM server, and send and receive messages:

# Call the llm to generate a response
from openai import OpenAI
# Create a client for interacting with the LLM server. Here, we are
# running LM Studio locally, therefore we use the localhost address and
# "lm-studio" as api key. You can replace this line with a proper api key
# to a remote LLM service if you have one.
client = OpenAI(base_url="http://localhost:1234/v1/", api_key="lm-studio")

Let’s use the client functionalities to create and send a message. Note that we are also specifying which language model to use (minicpm-llama3-v-2_5). If you are running LM Studio locally, you need to download the model first:

response = client.chat.completions.create(
model="minicpm-llama3-v-2_5",
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}],
max_tokens=300,
)

Finally, let’s check the answer:

# Extract the generated text from the response
print(response.choices[0].message.content)

The output should be as follows:

A possible missing link in this citation network could be between Alice and Bob. Since Alice is a software engineer who likes reading and Bob is mentioned as a friend of Carl (a data scientist), it would make sense for them to have some connection. Since Alice enjoys reading, she may appreciate discussions or debates about literature with someone who shares her interest.

The explanation is pretty clear: since Alice works in the tech industry and is a friend of Carl, it makes sense for Carl to introduce her to Bob, who shares similar interests.

Note that to add this link to the graph using NetworkX, you need to do some text processing. We leave this as an exercise for you. Furthermore, you may want to tune the prompt to let the model answer using a specific way to facilitate the parsing (e.g., it can answer something like “Alice -> Bob”).

In the next example, we will see how to use the LLM as an encoder.

When graphs are enriched with textual attributes, the LLM as encoder approach becomes powerful. For example, in a recommendation system, products (nodes) might have textual descriptions, reviews, and other metadata. This textual data can be processed with LLMs to create meaningful embeddings, which can be further combined with graph-structured features such as user-product interactions.

Let’s walk through an example of enhancing a movie recommendation graph using LLMs as encoders. Let’s define our graph where nodes represent movies, and edges represent similarities between movies. Each node also contains a textual description of the movie:

import networkx as nx
from openai import OpenAI
# Let's create a toy movie graph
G = nx.Graph()
G.add_node(1, title="Inception", description="A mind-bending thriller about dreams within dreams.")
G.add_node(2, title="The Matrix", description="A hacker discovers the shocking truth about reality.")
G.add_node(3, title="Interstellar", description="A team travels through a wormhole to save humanity.")
G.add_edge(1, 2, similarity=0.8)
G.add_edge(1, 3, similarity=0.9)

As in the previous example, let’s initialize the client to query the LLM server:

# Intialize the client
client = OpenAI(base_url="http://localhost:1234/v1/", api_key="lm-studio")

Let’s write a function to compute the text embedding using the LLM. It takes as input a text and returns the embedding. For convenience, our function will exploit the client.embeddings.create method from the OpenAI API. Also, in this case, we have to specify an LLM. We have chosen the powerful Nomic embedding model (recall you have to download it in advance through LM Studio):

def encode_text(text):
# Prepare the query for the LLM
response = client.embeddings.create(
input=text,
model="text-embedding-nomic-embed-text-v1.5-embedding"
)
# Get 768-dimensional embedding
embedding = response.data[0].embedding
return embedding

For each node in the graph, let’s compute the corresponding embedding and set it as a node attribute in the NetworkX graph:

# Encode movie descriptions and add embeddings to the graph
for node in G.nodes(data=True):
description = node[1]['description']
embedding = encode_text(description)
node[1]['embedding'] = embedding

Once we have textual embeddings, we can integrate them with structural features such as node degrees or edge similarities. This hybrid representation is then fed into a downstream GraphML model (e.g., graph neural network):

import numpy as np
# Combine embeddings with structural features
for node in G.nodes(data=True):
# We are using degree as a sample feature
structural_features = np.array([G.degree[node[0]]])
node[1]['combined_features'] = np.concatenate((node[1]['embedding'],
structural_features),
axis=None)

With the combined features, you can train a machine learning model to predict recommendations or similarities between nodes. For instance, we can build a simple transductive nearest-neighbor approach by computing the pairwise similarities between node features. This way, we can suggest “similar” movies to users:

from sklearn.metrics.pairwise import cosine_similarity
# Compute similarity between nodes based on combined features
node_features = [node[1]['combined_features'] for node in G.nodes(data=True)]
similarity_matrix = cosine_similarity(node_features)
# Example: Find movies similar to 'Inception' (node 1)
movie_index = 0 # Index of the movie 'Inception'
# Let's take the top 2 similar
similar_movies = np.argsort(-similarity_matrix[movie_index])[1:3]
print("Movies similar to Inception:", similar_movies)

Of course, once you have extracted the node features, you can also use the various models we have described in previous chapters, such as GNNs seen in Chapter 4, Unsupervised Graph Learning, for unsupervised learning, and in Chapter 5, Supervised Graph Learning, for supervised learning. However, it is important to observe that, when combining textual embeddings with structural features, it’s crucial to balance their influence. High-dimensional text embeddings can overshadaw low-dimensional structural features, potentially distorting similarity computations. Proper scaling ensures both types of features contribute meaningfully as well as weighting the contribution of each feature. For example, you may want to assign different weights to text versus structure when concatenating, and using structural encoders such as GNNs may help balance dimensionalities.

As we have previously learned in this section, there are two typical approaches for achieving text-graph alignment: prediction alignment and latent space alignment. In the rest of this section, we will explore each in more detail with practical examples.

First, let’s showcase how LLM-GNN prediction alignment can be achieved. Here’s how we present an approach based on iterative training. The LLM learns from the text information in the graph (e.g., node descriptions), while the GNN learns from the graph structure. Each model generates pseudo-labels, which the other model uses to improve its training. Summarizing:

  1. The LLM analyzes text data and generates node labels, which will serve as pseudo-labels for the GNN.
  2. The GNN then processes the graph structure and produces node labels based on connectivity and relationships, which are then fed back to the LLM.
  3. The process is repeated with each model refining its prediction based on insights from the other.

As we have previously said, LLMs are resource-intensive. As this example requires a bit of fine-tuning, it is difficult to showcase an example using very large models such as GPT. Therefore, we will be using a smaller but powerful model, BERT (https://arxiv.org/pdf/1810.04805). To access the model, we will use the transformer Python module.

Let’s consider a toy citation network, where nodes represent research papers, edges represent citations between papers, and each node is described by title and abstract:

from torch_geometric.data import Data
import torch
# Assume a toy dataset with 3 papers (nodes), edges, and labels
data = Data(
x=torch.rand(3, 10), # let's use random features for simplicity
edge_index=torch.tensor([[0, 1], [1, 2]], dtype=torch.long), # Edges
y=torch.tensor([0, 1, 2], dtype=torch.long), # True labels
text=["Paper A abstract", "Paper B abstract", "Paper C abstract"],
# Text data
)

Let’s define a GNN module to encode structural information and a TextEncoder module, which uses the transformer API, to download and create the BERT model. Note that, since transformer is built in PyTorch, we will define our GNN using PyG:

from torch_geometric.nn import GCNConv
from transformers import AutoTokenizer, AutoModel
# 1. Define the Graph Neural Network (GNN)
class GNN(torch.nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(GNN, self).__init__()
self.conv1 = GCNConv(input_dim, hidden_dim)
self.conv2 = GCNConv(hidden_dim, output_dim)
def forward(self, x, edge_index):
x = self.conv1(x, edge_index).relu()
x = self.conv2(x, edge_index)
return x
# 2. Define the LLM (e.g., BERT for text encoding)
class TextEncoder(torch.nn.Module):
def __init__(self, model_name="bert-base-uncased", output_dim=128):
super(TextEncoder, self).__init__()
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModel.from_pretrained(model_name)
self.fc = torch.nn.Linear(self.model.config.hidden_size, output_dim)
def forward(self, texts):
# Tokenize and encode text data
inputs = self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
outputs = self.model(**inputs)
cls_embedding = outputs.last_hidden_state[:, 0, :]
# [CLS] token embedding
return self.fc(cls_embedding)

In the notebook attached to the repository, we have built a pretty standard GNN using two graph convolution layers. The TextEncoder, instead, is composed of the pretrained LLM model, followed by a trainable linear fully connected (fc) projection layer. The forward pass first converts the text into a format that is digestible by the LLM (tokenization). The resulting embeddings are then forwarded to the linear layer to make a prediction. Please refer to the notebook attached in the repository for the implementation details of the GNN and the text encoder.

Finally, using these analytical components (GNN and text encoder), we can define our training loop as follows:

# 3. Training Loop with Pseudo-label Exchange
def train_prediction_alignment(data, gnn, text_encoder, num_iterations=5):
optimizer_gnn = torch.optim.Adam(gnn.parameters(), lr=0.01)
optimizer_text = torch.optim.Adam(text_encoder.parameters(), lr=0.0001)
# Initialize with true labels for first iteration
gnn_pseudo_labels = data.y.clone()
llm_pseudo_labels = data.y.clone()
for iteration in range(num_iterations):
# Train GNN using LLM pseudo-labels from previous iteration
gnn.train()
optimizer_gnn.zero_grad()
gnn_logits = gnn(data.x, data.edge_index)
gnn_loss = torch.nn.CrossEntropyLoss()(gnn_logits, llm_pseudo_labels)
gnn_loss.backward()
optimizer_gnn.step()
# Generate new GNN pseudo-labels
with torch.no_grad():
gnn_pseudo_labels = torch.argmax(gnn_logits, dim=1)
# Train Text Encoder using GNN pseudo-labels
text_encoder.train()
optimizer_text.zero_grad()
text_logits = text_encoder(data.text)
llm_loss = torch.nn.CrossEntropyLoss()(text_logits, gnn_pseudo_labels)
llm_loss.backward()
optimizer_text.step()
# Generate new LLM pseudo-labels for next iteration
with torch.no_grad():
llm_pseudo_labels = torch.argmax(text_logits, dim=1)
print(f"Iteration {iteration+1}: GNN Loss = {gnn_loss.item():.4f}, LLM Loss = {llm_loss.item():.4f}")
print(f" GNN predictions: {gnn_pseudo_labels.tolist()}")
print(f" LLM predictions: {llm_pseudo_labels.tolist()}")

In this supervised loop, the GNN model predicts pseudo-labels (the model is optimized using CrossEntropyLoss to minimize the difference between the prediction and the targets). The predicted labels are then used as targets to fine-tune the text encoder. This way, the final model benefits from both textual and structural insights, enabling more accurate classification of research papers.

Note

The “symmetric” approach can also be used in a unidirectional (asymmetric) manner, where pseudo-labels from only one model are used to train the other.

Of course, this is a toy example with random features, but we hope you grasp the principle to apply it in real-world cases and better understand related state-of-the-art approaches (check the end of this chapter for further reading!).

Instead of iteratively sharing labels, this method aligns the latent representations of text and graph data via contrastive learning. The goal is to force text and graph encodings for the same entity (e.g., a node) to be similar in a shared space while pushing encodings for unrelated entities far apart. Summarizing:

  1. Text Encoding: Use an LLM to encode the node descriptions into a latent vector.
  2. Graph Encoding: Use a GraphML model (e.g., GNN) to encode the graph structure around each node into latent vectors.
  3. Contrastive learning: Use contrastive learning to maximize the similarity between the text and graph encoding for the same node or neighbor nodes, while minimizing the similarity between unrelated nodes.

Let’s consider a toy knowledge graph, where nodes represent products, edges represent relationships such as “frequently bought together,” and each node has a text description:

# Toy data with 3 products and their relationships
data = Data(
x=torch.rand(3, 10), # Node features
edge_index=torch.tensor([[0, 1], [1, 2]], dtype=torch.long), # Edges
text=["Product A description", "Product B description", "Product C description"], # Text data
)

For simplicity, let’s use the same GNN and text encoder as in the previous example. Therefore, we only need to define our contrastive loss and training loop.

As previously described, the contrastive loss will force the model to minimize differences between “similar” nodes, while maximizing the difference between unrelated nodes. In more detail, we compute a similarity matrix sim of shape (batch_size, batch_size), where sim[i, j] is the similarity between the i-th graph embedding and the j-th text embedding. Here, we assume a perfect one-to-one correspondence (labels), where the i-th graph embedding should match the i-th text embedding:

import torch.nn.functional as F
# Contrastive Learning Objective
def contrastive_loss(graph_emb, text_emb, tau=0.1):
sim = F.cosine_similarity(graph_emb.unsqueeze(1), text_emb.unsqueeze(0), dim=2)
labels = torch.arange(sim.size(0)).to(sim.device)
loss = F.cross_entropy(sim / tau, labels)
return loss

The training loop simply optimizes the graph and text encoders using the contrastive loss:

# Training Loop for Latent Space Alignment
def train_latent_alignment(data, gnn, text_encoder, epochs=10):
optimizer = torch.optim.Adam(list(gnn.parameters()) + list(text_encoder.parameters()), lr=0.001)
for epoch in range(epochs):
optimizer.zero_grad()
# Encode graph and text
graph_emb = gnn(data.x, data.edge_index) # Graph embeddings
text_emb = text_encoder(data.text) # Text embeddings
# Compute contrastive loss
loss = contrastive_loss(graph_emb, text_emb)
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}: Loss = {loss.item()}")

This fusion may create richer node or entity embeddings, improving downstream tasks such as node classification and recommendation and retrieval systems (e.g., you may retrieve nodes from the graph based on their description). Interestingly, this unified representation can also support zero-shot and few-shot learning in graph-based tasks. Since LLMs process textual prompts, they can generalize to new, unseen categories within a graph without requiring extensive retraining. For example, if a graph-based dataset lacks labeled examples for a particular node class, an LLM can still classify nodes by leveraging semantic similarities and contextual cues from textual descriptions.

We have seen how text and graphs can be aligned to achieve a tight integration. In the next section, we will see another practical application of combining graphs and LLMs, which is how to build a knowledge graph from an unstructured text using an LLM.

In Chapter 8, Text Analytics and Natural Language Processing Using Graphs, we used spaCy to convert text into a graph. While spaCy is excellent for named entity recognition (NER) and dependency parsing, it has limitations when extracting complex relationships from text. Conventional NER performs well in domains with well-established taxonomies and is dependable for organized, predefined entity types. To extract entities and relationships from large, unstructured data sources, LLMs offer a more adaptable, context-aware alternative.

Here, we use an LLM-powered approach to build a Knowledge Graph (KG) from text. We will be using LangChain (https://www.langchain.com/), an open-source framework designed to help developers build applications powered by LLMs. It provides tools for prompt engineering, memory management, and data retrieval, amongst others.

In particular, we will make use of LLMGraphTransformer to extract entities and relationships from text, which features some nice properties:

  • It may handle complex relationships better than rule-based NLP methods.
  • It extracts a wider variety of entities beyond predefined spaCy models.
  • It adapts dynamically to different domains without retraining a model.

Let’s first consider a free text as follows:

text = """
Marie Curie, born in 1867, was a Polish and naturalized-French physicist and chemist who conducted pioneering research on radioactivity.
She was the first woman to win a Nobel Prize, the first person to win a Nobel Prize twice, and the only person to win a Nobel Prize in two scientific fields.
"""

In the following snippet of code, we will use LangChain objects to convert the text into a set of nodes and relationships (KG) using an LLM. LangChain will handle all the operations to convert the text into a proper object (Document) and send it to our backend server to be parsed by our MiniCPM model in LM Studio:

from langchain_experimental.graph_transformers.llm import LLMGraphTransformer
from langchain_openai import ChatOpenAI
from langchain_core.documents import Document
llm = ChatOpenAI(temperature=0, model_name="minicpm-llama3-v-2_5", base_url="http://localhost:1234/v1", api_key="lm-studio")
llm_transformer = LLMGraphTransformer(llm=llm)
documents = [Document(page_content=text)]
graph_documents = llm_transformer.convert_to_graph_documents(documents)
print(f"Nodes: {graph_documents[0].nodes}")
print(f"Relationships: {graph_documents[0].relationships}")

The output should be as follows:

Nodes:[Node(id='Marie_Curie', type='Person', properties={}), Node(id='Pierre_Curie', type='Person', properties={})] Relationships:[Relationship(source=Node(id='Marie_Curie', type='Person', properties={}), target=Node(id='Pierre_Curie', type='Person', properties={}), type='MARRIED_TO', properties={}), Relationship(source=Node(id='Marie_Curie', type='Person', properties={}), target=Node(id='Nobel_Prize', type='Award', properties={}), type='WON_NOBEL_PRIZE', properties={}), Relationship(source=Node(id='Pierre_Curie', type='Person', properties={}), target=Node(id='Marie_Curie', type='Person', properties={}), type='MARRIED_TO', properties={})]

That’s it! We can parse the nodes and relationships to encode the graph in a proper framework such as NetworkX or Neo4j.

Note that different results can be achieved using longer text (e.g., a custom PDF) and different models. For example, it is expected that fine-tuned models or larger models (more than 100B parameters) can achieve better results. However, they would need more resources.

In the next section, we will see how can we load the extracted graph into Neo4j to perform GraphRAG, that is, how we can augment an LLM using a knowledge graph for more precise question answering.

In the context of integrating LLMs with graph-based data, the term “LLM as aligner” refers to the role of LLMs in aligning or integrating textual information with graph structures to enhance understanding and retrieval. This approach is exemplified by techniques such as RAG and its extension, GraphRAG.

RAG is a framework that combines the strengths of traditional information retrieval systems with the generative capabilities of LLMs. In this setup, an LLM is augmented with a retrieval component that fetches relevant information from external data sources, such as knowledge bases or databases, to produce more accurate and contextually relevant responses. This method enhances the LLM’s output by grounding it in authoritative, up-to-date information.

GraphRAG builds upon the RAG framework by incorporating KG into the retrieval process. In this approach, the retrieval component utilizes a knowledge graph—a structured representation of entities and their relationships—to provide contextually relevant information to the LLM. This integration allows for a richer understanding of complex data by combining text extraction, network analysis, and LLM prompting into a cohesive system.

By acting as an aligner, the LLM effectively bridges the gap between unstructured textual data and structured graph representations, facilitating more comprehensive data analysis and retrieval. This alignment enhances the LLM’s ability to generate responses that are both contextually relevant and grounded in structured knowledge, leading to improved performance in tasks such as question answering, recommendation systems, and data summarization.

In recent years, several tools have risen for GraphRAG. Here, we will be using Neo4j and LangChain to achieve a fully local, efficient GraphRAG.

First of all, we need to start our Neo4j server. It will act as a backend for storing the KG and performing the RAG operations. As you can read in Chapter 10, Building a Data-Driven Graph-Powered Application, Neo4j is one of the most common graph databases, which can scale to fairly large datasets and can be distributed over multiple nodes.

Similarly to Chapter 10, Building a Data-Driven GraphPowered Application, we can locally deploy a Neo4j server instance using Docker. However, since here we need the apoc plugins, we need to feed to the docker commands some extra environment variables with respect to the command seen in the previous chapter:

Terminal window
docker run --rm --detach --name neo4j \
--publish=7474:7474 --publish=7687:7687 \
--env NEO4J_AUTH=neo4j/defaultpass \
--env NEO4J_PLUGINS='["apoc-extended"]' \
--env NEO4J_apoc_export_file_enabled=true \
--env NEO4J_apoc_import_file_enabled=true \
--env NEO4J_apoc_import_file_use__neo4j_config=true \
neo4j:5.26.0

It’s now time to implement our GraphRAG system! First of all, let’s connect to Neo4j (this part can be adapted if you are using a different edition):

from neo4j import GraphDatabase
from langchain_neo4j import Neo4jGraph
NEO4J_URI = "bolt://localhost:7687"
NEO4J_USER = "neo4j"
NEO4J_PASSWORD = "your_password"
driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
graph = Neo4jGraph(url=NEO4J_URI, username=NEO4J_USER, password=NEO4J_PASSWORD)

Once we have our graph connection instance, we can store the KG created above in Neo4j, as follows:

graph.add_graph_documents(graph_documents)

At this point, our extracted KG is stored in Neo4j and ready for querying. You can visualize it in your browser at localhost:7474, and it should look as follows:

Figure 12.4: Visualization of extracted KG in Neo4j

Figure 12.4: Visualization of extracted KG in Neo4j

Our GraphRAG method is fairly simple: we provide an LLM with our KG and a textual query, and we ask it to generate a Cypher query representing the textual query. Then, Neo4j performs the query and provides the LLM with the extracted results. Finally, the LLM uses this information to generate an answer.

To help the LLM generate a correct query, we first define a Cypher template to guide query generation:

CYPHER_GENERATION_TEMPLATE = """You are a Neo4j expert. Generate a Cypher query to answer the given question.
Database Schema:
- Nodes:
* Person (properties: id)
* Award (properties: id)
- Relationships:
* (Person)-[:MARRIED_TO]-(Person)
* (Person)-[:WON_NOBEL_PRIZE]->(Award)
Rules:
1. Always use explicit `MATCH` for relationships.
2. Never use `WHERE` for relationship matching.
3. Use `RETURN DISTINCT` when appropriate.
Example Queries:
1. Question: "Who won the Nobel Prize?"
Cypher: MATCH (p:Person)-[:WON_NOBEL_PRIZE]->(:Award) RETURN p.id AS winner
Question: {query}
Return only the Cypher query without any explanation or additional text.
Cypher:"""

Let’s use the GraphCypherQAChain object in LangChain. This object passes context to the Q&A prompt in the _call method. It retrieves the results from the graph database using the generated Cypher query and passes these results as the context to the LLM. The LLM then uses this context along with the question to generate an answer:

from langchain_neo4j import GraphCypherQAChain
from langchain_core.prompts import PromptTemplate
chain = GraphCypherQAChain.from_llm(
llm=llm,
graph=graph,
verbose=True,
cypher_prompt=PromptTemplate(
input_variables=["query"],
template=CYPHER_GENERATION_TEMPLATE
),
allow_dangerous_requests=True
)

Let’s ask something simple but not trivial, for example, “Who married a Nobel Prize winner?”:

question = "Who married a Nobel Prize winner?"
print(f"\nQuestion: {question}")
response = chain.invoke(question)
print("Response:", response['result'])
# Close the driver
driver.close()

The output should be as follows:

Response: Pierre Curie married a Nobel Prize winner.

The answer is correct! Note that, to answer the question, the engine had to build a specific Cypher query that looks like the following:

MATCH (p1:Person)-[:MARRIED_TO]-(p2:Person)-[:WON_NOBEL_PRIZE]->(:Award) RETURN p1.id AS winner

Therefore, the LLM received grounded information to prepare the answer, which makes the response more trustable compared to a pure generative method. However, while this method effectively retrieves structured data, alternative approaches (such as embedding-based retrieval) could further enhance results. GraphRAG can be implemented in multiple ways:

  • Cypher Query-Based Retrieval (our approach): Uses an LLM to translate queries into Cypher queries, which fetch structured data from a Neo4j graph
  • Graph Embedding Retrieval: Stores knowledge graph entities as vector embeddings and retrieves relevant nodes using similarity search
  • Hybrid Approach: Combines structured graph querying with embedding-based retrieval for greater flexibility

Neo4j and LangChain offer a well-curated and robust environment to implement and try new approaches, which can result in very powerful applications.

This section concludes our overview of practical examples of combining graphs with LLMs. However, in these rapidly evolving fields, it is important to stay updated on new discoveries that may overcome current challenges, some of which we will outline in the next section.

The integration of GraphML and LLMs opens up a lot of possibilities, but it also presents significant challenges that must be addressed for widespread adoption. One of the foremost concerns is scalability since dealing with large-scale graphs alongside computationally intensive LLMs requires expensive resources in terms of memory, processing power, and efficient data pipelines.

As with many other deep learning-based approaches, another major challenge is in interpretability. While knowledge graphs provide a structured and transparent way to store relationships, LLMs operate as a black box, making it difficult to understand how specific outputs are generated. For example, considering the presented GraphRAG approach, it is not guaranteed that the generated query will be semantically correct, and correcting the result is not an easy task.

Data alignment is also a key issue, as structured knowledge graphs and unstructured text data must be carefully preprocessed to ensure consistency. Differences in data formats, ontology mismatches, and information redundancy can create inefficiencies when integrating these two paradigms. Developing robust pipelines that seamlessly connect graph-based insights with LLM-generated text remains an open challenge.

By tackling these challenges, the synergy between GraphML and LLMs has the potential to bridge the gap between structured knowledge and flexible, natural language reasoning.

Being such a recent and rapidly evolving field, we encourage you to dive deeper into GraphML and LLMs. Reading scientific papers is probably the best way to stay updated. Packt has also a nice collection of books to further expand your knowledge. However, living in the AI era, you can easily find online blogs, materials, and resources to stay updated with the current trends!

This chapter has provided an introduction to combining GraphML and LLMs with practical examples. By leveraging the strengths of both technologies, researchers and practitioners can push the boundaries of what’s possible in AI-driven applications.

We have learned what LLMs are and how they can work with graphs using state-of-the-art techniques. We also explored the current trends and challenges in the landscape of GraphML and LLM integration. Finally, we saw how to start developing useful tools such as knowledge graph builders and GraphRAG systems.

In the next chapter, we will turn to some recent developments and the latest research and trends in machine learning that have been applied to graphs. In particular, we will describe some of the latest techniques (such as generative neural networks) and applications (such as graph theory applied in neuroscience) available in the scientific literature, providing some practical examples and possible applications.

There are some excellent books and papers that can help you further. Please have a look at the following:

  • Applied Deep Learning on Graphs by Lakshya Khandelwal and Subhajoy Das; Amazon Link
  • There is a great tutorial here: Packt Tutorial: Large Language Models and Knowledge Graphs
  • You can also get more information from Chapter 1 of Building LLM Powered Applications, by Valentina Alto: Packt Link: Building LLM Powered Applications
  • Li, Q., Zhao, T., Chen, L., Xu, J., & Wang, S. (2024, December). Enhancing Graph Neural Networks with Limited Labeled Data by Actively Distilling Knowledge from Large Language Models. In 2024 IEEE International Conference on Big Data (BigData) (pp. 741-746). IEEE.
  • Wang, D., Zuo, Y., Li, F., & Wu, J. (2024). LLms as zero-shot graph learners: Alignment of GNN representations with llm token embeddings. Advances in Neural Information Processing Systems, 37, 5950-5973.
  • Li, Y., Li, Z., Wang, P., Li, J., Sun, X., Cheng, H., & Yu, J. X. (2023). A survey of graph meets large language model: Progress and future directions. arXiv preprint arXiv:2311.12399.