Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/neo4j-labs/create-context-graph/llms.txt

Use this file to discover all available pages before exploring further.

When you run create-context-graph, the tool writes a complete full-stack application to the output directory. This page documents every file in that output, explains what it does, and lists every Makefile target you can use to operate the project.

Directory tree

my-app/
├── .env                               # Environment variables (Neo4j URIs, API keys) — gitignored
├── .env.example                       # Configuration template with placeholder values — committed to git
├── .gitignore                         # Git ignore rules
├── .dockerignore                      # Docker build context exclusions
├── Makefile                           # Build, run, seed, and test commands
├── docker-compose.yml                 # Neo4j container definition (Docker mode only)
├── README.md                          # Auto-generated project documentation

├── backend/
│   ├── pyproject.toml                 # Python dependencies (includes selected agent framework)
│   ├── app/
│   │   ├── __init__.py
│   │   ├── main.py                    # FastAPI application entry point
│   │   ├── config.py                  # Settings loaded from .env via Pydantic
│   │   ├── routes.py                  # REST and SSE API endpoints
│   │   ├── models.py                  # Pydantic models generated from the domain ontology
│   │   ├── agent.py                   # AI agent (varies by framework)
│   │   ├── constants.py               # Shared constants (index names, graph projection names)
│   │   ├── context_graph_client.py    # Neo4j read/write client + SSE event collector
│   │   ├── gds_client.py              # Neo4j Graph Data Science client
│   │   └── vector_client.py           # Vector search client
│   ├── tests/
│   │   ├── __init__.py
│   │   └── test_routes.py             # Generated test scaffold (health check, scenario tests)
│   └── scripts/
│       ├── generate_data.py           # Data seeding script
│       └── import_data.py             # SaaS import script (only if connectors selected)

├── frontend/
│   ├── package.json                   # Next.js + Chakra UI v3 + NVL dependencies
│   ├── next.config.ts                 # Next.js configuration
│   ├── tsconfig.json                  # TypeScript configuration
│   ├── app/
│   │   ├── layout.tsx                 # Root layout with Chakra provider
│   │   ├── page.tsx                   # Main page (chat + graph view + documents + traces)
│   │   └── globals.css                # Global styles
│   ├── components/
│   │   ├── ChatInterface.tsx          # Streaming chat UI with real-time tool call visualization
│   │   ├── ContextGraphView.tsx       # Interactive NVL graph visualization
│   │   ├── DecisionTracePanel.tsx     # Reasoning trace viewer
│   │   ├── DocumentBrowser.tsx        # Document browser with template filtering
│   │   └── Provider.tsx               # Chakra UI v3 provider wrapper
│   ├── lib/
│   │   └── config.ts                  # Frontend configuration constants
│   └── theme/
│       └── index.ts                   # Chakra UI v3 theme customization

├── cypher/
│   ├── schema.cypher                  # Node constraints and indexes from ontology
│   └── gds_projections.cypher         # Graph Data Science projection queries

└── data/
    ├── ontology.yaml                  # Copy of the domain ontology
    ├── _base.yaml                     # Copy of the base POLE+O ontology
    ├── fixtures.json                  # Generated demo data (present when --demo-data is used)
    └── documents/                     # Generated synthetic documents (present when --demo-data is used)
docker-compose.yml, make docker-up, and make docker-down are only generated when Docker is selected as the Neo4j connection type. Similarly, make neo4j-start, make neo4j-stop, and make neo4j-status are only present in local (--neo4j-local) mode. import_data.py and make import are only generated when at least one --connector is selected.

Backend

app/main.py

FastAPI application entry point. Configures CORS middleware, manages the Neo4j driver lifecycle via asynccontextmanager (connecting on startup, closing on shutdown), and mounts the route modules. The server listens on port 8000.

app/config.py

Pydantic Settings class that reads from the .env file at startup. Exposes Neo4j connection details, API keys, the selected framework identifier, and configurable timeouts. All environment variables in .env flow through this module.

app/routes.py

