Graph RAG with LangChain and Neo4j
Adam Cowley
Manager, Developer Education at Neo4j







from pydantic import BaseModel, Fieldfrom typing import Optionalclass Character(BaseModel): """A character from the play."""id: str = Field("A unique identifier for the character in slug-case",examples=["montague-romeo", "tybalt"])name: str = Field("The full name of the character", examples=["Romeo", "Tybalt"])family: Optional[str] = Field("The name of the family they belong to", examples=["Montague", "Capulet"])class CharacterOutput(BaseModel): characters: list[Character] = Field("A list of characters")
from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o-mini", 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...])
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])
Graph RAG with LangChain and Neo4j