Skip to content

md_generator.graph API Reference

Summary

Item Value
Purpose Convert Neo4j or NetworkX GraphML/GML to Node/relationship Markdown, Mermaid, Graphviz
CLI md-graph
Extra graph
Tier medium

Quick CLI reference

Argument Type Required Default Choices Help
--config Path optional None — Path to YAML config
--source str optional None ('networkx', 'neo4j') —
--uri str optional None — —
--user str optional None — —
--password str optional None — —
--database str optional None — Neo4j database name (e.g. neo4j); passed to driver session(database=...)
--graph-file Path optional None — —
--depth int optional None — —
--start-node str optional None — —
--max-nodes int optional None — —
--max-edges int optional None — —
--output Path optional None — —
--neo4j-id-mode str optional None ('element_id', 'internal_id') —
--async flag optional false — Enqueue background job (prints job_id; uses SQLite job store)
--markdown-layout str optional None ('combined', 'individual') combined (default): nodes.md, relationship.md, graph_summary with embedded sections; individual: nodes/ and relationships/ per entity

Primary symbols

Symbol Kind Notes
extract_to_markdown callable —
Neo4jAdapter callable —
GraphRunConfig callable —

Python API (mkdocstrings)

graph

Enterprise Knowledge Graph, Neo4j, and Hybrid GraphRAG infrastructure layer.

GraphError

Bases: Exception

Base exception for all knowledge graph and GraphRAG operations.

Neo4jDependencyError

Bases: ImportError, GraphError

Raised when neo4j optional package is missing, broken, or fails to initialize.

GraphStoreError

Bases: GraphError

Raised on graph storage, connection, persistence, or transaction faults.

GraphQueryError

Bases: GraphError

Raised on invalid Cypher queries, traversal parameters, cycle limits, or traversal budget overflows.

TenantBoundaryError

Bases: VectorError

Raised when a tenant isolation boundary constraint is violated.

EntityNode dataclass

EntityNode(node_id: str, tenant_id: str, entity_id: str, entity_type: str, name: str, qualified_name: str, properties: Dict[str, Any] = dict(), document_ids: List[str] = list(), chunk_ids: List[str] = list(), source_location: Optional[SourceLocation] = None)

Canonical Knowledge Graph entity node.

RelationEdge dataclass

RelationEdge(edge_id: str, tenant_id: str, source_id: str, target_id: str, relationship_type: str, weight: float = 1.0, document_ids: List[str] = list(), chunk_ids: List[str] = list(), provenance: List[EdgeProvenance] = list(), properties: Dict[str, Any] = dict())

Canonical Knowledge Graph relationship edge with multi-document provenance.

KnowledgeGraph dataclass

KnowledgeGraph(tenant_id: str, nodes: Dict[str, EntityNode] = dict(), edges: Dict[str, RelationEdge] = dict(), metadata: Dict[str, Any] = dict())

Unified multi-tenant knowledge graph container.

to_json_ld

to_json_ld(include_tenant: bool = False) -> Dict[str, Any]

Serializes to W3C JSON-LD format with canonical ontology context.

to_cytoscape

to_cytoscape() -> Dict[str, Any]

Serializes to Cytoscape elements schema for interactive graph visualization.

to_cypher_statements

to_cypher_statements() -> List[str]

Generates deterministic Cypher MERGE statements representing the graph.

EdgeProvenance dataclass

EdgeProvenance(document_id: str, chunk_id: Optional[str] = None, confidence: float = 1.0, source_location: Optional[SourceLocation] = None)

Tracks document and chunk provenance for a graph relationship edge.

GraphPath dataclass

GraphPath(seed_chunk_id: str, target_node_id: str, node_ids: List[str], edge_ids: List[str], depth: int, score: float)

Canonical representation of a graph traversal path from a seed node.

GraphStore

Bases: Protocol

Protocol defining multi-tenant graph storage, traversal, and lifecycle contracts.

initialize

initialize() -> None

Initializes the graph store connection, indices, and constraints.

health_check

health_check() -> bool

Executes a lightweight connectivity/liveness health check.

upsert_nodes

upsert_nodes(nodes: List[EntityNode], tenant_id: str) -> int

