Skip to content

Python API

Everything on this page is importable from the top-level kgeval package, except the schema types, which are in kgeval.schema, and Reference, which is in kgeval.reference.

import kgeval
from neo4j import GraphDatabase

with GraphDatabase.driver("<uri>", auth=("<username>", "<password>")) as driver:
    graph = kgeval.Neo4jSource(driver).load()

report = kgeval.evaluate(
    graph,
    schema=kgeval.load_schema("schema.yaml"),
    ground_truth=kgeval.load_ground_truth("ground_truth.yaml"),
    model=kgeval.Model("<model>"),
)

report["entity_uniqueness"].findings  # each with .message, .subject, and its element IDs
report.passed  # False when a metric misses its threshold

Evaluation

evaluate

evaluate(
    graph: Graph,
    metrics: Iterable[Metric] | None = None,
    *,
    schema: GraphSchema | None = None,
    ground_truth: GroundTruth | None = None,
    questions: QuestionSet | None = None,
    retrievals: Retrievals | None = None,
    model: Model | None = None,
    layout: Layout | None = None,
    metadata: Mapping[str, str] | None = None,
) -> Report

Evaluate a graph with the given metrics, or every metric whose inputs are given.

A metric that raises a KgevalError while it runs is reported as skipped, with the error as its reason, and the other metrics still run.

Parameters:

Name Type Description Default
graph Graph

The snapshot to evaluate.

required
metrics Iterable[Metric] | None

The metrics to run; every built-in metric whose inputs are given when omitted.

None
schema GraphSchema | None

A graph schema.

None
ground_truth GroundTruth | None

A ground truth.

None
questions QuestionSet | None

Test questions.

None
retrievals Retrievals | None

What a retriever returned for each test question.

None
model Model | None

The model that metrics ask when rules cannot decide.

None
layout Layout | None

How to read the graph; detected from its labels when omitted.

None
metadata Mapping[str, str] | None

Describes the run, such as the chunk size or prompt that built the graph; the report records it, and compare shows where two runs differ.

None

Returns:

Type Description
Report

A report with one result per metric, in the order given.

Raises:

Type Description
InputError

If two metrics share a name, a given metric needs an input that is not given, or retrievals are given without their test questions.

assert_passes

assert_passes(
    graph: Graph,
    metrics: Iterable[Metric],
    *,
    schema: GraphSchema | None = None,
    ground_truth: GroundTruth | None = None,
    questions: QuestionSet | None = None,
    retrievals: Retrievals | None = None,
    model: Model | None = None,
    layout: Layout | None = None,
) -> Report

Evaluate a graph and fail unless every metric meets its threshold.

Parameters:

Name Type Description Default
graph Graph

The snapshot to evaluate.

required
metrics Iterable[Metric]

The metrics to check, each with a threshold.

required
schema GraphSchema | None

A graph schema.

None
ground_truth GroundTruth | None

A ground truth.

None
questions QuestionSet | None

Test questions.

None
retrievals Retrievals | None

What a retriever returned for each test question.

None
model Model | None

The model that metrics ask when rules cannot decide.

None
layout Layout | None

How to read the graph; detected from its labels when omitted.

None

Returns:

Type Description
Report

The report.

Raises:

Type Description
InputError

If there are no metrics, a metric has no threshold or needs an input that is not given, or two metrics share a name.

AssertionError

If a metric misses its threshold.

load_suite

load_suite(path: str | Path) -> list[Metric]

Load the metrics that a suite file lists, with their settings.

A suite maps metric names to settings, which are the metrics' parameters, such as threshold, sample_size, or k; a built-in metric without settings needs only its name. An entry with a criterion or applies_to setting defines a criterion under its name: an EntityCriterion when applies_to is entities, and a FactCriterion when it is facts. A suite holds no inputs, so one suite serves every graph and model.

Parameters:

Name Type Description Default
path str | Path

The suite file, YAML or JSON.

required

Returns:

Type Description
list[Metric]

The metrics, in the order the suite lists them.

Raises:

Type Description
InputError

If the file cannot be read, names an unknown metric, holds an invalid setting, or defines a criterion under a built-in metric's name.

Reports

Report

Bases: BaseModel

Hold the results of one evaluation and everything needed to reproduce them.

Rerunning the same kgeval version, layout, and metric signatures on a graph with the same fingerprint reproduces every deterministic result. Index a report by metric name to get that metric's result.

Attributes:

Name Type Description
report_format int

The version of the report format; reports without it have format 1, the first.

kgeval_version str

The kgeval version that produced the report.

graph_fingerprint str

Identifies the exact graph content evaluated.

layout Layout

How the graph was read.

summary GraphSummary

Counts of the graph's nodes and relationships.

results tuple[MetricResult, ...]

One result per metric, in evaluation order.

metadata dict[str, str]

Describes the run, such as the chunk size or prompt that built the graph. It annotates the report without changing any result.

passed property

passed: bool

Return whether every metric with a threshold met it.

to_markdown

to_markdown(
    max_findings: int = DEFAULT_MAX_FINDINGS,
) -> str

Render the graph summary, score tables, and findings as Markdown.

Metric names and text taken from the graph are escaped, so they cannot inject Markdown.

Parameters:

Name Type Description Default
max_findings int

How many findings to list per metric; the rest are counted.

DEFAULT_MAX_FINDINGS

Returns:

Type Description
str

The Markdown text.

MetricResult

Bases: BaseModel

Hold one metric's score, the counts behind it, and its findings.

A metric checks each unit of its population, and by default its score is the share of units that passed, (evaluated - failed) / evaluated, so 1.0 is perfect. A metric may define its score otherwise, such as the mean over questions of each question's share, and its docstring then says so. A metric with nothing to evaluate is skipped and has no score.

Attributes:

Name Type Description
metric str

The metric's name.

category MetricCategory

The metric's group in reports.

signature str

The metric's name and every parameter that affects its score.

unit str

The plural noun for what the metric counts.

evaluated int

How many units were checked.

failed int

How many of them failed.

score Annotated[float, Field(ge=0, le=1)] | None

The score from 0 to 1, where 1 is perfect; None when skipped. Defaults to the share of evaluated units that passed.

undecided int

How many sampled units the model gave no usable verdict for, which evaluated leaves out.

threshold float | None

The minimum passing score, if any.

confidence_interval tuple[float, float] | None

A 95% interval for the score when it was estimated from a sample.

findings tuple[Finding, ...]

The defects found, with the element IDs involved.

skip_reason str | None

Why the metric was skipped, when it was.

passed property

passed: bool | None

Return whether the score meets the threshold; None without a threshold.

A skipped metric has no score, so it does not meet a threshold.

Finding

Bases: BaseModel

Describe one defect a metric found, and the exact nodes and relationships involved.

Attributes:

Name Type Description
message str

What is wrong, in plain language. It names elements by content, never by element ID, so the same defect has the same message in every run on the same graph content, even after a rebuild assigns new element IDs.

subject str

The unit at fault, named by content, such as an entity's name and node types. It names neither element IDs nor what is wrong, so it stays the same when a rebuild assigns new IDs, when the defect's details change, and when a kgeval release rewords the message; compare matches findings by it. Defaults to the message.

node_ids tuple[str, ...]

Element IDs of the nodes involved.

relationship_ids tuple[str, ...]

Element IDs of the relationships involved.

about classmethod

about(
    elements: Node
    | Relationship
    | Iterable[Node | Relationship],
    message: str,
    subject: str | None = None,
) -> Finding

Return a finding about one or more nodes and relationships.

Parameters:

Name Type Description Default
elements Node | Relationship | Iterable[Node | Relationship]

The node or relationship at fault, or several of them.

required
message str

What is wrong with them.

required
subject str | None

The unit at fault, named by content; the message when omitted.

None

Returns:

Type Description
Finding

The finding, with the IDs of the given nodes and of the given relationships'

Finding

sources and targets among its node IDs, and the IDs of the given

Finding

relationships among its relationship IDs, each once, in the order given.

GraphSummary

Bases: BaseModel

Count a graph's nodes and relationships, in total and by role.

Attributes:

Name Type Description
nodes int

All nodes.

relationships int

All relationships.

entities int

Entities.

lexical_nodes int

Lexical nodes.

community_nodes int

Community nodes.

