텍스트를 Cypher로: Neo4j 그래프 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

텍스트→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는 Dr Jesus Barrasa와 Dr Jim Webber가 집필했습니다...
LangChain과 Neo4j로 배우는 Graph RAG

연습해 봅시다!

LangChain과 Neo4j로 배우는 Graph RAG

Preparing Video For Download...