Graphes lexicaux

Graph RAG avec LangChain et Neo4j

Adam Cowley

Manager, Developer Education at Neo4j

Récapitulatif

Les résultats sont injectés dans l’invite, prêts à être envoyés au LLM

Graph RAG avec LangChain et Neo4j

Graphes lexicaux

 

  • Une représentation en graphe de textes et documents non structurés
  • Stocke la hiérarchie d’un livre, article, etc.
  • Au niveau fin, stocke le texte brut

Un diagramme représentant la hiérarchie d’un document : un-à-plusieurs vers des pages, chacune ayant de nombreux nœuds de fragments associés

Graph RAG avec LangChain et Neo4j

Roméo et Juliette

Introduction :

The Project Gutenberg eBook of Romeo and Juliet

This ebook is for the use of anyone anywhere in the United States and
most other parts of the world at no cost and with almost no restrictions

Title: Romeo and Juliet
Author: William Shakespeare

Informations sur les personnages :

Dramatis Personæ

ESCALUS, Prince of Verona.
MERCUTIO, kinsman to the Prince, and friend to Romeo.
PARIS, a young Nobleman, kinsman to the Prince.
Page to Paris.
...

Prologue :

 Enter Chorus.

CHORUS.
Two households, both alike in dignity,
In fair Verona, where we lay our scene,
From ancient grudge break to new mutiny,
...

Actes et scènes :

ACT I
SCENE I. A public place.
 Enter Sampson and Gregory armed with swords and bucklers.

SAMPSON.
Gregory, on my word, we’ll not carry coals.

GREGORY.
No, for then we should be colliers...
1 https://gutenberg.org/ebooks/1513
Graph RAG avec LangChain et Neo4j

Roméo et Juliette comme graphe de connaissances

 

  • La pièce comporte des Actes

Un graphe de connaissances mettant en évidence un nœud Acte

Graph RAG avec LangChain et Neo4j

Roméo et Juliette comme graphe de connaissances

 

  • La pièce comporte des Actes
  • Les actes comportent des Scènes

Un graphe de connaissances mettant en évidence la relation HAS_SCENE du nœud Acte vers le nœud Scène

Graph RAG avec LangChain et Neo4j

Roméo et Juliette comme graphe de connaissances

 

  • La pièce comporte des Actes
  • Les actes comportent des Scènes
  • Les scènes ont des Répliques

Un graphe de connaissances mettant en évidence la relation HAS_LINE du nœud Scène vers le nœud Réplique

Graph RAG avec LangChain et Neo4j

Roméo et Juliette comme graphe de connaissances

 

  • La pièce comporte des Actes
  • Les actes comportent des Scènes
  • Les scènes ont des Répliques
  • Les répliques sont dites par des Personnages

Un graphe de connaissances mettant en évidence la relation SPOKEN_BY du nœud Réplique vers le nœud Personnage

Graph RAG avec LangChain et Neo4j

Roméo et Juliette comme graphe de connaissances

 

  • La pièce comporte des Actes
  • Les actes comportent des Scènes
  • Les scènes ont des Répliques
  • Les répliques sont dites par des Personnages

 

→ Chaque nœud Réplique aura des propriétés de texte et d’embedding

Un diagramme de graphe montrant les relations suivantes : Acte HAS_SCENE Scène, Scène HAS_LINE Réplique, Réplique SPOKEN_BY Personnage

Graph RAG avec LangChain et Neo4j

Charger le document

Chargez un document en mémoire avec un chargeur de documents :

# Load the PDF
loader = PyPDFLoader("romeo-and-juliet.pdf")
pages = loader.load()
Graph RAG avec LangChain et Neo4j

Découper le document

act_splitter = RecursiveCharacterTextSplitter(
    # Split text into acts
    separators=[ r"\n\nTHE PROLOGUE.",  r"\n\nACT", r"\n\n\*\*\* END"],
    is_separator_regex=True
)

scene_splitter = RecursiveCharacterTextSplitter( # Split act into scenes separators=[r"\nSCENE "], is_separator_regex=True )
Graph RAG avec LangChain et Neo4j

Créer des nœuds et des relations

play = Node(

type="Play",
id="romeo-and-juliet",
properties={ "title": "Romeo and Juliet", "playwright": "William Shakespeare", "genres": ["Romance", "Tragedy"] }
)
# Store in a graph document graph_doc = GraphDocument(nodes=[play], relationships=[])
Graph RAG avec LangChain et Neo4j

Extraire les actes

parts = act_splitter.split_text(text)

for act in parts: print(act[:20])
THE PROLOGUE...

ACT I
ACT II
ACT III
Graph RAG avec LangChain et Neo4j

Extraire les actes

parts = act_splitter.split_text(text)

for a, act in enumerate(parts):

first_line = act_text.split("\n")[0].strip()
if first_line.startswith("ACT"):
act_node = Node(
type="Act",
id=first_line,
)
graph_doc.nodes.append(act_node)
Graph RAG avec LangChain et Neo4j

Extraire les actes

for a, act in enumerate(parts):
    # ...
    # act_node = Node(...)


# Create a relationship relationship = Relationship(
source=play,
target=act_node,
type="HAS_ACT",
properties=dict(order=a)
)
graph_doc.relationships.append(relationship)
Graph RAG avec LangChain et Neo4j

Enregistrer nœuds et relations

Avec l’objet Neo4jGraph :

graph = Neo4jGraph(
    url=NEO4J_URI, 
    username=NEO4J_USERNAME, 
    password=NEO4J_PASSWORD
)
graph.add_graph_documents([graph_doc])
Graph RAG avec LangChain et Neo4j

Passons à la pratique !

Graph RAG avec LangChain et Neo4j

Preparing Video For Download...