LangChain Neo4j Integration
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
-
neo4j.exceptions.AuthError: {code: Neo.ClientError.Security.Unauthorized} {message: The client is unauthorized due to authentication failure.}cause Incorrect Neo4j username, password, or token, or the Neo4j database requires a password reset (e.g., in Neo4j Desktop projects).fixDouble-check `NEO4J_USERNAME`, `NEO4J_PASSWORD`, or `NEO4J_TOKEN` values. For Neo4j Desktop, ensure the database-specific password is correct and reset it if necessary from the project details. -
ServiceUnavailable: Failed to establish connection to 'bolt://localhost:7687' (reason: None)
cause Neo4j database not running, incorrect URI, firewall blocking port 7687, or network connectivity issues (e.g., VPN blocking, DNS resolution failure).fixVerify Neo4j instance is running and accessible at the specified URI. Check firewall rules to ensure port 7687 is open. Test network connectivity (e.g., `ping` or `telnet` to the Neo4j host/port). Use `NEO4J_URI` with the correct protocol (e.g., `bolt://` or `neo4j://`). -
CypherSyntaxError: Invalid input 'schema': expected 'MATCH', 'CREATE', 'RETURN'...
cause An older Neo4j database version might have an incompatible Cypher syntax for schema introspection queries used by `Neo4jGraph`.fixUpdate your Neo4j database instance to a recent version (Neo4j 4.x or 5.x are generally compatible with `langchain-neo4j`). If using Docker, try a newer image. -
LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use langchain_openai.ChatOpenAI instead.
cause Using an older import path for LLM/embedding classes after upgrading LangChain to v0.1.0+.fixUpdate your import statements to use the new package structure, e.g., `from langchain_openai import ChatOpenAI` instead of `from langchain.chat_models import ChatOpenAI`. Install `langchain-openai` if not already installed.
Warnings
- breaking LangChain v1.0.0+ requires `langchain-classic` and drops Python 3.9 support. `langchain-neo4j` v0.6.0+ is updated to reflect this change, replacing `langchain` with `langchain-classic` as a dependency and removing Python 3.9 support.
- breaking The `GraphCypherQAChain` was fixed in v0.9.0 to improve compatibility with non-Neo4j `GraphStore` implementations by no longer requiring the private `_enhanced_schema` attribute.
- gotcha The `GraphCypherQAChain` constructor includes an `allow_dangerous_requests` parameter. Setting this to `True` can expose your database to potential data corruption or loss if the LLM generates malicious queries.
- deprecated When migrating to LangChain v0.1.0 and beyond, many core LangChain classes (e.g., `ChatOpenAI`, `OpenAIEmbeddings`, `initialize_agent`) moved to `langchain-community` or `langchain-openai` packages. Older `langchain.*` imports will trigger deprecation warnings.
- gotcha The `Neo4jGraph` class in older versions (prior to fix) might default to the 'neo4j' database even when a different database name is specified, leading to connection or data access issues.
Install
-
pip install -U langchain-neo4j -
pip install -U 'langchain-neo4j[mmr]' # For Maximal Marginal Relevance search
Imports
- Neo4jGraph
from langchain_neo4j import Neo4jGraph
- Neo4jVector
from langchain_neo4j import Neo4jVector
- Neo4jChatMessageHistory
from langchain_neo4j import Neo4jChatMessageHistory
- GraphCypherQAChain
from langchain.chains import GraphCypherQAChain
from langchain_neo4j import GraphCypherQAChain
- Neo4jSaver
from langchain_neo4j import Neo4jSaver
- AsyncNeo4jSaver
from langchain_neo4j import AsyncNeo4jSaver
Quickstart
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'])