建立 Graph RAG 鏈

使用 LangChain 的 Retrieval Augmented Generation(RAG)

Meri Nova

Machine Learning Engineer

建立 Graph RAG 架構

圖形資料庫。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

建立 Graph RAG 架構

文件轉換為圖文件並儲存在圖形資料庫中。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

建立 Graph RAG 架構

使用 Cypher 查詢自資料庫擷取圖文件。也顯示了使用者輸入與回傳的自然語言回覆。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

建立 Graph RAG 架構

自然語言到 Cypher 的轉換器,將自然語言輸入轉成 Cypher 查詢,並把擷取到的圖文件轉回自然語言。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

從使用者輸入到 Cypher 查詢

一個包含三個節點與三個關係的簡單圖。兩個節點代表人,另一個代表 James 造訪過的地點。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

從使用者輸入到 Cypher 查詢

一個使用者輸入:『Where has James visited?』。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

從使用者輸入到 Cypher 查詢

根據圖綱要與使用者輸入產生 Cypher 查詢。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

GraphCypherQAChain

Graph RAG 架構將使用者輸入翻譯為 Cypher 查詢,並回傳自然語言回覆。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

GraphCypherQAChain

Graph RAG 架構,標示出產生 cypher 鏈與摘要結果鏈。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

重新整理結構綱要(schema)

graph.refresh_schema()
print(graph.get_schema)
Node properties:
Document {title: STRING, id: STRING, text: STRING, summary: STRING, source: STRING}
Concept {id: STRING}
Organization {id: STRING}
Relationship properties:

The relationships:
(:Document)-[:MENTIONS]->(:Organization)
(:Concept)-[:DEVELOPED_BY]->(:Person)
使用 LangChain 的 Retrieval Augmented Generation(RAG)

查詢圖形

from langchain_community.chains.graph_qa.cypher import GraphCypherQAChain

chain = GraphCypherQAChain.from_llm( llm=ChatOpenAI(api_key="...", temperature=0), graph=graph, verbose=True )
result = chain.invoke({"query": "What is the most accurate model?"})
1 https://api.python.langchain.com/en/latest/chains/langchain_community.chains.graph_qa.cypher. GraphCypherQAChain.html
使用 LangChain 的 Retrieval Augmented Generation(RAG)

查詢圖形

print(f"Final answer: {result['result']}")
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (m:Model)
RETURN m
ORDER BY m.accuracy DESC
LIMIT 1;
Full Context:
[{'m': {'id': 'Artificial Neural Networks'}}]

> Finished chain.


Final answer: Artificial Neural Networks
使用 LangChain 的 Retrieval Augmented Generation(RAG)

客製化

chain = GraphCypherQAChain.from_llm(
    llm=ChatOpenAI(api_key="...", temperature=0), graph=graph, verbose=True
)
  • qa_prompt:產生結果的提示樣板
  • cypher_prompt:產生 Cypher 的提示樣板
  • cypher_llm:用於產生 Cypher 的 LLM
  • qa_llm:用於產生結果的 LLM
使用 LangChain 的 Retrieval Augmented Generation(RAG)

一起來練習吧!

使用 LangChain 的 Retrieval Augmented Generation(RAG)

Preparing Video For Download...