This notebook shows how to use LLMs to provide a natural language interface to a graph database you can query with the Cypher query language.

You will need to have a running Neo4j instance. One option is to create a free Neo4j database instance in their Aura cloud service. You can also run the database locally using the Neo4j Desktop application, or running a docker container. You can run a local docker container by running the executing the following script:

docker run \
    --name neo4j \
    -p 7474:7474 -p 7687:7687 \
    -d \
    -e NEO4J_AUTH=neo4j/pleaseletmein \
    -e NEO4J_PLUGINS=\[\"apoc\"\]  \

If you are using the docker container, you need to wait a couple of second for the database to start.

from langchain.chat_models import ChatOpenAI
from langchain.chains import GraphCypherQAChain
from langchain.graphs import Neo4jGraph
graph = Neo4jGraph(
    url="bolt://localhost:7687", username="neo4j", password="pleaseletmein"

Seeding the database#

Assuming your database is empty, you can populate it using Cypher query language. The following Cypher statement is idempotent, which means the database information will be the same if you run it one or multiple times.

MERGE (m:Movie {name:"Top Gun"})
UNWIND ["Tom Cruise", "Val Kilmer", "Anthony Edwards", "Meg Ryan"] AS actor
MERGE (a:Actor {name:actor})
MERGE (a)-[:ACTED_IN]->(m)

Refresh graph schema information#

If the schema of database changes, you can refresh the schema information needed to generate Cypher statements.

        Node properties are the following:
        [{'properties': [{'property': 'name', 'type': 'STRING'}], 'labels': 'Movie'}, {'properties': [{'property': 'name', 'type': 'STRING'}], 'labels': 'Actor'}]
        Relationship properties are the following:
        The relationships are the following:

Querying the graph#

We can now use the graph cypher QA chain to ask question of the graph

chain = GraphCypherQAChain.from_llm(
    ChatOpenAI(temperature=0), graph=graph, verbose=True
)"Who played in Top Gun?")
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie {name: 'Top Gun'})
Full Context:
[{'': 'Tom Cruise'}, {'': 'Val Kilmer'}, {'': 'Anthony Edwards'}, {'': 'Meg Ryan'}]

> Finished chain.
'Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan played in Top Gun.'