other_nodes int

Nodes the layout ignores.

facts int

Relationships between two entities that are still current.

expired_facts int

Relationships between two entities that the layout marks as no longer current.

provenance_relationships int

Relationships between an entity and a lexical node.

labels dict[str, int]

Node count per label.

relationship_types dict[str, int]

Relationship count per relationship type.

of classmethod

of(graph: GraphView) -> GraphSummary

Summarize a graph.

Parameters:

Name Type Description Default
graph GraphView

The graph to summarize.

required

Returns:

Type Description
GraphSummary

The summary, with label and type counts sorted by name.

compare

compare(
    base: Report, head: Report, *, max_drop: float = 0.0
) -> Comparison

Compare a head report with a base report, metric by metric.

Results pair up by metric name. Findings of deterministic metrics pair up by subject, which names the unit at fault by content, so the same defect matches in any run on the same content, even of a rebuilt graph with new element IDs; repeated subjects pair up one by one. Findings of model metrics are not compared, since each run asks about its own sample and verdicts vary.

Parameters:

Name Type Description Default
base Report

The report to compare against, such as a baseline.

required
head Report

The report to check against it.

required
max_drop float

The largest score drop, from 0 to 1, that is not a regression, which absorbs the noise of rebuilding a graph with an LLM.

0.0

Returns:

Type Description
Comparison

The comparison.

Raises:

Type Description
InputError

If max_drop is not between 0 and 1.

Comparison

Bases: BaseModel

Hold the comparison of a head report with a base report, metric by metric.

Attributes:

Name Type Description
base Report

The report compared against, such as a baseline.

head Report

The report checked against it.

changes tuple[MetricChange, ...]

One change per metric that either report ran, with the head's metrics in its order, then the others of the base.

regressed property

regressed: bool

Return whether any metric scores worse or is no longer scored.

trend_counts property

trend_counts: dict[Trend, int]

Count the metrics by how their score moved, leaving out those without a score change.

Returns:

Type Description
dict[Trend, int]

The count of every trend, in the order Trend lists them.

to_markdown

to_markdown(
    max_findings: int = DEFAULT_MAX_FINDINGS,
) -> str

Render both graphs, the score changes, and the changed findings as Markdown.

Metric names and text taken from the graph are escaped, so they cannot inject Markdown.

Parameters:

Name Type Description Default
max_findings int

How many new and resolved findings to list per metric; the rest are counted.

DEFAULT_MAX_FINDINGS

Returns:

Type Description
str

The Markdown text.

MetricChange

Bases: BaseModel

Pair one metric's results in two reports, with the findings that differ.

The two results are comparable when both reports ran the metric with the same signature; results under different parameters, such as another ground truth, measure different things, so their scores and findings are not compared.

Attributes:

Name Type Description
metric str

The metric's name.

category MetricCategory

The metric's group in reports.

base MetricResult | None

Its result in the base report, or None when the base did not run it.

head MetricResult | None

Its result in the head report, or None when the head did not run it.

new_findings tuple[Finding, ...]

The head's findings whose subject the base lacks, all of them when the base did not run the metric. Always empty for model metrics and for results that are not comparable.

resolved_findings tuple[Finding, ...]

The base's findings whose subject the head lacks, when the head scored the metric. Always empty for model metrics and for results that are not comparable.

max_drop float

The largest score drop, from 0 to 1, that is not a regression.

comparable property

comparable: bool

Return whether both reports ran the metric with the same parameters.

score_change property

score_change: float | None

Return the head's score minus the base's, or None without two comparable scores.

change_interval property

change_interval: tuple[float, float] | None

Return a 95% interval for score_change when either score was estimated from a sample.

The interval is Newcombe's hybrid score interval, built from each score's interval, with a score that has none counting as exact. It treats the two samples as independent, which is conservative when they share units.

Returns:

Type Description
tuple[float, float] | None

The interval, or None when there is no score change or neither score

tuple[float, float] | None

was estimated from a sample.

trend property

trend: Trend | None

Return how the score moved, or None without a score change.

regressed property

regressed: bool

Return whether the head scores worse than the base, or no longer scores the metric.

The head scores worse when the trend is worsened, so a sampled score must drop by more than sampling explains, and the score dropped by more than max_drop. For a metric whose findings are compared, the head must also have a new finding or more failed units, since a drop that a smaller population alone explains, as when removing duplicate facts that passed, adds no defect. New findings without a lower score are no regression either, since a rebuild that extracts different entities and facts fixes some defects as it adds others.

Trend

Bases: StrEnum

Name how a metric's score moved from the base report to the head report.

Attributes:

Name Type Description
IMPROVED

The head scores higher.

WORSENED

The head scores lower.

UNCHANGED

Both score the same.

INCONCLUSIVE

The scores differ, but the 95% interval of the change includes zero, so sampling alone can explain the difference.

Graphs

Neo4jSource

Neo4jSource(driver: Driver, database: str | None = None)

Load graph snapshots from a Neo4j database.

Snapshots keep only the length of each non-empty float-list property, which holds an embedding, and leave out vector and byte-array values and temporal values with years outside 1 to 9999, which Python cannot represent. Requires Neo4j 5.10 or later, the first release whose type predicates accept lists.

Parameters:

Name Type Description Default
driver Driver

An open driver; the caller owns it and closes it.

required
database str | None

The database to read; the server's default database when omitted.

None

load

load() -> Graph

Read every node and relationship into a graph snapshot.

Nodes and relationships are read in one transaction. Relationships created between the two reads, whose nodes the snapshot lacks, are dropped with a warning.

Returns:

Type Description
Graph

The snapshot.

Raises:

Type Description
SourceError

If the database cannot be read.

load_graph

load_graph(path: str | Path) -> Graph

Load a graph snapshot from a JSON file.

Parameters:

Name Type Description Default
path str | Path

The snapshot file, as kgeval snapshot or Graph.model_dump_json writes it.

required

Returns:

Type Description
Graph

The snapshot.

Raises:

Type Description
InputError

If the file cannot be read or holds no valid snapshot.

Graph

Bases: BaseModel

Hold an immutable snapshot of a property graph.

Nodes and relationships are kept sorted by ID, so every computation over a graph is deterministic whatever order its source returned them in. Construction fails on duplicate IDs and on relationships whose source or target node is missing.

Attributes:

Name Type Description
snapshot_format int

The version of the snapshot format.

nodes tuple[Node, ...]

Its nodes, sorted by ID.

relationships tuple[Relationship, ...]

Its relationships, sorted by ID.

fingerprint

fingerprint() -> str

Return a digest that changes when any element, property, or embedding dimension does.

Returns:

Type Description
str

The graph's content_digest, as "sha256:<hex>".

Node

Bases: BaseModel

Represent a node by its element ID, labels, and properties.

Attributes:

Name Type Description
id str

The node's element ID.

labels tuple[str, ...]

Its labels.

properties dict[str, PropertyValue]

Its properties, except embeddings.

embedding_dimensions EmbeddingDimensions

The dimension of each of its embeddings, whose values are not kept.

Relationship

Bases: BaseModel

Represent a relationship, which points from its source node to its target node.

Attributes:

Name Type Description
id str

The relationship's element ID.

type str

Its relationship type.

source_id str

The element ID of its source node.

target_id str

The element ID of its target node.

properties dict[str, PropertyValue]

Its properties, except embeddings.

embedding_dimensions EmbeddingDimensions

The dimension of each of its embeddings, whose values are not kept.

node_ids property

node_ids: tuple[str, ...]

Return the source and target node IDs, once each, so a self-loop yields one ID.

GraphView

GraphView(graph: Graph, layout: Layout | None = None)

Index a graph by role so metrics can ask about entities, facts, and chunks.

A fact is a relationship whose source and target nodes are both entities, unless it has one of the layout's expired keys, which makes it an expired fact that metrics do not evaluate. A provenance relationship joins an entity and a lexical node, in either direction; that lexical node is a chunk the entity is grounded in, and chunk_ids returns them. All other relationships are neither facts nor provenance relationships.

Parameters:

Name Type Description Default
graph Graph

The graph to index.

required
layout Layout | None

How to read the graph; detected from its labels when omitted.

None

Attributes:

Name Type Description
graph

The underlying graph.

layout

The layout in use.

entities

