LangChain Neo4j Integration

0.9.0 · active · verified Thu Apr 16

LangChain Neo4j is an integration package connecting the LangChain framework with the Neo4j graph database. It provides functionalities for building LLM applications, including graph data interaction via `Neo4jGraph`, semantic search with `Neo4jVector`, conversational memory using `Neo4jChatMessageHistory`, and LangGraph checkpoint savers for state persistence. The current version is 0.9.0, with regular updates providing new features and compatibility improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Neo4j database using `Neo4jGraph`, optionally load sample data, and then use `GraphCypherQAChain` with an OpenAI LLM to answer natural language questions by generating and executing Cypher queries against the graph. Ensure `NEO4J_URI`, `NEO4J_USERNAME`, `NEO4J_PASSWORD`, and `OPENAI_API_KEY` environment variables are set.

import os
from langchain_neo4j import Neo4jGraph, GraphCypherQAChain
from langchain_openai import ChatOpenAI

# Set environment variables for Neo4j connection
NEO4J_URI = os.environ.get('NEO4J_URI', 'bolt://localhost:7687')
NEO4J_USERNAME = os.environ.get('NEO4J_USERNAME', 'neo4j')
NEO4J_PASSWORD = os.environ.get('NEO4J_PASSWORD', 'password')
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '')

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY environment variable not set.")

# Initialize Neo4jGraph connection
graph = Neo4jGraph(url=NEO4J_URI, username=NEO4J_USERNAME, password=NEO4J_PASSWORD)

# Optional: Insert some sample movie data if the database is empty
graph.query(
    """
    MERGE (m:Movie {title:'The Matrix'}) WITH m
    UNWIND ['Keanu Reeves', 'Laurence Fishburne', 'Carrie-Anne Moss'] AS actor
    MERGE (a:Actor {name:actor})
    MERGE (a)-[:ACTED_IN]->(m)
    """
)

# Initialize LLM
llm = ChatOpenAI(temperature=0, api_key=OPENAI_API_KEY)

# Create GraphCypherQAChain
# IMPORTANT: allow_dangerous_requests=True is used for demonstration. 
# In production, ensure narrowly-scoped credentials and careful prompt engineering.
chain = GraphCypherQAChain.from_llm(
    llm=llm,
    graph=graph,
    verbose=True,
    allow_dangerous_requests=True
)

# Invoke the chain with a natural language query
result = chain.invoke({"query": "Who acted in The Matrix?"})
print(result['result'])

view raw JSON →