Skip to Content
Recodocs

Knowledge-graph contracts for GraphRAG

Dependency-free schema, statements, lexical graph, CSV import, extraction provenance, duplicate resolution, bounded retrieval, topology anchors, and evaluation helpers for graph-backed RAG.

8 min read

recohut_kit.graphs holds dependency-free knowledge-graph contracts. Integrations are explicit imports elsewhere in the kit. The package root re-exports nothing: you import submodules such as recohut_kit.graphs.schema or recohut_kit.graphs.retrieval directly. Most of the code is plain Python that builds parameterised Cypher statements, validates structured graph data, and scores duplicates or walk reachability without calling a model. Embedding vectors appear as caller-supplied tuples; nothing in this package invokes an embedding or generation provider.

The layer owns typed graph schemas, safe Cypher identifiers, statement records with bound parameters, a lexical document-and-chunk layer, CSV import plans, schema-guided extraction records and write statements, conservative duplicate proposal and merge intent statements, bounded vector and entity expansion and typed path queries, named exploration and validation queries, entity-topology text for anchor retrieval, portable harness summaries and reach sweeps, plus smaller contract modules under recohut_kit.graphs.plans and recohut_kit.graphs.operations. It does not open a database driver, run Neo4j, perform live embedding, execute planned Cypher, or authenticate human resume decisions. Those boundaries live in integration packages that consume these contracts.

Purpose

A graph represents relationships, not just a list of objects. Use this package when you need to preserve which entities are connected and query those relationships explicitly.

GraphRAG needs a stable seam between application configuration (node labels, relationship types, business IDs) and anything that talks to a graph database or a model. This package defines that seam: identifiers are validated before they appear in statement text, while values always travel as parameters. GraphSchema.render returns schema text, and GraphSchema.validate checks extraction-shaped entities and relationships. lexical_statements and friends emit Neo4j 5.26-oriented DDL and MERGE patterns for documents, chunks, and vector indexes. ImportPlan stores the CSV mapping and conversions; read_plan reports bad rows before import_statements builds writes. prime selects known entities to seed extraction under token and candidate budgets. entity_statements turns an ExtractionResponse into a statement batch with provenance. The Neo4j entity store validates the extraction and checks the source chunk. The database adapter executes the generated statements in one transaction. resolution_candidates only marks pairs for review; merging is a separate explicit operation. vector_statement, expansion_statement, entity_expansion_statement, and path_statement encode retrieval policies as statements. topology_texts builds deterministic per-entity text for topology-index anchors when chunks do not share the question’s wording. evaluation summarises repeated harness scores and reports what a bounded in-process walk could reach, without fabricating scores.

What stays outside: managed Neo4j stores and retrievers, structured extraction clients that call a model, exploration runners that execute queries, and LangGraph streaming or resume hosts. The plans subpackage adds constrained query-plan templates, small domain schemas, and incident mapping records; plans.plans classifies Cypher via recohut_kit.graphrag.cypher. The operations subpackage defines fork, replay, stream-mode, and resume verdict records with no runtime import side effects.

Public API

The package root (recohut_kit.graphs) is a marker only. Import from recohut_kit.graphs.<module> using the module shown for each row.

Core graph layer