Entity nodes, sorted by ID.

lexical_nodes

Lexical nodes, sorted by ID.

chunks

Lexical nodes that share a lexical label with a node some entity is grounded in, sorted by ID. In a lexical graph of documents and chunks, these are every chunk, whether or not it grounds an entity, and no document.

community_nodes

Community nodes, sorted by ID.

facts

Facts, sorted by ID.

expired_facts

Relationships between entities that the layout's expired keys mark as no longer current, sorted by ID.

provenance

Provenance relationships, sorted by ID.

node

node(node_id: str) -> Node

Return the node with the given ID.

Parameters:

Name Type Description Default
node_id str

The node's element ID.

required

Returns:

Type Description
Node

The node.

Raises:

Type Description
KeyError

If the graph has no such node.

role

role(node: Node) -> Role

Return the role a node plays in this graph.

Parameters:

Name Type Description Default
node Node

A node of this graph.

required

Returns:

Type Description
Role

The node's role.

chunk_ids

chunk_ids(entity_id: str) -> frozenset[str]

Return the IDs of the chunks an entity is grounded in.

Parameters:

Name Type Description Default
entity_id str

The entity's element ID.

required

Returns:

Type Description
frozenset[str]

The chunk IDs; empty when the entity has no provenance relationship.

fact_chunk_ids

fact_chunk_ids(fact: Relationship) -> frozenset[str]

Return the IDs of the chunks that ground both of a fact's entities.

Parameters:

Name Type Description Default
fact Relationship

The fact.

required

Returns:

Type Description
frozenset[str]

The chunk IDs; empty when no chunk grounds both its source and its target.

chunks_of

chunks_of(
    documents: Iterable[Mapping[str, str]],
) -> frozenset[str]

Return the IDs of the chunks that make up the selected documents.

A lexical node is selected when it has every property of one selector, with the selector's value. The chunks are the selected chunks, and the chunks that a relationship joins to a selected lexical node that is not a chunk, such as a document node.

Parameters:

Name Type Description Default
documents Iterable[Mapping[str, str]]

The selectors, each mapping property keys to values.

required

Returns:

Type Description
frozenset[str]

The chunk IDs.

name

name(node: Node) -> str | None

Return the first non-blank string a node holds under the layout's name keys.

Parameters:

Name Type Description Default
node Node

The node to name.

required

Returns:

Type Description
str | None

The stripped name, or None when the node has none.

text

text(node: Node) -> str | None

Return the first non-blank string a node holds under the layout's text keys.

Parameters:

Name Type Description Default
node Node

The node, usually a lexical one.

required

Returns:

Type Description
str | None

The stripped text, or None when the node has none.

relationship_type

relationship_type(relationship: Relationship) -> str

Return a relationship's type, read from the layout's type keys when it has one there.

Parameters:

Name Type Description Default
relationship Relationship

The relationship, usually a fact.

required

Returns:

Type Description
str

The first non-blank string among the layout's type keys, stripped, or else

str

the relationship's own type.

description

description(element: Node | Relationship) -> str | None

Return an entity's or fact's description, read from the layout's description keys.

Parameters:

Name Type Description Default
element Node | Relationship

The node or relationship, usually an entity or a fact.

required

Returns:

Type Description
str | None

The first non-blank string among the layout's description keys, stripped,

str | None

or None when the element has none.

describe

describe(element: Node | Relationship) -> str

Return a short human-readable reference to a node or relationship.

References name elements by content, never by element ID, so they are the same in every run on the same graph content.

Parameters:

Name Type Description Default
element Node | Relationship

The node or relationship to describe.

required

Returns:

Type Description
str

A node's quoted name, else a quoted preview of its text, else unnamed,

str

followed by its node types in parentheses. A relationship's source and

str

target nodes, each described as a node, joined by its relationship type in

str

Cypher arrow notation.

subject

subject(element: Node | Relationship) -> str

Return a reference that names a node or relationship by its full content.

It reads as describe does, but never shortens a name or text, so that the findings about different elements have different subjects, which compare matches findings by.

Parameters:

Name Type Description Default
element Node | Relationship

The node or relationship to name.

required

Returns:

Type Description
str

The reference.

Layout

Bases: BaseModel

Describe which labels give each role, and which properties hold names, text, and types.

A node's role is decided by its labels. A lexical label makes it a lexical node, and otherwise a community label makes it a community node. When base_labels is empty, every remaining node is an entity; otherwise only nodes with a base label are, and the rest are ignored as Role.OTHER.

Attributes:

Name Type Description
lexical_labels frozenset[str]

Labels of lexical nodes.

community_labels frozenset[str]

Labels of community nodes.

base_labels frozenset[str]

Labels that mark a node as an entity without naming its node type.

name_keys tuple[str, ...]

Property keys tried, in order, for a node's name.

text_keys tuple[str, ...]

Property keys tried, in order, for a lexical node's text.

type_keys tuple[str, ...]

Property keys tried, in order, for a fact's relationship type, for builders that store every fact under one generic relationship type, such as Graphiti's RELATES_TO, which keeps the type in name. A fact without a non-blank string under any of them keeps its own relationship type.

description_keys tuple[str, ...]

Property keys tried, in order, for an entity's or fact's description, such as Microsoft GraphRAG's description and Graphiti's fact, the statement a fact makes in words, and summary, its description of an entity.

expired_keys tuple[str, ...]

Property keys that mark a relationship between entities as no longer current when it has any of them, such as Graphiti's expired_at, set on facts that later information invalidated. Such relationships are the graph's history, not its facts.

detect classmethod

detect(
    graph: Graph, overrides: Layout | None = None
) -> Layout

Return the layout implied by the well-known labels and properties of a graph.

Parameters:

Name Type Description Default
graph Graph

The graph to inspect.

required
overrides Layout | None

A layout whose explicitly set fields replace the detected ones; its text and name keys also guide detection.

None

Returns:

Type Description
Layout

A layout using whichever of LEXICAL_LABELS, COMMUNITY_LABELS, and

Layout

BASE_LABELS the graph shows, as their docstrings describe, with the

Layout

default text and description keys. In a graph with Graphiti's Episodic

Layout

label, Entity is a base label and Community a community label too,

Layout

the type keys are name, where Graphiti keeps the relationship types of

Layout

its RELATES_TO facts, and the expired keys are expired_at. The name

Layout

keys are name and title, followed by id when the graph has the

Layout

__Entity__ label or no entity has a name or title, since LLM Graph

Layout

Builder and LangChain store entity names in id.

role

role(node: Node) -> Role

Return the role a node plays under this layout.

Parameters:

Name Type Description Default
node Node

The node to classify.

required

Returns:

Type Description
Role

The node's role.

node_types

node_types(node: Node) -> tuple[str, ...]

Return a node's labels other than base labels, which are its node types.

Parameters:

Name Type Description Default
node Node

The node whose labels to filter.

required

Returns:

Type Description
tuple[str, ...]

The node's labels minus base_labels, sorted.

Role

Bases: StrEnum

Name the part a node plays in a knowledge graph.

PropertyValue module-attribute

PropertyValue: TypeAlias = Scalar | list[Scalar]

Hold a property's value, a scalar or a list of scalars.

Point

Bases: BaseModel

Represent a Neo4j spatial point.

Duration

Bases: BaseModel

Represent a Neo4j duration, which keeps calendar months apart from exact time.

value_type

value_type(value: PropertyValue) -> PropertyTypeName

Return the Neo4j type name of a property value.

Parameters:

Name Type Description Default
value PropertyValue

The value to classify.

required

Returns:

Type Description
PropertyTypeName

The Neo4j type name; "LIST" for every list.

Graph schemas

load_schema

load_schema(path: str | Path) -> GraphSchema

Load a graph schema from a YAML or JSON file.

Parameters:

Name Type Description Default
path str | Path

The schema file.

required

Returns:

Type Description
GraphSchema

The schema.

Raises:

Type Description
InputError

If the file cannot be read or is not a valid schema.

infer_schema

infer_schema(graph: GraphView) -> GraphSchema

Return the graph schema a graph's entities and facts follow today.

