ドメイングラフ

Graph RAG with LangChain and Neo4j

Adam Cowley

Manager, Developer Education at Neo4j

ドメイングラフ

左に本・章・ページの語彙グラフ、右に本に登場する人物・企業とWikipediaなど外部参照を示すナレッジグラフの図

Graph RAG with LangChain and Neo4j

語彙グラフからドメイングラフへ

Journeyの「Don't Stop Believin'」の歌詞

Graph RAG with LangChain and Neo4j

語彙グラフからドメイングラフへ

Journeyの「Don't Stop Believin'」の歌詞で、「Small Town Boy」が人物として強調表示されている

Graph RAG with LangChain and Neo4j

語彙グラフからドメイングラフへ

Journeyの「Don't Stop Believin'」の歌詞で、「South Detroit」が場所として強調表示されている

Graph RAG with LangChain and Neo4j

語彙グラフからドメイングラフへ

Journeyの「Don't Stop Believin'」の歌詞で、人物「Small Town Boy」と場所「South Detroit」を結ぶ関係として「Born」が強調表示されている

Graph RAG with LangChain and Neo4j

語彙グラフからドメイングラフへ

Journeyの「Don't Stop Believin'」の歌詞で、人物「Small Town Boy」と場所「South Detroit」を結ぶ関係として「Raised」が強調表示されている

Graph RAG with LangChain and Neo4j

ドメイングラフの例

人物が会社で働き、その会社が住所に位置するというドメイングラフ例。人物はクレジットカードを持ち、同じ場所の会社でそのカードに対して注文が行われている

Graph RAG with LangChain and Neo4j

構造化出力

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")
Graph RAG with LangChain and Neo4j

構造化出力の活用

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


# 構造化出力を使用 character_model = llm.with_structured_output(CharacterOutput)
# チェーンで使用 chain = extraction_prompt | character_model
# 応答を処理 output = chain.invoke(...)
CharacterOutput(characters=[Character, Character, Character...])
Graph RAG with LangChain and Neo4j

エンティティの保存

nodes = [

Node(
type="Character",
id=character.id,
properties={"name": character.name, "family": character.family}
)
for character in output.characters
]
# GraphDocumentを作成 graph_document = GraphDocument(nodes=nodes, relationships=[])
# グラフに保存 graph.add_graph_documents([graph_document])
Graph RAG with LangChain and Neo4j

練習しましょう!

Graph RAG with LangChain and Neo4j

Preparing Video For Download...