Upserts a list of entity nodes within the specified tenant boundary.

upsert_edges

upsert_edges(edges: List[RelationEdge], tenant_id: str) -> int

Upserts a list of relationship edges within the specified tenant boundary.

upsert_graph

upsert_graph(graph: KnowledgeGraph, tenant_id: str) -> Tuple[int, int]

Upserts a complete KnowledgeGraph within the specified tenant boundary.

Returns:

Type Description
Tuple[int, int]

Tuple[int, int]: Count of upserted nodes and edges.

get_node

get_node(node_id: str, tenant_id: str) -> Optional[EntityNode]

Retrieves an entity node by ID scoped strictly to tenant_id.

get_neighbors

get_neighbors(node_id: str, tenant_id: str, direction: Literal['in', 'out', 'both'] = 'both', relationship_types: Optional[List[str]] = None, max_depth: int = 1, max_nodes: int = 500, max_edges: int = 2000, strict_limits: bool = False) -> List[Tuple[RelationEdge, EntityNode]]

Retrieves adjacent neighbors for a given node within tenant boundary.

Enforces resource safety caps (max_nodes, max_edges).

traverse

traverse(start_node_ids: List[str], tenant_id: str, max_depth: int = 2, relationship_types: Optional[List[str]] = None, direction: Literal['in', 'out', 'both'] = 'both', strategy: Literal['bfs', 'dfs'] = 'bfs', max_nodes: int = 500, max_edges: int = 2000, strict_limits: bool = False) -> KnowledgeGraph

Performs a multi-hop graph traversal starting from start_node_ids.

Enforces tenant isolation, cycle detection, and resource safety limits.

delete_by_tenant

delete_by_tenant(tenant_id: str) -> int

Deletes all graph nodes and edges belonging strictly to the specified tenant.

delete_by_document

delete_by_document(document_id: str, tenant_id: str) -> int

Reconciles and purges graph entities and edges associated with document_id.

contains_nodes

contains_nodes(node_ids: List[str], tenant_id: str) -> Set[str]

Returns the subset of node_ids that currently exist within tenant boundary.

close

close() -> None

Closes connections, pools, and releases store resources.

InMemoryGraphStore

InMemoryGraphStore()

Bases: GraphStore

Pure standard-library multi-tenant graph store.

initialize

initialize() -> None

Initializes the graph store.

health_check

health_check() -> bool

Returns True if the store is initialized and operational.

close

close() -> None

Closes store resources.

upsert_nodes

upsert_nodes(nodes: List[EntityNode], tenant_id: str) -> int

Upserts a list of entity nodes within the specified tenant boundary.

upsert_edges

upsert_edges(edges: List[RelationEdge], tenant_id: str) -> int

Upserts a list of relationship edges within the specified tenant boundary.

upsert_graph

upsert_graph(graph: KnowledgeGraph, tenant_id: str) -> Tuple[int, int]

Upserts a complete KnowledgeGraph within tenant boundary.

get_node

get_node(node_id: str, tenant_id: str) -> Optional[EntityNode]

Retrieves an entity node by ID scoped strictly to tenant_id.

contains_nodes

contains_nodes(node_ids: List[str], tenant_id: str) -> Set[str]

Returns the subset of node_ids that currently exist within tenant boundary.

get_neighbors

get_neighbors(node_id: str, tenant_id: str, direction: Literal['in', 'out', 'both'] = 'both', relationship_types: Optional[List[str]] = None, max_depth: int = 1, max_nodes: int = 500, max_edges: int = 2000, strict_limits: bool = False) -> List[Tuple[RelationEdge, EntityNode]]

Retrieves adjacent neighbors for a given node within tenant boundary.

traverse

traverse(start_node_ids: List[str], tenant_id: str, max_depth: int = 2, relationship_types: Optional[List[str]] = None, direction: Literal['in', 'out', 'both'] = 'both', strategy: Literal['bfs', 'dfs'] = 'bfs', max_nodes: int = 500, max_edges: int = 2000, strict_limits: bool = False) -> KnowledgeGraph

Performs a multi-hop graph traversal starting from start_node_ids.

delete_by_tenant

delete_by_tenant(tenant_id: str) -> int

