領域圖

使用 LangChain 與 Neo4j 的 Graph RAG

Adam Cowley

Manager, Developer Education at Neo4j

領域圖

知識圖示意圖:左側為詞彙圖,包含書本、章節與頁面;右側為書中的人物與公司,並含來自 Wikipedia 等來源的參照

使用 LangChain 與 Neo4j 的 Graph RAG

從詞彙圖到領域圖

Journey〈Don't Stop Believin'〉歌詞

使用 LangChain 與 Neo4j 的 Graph RAG

從詞彙圖到領域圖

Journey〈Don't Stop Believin'〉歌詞,將「Small Town Boy」標示為人物

使用 LangChain 與 Neo4j 的 Graph RAG

從詞彙圖到領域圖

Journey〈Don't Stop Believin'〉歌詞,將「South Detroit」標示為地點

使用 LangChain 與 Neo4j 的 Graph RAG

從詞彙圖到領域圖

Journey〈Don't Stop Believin'〉歌詞,將「Born」標示為人物「Small Town Boy」與地點「South Detroit」之間的關係

使用 LangChain 與 Neo4j 的 Graph RAG

從詞彙圖到領域圖

Journey〈Don't Stop Believin'〉歌詞,將「Raised」標示為人物「Small Town Boy」與地點「South Detroit」之間的關係

使用 LangChain 與 Neo4j 的 Graph RAG

領域圖範例

範例領域圖模型:一位人物在某公司任職,位於一個地址;此人持有信用卡,並在同地點的一家公司以該卡下單

使用 LangChain 與 Neo4j 的 Graph RAG

結構化輸出

from pydantic import BaseModel, Field

from typing import Optional
class Character(BaseModel): """A character from the play."""
id: str = Field(description="A unique identifier for the character in slug-case",
examples=["montague-romeo", "tybalt"])
name: str = Field(description="The full name of the character", examples=["Romeo", "Tybalt"])
family: Optional[str] = Field(description="The name of the family they belong to", examples=["Montague", "Capulet"])
class CharacterOutput(BaseModel): characters: list[Character] = Field(description="A list of characters")
使用 LangChain 與 Neo4j 的 Graph RAG

使用結構化輸出

from langchain.chat_models import init_chat_model
llm = init_chat_model("gpt-4o-mini", model_provider="openai", api_key="...")


# With a structured output character_model = llm.with_structured_output(CharacterOutput)
# Use within a chain chain = extraction_prompt | character_model
# Handle the response output = chain.invoke(...)
CharacterOutput(characters=[Character, Character, Character...])
使用 LangChain 與 Neo4j 的 Graph RAG

儲存實體

nodes = [

Node(
type="Character",
id=character.id,
properties={"name": character.name, "family": character.family}
)
for character in output.characters
]
# Build a GraphDocument graph_document = GraphDocument(nodes=nodes, relationships=[])
# Save to the graph graph.add_graph_documents([graph_document])
使用 LangChain 與 Neo4j 的 Graph RAG

一起來練習吧!

使用 LangChain 與 Neo4j 的 Graph RAG

Preparing Video For Download...