The result is a starting point to review and tighten, not a statement of what is correct. Every node type of an entity and every relationship type of a fact is declared, ordered from most to least used, with every property typed by its most common value type. Every observed (source node type, relationship type, target node type) combination becomes a pattern, also ordered by use, so rare patterns, which are often extraction mistakes, come last. Every property that all entities of a node type, or all facts of a relationship type, have gets an EXISTENCE constraint. Entities without a node type are left out.

Parameters:

Name Type Description Default
graph GraphView

The graph to describe.

required

Returns:

Type Description
GraphSchema

The inferred graph schema, closed to additional properties, and to additional

GraphSchema

node types, relationship types, and patterns when it declares some.

GraphSchema

Bases: BaseModel

Declare which node types, relationship types, and patterns a graph may contain.

Each additional_* switch defaults to true exactly when the matching list is empty, as in neo4j-graphrag, so declaring node types closes the set of node types unless additional_node_types says otherwise.

Attributes:

Name Type Description
node_types tuple[NodeType, ...]

The declared node types.

relationship_types tuple[RelationshipType, ...]

The declared relationship types.

patterns tuple[Pattern, ...]

The allowed (source, relationship, target) combinations.

constraints tuple[Constraint, ...]

Existence, uniqueness, and key constraints.

additional_node_types bool

Whether undeclared node labels are allowed.

additional_relationship_types bool

Whether undeclared relationship types are allowed.

additional_patterns bool

Whether undeclared patterns are allowed.

to_yaml

to_yaml() -> str

Return the schema as YAML that load_schema reads back.

Returns:

Type Description
str

The YAML text, leaving out fields equal to a fixed default.

digest

digest() -> str

Return a short digest that changes whenever the schema changes.

Returns:

Type Description
str

The first 12 hex digits of the schema's content digest.

NodeType

Bases: _ElementType

Declare a node type by label, with its properties.

A bare string is accepted as a node type with that label.

Attributes:

Name Type Description
label str

The node label.

description str

What the type means.

properties tuple[PropertyType, ...]

The declared properties.

additional_properties bool

Whether undeclared properties are allowed; defaults to true exactly when no properties are declared.

RelationshipType

Bases: _ElementType

Declare a relationship type by label, with its properties.

A bare string is accepted as a relationship type with that label.

Attributes:

Name Type Description
label str

The relationship type.

description str

What the type means.

properties tuple[PropertyType, ...]

The declared properties.

additional_properties bool

Whether undeclared properties are allowed; defaults to true exactly when no properties are declared.

max_targets int | None

The most distinct entities that one entity may relate to with this type, such as 1 for BORN_IN; unlimited when omitted. More targets contradict each other. This is a kgeval extension of neo4j-graphrag's format.

PropertyType

Bases: BaseModel

Declare a property by name and Neo4j type.

Attributes:

Name Type Description
name str

The property key.

type PropertyTypeName

The Neo4j type its values must have.

description str

What the property means.

required bool

Whether every element of the type must have it. neo4j-graphrag deprecates this in favor of EXISTENCE constraints; both are honored.

Pattern

Bases: BaseModel

Allow a relationship type between a source and a target node type.

Accepts and serializes as a [source, relationship, target] list, and also accepts neo4j-graphrag's mapping form.

Attributes:

Name Type Description
source str

The label of the source node type.

relationship str

The relationship type.

target str

The label of the target node type.

Constraint

Bases: BaseModel

Declare a uniqueness, existence, or key constraint on a node or relationship type.

EXISTENCE requires the properties to be present, UNIQUENESS requires their combined values to be unique among elements that have them all, and KEY requires both.

Attributes:

Name Type Description
type Literal['UNIQUENESS', 'EXISTENCE', 'KEY']

The constraint type, one of EXISTENCE, UNIQUENESS, and KEY.

property_names tuple[str, ...]

The constrained properties.

node_type str | None

The label of the constrained node type, when it constrains entities.

relationship_type str | None

The constrained relationship type, when it constrains facts.

Ground truths and questions

load_ground_truth

load_ground_truth(path: str | Path) -> GroundTruth

Load a ground truth from a YAML or JSON file.

The file holds either a list of ground truth facts or a mapping with the fields of GroundTruth. Each ground truth fact is a [source entity name, relationship type, target entity name] list, such as [Lee Kuan Yew, BORN_IN, Singapore].

Parameters:

Name Type Description Default
path str | Path

The ground truth file.

required

Returns:

Type Description
GroundTruth

The ground truth.

Raises:

Type Description
InputError

If the file cannot be read or holds no valid ground truth, such as one without facts, with a part of a ground truth fact that has no letter or digit, or with an alias that conflicts with a ground truth name.

GroundTruth

Bases: Reference

Hold the facts a graph should contain, and the variants under which they match.

Facts match as Reference describes. Validation also accepts a bare list of ground truth facts, the format of ground truths that need none of the other fields.

Attributes:

Name Type Description
documents tuple[DocumentSelector, ...]

Selectors of the lexical nodes of the documents the ground truth covers. When set, the ground truth lists every fact these documents state, and the ground truth metrics compare only the facts and entities grounded in the documents' chunks; when empty, it covers every chunk.

facts tuple[NamedFact, ...]

The ground truth facts.

named_facts

named_facts() -> Iterable[NamedFact]

Return the ground truth facts.

Returns:

Type Description
Iterable[NamedFact]

The facts.

named_entities

named_entities() -> Iterable[str]

Return the source and target names of every ground truth fact.

Returns:

Type Description
Iterable[str]

The entity names.

load_questions

load_questions(path: str | Path) -> QuestionSet

Load test questions from a YAML or JSON file.

The file holds either a list of questions or a mapping with the fields of QuestionSet. Each question has a text and at least one supporting fact or entity.

Parameters:

Name Type Description Default
path str | Path

The questions file.

required

Returns:

Type Description
QuestionSet

The question set.

Raises:

Type Description
InputError

If the file cannot be read or holds no valid question set.

QuestionSet

Bases: Reference

Hold test questions and the variants under which their supporting facts match.

Supporting facts and entities match the graph's as Reference describes. Validation also accepts a bare list of questions, the format of question sets that need none of the other fields.

Attributes:

Name Type Description
questions tuple[Question, ...]

The questions, each with a distinct text.

named_facts

named_facts() -> Iterable[NamedFact]

Return the supporting facts of every question.

Returns:

Type Description
Iterable[NamedFact]

The facts.

named_entities

named_entities() -> Iterable[str]

Return the supporting entities of every question, its supporting facts' included.

Returns:

Type Description
Iterable[str]

The entity names.

support

support(graph: GraphView) -> list[list[Support]]

Match every question's supporting facts and entities with the graph's.

Parameters:

Name Type Description Default
graph GraphView

The graph to match against.

required

Returns:

Type Description
list[list[Support]]

One list per question, in order, of its supporting facts, then its

list[list[Support]]

supporting entities, each with the graph elements that match it, if any.

Question

Bases: BaseModel

Pair a question with the facts and entities that a correct answer rests on.

Attributes:

Name Type Description
text Name

The question in natural language.

supporting_facts tuple[NamedFact, ...]

The facts the answer needs, each as [source entity name, relationship type, target entity name].

supporting_entities tuple[Name, ...]

The entities the answer needs beyond those of its facts, such as the entity whose property a question asks for.

Reference

Bases: BaseModel, ABC

Hold the variants under which a reference's entities and facts match a graph's.

Entity names match under normalize_name and relationship types under normalize_type. Aliases add the other names and relationship types the graph may use for an entity or relationship type of the reference; an alias may not be a name of the reference itself, nor stand for two.

Attributes:

Name Type Description
aliases dict[Name, tuple[Name, ...]]

Maps an entity name of the reference to other names the graph may give the entity.

relationship_type_aliases dict[Name, tuple[Name, ...]]

Maps a relationship type of the reference to other relationship types the graph may use for it.

symmetric_relationship_types tuple[Name, ...]

Relationship types whose facts match in either direction, such as MARRIED.

named_facts abstractmethod

named_facts() -> Iterable[NamedFact]

Return every fact the reference names.

Returns:

Type Description
Iterable[NamedFact]

The facts.

named_entities abstractmethod

named_entities() -> Iterable[str]

Return every entity name the reference uses, its facts' included.

Returns:

Type Description
Iterable[str]

The names.

digest

digest() -> str

Return a short digest that changes whenever the reference changes.

Returns:

Type Description
str

The first 12 hex digits of the reference's content digest.

entity_key

entity_key(name: str) -> str

Return the key under which an entity name matches the reference's names.

Parameters:

Name Type Description Default
name str

An entity name, from the graph or the reference.

required

Returns:

Type Description
str

The key normalize_name returns, or the key of the name it is an

str

alias of.

fact_key

fact_key(
    source: str, relationship_type: str, target: str
) -> tuple[str, str, str]

Return the key under which a fact matches the reference's facts.

Parameters:

Name Type Description Default
source str

The name of its source entity.

required
relationship_type str

Its relationship type.

required
target str

The name of its target entity.

required

Returns:

Type Description
str

The keys of its source name, relationship type, and target name, the names

str

in sorted order when the relationship type is symmetric.

graph_fact_key

graph_fact_key(
    graph: GraphView, fact: Relationship
) -> tuple[str, str, str]

Return the key of a fact of the graph, read through the graph's layout.

Parameters:

Name Type Description Default
graph GraphView

The graph the fact belongs to.

required
fact Relationship

The fact.

required

Returns:

Type Description
str

The fact's key, as fact_key returns it; a part is empty when the fact's

str

entity has no name, so the fact cannot match.

Retrievals

retrieve

retrieve(
    questions: QuestionSet, retriever: Retriever
) -> Retrievals

Ask a retriever every question and collect the element IDs of what it returns.

Parameters:

Name Type Description Default
questions QuestionSet

The questions to ask.

required
retriever Retriever

Called with each question's text; returns, in rank order, element IDs, or nodes, relationships, and paths as the Neo4j driver returns them, alone or within records and lists.

required

Returns:

Type Description
Retrievals

The retrievals, with each element ID once, at its first rank.

Raises:

Type Description
InputError

If the retriever returns anything else, such as a property value.

load_retrievals

load_retrievals(path: str | Path) -> Retrievals

Load retrievals from a YAML or JSON mapping of question text to element IDs.

A JSON file looks like {"Who founded Acme?": ["4:9c1e:0", "5:9c1e:2"]}.

Parameters:

Name Type Description Default
path str | Path

The retrievals file.

required

Returns:

Type Description
Retrievals

The retrievals, with each question's element IDs in the file's order, each once,

Retrievals

at its first rank.

Raises:

Type Description
InputError

If the file cannot be read or holds no such mapping.

Retriever module-attribute

Retriever: TypeAlias = Callable[[str], Iterable[object]]

Return a question's element IDs, or driver nodes, relationships, and paths.

Retrievals module-attribute

Retrievals: TypeAlias = Mapping[str, tuple[str, ...]]

Map each question's text to the element IDs retrieved for it, in rank order and each once.

Models

Model

Model(
    model: str,
    *,
    base_url: str | None = None,
    api_key: str | None = None,
    name: str | None = None,
    cache: str | Path | None = None,
    **settings: Any,
)

Get verdicts on evaluation prompts from any model that LiteLLM supports.

Each request asks for the verdict's JSON schema as structured output. Requests that hit a rate limit or a server error are retried for up to about a minute.

Parameters:

Name Type Description Default
model str

The model as LiteLLM names it, provider/model, such as openai/gpt-5-mini.

required
base_url str | None

The server's API base URL; the provider's when omitted.

None
api_key str | None

The API key; read from the provider's environment variable when omitted.

None
name str | None

Identifies the model in metric signatures and the cache; model when omitted. The settings follow it, since they change the verdicts.

None
cache str | Path | None

A SQLite file that keeps every verdict, so reruns reuse them; created when missing. A verdict is keyed by the model's name, the verdict's JSON schema, and the prompt. Delete the file to ask again.

None
**settings Any

Arguments for every request, such as temperature=0 or reasoning_effort="low".

{}

Raises:

Type Description
ModelError

If LiteLLM supports no provider of that name, the provider's API key or base URL is required but not set, or the cache file cannot be opened.

ask

ask(prompt: str, output_type: type[_OutputT]) -> _OutputT

Return the model's verdict on a prompt, from the cache when it has one.

Parameters:

Name Type Description Default
prompt str

The question for the model.

required
output_type type[_OutputT]

The Pydantic model class the verdict must validate against.

required

Returns:

Type Description
_OutputT

The validated verdict.

Raises:

Type Description
VerdictError

If the server rejects the request as a bad one, as when the prompt exceeds the context window, or the verdict does not validate.

ModelError

If the request fails otherwise, or the cache cannot be used.

Metrics

Metric

Bases: BaseModel, ABC

Measure one quality of a knowledge graph.

A metric holds its parameters, such as its threshold. The inputs it needs, such as a ground truth or a model, come with each evaluation. To add a metric, subclass this, set name, category, unit, and the needs it reads from the inputs, declare parameters as fields, and implement evaluate, building its return value with result or skip. Override signature when parameters or inputs change the score. Give every finding a subject that names its unit by content, so compare matches it across runs.

Attributes:

Name Type Description
threshold float | None

The minimum passing score; without one the result is informational.

evaluate abstractmethod

evaluate(graph: GraphView, inputs: Inputs) -> MetricResult

Evaluate this metric on a graph.

Parameters:

Name Type Description Default
graph GraphView

The graph to evaluate.

required
inputs Inputs

The inputs, of which the metric reads those it needs.

required

Returns:

Type Description
MetricResult

The metric's result.

Raises:

Type Description
InputError

If an input the metric needs is not given.

signature

signature(inputs: Inputs) -> str

Return this metric's name and every parameter and input that changes its score.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric is evaluated with.

required

Returns:

Type Description
str

The name alone, unless a subclass adds its parameters and inputs.

require

require(value: _T | None, name: InputName) -> _T

Return an input this metric needs, after checking that it was given.

Parameters:

Name Type Description Default
value _T | None

The input, as Inputs holds it.

required
name InputName

The input's name.

required

Returns:

Type Description
_T

The input.

Raises:

Type Description
InputError

If the input was not given.

result

result(
    inputs: Inputs,
    evaluated: int,
    failed: int,
    findings: Iterable[Finding] = (),
    confidence_interval: tuple[float, float] | None = None,
    *,
    score: float | None = None,
    undecided: int = 0,
) -> MetricResult

Build this metric's result, or a skipped one when nothing was evaluated.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric was evaluated with.

required
evaluated int

How many units were checked.

required
failed int

How many of them failed.

required
findings Iterable[Finding]

The defects found.

()
confidence_interval tuple[float, float] | None

A 95% interval for a score estimated from a sample.

None
score float | None

The score, for a metric that does not score the share of evaluated units that passed; that share when omitted.

None
undecided int

How many sampled units the model gave no usable verdict for.

0

Returns:

Type Description
MetricResult

The result.

skip

skip(inputs: Inputs, reason: str) -> MetricResult

Build a result recording that this metric does not apply to the graph.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric was evaluated with.

required
reason str

Why the metric does not apply.

required

Returns:

Type Description
MetricResult

The skipped result.

Inputs dataclass

Inputs(
    schema: GraphSchema | None = None,
    ground_truth: GroundTruth | None = None,
    questions: QuestionSet | None = None,
    retrievals: Retrievals | None = None,
    model: Model | None = None,
)

Hold what metrics use besides the graph, each None when not given.

Attributes:

Name Type Description
schema GraphSchema | None

A graph schema.

ground_truth GroundTruth | None

A ground truth.

questions QuestionSet | None

Test questions.

retrievals Retrievals | None

What a retriever returned for each test question.

model Model | None

The model that metrics ask when rules cannot decide.

Raises:

Type Description
InputError

If retrievals are given without their test questions.

missing

missing(needs: Iterable[InputName]) -> list[InputName]

Return the inputs among needs that are not given.

Parameters:

Name Type Description Default
needs Iterable[InputName]

The inputs a metric needs.

required

Returns:

Type Description
list[InputName]

The inputs not given, in the order of needs.

InputName module-attribute

InputName: TypeAlias = Literal[
    "schema",
    "ground_truth",
    "questions",
    "retrievals",
    "model",
]

Name an input that a metric needs, as Inputs and evaluate call it.

MetricCategory

Bases: StrEnum

Group metrics in reports by what they measure and how they decide.