Deletes all graph nodes and edges belonging strictly to the specified tenant.

delete_by_document

delete_by_document(document_id: str, tenant_id: str) -> int

Reconciles and purges graph entities and edges associated with document_id.

5-Step Reconciliation: 1. Identify chunk nodes owned by document_id (D_chunks). Delete them and incident edges. 2. Delete document node canonical_document_node_id(tenant_id, document_id). 3. Reconcile surviving entity nodes: remove document_id & D_chunks; delete if orphaned. 4. Reconcile surviving relation edges: remove document_id & D_chunks; prune provenance; delete if orphaned; update edge weight to max(provenance confidence). 5. Return count of purged nodes + edges.

Neo4jGraphStore

Neo4jGraphStore(uri: Optional[str] = None, auth: Optional[Tuple[str, str]] = None, database: Optional[str] = None, driver: Optional[Any] = None, fallback_to_memory: bool = False)

Bases: GraphStore

Production graph store backed by Neo4j graph database.

initialize

initialize() -> None

Initializes the Neo4j driver connection and multi-tenant constraints.

health_check

health_check() -> bool

Checks liveness of the graph store.

close

close() -> None

Closes driver connections and releases pool resources.

upsert_nodes

upsert_nodes(nodes: List[EntityNode], tenant_id: str) -> int

Upserts entity nodes idempotently using Cypher MERGE within tenant boundary.

upsert_edges

upsert_edges(edges: List[RelationEdge], tenant_id: str) -> int

Upserts relationship edges idempotently within tenant boundary.

upsert_graph

upsert_graph(graph: KnowledgeGraph, tenant_id: str) -> Tuple[int, int]

Upserts a complete KnowledgeGraph within tenant boundary.

get_node

get_node(node_id: str, tenant_id: str) -> Optional[EntityNode]

Retrieves an entity node by ID scoped strictly to tenant_id.

contains_nodes

contains_nodes(node_ids: List[str], tenant_id: str) -> Set[str]

Returns the subset of node_ids that exist within tenant boundary.

get_neighbors

get_neighbors(node_id: str, tenant_id: str, direction: Literal['in', 'out', 'both'] = 'both', relationship_types: Optional[List[str]] = None, max_depth: int = 1, max_nodes: int = 500, max_edges: int = 2000, strict_limits: bool = False) -> List[Tuple[RelationEdge, EntityNode]]

Retrieves adjacent neighbors for a given node within tenant boundary.

traverse

traverse(start_node_ids: List[str], tenant_id: str, max_depth: int = 2, relationship_types: Optional[List[str]] = None, direction: Literal['in', 'out', 'both'] = 'both', strategy: Literal['bfs', 'dfs'] = 'bfs', max_nodes: int = 500, max_edges: int = 2000, strict_limits: bool = False) -> KnowledgeGraph

Performs a multi-hop graph traversal starting from start_node_ids.

delete_by_tenant

delete_by_tenant(tenant_id: str) -> int

Deletes all graph nodes and edges belonging strictly to the specified tenant.

delete_by_document

delete_by_document(document_id: str, tenant_id: str) -> int

Reconciles and purges graph entities and edges associated with document_id.

GraphStoreFactory

Factory creating configured graph store implementations.

create staticmethod

create(provider: Literal['in_memory', 'neo4j'] = 'in_memory', uri: Optional[str] = None, auth: Optional[Tuple[str, str]] = None, database: Optional[str] = None, driver: Optional[Any] = None, fallback_to_memory: bool = False, **kwargs: Any) -> GraphStore

Creates a GraphStore instance based on the specified provider.

HybridGraphRAGRetriever

HybridGraphRAGRetriever(vector_retriever: Any, graph_store: GraphStore, tenant_id: str, top_k: int = 10, max_depth: int = 2, fusion_mode: Literal['rrf', 'linear'] = 'rrf', alpha: float = 0.7, rrf_k: int = 60, weight_vector: float = 1.0, weight_graph: float = 1.0)

Retrieves and fusions vector similarity results with graph expansion.

retrieve

retrieve(query: str) -> List[ScoredHybridResult]

Performs end-to-end hybrid retrieval with graph expansion and fusion.

invoke

