Neo4j GraphRAG Python Client

1.14.1 · active · verified Wed Apr 15

The neo4j-graphrag library provides Pythonic access and utilities for integrating with Neo4j's GraphRAG (Retrieval Augmented Generation) features. It simplifies building Knowledge Graphs from unstructured text, performing vector embeddings, and executing RAG queries against a Neo4j graph database. The current version is 1.14.1, with a release cadence that is quite active, often seeing minor releases monthly.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up and use the `GraphRAGPipeline` with an OpenAI LLM to query a Neo4j knowledge graph. It requires Neo4j to be running and accessible, and an OpenAI API key. Ensure `NEO4J_URI`, `NEO4J_USERNAME`, `NEO4J_PASSWORD`, and `OPENAI_API_KEY` environment variables are set.

import os
from neo4j import GraphDatabase
from neo4j_graphrag.graph_rag_pipeline import GraphRAGPipeline
from neo4j_graphrag.llm import OpenAILLM

# --- Configuration (Set environment variables or replace placeholders) ---
NEO4J_URI = os.environ.get("NEO4J_URI", "bolt://localhost:7687")
NEO4J_USERNAME = os.environ.get("NEO4J_USERNAME", "neo4j")
NEO4J_PASSWORD = os.environ.get("NEO4J_PASSWORD", "password")
NEO4J_DATABASE = os.environ.get("NEO4J_DATABASE", "neo4j")
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "") # Required for OpenAILLM

if not all([NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD, OPENAI_API_KEY]):
    print("Warning: Please set NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD, and OPENAI_API_KEY environment variables for a runnable example.")
    print("Using default values for Neo4j, which may not connect without a running instance.")
    print("OpenAI API key is missing. The LLM initialization might fail or proceed without API calls.")

try:
    # 1. Initialize Neo4j Driver
    driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USERNAME, NEO4J_PASSWORD))
    # Verify connection to ensure Neo4j is reachable and credentials are correct
    driver.verify_connectivity()
    print("Neo4j connection verified successfully.")

    # 2. Initialize your chosen LLM (e.g., OpenAI)
    llm = OpenAILLM(api_key=OPENAI_API_KEY)

    # 3. Initialize the GraphRAG pipeline
    # This pipeline is designed to work with a knowledge graph. For best results,
    # ensure your Neo4j database has relevant data, possibly built using SimpleKGPipeline.
    pipeline = GraphRAGPipeline(
        llm=llm,
        graph_driver=driver,
        database=NEO4J_DATABASE
    )

    # 4. Ask a question to the pipeline
    question = "Who is the CEO of Neo4j?"
    print(f"\nQuestion: {question}")
    response = pipeline.query(question)

    print(f"Answer: {response.answer}")

except Exception as e:
    print(f"An error occurred during quickstart: {e}")
finally:
    if 'driver' in locals():
        driver.close()
        print("Neo4j driver closed.")

view raw JSON →