The first four categories evaluate the graph; the last evaluates retrieval from it. A metric's needs name the inputs it reads.

Attributes:

Name Type Description
INTRINSIC

Deterministic metrics of the graph alone.

SCHEMA

Deterministic metrics of how the graph matches a graph schema.

REFERENCE

Deterministic metrics that compare the graph with a ground truth or test questions.

MODEL

Metrics that ask a model, so not fully deterministic.

RETRIEVAL

Deterministic metrics of what a retriever returned for test questions.

ModelMetric

Bases: Metric

Decide, with a model, a quality that rules cannot.

LLM verdicts are not fully deterministic, so the signature names the model.

Attributes:

Name Type Description
concurrency int

How many requests to the model run at once.

signature

signature(inputs: Inputs) -> str

Return the metric name with the model's name.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric is evaluated with.

required

Returns:

Type Description
str

The signature.

ask_all

ask_all(
    inputs: Inputs,
    prompts: Sequence[str],
    output_type: type[_OutputT],
) -> list[_OutputT | None]

Ask the model every prompt, concurrency at a time.

A prompt the model gives no usable verdict for, by raising VerdictError, is asked once more, since LLM verdicts vary, and is otherwise left undecided.

Parameters:

Name Type Description Default
inputs Inputs

The inputs, whose model is asked.

required
prompts Sequence[str]

The prompts.

required
output_type type[_OutputT]

The Pydantic model class each verdict must validate against.

required

Returns:

Type Description
list[_OutputT | None]

The verdicts, in the order of the prompts, with None for each prompt

list[_OutputT | None]

left undecided.

Raises:

Type Description
InputError

If the model was not given.

ModelError

If the model fails otherwise on any prompt, or gives no usable verdict for any; queued prompts are cancelled.

SampledMetric

Bases: ModelMetric

Estimate, with a model, a quality of a population from a reproducible sample.

Subclasses choose the population, write one prompt per sampled unit, and decide which verdicts fail; this class samples, asks the model, and builds the result. The sample is the sample_size units with the lowest SHA-256 of "{seed}:{key}", where a unit's key describes its content, so the sample is the same on every run and platform, and only extended when sample_size grows. Since keys hold no element IDs, a rebuilt graph with the same content gets the same sample, and graphs built from one corpus in different ways mostly sample the units they have in common, which pairs their scores and lets cached verdicts serve both. When the decided units are fewer than the population, the result carries a 95% Wilson score interval. Sampled units the model gives no usable verdict for are left out and counted as undecided.

Attributes:

Name Type Description
sample_size int

The most units to ask the model about.

seed int

Selects which units are sampled.

signature

signature(inputs: Inputs) -> str

Return the metric name with the model and the sampling parameters.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric is evaluated with.

required

Returns:

Type Description
str

The signature.

sample

sample(
    population: Sequence[_UnitT],
    key: Callable[[_UnitT], str],
) -> list[_UnitT]

Return the reproducible sample of a population.

Parameters:

Name Type Description Default
population Sequence[_UnitT]

Every unit the model could be asked about.

required
key Callable[[_UnitT], str]

Returns the content that ranks a unit, such as the text the model reads; units with equal keys keep their population order.

required

Returns:

Type Description
list[_UnitT]

Up to sample_size units, in rank order.

estimate

estimate(
    inputs: Inputs,
    population: int,
    sampled: int,
    findings: Sequence[Finding],
    undecided: int = 0,
) -> MetricResult

Build the result of asking about a sample of a population, one unit per item.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric was evaluated with.

required
population int

How many units the model could have been asked about.

required
sampled int

How many units were sampled.

required
findings Sequence[Finding]

One finding per decided unit that failed.

required
undecided int

How many sampled units the model gave no usable verdict for.

0

Returns:

Type Description
MetricResult

The result, with a confidence interval when fewer units were decided than

MetricResult

the population holds.

estimate_clusters

estimate_clusters(
    inputs: Inputs,
    population: int,
    clusters: Sequence[tuple[int, int]],
    findings: Sequence[Finding],
    undecided: int = 0,
) -> MetricResult

Build the result of asking about a sample of clusters of units, such as chunks.

The score is the share of units that passed over all decided clusters. Units of one cluster tend to pass or fail together, so the interval is Wilson's at Kish's effective sample size, which the variance of the clusters' shares sets between the number of clusters and the number of units.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric was evaluated with.

required
population int

How many clusters the model could have been asked about.

required
clusters Sequence[tuple[int, int]]

For each decided cluster, how many units it holds and how many of them passed.

required
findings Sequence[Finding]

One finding per decided cluster with a unit that failed.

required
undecided int

How many sampled clusters the model gave no usable verdict for.

0

Returns:

Type Description
MetricResult

The result, with a confidence interval when fewer clusters were decided than

MetricResult

the population holds.

SchemaMetric

Bases: Metric

Measure how a graph matches the graph schema among the inputs.

The graph schema's digest is part of every signature, so results against different graph schemas are never mistaken for each other.

signature

signature(inputs: Inputs) -> str

Return the metric name with a digest of the schema.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric is evaluated with.

required

Returns:

Type Description
str

The signature.

GroundTruthMetric

Bases: Metric

Compare the graph with a ground truth of facts, as precision, recall, or F1.

Entity names and relationship types match under the keys that the ground truth's entity_key and fact_key return, which normalize them, map aliases to the ground truth names they stand for, and match symmetric relationship types in either direction. Both sides are compared as sets, so duplicates count once. Facts and entities involving an entity without a name cannot match and are not evaluated; entity_naming reports them. When the ground truth names documents, only the facts and entities grounded in their chunks are compared. Precision scores the graph's distinct facts or entities, failing those the ground truth lacks, so it assumes the ground truth lists every fact that its documents, or without documents the chunks, state. Recall scores the ground truth facts or entities, failing those the graph lacks. F1 scores both, which makes its score 2 * matched / (distinct + ground_truth), the harmonic mean of precision and recall; its findings are those of precision and recall, so it reports none of its own.

signature

signature(inputs: Inputs) -> str

Return the metric name with a digest of the ground truth.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric is evaluated with.

required

Returns:

Type Description
str

The signature.

evaluate

evaluate(graph: GraphView, inputs: Inputs) -> MetricResult

Match distinct facts or entities with the ground truth; report each unmatched.

Parameters:

Name Type Description Default
graph GraphView

The graph to evaluate.

required
inputs Inputs

The inputs the metric is evaluated with.

required

Returns:

Type Description
MetricResult

The metric's result.

Raises:

Type Description
InputError

If no ground truth was given.

RetrievalMetric

Bases: Metric

Compare what was retrieved for each test question with what its answer needs.

The retrieved context holds a supporting fact or entity when it holds a matching fact or entity, or a chunk that grounds one, so retrievers that return chunks are evaluated as well as those that return graph elements. Each question counts equally: the score is the mean, over the questions the metric evaluates, of each question's share. evaluated and failed count units over all questions.

The digest of the questions is part of every signature, so results for different question sets are never mistaken for each other. The retrievals are what is evaluated, like the graph, so they are not part of it.

Attributes:

Name Type Description
k int | None

How many of the top-ranked element IDs of each retrieval to evaluate; all of them when omitted.

signature

signature(inputs: Inputs) -> str

Return the metric name with a digest of the questions, and k when set.

Parameters:

Name Type Description Default
inputs Inputs

The inputs the metric is evaluated with.

required

Returns:

Type Description
str

The signature.

retrieved

retrieved(
    graph: GraphView, inputs: Inputs
) -> list[tuple[Question, list[Support], frozenset[str]]]

Pair every question with its support in the graph and what was retrieved for it.

Parameters:

Name Type Description Default
graph GraphView

The graph that was retrieved from.

required
inputs Inputs

The inputs, whose questions and retrievals are paired.

required

Returns:

Type Description
list[tuple[Question, list[Support], frozenset[str]]]

Each question with its supporting facts and entities, matched as

list[tuple[Question, list[Support], frozenset[str]]]

QuestionSet.support matches them, and the top k retrieved element

list[tuple[Question, list[Support], frozenset[str]]]

IDs.

Raises:

Type Description
InputError

If no test questions or retrievals were given, a question has no retrieval, or no retrieved element ID is in the graph, as when the retrievals come from another database.