invoke(query: str) -> List[Any]

LangChain standard invoke method returning List[Document].

get_relevant_documents

get_relevant_documents(query: str) -> List[Any]

LangChain backward-compatible retriever API.

ScoredHybridResult dataclass

ScoredHybridResult(chunk_id: str, content: str, tenant_id: str, vector_score: float, graph_score: float, hybrid_score: float, provenance: Literal['VECTOR_ONLY', 'GRAPH_ONLY', 'HYBRID'], metadata: Dict[str, Any] = dict(), graph_paths: List[GraphPath] = list())

Unified hybrid retrieval candidate result.

to_document

to_document() -> Any

Converts result to a LangChain Document compatible object.

GraphContextAdapter

GraphContextAdapter(context_builder: Optional[PromptContextBuilder] = None, include_graph_paths: bool = True, max_paths_per_chunk: int = 5)

Adapts hybrid GraphRAG retrieval results for prompt synthesis.

format_graph_paths

format_graph_paths(paths: List[GraphPath], subgraph: Optional[KnowledgeGraph] = None) -> str

Formats graph traversal paths into human-readable deterministic markdown lines.

augment_result

augment_result(result: Union[ScoredHybridResult, Any], subgraph: Optional[KnowledgeGraph] = None) -> Any

Augments a single hybrid result with its graph traversal context.

augment_documents

augment_documents(results: List[Union[ScoredHybridResult, Any]], subgraph: Optional[KnowledgeGraph] = None) -> List[Any]

Augments a collection of hybrid retrieval results with graph paths.

build_context

build_context(results: List[Union[ScoredHybridResult, Any]], subgraph: Optional[KnowledgeGraph] = None) -> str

Augments results and synthesizes deterministic token-bounded prompt context.

canonical_entity_node_id

canonical_entity_node_id(tenant_id: str, entity_id: str) -> str

Authoritative entity node identity based on deterministic Entity.entity_id.

canonical_typed_node_id

canonical_typed_node_id(tenant_id: str, entity_type: str, qualified_name: str) -> str

Auxiliary helper / alias identity for hierarchical type lookup.

canonical_chunk_node_id

canonical_chunk_node_id(tenant_id: str, chunk_id: str) -> str

Authoritative chunk node identity.

canonical_document_node_id

canonical_document_node_id(tenant_id: str, document_id: str) -> str

Authoritative document node identity.

canonical_relation_edge_id

canonical_relation_edge_id(tenant_id: str, source_id: str, rel_type: str, target_id: str) -> str

Authoritative relation edge identity.

extract

extract(semantic_document: SemanticDocument, chunks: List[SemanticChunk], tenant_id: str) -> KnowledgeGraph

Extracts a unified KnowledgeGraph from a SemanticDocument and its SemanticChunks.

Invariants: 1. tenant_id is mandatory, non-empty, and validated. No inference from metadata.system. 2. Zero in-place mutation of semantic_document or chunks. 3. Option A deduplication: Unifies document-level and chunk-level entities/relationships. 4. Deterministic property conflict precedence: chunk > document for scalar keys. 5. Structural nodes: Document and Chunk nodes created with CONTAINS_CHUNK and CONTAINS_ENTITY edges.

to_dict

to_dict(graph: KnowledgeGraph) -> Dict[str, Any]

Serializes KnowledgeGraph to canonical dictionary format.

to_json_ld

to_json_ld(graph: KnowledgeGraph, include_tenant: bool = False) -> Dict[str, Any]

Serializes KnowledgeGraph to W3C JSON-LD format with canonical ontology context.

Security note: include_tenant is False by default to prevent leaking internal tenant identifiers in external or shared graph exports. When include_tenant=False, all tenantId fields are omitted AND tenant prefixes are stripped from canonical IDs (e.g., 'tenant:t1:entity:cls_order' becomes 'entity:cls_order').

to_cytoscape

to_cytoscape(graph: KnowledgeGraph) -> Dict[str, Any]

Serializes KnowledgeGraph to Cytoscape JSON elements schema for graph visualization.

to_cypher_statements

to_cypher_statements(graph: KnowledgeGraph) -> List[str]

Generates deterministic Cypher MERGE statements representing the graph.