Armazenando e consultando documentos

Retrieval Augmented Generation (RAG) com LangChain

Meri Nova

Machine Learning Engineer

Instanciando o banco 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) com LangChain

Armazenando documentos de 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) com LangChain

Armazenando documentos de grafo

graph.add_graph_documents(
  graph_documents,

include_source=True,
baseEntityLabel=True
)
  • include_source=True: vincula nós aos documentos de origem com a aresta MENTIONS
  • baseEntityLabel=True: adiciona o rótulo __Entity__ a cada nó
Retrieval Augmented Generation (RAG) com LangChain

Os documentos de grafo representados como nós e arestas.

Retrieval Augmented Generation (RAG) com LangChain

Versão ampliada da imagem anterior mostrando nós sobre modelos da OpenAI.

Retrieval Augmented Generation (RAG) com LangChain

Esquema do banco de dados

print(graph.get_schema)
Propriedades dos nós:
Concept {id: STRING}
Architecture {id: STRING}
Organization {id: STRING}
Event {id: STRING}
Paper {id: STRING}

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

Consultando no Neo4j — linguagem Cypher

Um nó chamado James com um relacionamento chamado friends apontando para um nó pessoa desconhecido.

Retrieval Augmented Generation (RAG) com LangChain

Consultando no Neo4j — linguagem Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) com LangChain

Consultando no Neo4j — linguagem Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) com LangChain

Consultando no Neo4j — linguagem Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) com LangChain

Consultando no Neo4j — linguagem Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) com LangChain

Consultando o grafo de LLMs

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

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

Vamos praticar!

Retrieval Augmented Generation (RAG) com LangChain

Preparing Video For Download...