テキストからCypherへ: Neo4jでのGraph RAG

Graph RAG with LangChain and Neo4j

Adam Cowley

Manager, Developer Education at Neo4j

自然言語をCypherへ変換

ユーザー入力がアプリに入り、プロンプトがLLMへ送信されるフロー

Graph RAG with LangChain and Neo4j

自然言語をCypherへ変換

Cypher文の生成を指示するアプリの図

Graph RAG with LangChain and Neo4j

自然言語をCypherへ変換

アプリのCypher生成ステップでグラフDBスキーマを使用

Graph RAG with LangChain and Neo4j

自然言語をCypherへ変換

Cypher生成の後に実行フェーズが続くアプリの図

Graph RAG with LangChain and Neo4j

自然言語をCypherへ変換

アプリがCypher文を実行し、結果を返す

Graph RAG with LangChain and Neo4j

自然言語をCypherへ変換

Cypherで取得した結果がアプリに返される

Graph RAG with LangChain and Neo4j

自然言語をCypherへ変換

結果がプロンプトに挿入され、LLM送信の準備ができる

Graph RAG with LangChain and Neo4j

テキストから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) ...
Graph RAG with LangChain and Neo4j
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}")
])
Graph RAG with LangChain and Neo4j
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...
Graph RAG with LangChain and Neo4j

練習しましょう!

Graph RAG with LangChain and Neo4j

Preparing Video For Download...