All REST and streaming API endpoints. The full set of endpoints:
MethodPathDescription
POST/chatSend a message to the AI agent; returns full response with graph_data
POST/chat/streamStreaming chat via Server-Sent Events — token-by-token text and real-time tool call events
POST/searchSearch entities in the knowledge graph
GET/graph/{entity_name}Get the subgraph centred on a named entity
GET/schemaGet graph schema (labels and relationship types)
GET/schema/visualizationGet schema as a graph via db.schema.visualization()
POST/expandExpand a node to show its immediate neighbours
POST/cypherExecute an arbitrary Cypher query
GET/documentsList documents with optional template filter
GET/documents/{title}Get full document content with mentioned entities
GET/tracesList decision traces with full reasoning steps
GET/entities/{name}Get full entity detail with properties and connections
GET/gds/statusCheck whether Graph Data Science is available
GET/gds/communitiesRun community detection
GET/gds/pagerankRun PageRank centrality
GET/scenariosGet domain demo scenarios
GET/healthHealth check with Neo4j connectivity status
The /chat/stream endpoint uses an asyncio.Queue attached to the CypherResultCollector to push events in real time. The SSE stream has a 120-second per-event idle timeout and a 300-second overall timeout.

app/models.py

Pydantic models generated from the domain ontology’s entity_types. Each entity label becomes a model class. Properties with enum values generate Python Enum classes. These models are used for request/response validation in routes and for type-safe data access in the agent.

app/agent.py

The AI agent implementation — the only backend file that varies between frameworks. All eight framework implementations export the same interface:
async def handle_message(
    message: str,
    session_id: str | None = None,
) -> dict:
    """Returns {"response": str, "session_id": str, "graph_data": dict | None}"""
Frameworks that support token-by-token text streaming (PydanticAI, Anthropic Tools, Claude Agent SDK, OpenAI Agents, LangGraph, Google ADK) also export:
async def handle_message_stream(
    message: str,
    session_id: str | None = None,
) -> dict:
    """Streams text deltas and tool events via the CypherResultCollector event queue."""
The agent is configured with:
  • The domain’s system_prompt from the ontology, plus a tool-use emphasis suffix
  • Domain-specific tools generated from agent_tools in the ontology, each executing Cypher queries against Neo4j
  • Session management for multi-turn conversation continuity via context_graph_client

Full streaming

Token-by-token text and real-time tool calls: PydanticAI, Claude Agent SDK, OpenAI Agents, LangGraph, Google ADK, Anthropic Tools

Tool streaming

Real-time tool calls with text delivered at end of turn: CrewAI, Strands

app/context_graph_client.py

Neo4j client for reading and writing the knowledge graph. Key responsibilities:
  • Entity CRUD — create, read, update, and delete domain entities
  • Relationship traversal — fetch neighbours, subgraphs, and schema
  • Cypher execution — arbitrary query execution with Cypher injection prevention
  • Schema visualization — calls db.schema.visualization() for the graph schema view
  • Node expansion — fetches immediate neighbours for double-click expand in the frontend
  • SSE event queue — the CypherResultCollector captures Cypher results and tool metadata, pushing tool_start, tool_end, text_delta, and done events to an asyncio.Queue for real-time streaming
  • Thread safety — detects worker threads (used by CrewAI and Strands via asyncio.to_thread()) and routes events through loop.call_soon_threadsafe()
  • Conversation memory — initializes the neo4j-agent-memory MemoryClient with graceful fallback; exposes get_conversation_history() and store_message() for multi-turn persistence
  • Embedding provider — uses local sentence-transformers (all-MiniLM-L6-v2) by default; automatically upgrades to OpenAI text-embedding-3-small when OPENAI_API_KEY is set
The module uses a custom _serialize() function instead of the Neo4j driver’s .data() method. This preserves Node elementId and labels, Relationship elementId, type, startNodeElementId, and endNodeElementId — metadata required by the frontend graph visualization and agent tools.

app/gds_client.py

Client for Neo4j Graph Data Science. Provides methods for running graph algorithms — PageRank, community detection, and similarity — on projected subgraphs defined in cypher/gds_projections.cypher.

app/vector_client.py

Client for Neo4j vector search. Supports storing and querying vector embeddings for semantic search over entities and documents.

app/constants.py

Shared constants used across the backend: vector index names, GDS graph projection names, and other configuration values that must be consistent between context_graph_client.py, gds_client.py, and the Cypher scripts.

scripts/generate_data.py

Standalone data seeding script that loads all fixture data into Neo4j in four sequential steps:
1

Schema

Applies uniqueness constraints and name indexes from cypher/schema.cypher.
2

Entities and relationships

Creates domain entity nodes and relationship edges from data/fixtures.json using ON CREATE SET / ON MATCH SET for constraint-safe upserts. All nodes are tagged with a domain property for cross-domain isolation when sharing a Neo4j instance.
3

Documents

Creates :Document nodes and links them to mentioned entities via :MENTIONS relationships.
4