NameModuleKindWhat it does
identifierschemafunctionAdmits simple Cypher identifiers; rejects executable fragments
StatementschemadataclassParameterised statement text plus parameters
Databaseschemaprotocolrun and write for adapters
NodeType, RelationshipTypeschemadataclassDeclared labels, endpoints, and allowed properties
GraphSchemaschemaclassRenders schema text; validates entities and relationships
DocumentNode, ChunkNodelexicaldataclassLexical document version and chunk records
lexical_statementslexicalfunctionConstraints and chunk vector index DDL for a schema
document_statementslexicalfunctionMERGE document and chunks with parameterised rows
sibling_statementlexicalfunctionNEXT_CHUNK links between ordered chunks
similarity_statementlexicalfunctionPer-chunk SIMILAR_TO links via vector index
ImportPlanimportsdataclassNode or relationship CSV mapping plan
ConversionFailure, ImportReceiptimportsdataclassRow conversion failure and import result records
read_planimportsfunctionReads CSV through a plan; returns rows and failures
import_statementsimportsfunctionMERGE structured nodes or relationships from rows
Entity, RelationshipextractiondataclassExtraction entity and relationship records
ExtractionResponse, ExtractionSchemaextractiondataclassResponse bundle and schema plus default instructions
Candidate, PrimingPolicy, PrimedextractiondataclassPriming inputs, policy, and result
normalise, primeextractionfunctionNFKC name normalisation; lexical-then-vector priming
ExtractionRun, ExtractionReceiptextractiondataclassRun identity via fingerprint; extraction receipt fields
entity_statementsextractionfunctionBuilds statements for entities, relationships, and a processed marker
ResolutionPolicy, ResolutionCandidateresolutiondataclassDuplicate scoring policy and proposed pair
duplicate_score, resolution_candidatesresolutionfunctionPair similarity; candidate pairs under budgets
merge_statement, rewire_statementresolutionfunctionAudit merge query; edge rewire pattern for a type
VectorRetrieval, EntityExpansion, PathRetrievalretrievaldataclassRetrieval policy records with validation
vector_statement, expansion_statement, entity_expansion_statement, path_statementretrievalfunctionParameterised retrieval statements
Retrieval, RetrievalReceipt, Edge, Retrieverretrievaldataclass / protocolRetrieval result shape and protocol
bounded_walk, Walk, WalkedTripleretrievalfunction / dataclassIn-process hop-limited graph walk
Query, ValidationReceiptqueriesdataclassNamed query with parameters; validation run receipt
EXPLORATION, VALIDATIONqueriesconstantsBundled exploration and validation Query tuples
TopologyTexttopologydataclassPer-entity topology summary text
edge_sentence, topology_textstopologyfunctionOne fact sentence; capped facts per entity
topology_index_statement, topology_embedding_statement, topology_anchor_statementtopologyfunctionTopology vector index, embedding write, anchor query
TOPOLOGY_INDEXtopologyconstantName of the entity topology vector index
ReferenceQuestion, HarnessResultevaluationdataclassEvaluation question spec; one harness trial row
summariseevaluationfunctionMean and variance of scores per retriever and question
ReachObservation, reach_sweep, reach_summaryevaluationclass / functionWalk reachability observations and summary rows

Query plans

NameModuleKindWhat it does
canonical_label, SmallSchema, ConsistencyReportplans.schemafunction / classLabel aliasing; compact schema; consistency report
licensing_schema, incident_schemaplans.schemafunctionPackaged small schemas
Intent, QueryPlan, InvestigationPlan, PlanRefusal, Template, BoundQueryplans.plansdataclassQuery-plan records and binding product
nearest_intents, validate_plan, bindplans.plansfunctionIntent matching; plan validation; template bind
licensing_templates, investigation_templates, review_extensionplans.plansfunctionTemplate libraries and extension review
PlainFacts, ValidatedExtraction, validate_extraction, score_extractionplans.extractionclass / functionPlan-side extraction validation and scoring
AlertRecord, IncidentExport, map_incidentsplans.incidentsdataclass / functionIncident export mapping to ExtractionResponse
ApproachDecision, score_decisions, FitCheck, CypherLanguageMatrix, CypherSqlMappingplans.decisiondataclass / functionscore_decisions scores approach decisions, and the other four names are dataclasses
CheckpointState, inspect, PitfallItem, PitfallChecklistplans.checkpointsclass / functionCheckpoint inspection contracts
StoreDescription, GraphStoreplans.storedataclass / protocolStore description and graph store protocol

Runtime operation contracts

NameModuleKindWhat it does
ForkRecord, ReplayRecord, ForkComparison, compare_forksoperations.lineagedataclass / functionFork and replay comparison records
InterruptRequest, Approve, Reject, ApproveWithModification, validateoperations.resumedataclass / functionTyped resume decisions and validation
StreamMode, StreamModeCatalogue, StreamReceipt, FrameReceiptoperations.streamsdataclassStream mode catalogue and receipts

How it composes

