Exploring entity extraction and resolution for knowledge graph construction — for agent memory and for document intelligence, which turn out to be genuinely different problems.
The first experiment is GLiNER2.5: a 194M-parameter encoder that does joint entity and relation extraction against a schema supplied at runtime, on a laptop CPU, with no API key.
| needs | ||
|---|---|---|
| 01 | Extraction end to end — two ontologies, two corpora, two graphs, entity resolution, a temporal layer | — |
| 02 | The graph in Neo4j — loading, Cypher, all six neo4j-graphrag retrievers, NVL visualization |
Neo4j |
| 03 | Extractors compared — GLiNER vs Claude vs spaCy vs escalation, scored on gold triples | claude CLI |
| 04 | Agent memory in Neo4j — bi-temporal facts, incremental write-back, prompt assembly | Neo4j |
| 05 | Entity resolution compared — the hand-rolled pipeline vs Splink, dedupe, cross-encoders, LLM adjudication | claude CLI |
| 06 | Distillation — LLM labels fine-tuned into a 74M encoder, and whether that pays | claude CLI |
| 07 | Frameworks compared — SimpleKGPipeline, LLMGraphTransformer, PropertyGraphIndex on one corpus | Neo4j, claude CLI |
| 08 | Coreference — four neural engines against the deterministic rules | — |
| 09 | Three domains, no LLM — travel, customer service and ecommerce end to end, with gazetteer linking and NVL | Neo4j |
| 10 | Typed judgments — TypeSafe System One for assertion gating, review-band adjudication, typing before blocking, a must-not-merge test, and judgments as graph data | TYPESAFE_API_KEY |
| 11 | Selection, not generation — relation extraction as one Choice per enumerated entity pair, scored against joint decoding; the recall experiment |
TYPESAFE_API_KEY |
| 12 | What contradicts what — a Noul as the temporal layer's alternative_fn, against embeddings and replaces edges, on the planted switches |
TYPESAFE_API_KEY |
| 13 | Escalate on confidence — the uncertain edge judgments and review pairs sent to Claude Haiku, swept from 0% to 100%, with cost |
TYPESAFE_API_KEY, claude CLI |
| 14 | The boundary of the no-LLM position — intent, priority and resolution for the eight support threads, as three questions and then as graph properties | TYPESAFE_API_KEY |
| 15 | Propose, then decide — GLiNER2.5-Decide checking GLiNER2.5's edges and typing its mentions against the same ontology, the must-not-merge traps, and the judgments loaded into Neo4j as properties | Neo4j (§5 only) |
| 16 | The alignment cookbook, locally — TypeSafe's entity-alignment recipe (450 Magellan Beer pairs, one Score + three Nouls, routed with no fitted threshold) reproduced with GLiNER2.5-Decide in place of Jev, then both models scored against the benchmark's labels |
TYPESAFE_API_KEY or its cache (§6 only) |
| 17 | GLiNER2.5 inside neo4j-graphrag — the package's KG pipeline with a GLiNER2.5 extractor component in the LLM's slot, every resolver it ships measured against gold and against what gold cannot see, and a mention-level resolver that keeps names, aliases and edge support | Neo4j + APOC (§4 on) |
| The neo4j-graphrag agent-memory series — below | ||
| 18 | Atlas — every major surface of neo4j-graphrag 1.24 with a runnable example: LLM interfaces, structured output, tool calling, embeddings, message history, indexes, filters and the SEARCH clause, every retriever, prompt templates, a deprecation census |
memory Neo4j, OpenAI (cached) |
| 19 | Conversations as a lexical graph — turns vs characters, loaders, the lexical graph as Session/Message, batched embedding, tool calls as structure with no LLM, in-database ai.text.embed, and chunk granularity against BEAM's gold evidence |
memory Neo4j, OpenAI (cached) |
| 20 | A schema for memory — GraphSchema in depth, schemas learned from text and read from the graph, pruning on a real extraction, schema-as-prompt vs schema-as-response-format, constraints on Community |
memory Neo4j, OpenAI (cached) |
| 21 | Extracting memories — graphrag's extractor vs a windowed, evidence-linked memory extractor; the canonical build (4 BEAM conversations, 300 DolphinBench messages, 100 STATE-Bench trajectories); recall against gold facts | memory Neo4j, OpenAI (cached) |
| 22 | Resolving entities across sessions — graphrag's three resolvers vs vector-candidate + LLM adjudication and a GDS resolver, scored on independently labelled held-out gold | memory Neo4j + GDS, OpenAI (cached) |
| 23 | Time and change — bi-temporal memory, supersession / contradiction / reinforcement by an LLM judge + verifier vs aspect keys and cosine thresholds, held out on BEAM's own probes | memory Neo4j, OpenAI (cached) |
| 24 | The write pipeline — the 1.x orchestrator in depth via the full memory write pipeline; events, SimpleKGPipeline, config files, ParquetWriter, failure semantics | memory Neo4j, OpenAI (cached) |
| 25 | Retrievers I — every built-in retriever and GraphRAG on a multi-user memory graph, with a shared evidence-recall harness and rubric judge | memory Neo4j, OpenAI (cached) |
| 26 | GDS for agent memory — the GDS 2.x client on per-user projections: importance, topics, consolidation, FastRP, paths, Steiner trees, a sleep-time analytics job | memory Neo4j + GDS, OpenAI (cached) |
| 27 | Retrievers II and context assembly — custom graphrag retrievers (as-of, profile, PPR, Steiner, time window, topics, fusion), a router, and a token-budgeted ContextAssembler, tuned on a dev split and held out | memory Neo4j + GDS, OpenAI (cached) |
| 28 | The memory agent, end to end — a tool-calling memory agent on BEAM, DolphinBench (its own harness and graders) and STATE-Bench (its Agent Learning Track) against no-memory and full-context baselines | memory Neo4j + GDS, OpenAI (cached), --extra bench |
| 29 | v2 — issue #555 and the v2 branch, the dataflow Pipeline DSL with the write path ported to it, v2 hands-on, a migration grep and a gap analysis |
memory Neo4j, uv, OpenAI (cached) |
| 30 | TypeSafe judgments for memory — remember gate, memory kind, supersession, reranking, abstention and a tool-call gate as System One judgments. Built, not yet run: the TypeSafe account needs API credits | TYPESAFE_API_KEY with credits |
Notebooks 01–09 and 15–17 need no API key (16's Jev section excepted; it skips itself without one). 03, 05, 06 and 07 use the claude CLI (already authenticated if you use
Claude Code) through kgx.llm.ClaudeCLI; notebooks 09 and 17 use no LLM at all, by design.
Notebooks 10–14 are the exception and need a hosted API key, TYPESAFE_API_KEY (13 also needs the
claude CLI). Export it, or copy .env.example to .env (gitignored) and fill it in; kgx.env.getenv
reads the environment first and .env second. They are kept separate for that reason: kgx.typesafe is not exported from kgx, so
importing it is a deliberate act and nothing else in the repo acquires the dependency. Like kgx.llm.ClaudeCLI, it caches every response to disk
content-addressed on (model, state, questions) — a re-run is free, byte-identical, and needs no key.
Notebook 15 asks notebook 10's questions locally, with
GLiNER2.5-Decide, the classification model in the GLiNER2.5
family, through kgx.decide. It needs no key and no cache, and its measured bar is notebook 10's.
Notebook 16 does the same for a published TypeSafe cookbook, entity
alignment, on the cookbook's own 450 benchmark pairs
under the same ids (kgx.data.beer downloads them once into output/beer/), and then runs Jev itself on
every pair so both models are scored against the benchmark's labels.
Notebook 17 answers notebook 07's open question, whether neo4j-graphrag's pipeline can run without an
LLM and with a real resolver. kgx.graphrag.GlinerEntityRelationExtractor is an EntityRelationExtractor
that decodes each chunk against the pipeline's own GraphSchema, so the package's splitter, chunk embedder,
pruner, writer, resolvers and retrievers run on GLiNER2.5 output unchanged. It needs neo4j-graphrag ≥ 1.19,
where the components moved out of experimental.
Every surface of neo4j-graphrag 1.24 and the GDS Python client 2.4, learned through one use case — agent memory: entities, preferences, decisions, facts, goals, commitments and instructions extracted from user and agent messages and tool calls, resolved across sessions, kept current as they change, and assembled into context — measured on three public benchmarks: BEAM, DolphinBench and Microsoft's STATE-Bench. The plan, decisions and graph model are in docs/AGENT_MEMORY_SERIES.md.
What it needs. The 2026.x Neo4j with APOC, GDS and the GenAI plugin (scripts/neo4j_memory_up.sh, bolt
7691 — separate from the 5.26 database notebooks 01–17 use), and OPENAI_API_KEY in .env. All OpenAI
traffic goes through kgx.glm, which wraps graphrag's own OpenAILLM/OpenAIEmbeddings at the client:
every request is cached content-addressed, every live call is written to a ledger with its list-price cost,
and a hard cap (KGX_OPENAI_BUDGET_USD) refuses live calls past it. Every notebook re-executes with
KGX_OPENAI_OFFLINE=1 at zero cost; the first full build of the series cost about $73. Benchmark data is
downloaded at runtime into output/bench/ (BEAM is CC-BY-SA; nothing is vendored). Notebook 28 also needs
uv sync --extra bench for the DolphinBench and STATE-Bench harnesses.
How it was built. Each notebook was implemented, executed headless, reviewed by an independent agent that re-executed it offline and checked every claim against the outputs and the installed package source, then fixed. Three reviews found in-sample evaluation and forced held-out tests: gold labelled by an agent that had never seen the resolver (22), BEAM's own probes on conversations the method was never developed on (23), and a dev/held-out split with frozen code hashes (27, 28).
Findings (each notebook shows the working; numbers are from the committed outputs):
- Filtered vector search never reaches the
SEARCHclause on Neo4j 2026.10 (19, 25): graphrag reads the index's filterable properties from anindexConfigkey the server no longer reports, so every filtered search falls back to an exact scan. Supplying them makes in-index search 3–4× faster at top-10 overlap ≥ 0.998. And a filter that matches no node crashes theSEARCHpath with aDatabaseErrorgraphrag's fallback does not catch — a new user's first query.kgx.memory.retrievalguards both. - graphrag's
Neo4jWriterclears its temporary ids on every node in the database (29), so two writers can drop each other's relationships while both reportSUCCESS.kgx.memory.extract.AtomicMemoryWriterwrites nodes, relationships and its own cleanup in one transaction. - Pruning removes any node left without properties (20, 21) — including the per-turn
Usernodes an extractor emits, which detached the user from 47 of 49 memories. - A memory is not a triple, but graphrag's extractor kept stance anyway (21): given the memory schema it preserved polarity and comparisons in 9 of 10 stance-bearing turns (the series' own extractor 7 of 10; n = 10, not significant), at 1.25× the cost per turn at equal granularity.
- Supersession cannot ride on a key (23): the extractor's
aspectagrees with itself across runs only ~56% of the time, and exact keys connect 3 of 13 gold updates. An LLM judge plus a verifier halves over-supersession; held out on BEAM's own probes it gets 2 of 4 knowledge updates and 2 of 4 contradictions, against 6 of 8 and 5 of 8 in sample. - Entity resolution needs reading, not string similarity (22): SEARCH-clause candidates, rules and an LLM adjudicator under cannot-links reach F1 0.995 on held-out beam:16 and 0.912 (7 violations) on DolphinBench's hard service-vs-work-vs-document mentions; there graphrag's exact match scores 0.730 and its fuzzy resolver 0.633 with 27 must-not-merge violations.
- Graph structure did not help retrieval here (26, 27): PageRank importance does not predict what the
benchmarks ask about (AUC 0.50 on BEAM, 0.57 on DolphinBench), recency predicts it backwards, and FastRP, personalised PageRank and
prize-collecting Steiner trees add nothing reliable over text. GDS's
prize_steiner_treereturns empty solutions where trees exist (4-node repro in 26). - Memories carry as much as raw messages at a thirteenth of the context (25): 0.559 vs 0.560 on 80 BEAM probes, no detectable difference. Built-in hybrid search leaks other users' memories, and its weights tuned on one benchmark do not transfer to the other.
- Assembling context helps with conflicts more than with recall (27, 28): the token-budgeted assembler does not recover more gold than scoped vector search, and end to end its gain over plain memories is not significant on held-out probes — except on contradiction resolution, where its explicit CONFLICT lines lift every held-out probe.
- End to end, full context is the bar while it fits (28): graph memory beats no memory on BEAM by +0.33 but trails putting the whole conversation in gpt-5.6-luna's million-token window by about 0.12; the assembler is indistinguishable from full context on the canonical probes at ~960 tokens. On DolphinBench, memories plus their evidence turns tie the full history at 1/15 of the tokens — what memory loses is detail at extraction, not retrieval. On STATE-Bench, procedural learnings changed nothing (0.60 vs 0.60).
- v2 is early (29): one of #555's six breaking changes has landed on the
v2branch (a single message-listBaseLLM). The new dataflow DSL contains a poisoned episode where the 1.x orchestrator aborts, and one session of the series' write path runs on the branch with byte-identical extraction.
uv sync
uv run jupyter lab notebooks/01_gliner25_knowledge_graphs.ipynbFirst run downloads ~400 MB (GLiNER2.5-base) plus ~90 MB (MiniLM, for entity resolution); notebook 15 adds ~1.9 GB (GLiNER2.5-Decide, a DeBERTa-v3-large), which notebook 16 reuses. Everything after that is local; the only hosted dependency in the repo is notebooks 10–14's.
import kgx
extractor = kgx.GlinerExtractor() # fastino/gliner2.5-base-v1
graphs = extractor.extract_batch(docs, kgx.BUSINESS_NEWS)
resolver = kgx.EntityResolver().learn_aliases(d["text"] for d in docs)
mentions = [m for g in graphs for m in g.mentions]
kg = kgx.build_graph(graphs, resolver.resolve(mentions), kgx.BUSINESS_NEWS)
print(kg.summary())
print(kgx.to_cypher(kg, min_support=2))ontology → extract → [coref] → resolve → graph → [temporal]
| module | what it does |
|---|---|
kgx.ontology |
The graph model as data — node labels, edge types, legal (head, REL, tail) triples. Compiles to a GLiNER JointSchema; also drives validation and Cypher export. JSON round-trippable. |
kgx.extract |
Joint entity+relation decoding, plus a span-attribute pass for qualifiers (modality, direction) that typed edges cannot carry. |
kgx.coref |
Deterministic conversation preprocessing. Encoder models have no coreference; this is what stops that from looking like an extraction failure. |
kgx.resolve |
normalize → block → score → cluster → canonicalize, plus an incremental registry for episode-at-a-time memory, corpus alias mining, and B-cubed scoring. |
kgx.graph |
Canonical, evidence-backed graph assembly. matplotlib, pyvis, and Cypher output. |
kgx.temporal |
Bi-temporal fact store — supersede contradictions instead of accumulating them. |
kgx.neo4j_io |
Idempotent loading into Neo4j via $() dynamic labels, with schema introspection. |
kgx.llm |
The claude CLI as a cached LLM backend, plus an LLMExtractor that returns the same DocGraph as GLiNER. |
kgx.typesafe |
TypeSafe System One as a pipeline stage — a disk-cached client; assertion gating, pair adjudication, referent typing and soft blocking, relation selection over enumerated pairs, and an alternative_fn for the temporal layer. The one module that needs a hosted API key. |
kgx.decide |
GLiNER2.5-Decide as a pipeline stage — edge checks (sentence modality, and whether Decide picks the same legal relation GLiNER decoded), context-free typing as a second opinion for blocking, and the selection and pair-matching experiments it fails. Local, no key. |
kgx.graphrag |
GLiNER2.5 as a neo4j-graphrag component — an EntityRelationExtractor for the package's Pipeline, Ontology → GraphSchema, a transitive FuzzyMatchResolver, and KgxResolver: kgx.EntityResolver over a :Mention layer, keeping canonical names, aliases and edge support through APOC merges. No LLM. |
kgx.evaluate |
Triple-level P/R/F1 with an explicit, auditable matching policy. |
kgx.baselines |
spaCy as the closed-vocabulary floor, with the ontology-coverage gap made explicit. |
kgx.frameworks |
Adapters so LangChain / LlamaIndex / graphrag can run on a subprocess-backed LLM. |
kgx.gazetteer |
Dictionary linking against a controlled vocabulary — stable ids, not clusters. |
kgx.domains |
Travel, customer-service and shopping ontologies. |
Two ontologies ship: kgx.AGENT_MEMORY (13 node labels, 16 edge types) and kgx.BUSINESS_NEWS (13 / 15).
Both are ordinary data — write your own in Python, JSON, or YAML.
| Agent memory | Document intelligence | |
|---|---|---|
| input | conversation episodes, one at a time | a corpus, all at once |
| resolution | incremental — link each episode into what's known | batch |
| time | facts expire; contradictions must supersede | facts are stamped, not superseded |
| hard part | coreference ("I", "he", "the migration") | alias variation (NWL / Northwind / the Company) |
| read pattern | every turn, latency-critical | analytical, offline |
Same model, same joint decoding, different everything else.
Measured on this repo's corpora, not asserted. The notebook shows the working for each.
Joint decoding is the reason to use GLiNER2.5 over GLiNER2. Across both corpora, zero extracted edges violated the ontology's endpoint types. Extracting entities and relations separately gives you no such guarantee — you get a post-filter instead of a constraint.
Relation recall falls off a cliff past ~400 words, and lands on zero. A 518-word transcript decoded to
0 relations with feasible=True — indistinguishable from "no facts here". Entity recall over the same
window was fine. Window the input: extract per episode, or extract_long(chunk_size=256..384), or
JointIEConfig(max_len=512). kgx warns on this.
symmetric=True is broken in gliner2 2.0.0. It compiles to a constraint set that rejects every
candidate edge — the relation silently returns nothing, with feasible=True. Use a directed relation plus
inverse=, which works and emits the mirror edge tagged derived=True.
First-person substitution is worth ~500× on conversational text. Edges recovered about the user, over the same 5 sessions: 1 with raw turns → 210 with speaker labels → 539 with the full preprocessing stack. Not a model limitation; a preprocessing requirement of any coreference-free extractor.
Entity resolution: B-cubed F1 0.85 → 0.95, precision 1.00 throughout — all the movement is in recall.
Embeddings buy the most F1, but mining aliases from the corpus text (Northwind Logistics Inc. (NASDAQ: NWL))
buys the most blocking recall, which is the harder ceiling: embeddings raise the score of pairs that are
already candidates, alias mining creates candidates nothing else would propose. Complementary, not redundant.
Deciding what contradicts what needs world knowledge these models don't have. Embedding similarity does
not separate genuine alternatives (npm/pnpm) from unrelated pairs (npm/Berlin) — the distributions overlap
under every template tried. Asking the extractor to classify tools into categories fails too. What does
work: declare replaces(tool → tool) in the ontology and let joint decoding find the switch the user
announced in the text. Extracted at 0.99 confidence, with the sentence attached.
A classifier checks what an extractor proposes, and cannot do the proposing. GLiNER2.5-Decide, asked two questions per extracted edge — is its sentence a fact, and would it pick the same relation from the ontology's legal ones — lifts gold-triple F1 0.330 → 0.396 at no recall cost, near the hosted gate's 0.404; as a second type for blocking it takes resolution to B-cubed 1.000. Asked to find relations among co-occurring pairs, or to decide whether two mentions are one entity, it fails. And the wording that works is its own: short concept labels, the span as the whole text, and a task name chosen for meaning, because the name is part of the prompt.
"No threshold to fit" belongs to the model, not the recipe. TypeSafe's entity-alignment cookbook routes
450 Magellan Beer pairs by rounding one Score to the nearest of three worded levels (Jev: 40 merged, 50 to
a curator, 360 unlinked, as published). Asked the same four questions, GLiNER2.5-Decide sends all 450 to the curator:
its distribution over the levels is nearly flat on every pair, and it answers no to "same beer name?" on
all twelve pairs whose names are identical. Its P(same) still orders the pairs (AUC 0.87 against the
benchmark's labels), so cut points fitted on the train split can route. But they sit about two hundredths
apart, make false merges when the wording changes, and a one-line string ratio on the names orders the pairs
better (0.951). Jev, re-run on every pair (jev-latest, now 1.13.0; 1.12 is no longer served), merges 39 —
every one a match, with no threshold fitted — hands the curator 38, and leaves 4 of the 68 matches
unlinked, each a pair naming two different breweries. Its score orders the pairs at AUC 0.992.
Errors move between stages wearing a disguise. A mistyped entity in extraction and an under-merge in resolution both surface as "the user changed their mind" in the temporal layer. A subject that flip-flops back to a value it already held is the tell. Carrying evidence on every edge is what makes them separable.
A prefix match is not an identity. Northwind / Northwind Logistics should merge; Apple / Apple Bank
should not, and the string evidence is identical. Requiring context agreement splits them at no measured cost
to F1 — the kind of rule that is invisible on a corpus without the trap and expensive on one with it.
src/kgx/ the library
ontology.py graph model as data; AGENT_MEMORY + BUSINESS_NEWS
extract.py GLiNER2.5 joint extraction + qualifier pass
coref.py conversation preprocessing (3 ablatable layers)
resolve.py entity resolution + incremental registry + B-cubed
graph.py canonical graph, evidence, matplotlib/pyvis/Cypher
temporal.py bi-temporal facts, supersession
neo4j_io.py idempotent Neo4j loading, schema introspection
llm.py cached claude-CLI backend + LLM extractor
typesafe.py cached TypeSafe System One client; edge gating + pair adjudication
env.py TYPESAFE_API_KEY and friends: environment first, then .env
decide.py GLiNER2.5-Decide edge checks + typing ahead of blocking (local)
alignment.py the entity-alignment cookbook's decision, asked of Decide; AUC + fitted cuts
graphrag.py GLiNER2.5 extractor + mention-level resolver as neo4j-graphrag components
evaluate.py triple scoring against gold
baselines.py spaCy closed-vocab baseline
frameworks.py LangChain / LlamaIndex / graphrag adapters
gazetteer.py controlled-vocabulary entity linking
domains.py travel / customer service / shopping ontologies
data/ synthetic corpora with gold labels; beer.py fetches Magellan Beer;
memory_er_gold*.json and memory_change_gold.json for notebooks 22-23
glm.py graphrag's OpenAI classes over a cached client, spend ledger and hard cap (18-30)
bench.py BEAM, DolphinBench and STATE-Bench loaders (runtime download, pinned commits)
memory/ the agent-memory library behind notebooks 18-30:
store.py the 2026.x Neo4j: partitions by source, indexes, users
conversation.py benchmark data as episodes and graphrag TextChunks; TurnSplitter
schema.py memory ontology as GraphSchema + strict Pydantic
extract.py MemoryExtractor, ToolCallExtractor, AtomicMemoryWriter, GraphEmbedder, ingest
build.py the canonical partitions (ensure_all) and the Batch API path
resolve.py entity resolution across sessions; the :Mention layer; ensure_resolved
temporal.py supersession / contradiction; bi-temporal queries; ensure_temporal
analytics.py the GDS layer: importance, topics, RELATED, FastRP; ensure_analytics
retrieval.py guarded retriever factories, the evidence-recall harness, the rubric judge
retrievers.py custom graphrag Retrievers: as-of, profile, PPR, Steiner, time window, fusion
context.py the token-budgeted ContextAssembler
pipeline.py the write path in graphrag's 1.x orchestrator; dataflow.py, in the v2 DSL
agent.py the memory agent; benchmarks.py, the three benchmarks' harness adapters
lexical.py, schemas.py, evaluate.py, judgments.py notebook helpers (19, 20, 21, 30)
notebooks/ 01-30, see the table above
docs/AGENT_MEMORY_SERIES.md the plan and graph model for notebooks 18-30
docs/LANDSCAPE.md survey of the alternatives at every stage
output/ generated graphs, Cypher, CSVs (gitignored)
src/kgx/data/ ships 5 conversation sessions (80 turns) and 10 business-news documents (~2,300 words), both
synthetic, both written with deliberate alias variation, planted contradictions, coreference stress, and
modality traps — plus gold labels for entity resolution and a gold triple set. All companies, people, and
events are fictional.
Notebook 02 needs a Neo4j 5.26+ instance. Nothing else — the embeddings are a local MiniLM and the two
retrievers that genuinely need an LLM run against a deterministic stub (with a live path if
ANTHROPIC_API_KEY is set). Notebook 17 also needs APOC, which neo4j-graphrag's writer and resolvers call
and neo4j_up.sh installs. It writes only under the :__KGBuilder__ label, and leaves its graph in place
for browsing.
scripts/neo4j_up.sh # docker if available, a local tarball under .neo4j/ if not
uv run python scripts/neo4j_restore.py # reload notebook 02's graph + the four indexes
scripts/neo4j_memory_up.sh # notebooks 18-30: Neo4j 2026.10 + APOC + GDS + GenAI on bolt 7691Notebooks 18–30 use their own database. Each rebuilds what it needs from the OpenAI cache in its setup cell
(build.ensure_all → resolve.ensure_resolved → temporal.ensure_temporal → analytics.ensure_analytics, all
idempotent and free on re-run). On Community, the default store format cannot hold the native VECTOR
type, so embeddings stay float lists — which is what graphrag writes anyway.
Both are idempotent. neo4j_up.sh prefers Docker and falls back to a native install, so the notebooks keep
working when Docker Desktop is down. neo4j_restore.py rebuilds the database from
output/business_news_kg.json — the graph is fully reproducible, so a lost container costs a minute, not a
re-extraction.
Override the connection with NEO4J_URI / NEO4J_USER / NEO4J_PASSWORD. Browse at http://localhost:7476.
More findings, from the Neo4j and comparison notebooks:
Dynamic labels work in 5.26 — you don't need APOC. MERGE (n:$($label)) takes the label as data.
MERGE (n:$label) is a syntax error. APOC's apoc.merge.node(labels, ident, onCreate, onMatch) is a trap:
pass properties only as onMatch and a first load writes nothing but the id — invisible on any database
you have already loaded once.
CREATE INDEX ... IF NOT EXISTS is satisfied by an equivalent index under a different name. It succeeds,
creates nothing, and the retriever fails several cells later with "No index with name … found".
Give every entity one shared :__Entity__ label. Cypher indexes are per label, so 13 ontology labels
would mean 13 vector indexes. The shortcut create_fulltext_index(label="Company|Person") silently creates
an index on one literal label named Company|Person that matches nothing, forever.
Entity lookup is a lexical task; rank it that way. HybridCypherRetriever with the default ranker
returns Dresden for the query NWL. ranker="linear", alpha=0.2 fixes it.
Provenance filtering fixes multi-hop queries. A hallucinated subsidiary_of edge propagates into a
two-hop ownership chain that never existed; filtering on r.support >= 2 inside the quantified path pattern
prunes it before the path is built.
The "encoder cannot do implicit facts" claim was wrong (notebook 03). GLiNER2.5 recovered an implied relation, a cross-sentence syllogism and a bridged referent. The real boundary is about arguments: a relation can be inferred from context, an entity argument has to be anchored in the text. The same probe caught the encoder asserting a relation an explicitly negated sentence denies — which the LLM did not.
Splink beats the hand-rolled resolver, and so does an LLM tier (notebook 05). Both reach B³ F1 1.000 against the repo's 0.946, and both do it the same way: by fixing blocking recall (0.879 → 1.000), not by scoring better. Splink's own machinery contributes little here — EM training is worthless with one informative column, and its match probability is uncalibrated (optimal threshold 0.1, not 0.9).
Distillation worked and did not help (notebook 06). A full fine-tune learned the teacher's labelling function far better than its starting point (mention fidelity 0.453 → 0.641) and scored below its own zero-shot baseline on the benchmark. Seed variance inside one config (0.080 F1) exceeded the gap between the 74M and 194M models the experiment set out to close.
Coreference models lose to four regexes on chat (notebook 08). fastcoref added exactly zero gold facts over the deterministic layers; its small F1 edge came from emitting fewer spurious edges. All four engines fail on first person without a speaker prefix — and writing that prefix is what the rule layer does.
Frameworks mostly skip entity resolution (notebook 07). Bolting kgx.EntityResolver onto their output,
with zero LLM calls, recovered ~96% of the gap between strict and alias-tolerant scoring.
Each NVL render() inlines an ~8.5 MB bundle, and from_neo4j copies every property — including your
384-float embeddings — into it. Strip them in Python; a map projection does not help.
"Precision 1.000" was a property of the corpus, not the resolver (notebook 09). Notebooks 01 and 05 both
report perfect B-cubed precision on business news. Given an ecommerce corpus where Aurora 14 and
Aurora 14 Pro are different products, the same code at the same threshold merges them — along with
N600/N600X and Halcyon Buds/Halcyon Buds Pro. The distinguishing token is exactly the kind of short
suffix normalisation is built to ignore.
Where a controlled vocabulary exists, stop computing similarity. A gazetteer links LHR to
London Heathrow exactly, where Jaro-Winkler scores 0.45 and no threshold reaches it — and it yields a
stable id that survives a rerun and a change of corpus, which clustering cannot. But validate any type
constraint you put on it: matching the extractor's type against the vocabulary's kind cost 20 points of
coverage and prevented zero errors, because both sides reasonably disagreed about whether an airport is a place.
Document-level judgement is the boundary of the no-LLM position. GLiNER2.5 classified support-ticket
intent near chance and priority at chance — a near-constant predictor emitting high for seven of eight
threads at 0.75–1.00 confidence. Intent is written down; severity is not, so a span model has nothing to key
on. Of every task in notebook 09, that is the one worth escalating.
An ontology is a hypothesis about the text. replaces fires at 0.99 on agent memory ("I've switched to
pnpm" — one clause, two named tools, an explicit verb) and never fires on support threads, where the same
supersession is spread across a four-turn negotiation. Same relation, same model, different discourse shape.
More findings, from the typed-judgment notebook:
An assertion gate raised precision 0.279 → 0.404 and did not cost a single point of recall (notebook
10). A Noul for does the document connect these two things plus a Choice over four assertion statuses
dropped 56 of GLiNER's 170 edges — 31 the document never related at all, 25 it related and then hedged or
denied — and not one of the 56 was a gold triple. GLiNER's own confidence does not separate the two groups,
because span confidence is about the decoding and not about the claim.
A yes/no question that hides a second reading gets a confident answer to the wrong one. The first
wording of a Noul caught 8 of 11 modality traps; a Choice in the same request called 11 of 11. Every miss
is a denial — "Management has no plans to divest…" — where the sentence really does assert a fact, about an
intention not to act. The misses come back at 0.66–0.74, not at 0.5: ambiguity in the question does not
surface as an uncertain answer. The Choice never had the problem because negated is one of its outcomes;
rewording the Noul to say which reading to take — a sentence saying something will NOT happen does not
make it a fact — took it to 11 of 11 with the controls intact. Keep the distinction in the answer type, or
state it in the question.
A perfect judge on the wrong queue is worth exactly nothing. Adjudicating the entity-resolution review band produced 28 merges, all correct, none contradicting the gold labels — and moved B-cubed by zero to four decimal places. All 28 were already co-clustered by transitivity, and the 10 merges that did change clusters were on mentions outside the gold set. This is notebook 05's finding with the scoring hypothesis eliminated: the judge was flawless and it still bought nothing.
The pairs it never saw were a type disagreement, not a string-similarity failure. 41 gold-same pairs
stayed split and none had ever been proposed — HLCN against every spelling of Halcyon, and Torrent Microsystems against itself. The extractor types HLCN as security and Halcyon Semiconductor as
company, and types the identical string Torrent Microsystems both ways in different documents; blocking
is type-scoped, so none of it is ever a candidate. Handed those 8 pairs directly, the same adjudicator
reaches B-cubed F1 1.000 at precision 1.000 — where notebook 05's best configurations also land, from
the opposite direction. The type constraint in notebook 09's gazetteer cost 20 points of coverage; here it
cost the entire remaining recall gap.
The type wall comes down when blocking reads the distribution, not the label. Re-typing every mention
by referent against the ontology's own descriptions agrees with GLiNER on 192 of 214 and moves recall
0.897 → 0.914 — but HLCN stays security at 0.56, company at 0.41, because the ontology defines a
ticker as a security and the model reports that ambiguity faithfully. Cloning each ambiguous mention into
every type block with ≥ 25% of the mass (17 clones) takes the unchanged resolver to B-cubed 1.000 at
precision 1.000 — no pairs hand-fed, no scoring rule touched. A Choice at 0.56/0.41 is a request to be
allowed both readings; type-scoped blocking that reads only the label makes a wall of it.
It refuses, too. On the shopping corpus's must-not-merge pairs (Aurora 14 / Aurora 14 Pro,
N600 / N600X) the repo's resolver merges three of twelve; the adjudicator merges none, while holding
every must-merge pair — zero false merges, zero false rejects. Putting the shopping ontology's own rule
("'Aurora 14' and 'Aurora 14 Pro' are two products, not one") into the question turns its one hedge
into reject at ≤ 0.06, at the cost of moving one cross-type must-merge pair from merge to review.
Nothing wrong, something curated.
pair_completeness is not a ceiling on B-cubed recall. 0.879 against a baseline recall of 0.897 and a
recovered recall of 1.000. Clustering is transitive, so it unites pairs blocking never proposed. What it
bounds is what an adjudicator can be asked about — which is the constraint that actually bit.
Selection over enumerated pairs is the best relation extractor measured here — but only combined and
confidence-filtered (notebook 11). Given GLiNER's entities, code enumerates every ontology-legal ordered pair
in a document and one Choice picks the relation or none. Alone it is not a better extractor: the same
recall as joint decoding at half the precision, because none (rightly) takes 64–71% of candidates and the
residue includes low-probability picks of the ontology's most permissive relation. But the two find
different things — six gold triples each that the other misses at paragraph scope — and at document scope
selection reaches recall 0.596, the highest on this corpus. Kept at p ≥ 0.95, gated, and unioned with
GLiNER's gated edges: F1 0.442, against 0.404 for notebook 10's best. Three high-confidence relabels of
GLiNER edges are all gold-correct.
130 of GLiNER's 170 edges cross a paragraph. The first draft of notebook 11 asserted zero, from a probe with a precedence bug; the notebook's own check said 130 and reframed the experiment. Paragraph-scoped candidate enumeration is a handicap, document scope is the fair comparison, and it costs 3× the requests. Measure the scope.
Whether two things are alternatives is a world-knowledge question, and one Noul answers it where
similarity cannot (notebook 12). Over every pair of the things the agent-memory gold facts name, are a
and b alternatives? puts the two planted switches at 0.92 (npm/pnpm) and 0.63 (Python/Go) and
all 26 other pairs at ≤ 0.21. MiniLM cosine puts Python/Go at 0.166 — below most non-alternatives —
because it measures how alike two names are, and competing for the same role is not that. Plugged in as
TemporalGraph(alternative_fn=JevAlternatives(ts)), it is the whole integration.
In the pipeline it never got to show it. Four different alternative_fns produced identical
supersessions, because extraction delivered exactly one real switch (uses_tool npm → pnpm) and even
embeddings cleared 0.55 on it, by 0.018. Go was never extracted; prefers pnpm was extracted a session
before the user switched. The judge is only as good as its queue — the third stage in a row to say so.
Escalating the fast judge's uncertain calls to Claude Haiku bought nothing, and the sweep proves it
(notebook 13). F1 0.404 with the System One gate; 0.400 sending its 31 least-confident edge judgments to
Haiku; 0.388 sending all 170 — recall identical throughout, precision falling as escalation rises, no width
of the band at which the slow judge helps. Haiku agreed with System One on 28 of the 31; the three flips
were a coin-flip acquisition the source itself hedges, and one spurious edge Haiku asserted. On the fourteen
review pairs, Haiku got none of the six gold-same right ("different legal names"), where the
adjudicator had calibratedly declined to decide. A larger model is not a curator. 20× the latency, $0.12.
What is written down, the model reads; what is a definition, it has to be given (notebook 14). On the
eight support threads where GLiNER classified priority at chance, a Noul on is this resolved — which is
in the customer's last turn — scores 8 of 8 with a clean gap (open 0.05–0.08, resolved 0.64–0.97). Intent
goes from 3 of 8 to 5 of 8; the three misses are the question reading the thread's end ("Do it" on a
refund) where the gold reads its opening ask. Priority stays at 3 of 8 with the misses confident, because
the Score levels were the notebook's and the gold's scale was never shown to it. Confidence routing sent
the three hedged calls to a person and let every confident disagreement through — it routes model
uncertainty, not definitional disagreement. Fix the question, not the threshold.
Batching is a property of the state, not a flag. 627 questions in 98 requests at ~180 ms each; edge gating alone was 340 questions in 35, because one request carries a dozen edges over one shared document. One question per request would re-send each document 34 times — ~128k tokens of document text against ~6.8k. The cost is paid in how the questions are written: every question in a request sees the same state and question ids are never sent to the model, so each has to name its own edge.
More findings, from the neo4j-graphrag notebook:
The extractor slot is the only place neo4j-graphrag needs an LLM (notebook 17). A GLiNER2.5
EntityRelationExtractor reproduces notebook 01's extraction exactly (214 mentions, 170 relations), and the
package's own pipeline around it — splitter, MiniLM chunk embedder, pruner, writer, resolver — reproduces the
hand-built numbers exactly: B-cubed 0.946 and gold-triple F1 0.330, ten documents in about nine seconds on a
laptop CPU. GraphPruning prunes nothing, because joint decoding cannot emit an edge the schema forbids.
The one thing it will prune is your properties. A node type that declares any properties defaults to
additional_properties=False, and a name-only schema silently strips confidence and the offsets from all
214 nodes.
FixedSizeSplitter's default is past GLiNER's cliff. 4,000 characters is ~600 words. On the corpus as
one long document it cost a sixth of relation recall and a third of the mentions (115 against 180 at 2,500
characters). It is neither truncation nor top_k_entities. Size chunks in words, under ~400.
The package's resolvers deduplicate; they do not canonicalise. All three merge with
apoc.refactor.mergeNodes(..., {properties: 'discard'}), and the similarity resolvers pass the nodes as
list(set_of_element_ids). So the surviving name — and the surviving edge confidence — is set order over
element ids, and changes between identical runs: Halcyon came out as Halcyon, Halcyon Semiconductor or
Halcyon Semiconductor Corporation. Strict triple F1 swings with the name on an identical clustering. No alias and no
edge support survives. SimpleKGPipeline's default resolver is an exact match (B-cubed 0.779 here); the
fuzzy one reaches 0.898.
Gold labels certify the fuzzy resolver, and triple scores reward it. FuzzyMatchResolver at 0.9 has
B-cubed precision 1.000 on the 13 gold entities while merging Phoenix into Arizona, Dresden into
Germany and every margin into one metric — mentions no gold label covers. WRatio's partial matching
scores containment at 90. spaCy's static vectors merge Seattle with Chicago. And the over-merges raise
triple precision, because collapsed places mean fewer triples.
Resolve mentions, not nodes. A resolver that compares nodes sees one surviving name per merged node.
Run per document, as SimpleKGPipeline runs it, the repo's resolver pointed at nodes drops from 0.946 to
about 0.92 B-cubed. Keeping a :Mention per span (its own HAS_MENTION, which survives mergeRels, where
FROM_CHUNK collapses) and clustering mentions on every run gives the same answer per document as once.
It is also what makes aliases, edge support and every merge auditable.
Two latent bugs, neither biting this corpus. _consolidate_sets is one pass, not a union-find:
{a,b}, {c,d}, {b,c} becomes two overlapping merge sets, and on a scripted probe the real run() left two
nodes instead of one on some runs and not others. And a node's every label except __Entity__/__KGBuilder__ is
treated as a type, so a partition label makes each node resolved twice.
- Requires Python ≥3.10 (this repo pins 3.12).
sentencepieceandprotobufare required — GLiNER2.5 uses a DeBERTa-v3 SPM tokenizer and will fail confusingly without them. - Load with
AutoExtractor, neverGLiNER2.from_pretrained— the latter is the legacy span loader and raisesArchitectureMismatchErroron a 2.5 checkpoint. - Extraction is not bit-reproducible; exact counts will shift slightly between runs.
- GLiNER2.5's published benchmarks are vendor-reported and unreplicated. Nothing here depends on them.