Get startedGet started for free

Text-to-Cypher Graph RAG with Neo4j

1. Text-to-Cypher Graph RAG with Neo4j

Rather than relying on vector embeddings to speculatively search for similar text, the same natural language can be converted into a Cypher statement to query the knowledge graph and retrieve the results.

2. Converting natural language to Cypher

We can use a user input to trigger the

3. Converting natural language to Cypher

generation of a Cypher statement,

4. Converting natural language to Cypher

using the node labels, relationships, and properties in the knowledge graph as a guide.

5. Converting natural language to Cypher

Our application will then

6. Converting natural language to Cypher

execute the Cypher statement to retrieve the results

7. Converting natural language to Cypher

and those results are

8. Converting natural language to Cypher

inserted into a prompt, giving it the information required to answer the question.

9. Building a text-to-Cypher chain

This is achieved with an LCEL chain that instructs the LLM to use the graph schema to generate a Cypher statement that answers the user's question. We start by writing a system prompt template to insert the graph schema and instruct the LLM to generate the required Cypher to respond to the user input. The graph schema is available through the .schema property of the Neo4jGraph object. The chain can be compiled by chaining the prompt template, LLM, and output parser, and invoked to generate a Cypher statement.

10. Using text-to-cypher in an LCEL Chain

We then create an overall Question and Answer chain to combine the text-to-cypher chain with database querying and retrieval. This starts with a prompt template to combine the context returned from the Cypher query with the user's input, which we'll call answer_prompt.

11. Using text-to-cypher in an LCEL Chain

The chain starts with a dictionary of keys. The RunnablePassthrough passes the original user input through to the next stage of the chain unchanged. The context parameter executes the text_to_cypher_chain to generate the Cypher statement and uses the RunnableLambda function to execute it using the .query() method. The context and input variables can then be passed to the answer_prompt and sent to the LLM. As the knowledge graph is a source of truth, and providing the data exists to answer the question, the LLM can generate an answer with full authority.

12. Let's practice!

Now let's build a text-to-Cypher chain!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.