Graph store — Low-Level Design
Created: 2026-12-01
Last updated: 2026-12-01
HLD Link: ../../high-level-design.md
Requirements (EARS)
- graphstore-EARS.md — models, store interface, Ladybug and NetworkX backends, extractor, packaging.
Overview
LlamaBot already has document stores (LanceDBDocStore and friends) for RAG. Knowledge graphs need a parallel convenience layer: extract entities and relations from text, persist them in an embedded graph database, retrieve a neighborhood around a query, and feed that neighborhood to a bot.
This feature adds llamabot.components.graphstore with:
- Pydantic models
Entity,Relation,ExtractedGraph, andRetrievedSubgraph AbstractGraphStorewithappend,extend,retrieve,reset, andqueryLadybugGraphStore— on-disk LadybugDB (MIT, embedded Cypher, community continuation of archived Kuzu)NetworkXGraphStore— in-memory implementation used as a lightweight backend and test doubleextract_graph/KnowledgeGraphBot— thinStructuredBotwrapper withExtractedGraphaspydantic_model
It does not wrap GraphRAG, LlamaIndex, or Graphiti.
Modules
| Module | Role |
|---|---|
llamabot.components.graphstore.models |
Pydantic graph types and LLM-ready text formatting |
llamabot.components.graphstore.store |
AbstractGraphStore, embedding helpers, seed ranking |
llamabot.components.graphstore.ladybug |
LadybugGraphStore |
llamabot.components.graphstore.networkx_store |
NetworkXGraphStore |
llamabot.components.graphstore.extract |
extract_graph, KnowledgeGraphBot |
Public names are re-exported from llamabot.components.graphstore.
Data models
Entity
| Field | Type | Description |
|---|---|---|
| name | str | Canonical entity name |
| label | str | Type or class (Person, Org, …) |
| properties | dict[str, Any] | Optional extra attributes |
Identity in the store is label:name.
Relation
| Field | Type | Description |
|---|---|---|
| source | str | Name of the source entity |
| relation | str | Relationship type |
| target | str | Name of the target entity |
| properties | dict[str, Any] | Optional extra attributes |
ExtractedGraph
| Field | Type | Description |
|---|---|---|
| entities | list[Entity] | Nodes to upsert |
| relations | list[Relation] | Edges to upsert |
append / extend accept ExtractedGraph objects. Relation endpoints that are missing from entities and from the store are created as stubs with label Entity. An endpoint that already exists is reused and not overwritten. A later fully labeled entity with the same name replaces the stub and inherits its relations. When the same name exists under multiple labels, an extracted entity’s label wins; otherwise a non-stub entity is preferred.
RetrievedSubgraph
| Field | Type | Description |
|---|---|---|
| entities | list[Entity] | Nodes in the neighborhood |
| relations | list[Relation] | Edges among those nodes |
| text | str | LLM-ready serialization (computed) |
retrieve returns RetrievedSubgraph. n_results is the number of seed nodes, not the size of the expanded subgraph.
LadybugGraphStore
Constructor mirrors LanceDBDocStore convenience:
graph_name: str(slugified with underscores for Cypher identifiers)storage_pathdefaults to~/.llamabot/ladybug- Database file is
storage_path / "graphs.lbdb"(Ladybug rejects a directory path) embedding_modeldefaults tominishlab/potion-base-8Membedderis an optionalCallable[[str], list[float]]so tests can inject a fake
Ladybug is imported inside __init__. Missing install raises ImportError telling the user to pip install llamabot[graph].
Schema
Verified against Ladybug 0.23.1:
CREATE GRAPH {name} ANYthenUSE GRAPH {name}(notUSE {name}; that looks up a database)- Open-type nodes store properties as JSON on
_nodesand cannot host aFLOAT[n]vector index - Therefore the store also declares a typed
Entitynode table andRelationrel table inside the ANY graph, with extracted types inEntity.label
CREATE GRAPH {name} ANY;
USE GRAPH {name};
CREATE NODE TABLE IF NOT EXISTS Entity(
id STRING PRIMARY KEY,
name STRING,
label STRING,
properties STRING,
text STRING,
embedding FLOAT[{dim}]
);
CREATE REL TABLE IF NOT EXISTS Relation(
FROM Entity TO Entity,
relation STRING,
properties STRING
);
dim is len(embedder("dimension-probe")). Reopening a store whose on-disk FLOAT[dim] does not match the embedder raises ValueError.
INSTALL VECTOR / LOAD VECTOR and INSTALL FTS / LOAD FTS run on the connection before USE GRAPH. Native CREATE_VECTOR_INDEX / CREATE_FTS_INDEX are not persisted: Ladybug 0.23.1 keeps those indexes on disk, but after close/reopen SHOW_INDEXES reports extension_loaded=False even after LOAD, and MERGE then fails with “Trying to insert into an index on table Entity but its extension is not loaded.” Retrieve therefore ranks stored embeddings in Python and matches query tokens against text, then fuses the two rankings with reciprocal rank fusion. If a same-session index is already loaded (extension_loaded=True), retrieve may query it and still fuse vector and FTS lists with RRF instead of truncating FTS hits behind vector hits.
query(cypher, params=None) is a Cypher escape hatch on the current graph.
reset drops the named graph and recreates the schema. close closes the Ladybug connection and database so a later process can reopen the same file.
NetworkXGraphStore
Same interface, in memory, networkx.MultiDiGraph. query raises NotImplementedError because there is no Cypher engine. Used when Ladybug is unavailable and as a test double.
Retrieve
- Embed the query with the store embedder.
- Rank entity nodes by cosine similarity and by full-text (Ladybug
QUERY_FTS_INDEXwhen that index is loaded, otherwise token overlap); fuse the two ranked lists with reciprocal rank fusion. - Take up to
n_resultsseeds. - Expand
hopsneighbors (undirected). - Return
RetrievedSubgraphfor that node set.
Extractor
KnowledgeGraphBot constructs a StructuredBot with pydantic_model=ExtractedGraph and stream_target="none". extract_graph(text, model_name=...) instantiates that bot and returns ExtractedGraph. Tests inject a mock bot via the bot argument.
The older llamabot.bot.kgbot.KGBot is unchanged (JSON triplets, not this store).
Packaging
Optional extra llamabot[graph]:
ladybug>=0.23networkxsentence-transformers(same default model asLanceDBDocStore)
LlamaBot requires >=3.13,<3.15, which is inside Ladybug 0.23’s >=3.11 range, so the extra installs Ladybug with no environment marker. CI unit tests run on 3.13/3.14.
Ladybug, networkx, and sentence-transformers are imported lazily so pip install . (no extras) and the import-time benchmark do not load them.
Traceability
| EARS ID | Code |
|---|---|
GRAPH-MODEL-* |
llamabot/components/graphstore/models.py |
GRAPH-STORE-* |
llamabot/components/graphstore/store.py |
GRAPH-LB-* |
llamabot/components/graphstore/ladybug.py |
GRAPH-NX-* |
llamabot/components/graphstore/networkx_store.py |
GRAPH-EXT-* |
llamabot/components/graphstore/extract.py |
GRAPH-PKG-* |
pyproject.toml |
Related Documents
- High-Level Design
- Graph store EARS
- StructuredBot LLD — extractor uses
StructuredBot - QueryBot LLD — document-store analogue, not a dependency