Decision traces

Creates :DecisionTrace:HAS_STEP:TraceStep chains representing multi-step agent reasoning.
Run via make seed or directly:
cd backend && python scripts/generate_data.py

scripts/import_data.py

SaaS data import script generated only when --connector options are selected. Authenticates with each configured service, fetches data, normalises it into the fixture schema, and writes it to data/fixtures.json. Run via make import.

Frontend

app/page.tsx

Main application page with a three-panel layout: chat interface on the left, interactive graph visualization in the centre, and a tabbed right panel with Decision Traces and Documents tabs. Manages shared state — graphData is lifted to the page level and flows from ChatInterface (via onGraphUpdate callback) to ContextGraphView (via externalGraphData prop).

components/ChatInterface.tsx

Streaming chat UI with multi-turn conversation support. Connects to POST /chat/stream via the Fetch API (not EventSource, which only supports GET). Behaviour:
  • Tool calls appear as a Chakra UI Timeline with live Spinner indicators as each tool executes
  • Text tokens are batched at ~50 ms before updating the ReactMarkdown renderer to avoid excessive re-renders
  • Graph data flows to ContextGraphView incrementally after each tool_end SSE event
  • session_id is captured from the first SSE response and sent in all subsequent requests
  • Chat history is scoped by domain ID to prevent cross-app pollution
  • SSR hydration mismatches are avoided by deferring session storage reads to useEffect
  • A 60-second request timeout is enforced via AbortController
Additional UI features: “New Conversation” button, clickable demo scenario buttons from the ontology, collapsible tool detail cards showing inputs and outputs, a retry button on error messages, and an elapsed time counter during loading.

components/ContextGraphView.tsx

Interactive graph visualization built on the Neo4j Visualization Library (NVL) with d3-force layout. Operates in two view modes:
  • Schema view (initial state) — Calls GET /schema/visualization and renders entity types as nodes with relationship types as edges. Double-clicking a schema node loads data instances of that label.
  • Data view — Displays actual graph data from agent tool calls or manual exploration. Double-clicking a data node calls POST /expand to fetch and merge its neighbours (deduplicated).
Interaction model: drag to move nodes, scroll to zoom, click a node or relationship to open the property detail panel (showing labels, all properties, and connection counts), click the canvas to deselect. A Back to schema button returns to schema view. An Ask about [entity] button on the detail panel sends a chat query via the onAskAboutexternalInputChatInterface callback chain. UI overlays: colour legend for the top 6 node types, usage instructions, and a loading spinner during node expansion.

components/DecisionTracePanel.tsx

Displays pre-seeded decision traces loaded from GET /traces. Each trace shows the overall task, the reasoning steps (thought, action, observation), and the final outcome. Traces are stored as :DecisionTrace:HAS_STEP:TraceStep chains and created during make seed.

components/DocumentBrowser.tsx

Document browser panel with template type filter badges (for example, Discharge Summary, Lab Report, Trade Confirmation). Lists documents with content previews. Clicking a document shows its full content and the entity badges for all entities mentioned in it. Documents are stored as :Document nodes with :MENTIONS relationships to entities, created during make seed.

components/Provider.tsx

Chakra UI v3 provider component that wraps the application with the custom theme and configures the color mode.

lib/config.ts