BUILTIN_METRICS module-attribute

BUILTIN_METRICS: tuple[type[Metric], ...] = (
    *INTRINSIC_METRICS,
    *SCHEMA_METRICS,
    *REFERENCE_METRICS,
    *MODEL_METRICS,
    *RETRIEVAL_METRICS,
)

List every built-in metric, grouped by category.

Intrinsic metrics

EntityUniqueness

Bases: Metric

Measure the share of entities with a name that are distinct, counting duplicates once.

Entities are duplicates when their names share the key that normalize_name returns, whatever their node types; findings list each entity's node types so that homonyms can be dismissed. Entities without a name that has a letter or digit are not evaluated. failed counts redundant entities, so a group of n duplicates adds n - 1, the merges that entity resolution would make.

EntityConnectivity

Bases: Metric

Measure the share of entities that are the source or target of a fact with another entity.

An isolated entity, in no such fact, cannot be reached by a traversal from any other entity. A self-loop does not count.

EntityNaming

Bases: Metric

Measure the share of entities whose name identifies a thing on its own.

An entity fails when it has no name, a non-blank string under one of the layout's name keys, since it then cannot be shown to people, resolved as a duplicate, or matched against ground truth facts and test questions. It also fails when its name is an English pronoun, such as "he" or "they", which refers to an entity only within its sentence, so the builder did not resolve the reference to the entity it stands for. And it fails when its name has no letter, such as "1923" or "50%", since such a name is a value, which belongs in a property of the entity it describes. A name in capitals of two or more letters, such as "US" or "IT", is an acronym rather than a pronoun, but a work titled like a pronoun, such as the novel "It", fails.

EntityProvenance

Bases: Metric

Measure the share of entities grounded in at least one chunk.

An entity is grounded in a chunk when a provenance relationship joins them. Every entity extracted from text should be; an ungrounded entity cannot be checked against the text it came from.

FactUniqueness

Bases: Metric

Measure the share of facts that are distinct, counting repeated facts once.

Facts repeat each other when they share source node, relationship type, and target node, as GraphView.relationship_type reads the type, whatever their properties, since a fact is its source, relationship type, and target, as the ground truth metrics also match it, and its properties describe it. Repeats come from running a CREATE-based import twice, or from storing every extraction of a fact as its own relationship, with its own ID, timestamp, or chunk. failed counts redundant copies, so n repeats of a fact add n - 1.

FactProvenance

Bases: Metric

Measure the share of facts whose source and target are grounded in a common chunk.

A builder creates a fact from one chunk, which then grounds both of its entities and is the fact's provenance. A fact whose entities share no chunk cannot be traced to any text, because it was added by hand, hallucinated across chunks, or left behind by entity resolution.

VocabularyUniqueness

Bases: Metric

Measure the share of vocabulary terms in use that are distinct, counting variants once.

The vocabulary is the node types and property keys of the entities, and the relationship types and property keys of the facts. Terms of one kind are spelling variants when they differ only in case, separators, camel case, or plural form, as normalize_type defines. In each group of variants, the one most elements use counts as intended, ties going to the alphabetically first, and failed counts the others; each finding lists the elements that use them. vocabulary_resolution also finds terms that mean the same in different words.

PropertyTypeConsistency

Bases: Metric

Measure the share of property values whose type matches the rest of their group.

Values are grouped by property key and by an entity's node types, taken together, or a fact's relationship type. In each group the most common value type counts as intended, ties going to the alphabetically first type name, and every other value fails. Only entities and facts are evaluated.

EmbeddingConsistency

Bases: Metric

Measure the share of expected embeddings that elements hold, with the expected dimension.

Vector search reaches a graph through its embeddings, so an element whose embedding is missing, or has another dimension than the vector index expects, cannot be found. Entities are grouped by node types, taken together, lexical and community nodes by labels, and facts by relationship type. As for property types, what most members hold is intended, so a group expects every embedding property that at least half of its members hold, with the dimension most of those members have, ties going to the smaller dimension, so a stray embedding on a few members fails no one. Each member of the group is one unit per expected embedding, and fails when it lacks the embedding or holds another dimension. kgeval reads every non-empty list of floats as an embedding.

ExtractionCoverage

Bases: Metric

Measure the share of chunks from which at least one entity was extracted.

Chunks are as GraphView.chunks defines them, which in a lexical graph of documents and chunks means every chunk and no document. A chunk that grounds no entity usually marks a failed or empty extraction.

Schema metrics

EntityConformance

Bases: SchemaMetric

Measure the share of entities that conform to the graph schema.

An entity conforms when all of these hold:

  • unless the graph schema allows additional node types, it has a node type and every node type it has is declared;
  • every declared property it has holds a value of the declared type, and every required one is present;
  • unless one of its declared node types allows additional properties, it has no undeclared property;
  • it satisfies every EXISTENCE, UNIQUENESS, and KEY constraint on its node types.

Lexical nodes and community nodes are not evaluated, since graph schemas describe only extracted entities and the relationships between them, as in neo4j-graphrag.

FactConformance

Bases: SchemaMetric

Measure the share of facts that conform to the graph schema.

A fact conforms when all of these hold:

  • unless the graph schema allows additional relationship types, its relationship type is declared;
  • unless the graph schema allows additional patterns, one combination of a node type of its source, its relationship type, and a node type of its target is a declared pattern;
  • its properties follow its declared relationship type, as for entities;
  • it satisfies every EXISTENCE, UNIQUENESS, and KEY constraint on its relationship type;
  • when its relationship type declares max_targets, its source has facts of that type to no more distinct targets.

Two birthplaces contradict each other, so a source with more distinct targets than max_targets fails every fact of that type, not only the extra ones.

The pattern rule alone is Text2KGBench's ontology conformance, the share of facts that conform to the ontology; this metric adds property, constraint, and cardinality checks.

SchemaCompleteness

Bases: SchemaMetric

Measure the share of declared node types, relationship types, and patterns in use.

A node type is in use when an entity has it, a relationship type when a fact has it, and a pattern when a fact realizes it by having its relationship type, a source with its source node type, and a target with its target node type. This is the schema completeness of the linked data quality literature; for node types alone, it is the class richness of OntoQA.

PropertyCompleteness

Bases: SchemaMetric

Measure the share of declared properties that entities and facts actually hold.

Each property declared by any of an entity's node types is one unit for that entity, and each property declared by a fact's relationship type is one unit for that fact. A unit fails when the entity or fact lacks the property. This is the property, or column, completeness of the data quality literature, which measures how filled-in the graph is, not whether it is wrong, so legitimately optional properties lower the score without being defects.

Reference metrics

FactPrecision

Bases: _FactMetric

Measure the share of the graph's distinct facts that the ground truth contains.

A fact matches a ground truth fact when its source entity's name, relationship type, and target entity's name match the ground truth fact's, in that direction unless the relationship type is symmetric.

FactRecall

Bases: _FactMetric

Measure the share of ground truth facts that the graph contains.

Facts match ground truth facts as in fact_precision.

FactF1

Bases: _FactMetric

Measure the harmonic mean of fact_precision and fact_recall.

It reports no findings, since fact_precision and fact_recall list the facts it counts as failed.

EntityPrecision

Bases: _EntityMetric

Measure the share of the graph's distinct entities that the ground truth contains.

The ground truth entities are the source and target entities of the ground truth facts, and entities match them by name.

EntityRecall

Bases: _EntityMetric

Measure the share of ground truth entities that the graph contains.

Ground truth entities match entities as in entity_precision.

EntityF1

Bases: _EntityMetric

Measure the harmonic mean of entity_precision and entity_recall.

It reports no findings, since entity_precision and entity_recall list the entities it counts as failed.

Competency

Bases: Metric

Measure the share of test questions whose supporting facts the graph holds.

A question passes when every one of its supporting facts and entities matches a fact or entity of the graph, as QuestionSet describes; an answer missing any of them cannot be right. The retrieval metrics evaluate only what this metric finds in the graph, so a failure here is the graph's, and a failure there the retriever's.

Model metrics

EntityResolution

Bases: SampledMetric

Estimate the share of entities with a name that duplicate no other entity.