Within the kit, composition is narrow and explicit. schema imports JsonValue, imports imports as_json_value, and extraction imports JsonValue and fingerprint; lexical, resolution, and topology do not import recohut_kit.json. Internal edges use relative imports between graphs modules (lexical → schema, resolution → extraction and schema, topology → extraction, retrieval, schema, and so on). recohut_kit.graphs.plans.schema and recohut_kit.graphs.plans.extraction build on graphs.extraction and graphs.schema. recohut_kit.graphs.plans.plans additionally imports recohut_kit.graphrag.cypher.classify_cypher. recohut_kit.graphs.operations.lineage and recohut_kit.graphs.operations.resume use recohut_kit.json; operations.streams imports nothing else from the kit.

Module docstrings name downstream consumers (for example Neo4j GraphRAG stores, retrieval, exploration, evaluation, LangGraph operations, and other graph modules). Those integrations import these contracts; this package does not import them back. The root docstring says it uses nothing else in the kit and is not imported by other kit modules.

Minimal usage example

The tests build a small GraphSchema, reject unsafe identifiers, and validate a well-typed extraction payload before any driver runs. That pattern shows how configuration becomes checkable structure.

from recohut_kit.graphs.extraction import Entity, Relationship
from recohut_kit.graphs.schema import GraphSchema, NodeType, RelationshipType, identifier

schema = GraphSchema(
    (NodeType("Person"), NodeType("Project"), NodeType("Technology")),
    (
        RelationshipType("WORKED_ON", "Person", "Project"),
        RelationshipType("USES", "Project", "Technology"),
    ),
)
assert "Person -WORKED_ON-> Project" in schema.render()

identifier("Person")  # raises ValueError on strings like "Person) DELETE n"

schema.validate(
    (
        Entity("EMP012", "Person", "Maren Kestrel", ("Marren Kestrel",)),
        Entity("PRJ009", "Project", "Intake"),
    ),
    (Relationship("EMP012", "PRJ009", "WORKED_ON"),),
)

This shows declared node and relationship types, a valid identifier, and a passing GraphSchema.validate call on a well-typed extraction.

Limits and gotchas

  • Parameters, not interpolation. Document and chunk IDs, merge endpoints, and import rows must pass as statement parameters. Tests assert attacker-shaped IDs do not appear raw in Cypher text.
  • Identifier gate. Only simple [A-Za-z_][A-Za-z0-9_]* names are admitted for labels, types, and plan columns wired into statements.
  • Schema fail-fast. Unknown labels, undeclared properties, reversed relationship endpoints, and duplicate entity IDs raise ValueError on GraphSchema.validate.
  • Chunk embeddings. Chunks require nonempty text, finite embeddings, and a nonzero vector; ChunkNode rejects all-zero vectors.
  • Import plans. Exactly one of label or relationship must be set; relationship CSV plans require source_label and target_label.
  • Priming budgets. prime prefers lexical matches over vector neighbours, deduplicates by entity id, and truncates when max_candidates or max_tokens (counted with your count_tokens callable, including separators) is exceeded. Unmatched lexical entities are excluded when only lexical evidence would apply.
  • Extraction provenance. entity_statements requires every relationship endpoint to appear in the response entities. ExtractionRun.identity fingerprints prompt version, model name, and schema digest, and does not include the run id.
  • Resolution is conservative. resolution_candidates returns scored id pairs with review true; it does not merge those pairs. merge_statement returns an audit read of keep and drop properties and labels; a native writer performs the merge. Shared surnames alone cap similarity for Person. Optional digit_guard prevents matching names whose digit runs differ. Large entity sets must respect max_pairs.
  • Retrieval bounds. EntityExpansion requires an explicit positive weight per allowed relationship type. Path patterns must chain connected hops (at most four). Walk simulation caps hops and triple counts; order of input relationships does not change bounded_walk results.
  • Topology text. Facts per entity are sorted and capped; excess facts set truncated on TopologyText. Embedding the text is the caller’s job.
  • Evaluation records. ReferenceQuestion requires either a reference string or a ground-truth Query. HarnessResult scores must lie in [0, 5]. reach_sweep reports reachability only, not answer quality.
  • No root re-exports. Import the submodule you need; do not expect names on recohut_kit.graphs itself.

Verification

The example checks schema rendering and validates extraction records against the declared types. See Verify the examples.

How is this page?

Last updated on