领域图

使用 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...