entity_uniqueness finds duplicates whose names normalize alike. This metric also finds duplicates named differently, such as "Taylor Swift" and "Taylor Alison Swift" or "IBM" and "International Business Machines", which split one thing's facts between entities. Entities are ordered by name and node types, and an entity fails when it duplicates an entity before it, so a group of n duplicates fails n - 1 entities, as in entity_uniqueness. Rules propose as each sampled entity's candidates the entities before it whose names share a word other than a stopword such as "of", when every such word of one name is in the other or the names are spelled alike, and those whose name is an acronym of the other's. The model sees each sampled entity and up to five candidates, the closest in spelling first, each with its name, node types, description, and excerpts of up to MAX_CHUNKS chunks, and decides which are the same thing; an entity without candidates passes without a call. Candidates are proposed for the sampled entities only, so every entity sharing a word can be one however large the graph grows. Sampling and the confidence interval work as described in SampledMetric; the sample is keyed by name and node types.

EntityDisambiguation

Bases: SampledMetric

Estimate the share of entities in several chunks that stand for one specific thing.

Builders merge entities by name, so one entity can conflate different things that share a name, such as the country Jordan and a person called Jordan; they also make entities of generic terms, such as "the company", that mean different things in different places. Either way, a retriever that reaches the entity returns facts about the wrong thing. This metric considers entities with a name, one with a letter or digit, grounded in at least two chunks with text, and shows the model each sampled entity's name and node types with up to MAX_CHUNKS of its chunks, those that contain its name first. Sampling and the confidence interval work as described in SampledMetric; the sample is keyed by name and node types.

NodeTypeAccuracy

Bases: SampledMetric

Estimate the share of entities with a node type whose node types their chunks support.

Builders often give entities the wrong node type. This metric considers entities with a name, one with a letter or digit, at least one node type, and at least one chunk with text, and shows the model each sampled entity's name and node types with up to MAX_CHUNKS of its chunks, those that contain its name first. An entity whose chunks use its name for different things passes when each node type fits one of them, since entity_disambiguation reports such entities. Sampling and the confidence interval work as described in SampledMetric; the sample is keyed by name and node types.

FactAccuracy

Bases: SampledMetric

Estimate the share of grounded facts that their chunks support.

This is knowledge graph accuracy as Gao et al. estimate it, from an annotated sample with a confidence interval, with an LLM as the annotator. Rules can tell whether a fact is grounded in a chunk (fact_provenance) but not whether the chunk says it, so this metric asks a model. It considers facts whose source and target have a name, one with a letter or digit, and share at least one chunk with text, and shows the model each sampled fact, with its description when it has one, and up to MAX_CHUNKS of the shared chunks, those that contain both entities' names first. A wrong direction fails, since the model reads the fact from source to target. Sampling and the confidence interval work as described in SampledMetric; the sample is keyed by the fact and its description.

VocabularyResolution

Bases: ModelMetric

Measure the share of distinct vocabulary terms that no other term duplicates in meaning.

vocabulary_uniqueness finds terms spelled alike; this metric finds terms used for the same thing in other words, such as WORKS_AT and EMPLOYED_BY, and the near-copies that builders without a schema invent. Its unit is a distinct term, which counts the spelling variants that normalize_type merges as one term, named by the variant most elements use, so the two metrics never report the same defect.

The model sees every distinct node type, relationship type, and property key in use, one kind per call, each with its usage and up to three samples, and groups the terms the graph uses for the same thing. A relationship type shows the node types it connects and sample facts, each with an excerpt of a chunk that grounds it; a node type shows the relationship types its entities take part in and sample names; a property key shows what carries it, its value types, and sample values. Samples are those with the lowest SHA-256 of their content, so they are the same on every run. A kind of more than 200 terms is checked in several calls, each listing the 100 most used terms, where a split meaning's main term almost always sits, and a window of the others sorted by usage, so that terms used alike share a call; windows overlap by half, as in the sorted-neighborhood method of Hernández and Stolfo (SIGMOD 1995). Groups that share a term merge. In each group, the term most elements use counts as intended, ties going to the alphabetically first, and failed counts the others; each finding lists the elements that use them. Every term is checked rather than sampled, and terms only in calls the model gave no usable verdict for are left out as undecided.

ExtractionCompleteness

Bases: SampledMetric

Estimate the share of the facts that chunks state which the graph holds.

This is recall without a ground truth. extraction_coverage finds chunks that yielded nothing and fact_recall needs annotated facts; this metric shows the model each sampled chunk with text whole, with the entities grounded in it and the facts grounded in it, those whose source and target both are. The model lists each fact the chunk states and whether an extracted fact holds it. Each stated fact is a unit, so a chunk missing one fact of twenty weighs less than one missing all, and a chunk with a missing fact gets a finding that lists them. Chunks are sampled as described in SampledMetric, keyed by the chunk's text; the facts of one chunk are a cluster, so the confidence interval is estimate_clusters's.

Criteria

CriterionMetric

Bases: SampledMetric

Estimate the share of the entities or facts a criterion applies to that meet it.

A criterion defines a model metric in one sentence, for a quality that no built-in metric checks, such as "The fact gives the year of the founding." The model sees the criterion and each sampled entity or fact with its name, types, properties, and chunks, and answers yes, no, or not applicable, when the criterion is limited to entities or facts unlike this one. The score is the share of the sampled units the criterion applies to that meet it, and each unit that does not meet it gets a finding with the model's reason. Sampling and the confidence interval work as described in SampledMetric, over the units the criterion applies to; the sample is keyed by names and types. The signature holds a digest of the criterion, what it applies to, and its types, so compare pairs only runs of the same criterion.

Attributes:

Name Type Description
name Annotated[str, Field(pattern='^[a-z][a-z0-9_]*$')]

The metric's name: lowercase letters, digits, and underscores, starting with a letter.

criterion Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]

The sentence that each entity or fact must meet.

applies_to Literal['entities', 'facts']

What the criterion applies to, "entities" or "facts", which its class fixes.

EntityCriterion

Bases: CriterionMetric

Estimate the share of the entities a criterion applies to that meet it.

The chunks shown are up to MAX_CHUNKS of the entity's chunks, those that contain its name first. Checking and scoring work as described in CriterionMetric.

Attributes:

Name Type Description
node_types frozenset[str]

Limits the criterion to entities with one of these node types; every entity when empty.

FactCriterion

Bases: CriterionMetric

Estimate the share of the facts a criterion applies to that meet it.

The chunks shown are up to MAX_CHUNKS of the chunks that ground both of the fact's entities, those that contain both names first. Checking and scoring work as described in CriterionMetric.

Attributes:

Name Type Description
relationship_types frozenset[str]

Limits the criterion to facts with one of these relationship types; every fact when empty.

Retrieval metrics

RetrievalRecall

Bases: RetrievalMetric

Measure the share of supporting facts and entities in the graph that were retrieved.

Only what the graph holds is evaluated, so that the retriever is never blamed for a gap in the graph, which competency reports. A supporting fact counts as retrieved when one of its matching facts is, or a chunk that grounds one; retrieving both of its entities without the relationship between them does not count. A supporting entity counts as retrieved when one of its matching entities is, or a chunk that grounds one. The score is the mean of each question's recall, over the questions whose support the graph holds. Each finding lists what was missed for one question.

RetrievalPrecision

Bases: RetrievalMetric

Measure the share of retrieved entities, facts, and chunks that a question's answer needs.

An entity or fact is needed when it matches a supporting fact or entity of the question, or is the source or target of a matching fact; a chunk is needed when it grounds one of those matching facts or entities. Other retrieved nodes, such as documents and community nodes, are not evaluated. Irrelevant context costs tokens and distracts the model that answers. The score is the mean of each question's precision, over the questions whose retrieval holds an entity, fact, or chunk. Each finding lists the unneeded elements of one question.

Errors

KgevalError

Bases: Exception

Signal any failure raised by kgeval itself.

SourceError

Bases: KgevalError

Signal that a graph source could not load the graph or run a query.

InputError

Bases: KgevalError

Signal that a user-supplied file or argument is invalid.

ModelError

Bases: KgevalError

Signal that a model cannot be set up or fails to return a usable verdict.

VerdictError

Bases: ModelError

Signal that a model gave no usable verdict for one prompt, though others may succeed.

Model metrics retry such a prompt once, then leave its unit out as undecided, while any other ModelError, such as a rejected API key, fails the metric.