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.
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.
upsert_nodes ¶
Upserts a list of entity nodes within the specified tenant boundary.
upsert_edges ¶
Upserts a list of relationship edges within the specified tenant boundary.
upsert_graph ¶
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 ¶
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 ¶
Deletes all graph nodes and edges belonging strictly to the specified tenant.
delete_by_document ¶
Reconciles and purges graph entities and edges associated with document_id.
contains_nodes ¶
Returns the subset of node_ids that currently exist within tenant boundary.
InMemoryGraphStore ¶
Bases: GraphStore
Pure standard-library multi-tenant graph store.
upsert_nodes ¶
Upserts a list of entity nodes within the specified tenant boundary.
upsert_edges ¶
Upserts a list of relationship edges within the specified tenant boundary.
upsert_graph ¶
Upserts a complete KnowledgeGraph within tenant boundary.
get_node ¶
Retrieves an entity node by ID scoped strictly to tenant_id.
contains_nodes ¶
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 ¶
Deletes all graph nodes and edges belonging strictly to the specified tenant.
delete_by_document ¶
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 ¶
Initializes the Neo4j driver connection and multi-tenant constraints.
upsert_nodes ¶
Upserts entity nodes idempotently using Cypher MERGE within tenant boundary.
upsert_edges ¶
Upserts relationship edges idempotently within tenant boundary.
upsert_graph ¶
Upserts a complete KnowledgeGraph within tenant boundary.
get_node ¶
Retrieves an entity node by ID scoped strictly to tenant_id.
contains_nodes ¶
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 ¶
Deletes all graph nodes and edges belonging strictly to the specified tenant.
delete_by_document ¶
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)
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.
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 ¶
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 ¶
Authoritative entity node identity based on deterministic Entity.entity_id.
canonical_typed_node_id ¶
Auxiliary helper / alias identity for hierarchical type lookup.
canonical_chunk_node_id ¶
Authoritative chunk node identity.
canonical_document_node_id ¶
Authoritative document node identity.
canonical_relation_edge_id ¶
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 ¶
Serializes KnowledgeGraph to canonical dictionary format.
to_json_ld ¶
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 ¶
Serializes KnowledgeGraph to Cytoscape JSON elements schema for graph visualization.
to_cypher_statements ¶
Generates deterministic Cypher MERGE statements representing the graph.