Build a knowledge graph and query it
LlamaBot can extract entities and relations from text, store them in an
embedded graph database, retrieve a neighborhood for a question, and pass
that neighborhood to a bot. This is a graph analogue of
LanceDBDocStore: optional extra, lazy import, local files under
~/.llamabot, no server.
Install the extra:
pip install "llamabot[graph]"
This installs LadybugDB
(MIT, embedded Cypher, maintained fork of archived Kuzu) plus NetworkX and
sentence-transformers. Use NetworkXGraphStore when you want an in-memory
store or a test double.
Set a provider key through the environment. Do not paste keys into code:
export OPENAI_API_KEY="your-key"
Extract, store, retrieve, then ask a bot
import os
from pathlib import Path
from llamabot import SimpleBot, extract_graph
from llamabot.components.graphstore import LadybugGraphStore
text = """
Alice is a researcher at Acme. She knows Bob, who reports to Carol.
"""
graph = extract_graph(
text,
model_name=os.environ.get("DEFAULT_LANGUAGE_MODEL", "gpt-4o-mini"),
)
store = LadybugGraphStore(
graph_name="org-chart",
storage_path=Path.home() / ".llamabot" / "ladybug",
)
store.append(graph)
context = store.retrieve("Who does Alice know?", n_results=5, hops=2)
bot = SimpleBot(
"Answer using only the knowledge-graph context. If the graph is silent, say so.",
model_name=os.environ.get("DEFAULT_LANGUAGE_MODEL", "gpt-4o-mini"),
)
response = bot(f"{context.text}\n\nQuestion: Who does Alice know?")
print(response.content)
retrieve returns a RetrievedSubgraph with structured entities /
relations and an LLM-ready .text string.
In-memory store
NetworkXGraphStore implements the same append / extend / retrieve /
reset interface without Ladybug. Use it in tests (inject a fake embedder)
or when you do not need persistence:
from llamabot.components.graphstore import NetworkXGraphStore
store = NetworkXGraphStore()
store.append(graph)
print(store.retrieve("Alice", n_results=1, hops=1).text)
NetworkXGraphStore.query raises NotImplementedError. Cypher belongs on
LadybugGraphStore.query.
Cypher escape hatch
rows = store.query(
"MATCH (e:Entity {name: $name})-[r:Relation]->(other) "
"RETURN other.name AS name, r.relation AS rel",
{"name": "Alice"},
)
Default embeddings
Stores embed entity text with sentence-transformers
minishlab/potion-base-8M, the same default as LanceDBDocStore. Pass
embedder= to inject a callable in tests so you never load the model.