Frontend configuration constants: the backend base URL (http://localhost:8000), domain display name, and any domain-specific UI settings.

theme/index.ts

Chakra UI v3 theme customization. Applies domain-specific primary color and typography settings.

Cypher

schema.cypher

Auto-generated from the domain ontology. Contains uniqueness constraints for every property marked unique: true in the ontology YAML, a name index on every entity type for fast lookups, and infrastructure indexes for :Document (title, template_id) and :DecisionTrace (unique id) nodes.
CREATE CONSTRAINT account_account_id_unique IF NOT EXISTS
FOR (n:Account) REQUIRE n.account_id IS UNIQUE;

CREATE INDEX account_name IF NOT EXISTS
FOR (n:Account) ON (n.name);
Run via make seed (which calls generate_data.py) or directly against a running Neo4j instance.

gds_projections.cypher

Graph Data Science projection queries for running algorithms on domain-specific subgraphs. Referenced by gds_client.py and the GET /gds/communities and GET /gds/pagerank endpoints.

Data

ontology.yaml and _base.yaml

Copies of the domain ontology and the base POLE+O definitions (Person, Organization, Location, Event, Object) bundled into the generated project. These serve as human-readable documentation of the domain model and can be used to regenerate the schema or fixture data.

fixtures.json

Structured demo data written by --demo-data. The schema:
{
  "entities": {
    "Person": [{"name": "Alice Chen", "email": "alice@example.com"}],
    "Account": [{"name": "Acct-001", "balance": 15000.00}]
  },
  "relationships": [
    {"type": "OWNS_ACCOUNT", "source_name": "Alice Chen", "target_name": "Acct-001"}
  ],
  "documents": [
    {
      "template_id": "trade_confirmation",
      "title": "Trade Confirmation — AAPL 2026-01-15",
      "content": "..."
    }
  ],
  "traces": [
    {
      "task": "Identify high-risk accounts",
      "steps": [
        {"thought": "...", "action": "...", "observation": "..."}
      ],
      "outcome": "..."
    }
  ]
}

documents/

Directory of synthetic document files generated by --demo-data. Each file corresponds to a document template defined in the ontology (for example, discharge summaries, lab reports, trade confirmations). Created alongside fixtures.json and referenced by :Document nodes during seeding.

Configuration files

.env

Populated at scaffold time with the Neo4j connection details and any API keys provided on the command line. Gitignored — never committed to version control.
NEO4J_URI=neo4j://localhost:7687
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=password
ANTHROPIC_API_KEY=
OPENAI_API_KEY=
GOOGLE_API_KEY=

.env.example

Identical in structure to .env but with placeholder values. Committed to git so new contributors know what variables to set.

docker-compose.yml

Defines a Neo4j container with the APOC and Graph Data Science plugins enabled, mapped to ports 7474 (Neo4j Browser) and 7687 (Bolt). Generated only when Docker is selected as the Neo4j connection type.

Makefile targets

Every generated project includes a Makefile with the following targets. Targets marked as conditional are only present when the relevant option was selected at scaffold time.
TargetDescriptionRequirements
make installInstall backend Python dependencies (uv pip install -e .) and frontend Node.js dependencies (npm install)uv, Node.js
TargetDescriptionRequirements
make docker-upStart the Neo4j container via Docker ComposeDocker, Docker Compose
make docker-downStop and remove the Neo4j containerDocker, Docker Compose
Generated only when Docker is selected as the Neo4j connection type.
TargetDescriptionRequirements
make neo4j-startStart Neo4j via @johnymontana/neo4j-localNode.js, npx
make neo4j-stopStop the neo4j-local instanceNode.js
make neo4j-statusCheck neo4j-local statusNode.js
Generated only when --neo4j-local is selected.
TargetDescriptionRequirements
make seedApply schema constraints and load all fixture data (entities, relationships, documents, decision traces) into Neo4jRunning Neo4j
make resetClear all data from Neo4j (MATCH (n) DETACH DELETE n)Running Neo4j
make test-connectionValidate Neo4j credentials and connectivityRunning Neo4j
make importRe-import data from connected SaaS services and write to data/fixtures.jsonSaaS credentials in .env
make import is generated only when at least one --connector is selected.
TargetDescriptionRequirements
make startStart both the FastAPI backend (port 8000) and Next.js frontend (port 3000) concurrently; uses trap for clean Ctrl+C shutdownRunning Neo4j
make dev-backendStart only the FastAPI backendRunning Neo4j
make dev-frontendStart only the Next.js frontendRunning backend
TargetDescriptionRequirements
make testRun backend pytest tests and frontend testsNone (unit tests only)
make cleanRemove generated build artifacts and cachesNone
The typical first-run sequence is:
make install
make docker-up    # or: make neo4j-start
make seed
make start
After that, open http://localhost:3000 for the chat interface and http://localhost:8000/docs for the FastAPI auto-generated API docs.

Backend pyproject.toml

The generated pyproject.toml declares:
  • fastapi, uvicorn, neo4j, pydantic-settings — core backend dependencies present in all projects
  • The framework-specific dependency (for example, pydantic-ai>=0.1 for pydanticai, google-adk>=0.1 for google-adk)
  • neo4j-agent-memory[spacy,gliner] and sentence-transformers>=2.0 — conversation memory with local embeddings (no API key required)
  • anthropic>=0.30 and/or openai as needed by the selected framework
neo4j-agent-memory is included without the [openai] extra so local sentence-transformers embeddings work out of the box. If you add OPENAI_API_KEY to .env, the generated context_graph_client.py detects it at startup and automatically upgrades to OpenAI text-embedding-3-small.