### Quickstart: Perform a GraphRAG query with neo4j-graphrag Source: https://neo4j.com/docs/neo4j-graphrag-python/current/user_guide_rag.html Sets up a Neo4j driver, a VectorRetriever with OpenAI embeddings, an OpenAILLM, and a GraphRAG pipeline to query the graph. Requires the openai Python client (install with pip install "neo4j_graphrag[openai]") and the OPENAI_API_KEY in environment variables. Note: OpenAI reasoning models (gpt-5 family) reject max_tokens, only accept temperature=1, and reasoning tokens count against max_completion_tokens. ```python from neo4j import GraphDatabase from neo4j_graphrag.retrievers import VectorRetriever from neo4j_graphrag.llm import OpenAILLM from neo4j_graphrag.generation import GraphRAG from neo4j_graphrag.embeddings import OpenAIEmbeddings # 1. Neo4j driver URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") INDEX_NAME = "index-name" # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # 2. Retriever # Create Embedder object, needed to convert the user question (text) to a vector embedder = OpenAIEmbeddings(model="text-embedding-3-large") # Initialize the retriever retriever = VectorRetriever(driver, INDEX_NAME, embedder) # 3. LLM # Note: the OPENAI_API_KEY must be in the env vars llm = OpenAILLM(model_name="gpt-5") # Initialize the RAG pipeline rag = GraphRAG(retriever=retriever, llm=llm) # Query the graph query_text = "How do I do similarity search in Neo4j?" response = rag.search(query_text=query_text, retriever_config={"top_k": 5}) print(response.answer) ``` -------------------------------- ### QdrantNeo4jRetriever usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/api.html Shows how to instantiate QdrantNeo4jRetriever with a Neo4j driver and Qdrant client, then perform a search with a query vector. The example uses placeholders NEO4J_URL and NEO4J_AUTH for connection details. ```python from neo4j import GraphDatabase from neo4j_graphrag.retrievers import QdrantNeo4jRetriever from qdrant_client import QdrantClient with GraphDatabase.driver(NEO4J_URL, auth=NEO4J_AUTH) as neo4j_driver: client = QdrantClient() retriever = QdrantNeo4jRetriever( driver=neo4j_driver, client=client, collection_name="my_collection", using="my_vector", id_property_external="neo4j_id" ) embedding = ... retriever.search(query_vector=embedding, top_k=2) ``` -------------------------------- ### Start e2e test services with Docker Compose Source: https://neo4j.com/docs/neo4j-graphrag-python/current/index.html Starts Neo4j, Weaviate, and Weaviate text2vec-transformers services for e2e tests. Uses the vectordb profile; omit it to start Neo4j alone. ```bash docker compose -f tests/e2e/docker-compose.yml --profile vectordb up -d --wait ``` -------------------------------- ### Text2CypherRetriever usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/user_guide_rag.html Initializes a Text2CypherRetriever with a Neo4j driver, an OpenAI LLM, optional schema and examples, then searches for movies. Requires the openai client (pip install neo4j_graphrag[openai]). No embedder needed. Raises Text2CypherRetrievalError if the generated query cannot be executed. ```python from neo4j import GraphDatabase from neo4j_graphrag.retrievers import Text2CypherRetriever from neo4j_graphrag.llm import OpenAILLM URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Create LLM object llm = OpenAILLM(model_name="gpt-5") # (Optional) Specify your own Neo4j schema neo4j_schema = """ Node properties: Person {name: STRING, born: INTEGER} Movie {tagline: STRING, title: STRING, released: INTEGER} Relationship properties: ACTED_IN {roles: LIST} REVIEWED {summary: STRING, rating: INTEGER} The relationships: (:Person)-[:ACTED_IN]->(:Movie) (:Person)-[:DIRECTED]->(:Movie) (:Person)-[:PRODUCED]->(:Movie) (:Person)-[:WROTE]->(:Movie) (:Person)-[:FOLLOWS]->(:Person) (:Person)-[:REVIEWED]->(:Movie) """ # (Optional) Provide user input/query pairs for the LLM to use as examples examples = [ "USER INPUT: 'Which actors starred in the Matrix?' QUERY: MATCH (p:Person)-[:ACTED_IN]->(m:Movie) WHERE m.title = 'The Matrix' RETURN p.name" ] # Initialize the retriever retriever = Text2CypherRetriever( driver=driver, llm=llm, # type: ignore neo4j_schema=neo4j_schema, examples=examples, ) # Generate a Cypher query using the LLM, send it to the Neo4j database, and return the results query_text = "Which movies did Hugo Weaving star in?" print(retriever.search(query_text=query_text)) ``` -------------------------------- ### VertexAILLM initialization with GenerationConfig Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/llm/vertexai_llm.html Shows how to instantiate VertexAILLM with a GenerationConfig for temperature control and invoke it with a prompt. Requires the Vertex AI Python client installed via `pip install "neo4j-graphrag[google]"`. ```python generation_config = GenerationConfig(temperature=0.0) llm = VertexAILLM( model_name="gemini-2.5-flash", generation_config=generation_config ) llm.invoke("Who is the mother of Paul Atreides?") ``` -------------------------------- ### CohereLLM usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/llm/cohere_llm.html Example from the class docstring showing how to instantiate CohereLLM with an API key and invoke it with a string message. ```python from neo4j_graphrag.llm import CohereLLM llm = CohereLLM(api_key="...") llm.invoke("Say something") ``` -------------------------------- ### HybridRetriever usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/retrievers/hybrid.html Example from the class docstring showing how to instantiate HybridRetriever with a driver, vector index name, fulltext index name, and custom embedder, then perform a search. ```python import neo4j from neo4j_graphrag.retrievers import HybridRetriever driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retriever = HybridRetriever( driver, "vector-index-name", "fulltext-index-name", custom_embedder ) retriever.search(query_text="Find me a book about Fremen", top_k=5) ``` -------------------------------- ### PromptTemplate usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/generation/prompts.html Shows how to instantiate a PromptTemplate with a custom template and expected inputs, then call format() with positional and keyword arguments. The output is a formatted prompt string. ```python prompt_template = PromptTemplate( template='''Explain the following concept to {target_audience}: Concept: {concept} Answer: ''', expected_inputs=['target_audience', 'concept'] ) prompt = prompt_template.format('12 yo children', concept='graph database') print(prompt) # Result: # '''Explain the following concept to 12 yo children: # Concept: graph database # Answer: # ''' ``` -------------------------------- ### BedrockEmbeddings usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/embeddings/bedrock.html Example of creating a BedrockEmbeddings instance and embedding a query. Requires the boto3 package, installable with `pip install "neo4j-graphrag[bedrock]"`. ```python from neo4j_graphrag.embeddings import BedrockEmbeddings embedder = BedrockEmbeddings( model_id="amazon.titan-embed-text-v2:0", dimensions=1024, region_name="us-east-1", ) vector = embedder.embed_query("my question") ``` -------------------------------- ### Install dependencies with uv sync --all-extras Source: https://neo4j.com/docs/neo4j-graphrag-python/current/index.html Installs all dependencies including extras for the project using uv. Run this before starting development. ```bash uv sync --all-extras ``` -------------------------------- ### Neo4jWriter usage example with Pipeline Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/kg_writer.html Shows how to create a Neo4j driver, instantiate Neo4jWriter, and add it to a Pipeline. Requires a running Neo4j instance and valid credentials. ```python from neo4j import GraphDatabase from neo4j_graphrag.components.kg_writer import Neo4jWriter from neo4j_graphrag.experimental.pipeline import Pipeline URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") DATABASE = "neo4j" driver = GraphDatabase.driver(URI, auth=AUTH) writer = Neo4jWriter(driver=driver, neo4j_database=DATABASE) pipeline = Pipeline() pipeline.add_component(writer, "writer") ``` -------------------------------- ### ToolsRetriever usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/retrievers/tools_retriever.html Shows how to instantiate ToolsRetriever with a Neo4j driver, an OpenAI LLM, and tools created from VectorRetriever and Text2CypherRetriever, then perform a search. ```python import neo4j from neo4j_graphrag.retrievers import ToolsRetriever, VectorRetriever, Text2CypherRetriever from neo4j_graphrag.llm import OpenAILLM from neo4j_graphrag.embeddings import OpenAIEmbeddings driver = neo4j.GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "password")) llm = OpenAILLM(model_name="gpt-5", api_key="your-api-key") embedder = OpenAIEmbeddings(model="text-embedding-3-small", api_key="your-api-key") # Create retrievers and convert them to tools vector_retriever = VectorRetriever(driver, "vector-index", embedder) vector_tool = vector_retriever.convert_to_tool( name="vector_search", description="Search for documents using semantic similarity" ) text2cypher_retriever = Text2CypherRetriever(driver, llm) cypher_tool = text2cypher_retriever.convert_to_tool( name="cypher_search", description="Generate and execute Cypher queries for structured data retrieval" ) # Initialize ToolsRetriever with the tools tools_retriever = ToolsRetriever( driver=driver, llm=llm, tools=[vector_tool, cypher_tool] ) # Use the retriever - the LLM will automatically select appropriate tools result = tools_retriever.search("What movies did Tom Hanks act in and what are their plots?") ``` -------------------------------- ### WeaviateNeo4jRetriever search example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/api.html Shows how to use WeaviateNeo4jRetriever to get top_k nearest neighbor embeddings using either query_vector or query_text. If query_vector is provided, it is preferred over embedded query_text. If query_text is provided, an embedder must be provided to generate the query_vector; otherwise, the vectorizer is assumed. ```python import neo4j from neo4j_graphrag.retrievers import WeaviateNeo4jRetriever driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retriever = WeaviateNeo4jRetriever( driver=driver, client=weaviate_client, collection="Jeopardy", id_property_external="neo4j_id", id_property_neo4j="id", node_label_neo4j="Document", ) biology_embedding = ... retriever.search(query_vector=biology_embedding, top_k=2) ``` -------------------------------- ### SpaCySemanticMatchResolver usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/resolver.html Example usage of SpaCySemanticMatchResolver, showing how to import the class and instantiate it with a Neo4j driver. The example is incomplete as it only shows the import and class instantiation. ```python from neo4j import GraphDatabase from neo4j_graphrag.components.resolver import SpaCySemanticMatchResolver ``` -------------------------------- ### Example usage of SinglePropertyExactMatchResolver Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/resolver.html Shows how to instantiate and run the resolver with a Neo4j driver. Requires a running Neo4j instance and valid credentials. ```python from neo4j import GraphDatabase from neo4j_graphrag.components.resolver import SinglePropertyExactMatchResolver URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") DATABASE = "neo4j" driver = GraphDatabase.driver(URI, auth=AUTH) resolver = SinglePropertyExactMatchResolver(driver=driver, neo4j_database=DATABASE) await resolver.run() # no expected parameters ``` -------------------------------- ### Create and run a simple pipeline with component connection Source: https://neo4j.com/docs/neo4j-graphrag-python/current/user_guide_pipeline.html Creates a Pipeline, adds two ComponentAdd instances named 'a' and 'b', connects 'b' to receive 'a.result' as its 'number2' input, and runs the pipeline with initial inputs. The result is 15 (10+1+4). ```python import asyncio from neo4j_graphrag.experimental.pipeline import Pipeline pipe = Pipeline() pipe.add_component(ComponentAdd(), "a") pipe.add_component(ComponentAdd(), "b") pipe.connect("a", "b", input_config={"number2": "a.result"}) asyncio.run(pipe.run({"a": {"number1": 10, "number2": 1}, "b": {"number1": 4}})) # result: 10+1+4 = 15 ``` -------------------------------- ### ToolsRetriever.__init__ Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/retrievers/tools_retriever.html Initializes the ToolsRetriever with a Neo4j driver, an LLM instance, a list of tools, and optional database name and system instruction. Validates that all tool names are unique. ```APIDOC ## ToolsRetriever.__init__ ### Description Initializes the ToolsRetriever with a Neo4j driver, an LLM instance, a list of tools, and optional database name and system instruction. Validates that all tool names are unique. ### Method Constructor ### Signature ```python def __init__( self, driver: neo4j.Driver, llm: LLMInterface, tools: Sequence[Tool], neo4j_database: Optional[str] = None, system_instruction: Optional[str] = None, ) ``` ### Parameters - **driver** (neo4j.Driver) - Required - The Neo4j Python driver. - **llm** (LLMInterface) - Required - LLM instance used to select and coordinate tool execution. - **tools** (Sequence[Tool]) - Required - List of tools available for selection. All tools must have unique names. - **neo4j_database** (Optional[str]) - Optional - The name of the Neo4j database. If not provided, defaults to the server's default database ("neo4j" by default). - **system_instruction** (Optional[str]) - Optional - Custom system instruction for the LLM to guide tool selection. If not provided, a default instruction is used. ### Raises - **ValueError** - If duplicate tool names are found in the tools list. ### Example ```python import neo4j from neo4j_graphrag.retrievers import ToolsRetriever, VectorRetriever, Text2CypherRetriever from neo4j_graphrag.llm import OpenAILLM from neo4j_graphrag.embeddings import OpenAIEmbeddings driver = neo4j.GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "password")) llm = OpenAILLM(model_name="gpt-5", api_key="your-api-key") embedder = OpenAIEmbeddings(model="text-embedding-3-small", api_key="your-api-key") # Create retrievers and convert them to tools vector_retriever = VectorRetriever(driver, "vector-index", embedder) vector_tool = vector_retriever.convert_to_tool( name="vector_search", description="Search for documents using semantic similarity" ) text2cypher_retriever = Text2CypherRetriever(driver, llm) cypher_tool = text2cypher_retriever.convert_to_tool( name="cypher_search", description="Generate and execute Cypher queries for structured data retrieval" ) # Initialize ToolsRetriever with the tools tools_retriever = ToolsRetriever( driver=driver, llm=llm, tools=[vector_tool, cypher_tool] ) ``` ``` -------------------------------- ### VertexAILLM usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/llm/vertexai_llm.html Example usage of the VertexAILLM class with a GenerationConfig object. ```python from neo4j_graphrag.llm import VertexAILLM from vertexai.generative_models import GenerationConfig ``` -------------------------------- ### drop_index_if_exists usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/indexes.html Example from the docstring of drop_index_if_exists showing how to connect to Neo4j and drop an index if it exists. ```python from neo4j import GraphDatabase from neo4j_graphrag.indexes import drop_index_if_exists URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") INDEX_NAME = "fulltext-index-name" # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Dropping the index if it exists drop_index_if_exists( driver, INDEX_NAME, ) ``` -------------------------------- ### async_upsert_vector_on_relationship example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/indexes.html Example usage of the deprecated async_upsert_vector_on_relationship function, showing how to connect to Neo4j and upsert a vector on a relationship. ```python from neo4j import AsyncGraphDatabase from neo4j_graphrag.indexes import upsert_vector_on_relationship URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") # Connect to Neo4j database driver = AsyncGraphDatabase.driver(URI, auth=AUTH) # Upsert the vector data async_upsert_vector_on_relationship( driver, node_id="nodeId", embedding_property="vectorProperty", vector=..., ) ``` -------------------------------- ### VectorRetriever usage example with custom embedder Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/retrievers/vector.html Shows how to instantiate VectorRetriever with a driver, index name, and custom embedder, then perform a search with query text and top_k. ```python import neo4j from neo4j_graphrag.retrievers import VectorRetriever driver = neo4j.GraphDatabase.driver(URI, auth=AUTH) retriever = VectorRetriever(driver, "vector-index-name", custom_embedder) retriever.search(query_text="Find me a book about Fremen", top_k=5) ``` -------------------------------- ### QdrantNeo4jRetriever usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/api.html Shows how to create a QdrantNeo4jRetriever with a Neo4j driver and Qdrant client, then perform a vector search. Requires NEO4J_URL, NEO4J_AUTH, and an embedding vector. The search returns a list of neo4j.Record and optional metadata. ```python from neo4j import GraphDatabase from neo4j_graphrag.retrievers import QdrantNeo4jRetriever from qdrant_client import QdrantClient with GraphDatabase.driver(NEO4J_URL, auth=NEO4J_AUTH) as neo4j_driver: client = QdrantClient() retriever = QdrantNeo4jRetriever( driver=neo4j_driver, client=client, collection_name="my_collection", id_property_external="neo4j_id", node_label_neo4j="Document", ) embedding = ... retriever.search(query_vector=embedding, top_k=2) ``` -------------------------------- ### LLMBase.__init__ Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/llm/base.html Initializes the LLMBase instance, delegating to LLMInterfaceV2's initializer. ```APIDOC ## LLMBase.__init__ ### Description Initializes the LLMBase instance, passing model configuration and rate limit handler to the parent LLMInterfaceV2 initializer. ### Method Constructor ### Signature ```python def __init__( self, model_name: str, model_params: Optional[dict[str, Any]] = None, rate_limit_handler: Optional[RateLimitHandler] = None, **kwargs: Any, ) -> None ``` ### Parameters - **model_name** (str) - Required - The name of the model to use. - **model_params** (Optional[dict[str, Any]]) - Optional - Additional model parameters. - **rate_limit_handler** (Optional[RateLimitHandler]) - Optional - Handler for rate limiting. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the parent initializer. ### Returns None ``` -------------------------------- ### create_fulltext_index usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/indexes.html Example from the docstring of create_fulltext_index showing how to connect to Neo4j and create a fulltext index using the neo4j_graphrag.indexes.create_fulltext_index function. ```python from neo4j import GraphDatabase from neo4j_graphrag.indexes import create_fulltext_index URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") INDEX_NAME = "fulltext-index-name" # Connect to Neo4j database driver = GraphDatabase.driver(URI, auth=AUTH) # Creating the index create_fulltext_index( driver, INDEX_NAME, label="Document", node_properties=["vectorProperty"], fail_if_exists=False, ) ``` -------------------------------- ### Neo4jChunkReader usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/neo4j_reader.html Shows how to instantiate Neo4jChunkReader with a Neo4j driver and database name, then call its run method asynchronously. Requires a running Neo4j instance and valid credentials. ```python from neo4j import GraphDatabase from neo4j_graphrag.components.neo4j_reader import Neo4jChunkReader URI = "neo4j://localhost:7687" AUTH = ("neo4j", "password") DATABASE = "neo4j" driver = GraphDatabase.driver(URI, auth=AUTH) reader = Neo4jChunkReader(driver=driver, neo4j_database=DATABASE) await reader.run() ``` -------------------------------- ### Usage example from docstring: LangChainTextSplitterAdapter with RecursiveCharacterTextSplitter Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/text_splitters/langchain.html Example code from the class docstring showing how to instantiate the adapter with a RecursiveCharacterTextSplitter and add it to a Pipeline component. ```python from langchain_text_splitters import RecursiveCharacterTextSplitter from neo4j_graphrag.components.text_splitters.langchain import LangChainTextSplitterAdapter from neo4j_graphrag.experimental.pipeline import Pipeline pipeline = Pipeline() text_splitter = LangChainTextSplitterAdapter(RecursiveCharacterTextSplitter()) pipeline.add_component(text_splitter, "text_splitter") ``` -------------------------------- ### Install neo4j-graphrag with pip Source: https://neo4j.com/docs/neo4j-graphrag-python/current/index.html Installs the latest stable version of the neo4j-graphrag package. Requires Python >=3.10. It is recommended to use a virtual environment. ```bash pip install neo4j-graphrag ``` -------------------------------- ### VertexAILLM initialization and invocation example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/api.html Shows how to create a VertexAILLM instance with a GenerationConfig and invoke it with a prompt. The constructor accepts a rate_limit_handler and additional kwargs passed to the model. ```python from neo4j_graphrag.llm import VertexAILLM from vertexai.generative_models import GenerationConfig generation_config = GenerationConfig(temperature=0.0) llm = VertexAILLM( model_name="gemini-2.5-flash", generation_config=generation_config ) llm.invoke("Who is the mother of Paul Atreides?") ``` -------------------------------- ### QdrantNeo4jRetriever.__init__ Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/retrievers/external/qdrant/qdrant.html Initializes a QdrantNeo4jRetriever instance with a Neo4j driver, Qdrant client, collection name, and optional parameters for vector search and result formatting. ```APIDOC ## QdrantNeo4jRetriever.__init__ ### Description Initializes a QdrantNeo4jRetriever instance for vector search over Qdrant and Neo4j. ### Method Constructor ### Endpoint QdrantNeo4jRetriever(driver, client, collection_name, using, id_property_neo4j, id_property_external, embedder, return_properties, result_formatter, neo4j_database, node_label_neo4j, id_property_getter) ### Parameters #### Constructor Parameters - **driver** (neo4j.Driver) - Required - The Neo4j Python driver. - **client** (QdrantClient) - Required - The Qdrant client object. - **collection_name** (str) - Required - The name of the Qdrant collection to use. - **using** (str) - Optional - The name of the Qdrant vector contained in your collection in case of multi-vector collection. - **id_property_neo4j** (str) - Optional - The name of the Neo4j node property that's used as the identifier for relating matches from Qdrant to Neo4j nodes. - **id_property_external** (str) - Optional - The name of the Qdrant payload property with identifier that refers to a corresponding Neo4j node id property. - **embedder** (Optional[Embedder]) - Optional - Embedder object to embed query text. - **return_properties** (Optional[list[str]]) - Optional - List of node properties to return. - **result_formatter** (Optional[Callable[[neo4j.Record], RetrieverResultItem]]) - Optional - Function to transform a neo4j.Record to a RetrieverResultItem. - **neo4j_database** (Optional[str]) - Optional - The name of the Neo4j database. If not provided, defaults to the server's default database ("neo4j" by default). - **node_label_neo4j** (Optional[str]) - Optional - The label of the Neo4j node to retrieve. Must be properly escaped if needed, eg "`Label with spaces`". - **id_property_getter** (Optional[Callable[[ScoredPoint], str]]) - Optional - Function to get the id property from a ScoredPoint. Defaults to point.payload.get(id_property_external, point.id). ### Request Example ```python from neo4j import GraphDatabase from neo4j_graphrag.retrievers import QdrantNeo4jRetriever from qdrant_client import QdrantClient with GraphDatabase.driver(NEO4J_URL, auth=NEO4J_AUTH) as neo4j_driver: client = QdrantClient() retriever = QdrantNeo4jRetriever( driver=neo4j_driver, client=client, collection_name="my_collection", using="my_vector", id_property_external="neo4j_id" ) ``` ### Response #### Success Response - **retriever** (QdrantNeo4jRetriever) - The initialized retriever instance. #### Error Handling - **RetrieverInitializationError** - If validation of the input arguments fail. ``` -------------------------------- ### SpaCySemanticMatchResolver _load_or_download_spacy_model static method Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/resolver.html Attempts to load a spaCy model by name, auto-downloading it if not installed. Raises ImportError if spaCy is not installed, and OSError if auto-download fails or is disabled. ```python @staticmethod def _load_or_download_spacy_model( model_name: str, *, auto_download_spacy_model: bool = True ) -> Language: """ Attempt to load the specified spaCy model by name. If not installed, automatically download and then load it. """ try: if not IS_SPACY_INSTALLED: raise ImportError("""`spacy` python module needs to be installed to use the SpaCySemanticMatchResolver. Install it with: `pip install "neo4j-graphrag[nlp]"` . SpaCy is not supported on Python 3.14 and later. """) return spacy.load(model_name) except OSError as e: if "doesn't seem to be a Python package or a valid path" in str(e): if not auto_download_spacy_model: raise OSError( f"spaCy model '{model_name}' is not installed. " "Install it manually (e.g. `python -m spacy download " f"{model_name}`) or pass a pre-loaded `nlp` instance." ) from e logger.info(f"Model '{model_name}' not found. Downloading...") try: spacy_download(model_name) except SystemExit as se: raise OSError( f"Failed to auto-download spaCy model '{model_name}'. " "Install it manually (e.g. `python -m spacy download " f"{model_name}`) or pass a pre-loaded `nlp` instance." ) from se return spacy.load(model_name) else: raise e ``` -------------------------------- ### SchemaBuilder usage example with Pipeline Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/schema.html Example from the SchemaBuilder class docstring showing how to construct node types, relationship types, patterns, and run the schema builder within a Pipeline. ```python from neo4j_graphrag.components.schema import ( SchemaBuilder, NodeType, PropertyType, RelationshipType, ) from neo4j_graphrag.experimental.pipeline import Pipeline node_types = [ NodeType( label="PERSON", description="An individual human being.", properties=[ PropertyType( name="name", type="STRING", description="The name of the person" ) ], ), NodeType( label="ORGANIZATION", description="A structured group of people with a common purpose.", properties=[ PropertyType( name="name", type="STRING", description="The name of the organization" ) ], ), ] relationship_types = [ RelationshipType( label="EMPLOYED_BY", description="Indicates employment relationship." ), ] patterns = [ ("PERSON", "EMPLOYED_BY", "ORGANIZATION"), ] pipe = Pipeline() schema_builder = SchemaBuilder() pipe.add_component(schema_builder, "schema_builder") pipe_inputs = { "schema": { "node_types": node_types, "relationship_types": relationship_types, "patterns": patterns, }, ... } pipe.run(pipe_inputs) ``` -------------------------------- ### SimpleKGPipeline.__init__ Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/experimental/pipeline/kg_builder.html Initializes a SimpleKGPipeline instance with the provided LLM, Neo4j driver, embedder, and optional configuration parameters for entities, relations, schema, file handling, text splitting, KG writing, error handling, and entity resolution. ```APIDOC ## SimpleKGPipeline.__init__ ### Description Initializes a SimpleKGPipeline instance for building a knowledge graph from text or files. ### Method Constructor ### Signature ```python SimpleKGPipeline( llm: LLMInterface, driver: neo4j.Driver, embedder: Embedder, entities: Optional[Sequence[EntityInputType]] = None, relations: Optional[Sequence[RelationInputType]] = None, potential_schema: Optional[List[tuple[str, str, str]]] = None, schema: Optional[Union[GraphSchema, dict[str, list[Any]], Literal["FREE", "EXTRACTED"]]] = None, from_file: bool = True, from_pdf: Optional[bool] = None, text_splitter: Optional[TextSplitter] = None, file_loader: Optional[DataLoader] = None, pdf_loader: Optional[DataLoader] = None, kg_writer: Optional[KGWriter] = None, on_error: str = "IGNORE", prompt_template: Union[ERExtractionTemplate, str] = ERExtractionTemplate(), perform_entity_resolution: bool = True, lexical_graph_config: Optional[LexicalGraphConfig] = None, neo4j_database: Optional[str] = None, ) ``` ### Parameters - **llm** (LLMInterface) - Required - The language model interface for extraction. - **driver** (neo4j.Driver) - Required - Neo4j driver for database connection. - **embedder** (Embedder) - Required - Embedder component for vector embeddings. - **entities** (Optional[Sequence[EntityInputType]]) - Optional - List of entity types to extract. - **relations** (Optional[Sequence[RelationInputType]]) - Optional - List of relation types to extract. - **potential_schema** (Optional[List[tuple[str, str, str]]]) - Optional - Potential schema triples (head, relation, tail). - **schema** (Optional[Union[GraphSchema, dict[str, list[Any]], Literal["FREE", "EXTRACTED"]]]) - Optional - Schema definition; can be a GraphSchema, a dict, or the strings "FREE" or "EXTRACTED". - **from_file** (bool) - Optional - Determines whether to include a file loader in the pipeline. If True, expects `file_path` input in `run` methods (PDF or Markdown). If False, expects `text` input in `run` methods. Default: True. - **from_pdf** (Optional[bool]) - Deprecated - If set, overrides `from_file` and emits a warning. Prefer `from_file`. - **text_splitter** (Optional[TextSplitter]) - Optional - A text splitter component. Defaults to FixedSizeSplitter(). - **file_loader** (Optional[DataLoader]) - Optional - A document loader component. Defaults to an internal extension-based loader that supports `.pdf`, `.md`, and `.markdown`. Use PdfLoader for PDF-only paths. - **pdf_loader** (Optional[DataLoader]) - Deprecated - If set, used as `file_loader` and emits a warning. Do not pass both `file_loader` and `pdf_loader`. Prefer `file_loader`. - **kg_writer** (Optional[KGWriter]) - Optional - A knowledge graph writer component. Defaults to Neo4jWriter(). - **on_error** (str) - Optional - Error handling strategy for the Entity and relation extractor. Defaults to "IGNORE", where chunk will be ignored if extraction fails. Possible values: "RAISE" or "IGNORE". - **prompt_template** (Union[ERExtractionTemplate, str]) - Optional - A custom prompt template to use for extraction. Defaults to ERExtractionTemplate(). - **perform_entity_resolution** (bool) - Optional - Merge entities with same label and name. Default: True. - **lexical_graph_config** (Optional[LexicalGraphConfig]) - Optional - Lexical graph configuration to customize node labels and relationship types in the lexical graph. - **neo4j_database** (Optional[str]) - Optional - The Neo4j database name to use. ### Raises - **PipelineDefinitionError** - If configuration validation fails (ValidationError or ValueError). ### Notes - Deprecated parameters `from_pdf` and `pdf_loader` emit DeprecationWarning and are overridden by `from_file` and `file_loader` respectively. - Passing both `file_loader` and `pdf_loader` raises a ValueError. ``` -------------------------------- ### PineconeNeo4jRetriever.__init__ Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/retrievers/external/pinecone/pinecone.html Initializes a PineconeNeo4jRetriever instance with a Neo4j driver, Pinecone client, index name, and configuration options. Validates inputs and sets up the retriever for subsequent searches. ```APIDOC ## PineconeNeo4jRetriever.__init__ ### Description Initializes a PineconeNeo4jRetriever instance. This constructor validates the provided driver, client, and configuration, then sets up the retriever for vector search and graph retrieval. ### Method Constructor ### Signature ```python def __init__( self, driver: neo4j.Driver, client: Pinecone, index_name: str, id_property_neo4j: str, embedder: Optional[Embedder] = None, return_properties: Optional[list[str]] = None, retrieval_query: Optional[str] = None, result_formatter: Optional[Callable[[neo4j.Record], RetrieverResultItem]] = None, neo4j_database: Optional[str] = None, node_label_neo4j: Optional[str] = None, ) ``` ### Parameters - **driver** (neo4j.Driver) - Required - Neo4j driver instance. - **client** (Pinecone) - Required - Pinecone client instance. - **index_name** (str) - Required - Name of the Pinecone index. - **id_property_neo4j** (str) - Required - Property name in Neo4j that stores the external ID. - **embedder** (Optional[Embedder]) - Optional - Embedder instance used to generate query vectors from text. - **return_properties** (Optional[list[str]]) - Optional - List of Neo4j properties to return in results. - **retrieval_query** (Optional[str]) - Optional - Custom Cypher query for retrieval. - **result_formatter** (Optional[Callable[[neo4j.Record], RetrieverResultItem]]) - Optional - Function to format raw Neo4j records into RetrieverResultItem objects. - **neo4j_database** (Optional[str]) - Optional - Name of the Neo4j database to use. - **node_label_neo4j** (Optional[str]) - Optional - Label of the Neo4j node to target. ### Raises - **RetrieverInitializationError** - If validation of the input arguments fails. ### Example ```python from neo4j import GraphDatabase from neo4j_graphrag.retrievers import PineconeNeo4jRetriever from pinecone import Pinecone with GraphDatabase.driver(NEO4J_URL, auth=NEO4J_AUTH) as neo4j_driver: pc_client = Pinecone(PC_API_KEY) retriever = PineconeNeo4jRetriever( driver=neo4j_driver, client=pc_client, index_name="jeopardy", id_property_neo4j="id", node_label_neo4j="Document", ) ``` ``` -------------------------------- ### TextChunkEmbedder usage example with OpenAIEmbeddings and Pipeline Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/embedder.html Example from the class docstring showing how to instantiate TextChunkEmbedder with an OpenAIEmbeddings instance and add it to a Pipeline. Requires the neo4j_graphrag.components.embedder, neo4j_graphrag.embeddings.openai, and neo4j_graphrag.experimental.pipeline modules. ```python from neo4j_graphrag.components.embedder import TextChunkEmbedder from neo4j_graphrag.embeddings.openai import OpenAIEmbeddings from neo4j_graphrag.experimental.pipeline import Pipeline embedder = OpenAIEmbeddings(model="text-embedding-3-large") chunk_embedder = TextChunkEmbedder(embedder) pipeline = Pipeline() pipeline.add_component(chunk_embedder, "chunk_embedder") ``` -------------------------------- ### PromptTemplate.__init__ Source: https://neo4j.com/docs/neo4j-graphrag-python/current/api.html Constructor for the PromptTemplate class. Initializes a prompt template with a template string, expected inputs, and optional system instructions. ```APIDOC ## PromptTemplate.__init__ ### Description Initializes a PromptTemplate instance with a template string, expected inputs, and optional system instructions. ### Method Constructor ### Signature `PromptTemplate(template=None, expected_inputs=None, system_instructions=None)` ### Parameters - **template** (Optional[str]) - Optional - The template string using Python format syntax. - **expected_inputs** (Optional[List[str]]) - Optional - List of expected input parameter names. - **system_instructions** (Optional[str]) - Optional - System instructions for the prompt. ### Return Type None ``` -------------------------------- ### SimpleKGPipeline basic usage Source: https://neo4j.com/docs/neo4j-graphrag-python/current/user_guide_kg_builder.html Initializes a SimpleKGPipeline with an LLM, Neo4j driver, and embedder, then runs it on a file. Set from_file=False to pass text directly. ```python from neo4j_graphrag.experimental.pipeline.kg_builder import SimpleKGPipeline kg_builder = SimpleKGPipeline( llm=llm, # an LLMInterface for Entity and Relation extraction driver=neo4j_driver, # a neo4j driver to write results to graph embedder=embedder, # an Embedder for chunks from_file=True, # set to False if parsing an already extracted text ) await kg_builder.run_async(file_path=str(file_path)) # await kg_builder.run_async(text="my text") # if using from_file=False ``` -------------------------------- ### Install neo4j-graphrag with openai extra Source: https://neo4j.com/docs/neo4j-graphrag-python/current/index.html Installs the package with the 'openai' extra dependency, which provides LLM support from OpenAI (including AzureOpenAI). Other extras are available for different LLM providers and vector databases. ```bash pip install "neo4j-graphrag[openai]" ``` -------------------------------- ### PineconeNeo4jRetriever usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/api.html Shows how to instantiate PineconeNeo4jRetriever with a Neo4j driver and Pinecone client, then perform a vector search. Requires NEO4J_URL, NEO4J_AUTH, PC_API_KEY, and a precomputed biology_embedding. ```python from neo4j import GraphDatabase from neo4j_graphrag.retrievers import PineconeNeo4jRetriever from pinecone import Pinecone with GraphDatabase.driver(NEO4J_URL, auth=NEO4J_AUTH) as neo4j_driver: pc_client = Pinecone(PC_API_KEY) retriever = PineconeNeo4jRetriever( driver=neo4j_driver, client=pc_client, index_name="jeopardy", id_property_neo4j="id", node_label_neo4j="Document", ) biology_embedding = ... retriever.search(query_vector=biology_embedding, top_k=2) ``` -------------------------------- ### LlamaIndexTextSplitterAdapter class definition and usage example Source: https://neo4j.com/docs/neo4j-graphrag-python/current/_modules/neo4j_graphrag/components/text_splitters/llamaindex.html Full source code of the adapter class, including imports, license header, and the iter_chunks method. The docstring includes a usage example showing how to instantiate the adapter with a SentenceSplitter and add it to a Pipeline. ```python # Copyright (c) "Neo4j" # Neo4j Sweden AB [https://neo4j.com] # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # # https://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from collections.abc import Iterator from llama_index.core.node_parser import TextSplitter as LlamaIndexTextSplitter from neo4j_graphrag.components.text_splitters.base import TextSplitter from neo4j_graphrag.components.types import TextChunk [docs] class LlamaIndexTextSplitterAdapter(TextSplitter): """Adapter for LlamaIndex TextSplitters. Allows instances of this class to be used in the knowledge graph builder pipeline. Args: text_splitter (LlamaIndexTextSplitter): An instance of LlamaIndex's TextSplitter class. Example: .. code-block:: python from llama_index.core.node_parser.text.sentence import SentenceSplitter from neo4j_graphrag.components.text_splitters.llamaindex import ( LlamaIndexTextSplitterAdapter, ) from neo4j_graphrag.experimental.pipeline import Pipeline pipeline = Pipeline() text_splitter = LlamaIndexTextSplitterAdapter(SentenceSplitter()) pipeline.add_component(text_splitter, "text_splitter") """ def __init__(self, text_splitter: LlamaIndexTextSplitter) -> None: self.text_splitter = text_splitter [docs] def iter_chunks(self, text: str) -> Iterator[TextChunk]: """ Splits text into chunks, yielding them one at a time. Args: text (str): The text to split. Returns: Iterator[TextChunk]: The chunks, in document order. """ for index, chunk in enumerate(self.text_splitter.split_text(text)): yield TextChunk(text=chunk, index=index) ```