Archiviare e interrogare documenti

Retrieval Augmented Generation (RAG) con LangChain

Meri Nova

Machine Learning Engineer

Istanziare il database Neo4j

from langchain_community.graphs import Neo4jGraph

graph = Neo4jGraph(url="bolt://localhost:7687", username="neo4j", password="...")
import os

url = os.environ["NEO4J_URI"]
user = os.environ["NEO4J_USERNAME"]
password = os.environ["NEO4J_PASSWORD"]

graph = Neo4jGraph(url=url, username=user, password=password)
1 https://neo4j.com/download/
Retrieval Augmented Generation (RAG) con LangChain

Archiviare i documenti grafo

from langchain_experimental.graph_transformers import LLMGraphTransformer

llm = ChatOpenAI(api_key="...", temperature=0, model="gpt-4o-mini")
llm_transformer = LLMGraphTransformer(llm=llm)

graph_documents = llm_transformer.convert_to_graph_documents(documents)
Retrieval Augmented Generation (RAG) con LangChain

Archiviare i documenti grafo

graph.add_graph_documents(
  graph_documents,

include_source=True,
baseEntityLabel=True
)
  • include_source=True: collega i nodi ai documenti di origine con l'arco MENTIONS
  • baseEntityLabel=True: aggiunge l'etichetta __Entity__ a ogni nodo
Retrieval Augmented Generation (RAG) con LangChain

I documenti grafo rappresentati come nodi e archi.

Retrieval Augmented Generation (RAG) con LangChain

Un ingrandimento dell'immagine precedente con nodi su modelli OpenAI.

Retrieval Augmented Generation (RAG) con LangChain

Schema del database

print(graph.get_schema)
Proprietà dei nodi:
Concept {id: STRING}
Architecture {id: STRING}
Organization {id: STRING}
Event {id: STRING}
Paper {id: STRING}

Relazioni:
(:Concept)-[:DEVELOPED_BY]->(:Person)
(:Architecture)-[:BASED_ON]->(:Concept)
(:Organization)-[:PROPOSED]->(:Concept)
(:Document)-[:MENTIONS]->(:Event)
(:Paper)-[:BASED_ON]->(:Concept)
Retrieval Augmented Generation (RAG) con LangChain

Interrogare Neo4j - Cypher Query Language

Un nodo chiamato James con una relazione "friends" che punta a un nodo persona sconosciuto.

Retrieval Augmented Generation (RAG) con LangChain

Interrogare Neo4j - Cypher Query Language

cypher4.jpg

Retrieval Augmented Generation (RAG) con LangChain

Interrogare Neo4j - Cypher Query Language

cypher4.jpg

Retrieval Augmented Generation (RAG) con LangChain

Interrogare Neo4j - Cypher Query Language

cypher4.jpg

Retrieval Augmented Generation (RAG) con LangChain

Interrogare Neo4j - Cypher Query Language

cypher4.jpg

Retrieval Augmented Generation (RAG) con LangChain

Interrogare il grafo LLM

results = graph.query("""
MATCH (gpt4:Model {id: "Gpt-4"})-[:DEVELOPED_BY]->(org:Organization)
RETURN org
""")

print(results)
[{'org': {'id': 'Openai'}}]
Retrieval Augmented Generation (RAG) con LangChain

Esercitiamoci!

Retrieval Augmented Generation (RAG) con LangChain

Preparing Video For Download...