使用 Neo4j 的 Text-to-Cypher 圖形 RAG

使用 LangChain 與 Neo4j 的 Graph RAG

Adam Cowley

Manager, Developer Education at Neo4j

將自然語言轉成 Cypher

應用程式流程:使用者輸入進入應用程式,並將提示送到 LLM

使用 LangChain 與 Neo4j 的 Graph RAG

將自然語言轉成 Cypher

應用程式示意圖:負責產生 Cypher 陳述式

使用 LangChain 與 Neo4j 的 Graph RAG

將自然語言轉成 Cypher

應用程式在產生 Cypher 時使用圖形資料庫綱要

使用 LangChain 與 Neo4j 的 Graph RAG

將自然語言轉成 Cypher

應用程式示意圖:產生 Cypher 後進入執行階段

使用 LangChain 與 Neo4j 的 Graph RAG

將自然語言轉成 Cypher

應用程式執行 Cypher 陳述式並將結果回傳給應用程式

使用 LangChain 與 Neo4j 的 Graph RAG

將自然語言轉成 Cypher

由 Cypher 取得的結果傳回應用程式

使用 LangChain 與 Neo4j 的 Graph RAG

將自然語言轉成 Cypher

將結果插入提示中,準備送給 LLM

使用 LangChain 與 Neo4j 的 Graph RAG

建構 text-to-Cypher 鏈

prompt = SystemMessagePromptTemplate.from_template(""" 
You are an expert Neo4j developer. Use the following database schema to write 
a Cypher statement to answer the user's question...

Schema: {schema}
Question: {question}
""", partial_variables={"schema": graph.schema})


# Compile the chain cypher_chain = cypher_prompt | llm | StrOutputParser()
# Invoke the chain cypher_chain.invoke({"question": "Who wrote Building Knowledge Graphs?"})
MATCH (b:Book {title: "Building Knowledge Graphs"})-[:WRITTEN_BY]->(a:Author) ...
使用 LangChain 與 Neo4j 的 Graph RAG
QA_PROMPT = "You are a helpful assistant. Use the data retrieved from the graph to answer the
user's question. Data: {context}"

answer_prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template(QA_PROMPT),
    HumanMessagePromptTemplate.from_template("Question: {question}")
])
使用 LangChain 與 Neo4j 的 Graph RAG
cypher_qa_chain = (
  # Generate and execute the Cypher to get results
  {

"question": RunnablePassthrough()
"context": text_to_cypher_chain | RunnableLambda(lambda cypher: graph.query(cypher)),
}
# Format prompt and pass to LLM | answer_prompt | answer_llm | StrOutputParser()
)
res = cypher_qa_chain.invoke({"question": "Who wrote Building Knowledge Graphs?"})
Building Knowledge Graphs was written by Dr Jesus Barrasa and Dr Jim Webber...
使用 LangChain 與 Neo4j 的 Graph RAG

一起來練習吧!

使用 LangChain 與 Neo4j 的 Graph RAG

Preparing Video For Download...