Turn unstructured text into a queryable, versioned knowledge graph.
One SDK for graphs and ontologies, over any graph database, in Python and TypeScript.
- Text in, graph out. Extract entities and relations with any LLM, or without one.
- Any graph database. Neo4j, Memgraph, FalkorDB, HydraDB, or embedded Kuzu, behind one API.
- Facts that change. Every change is versioned, newer facts retire older ones, and you can read the graph as of any past time, or as it was known then.
- An ontology, not just a graph. Types, synonyms, and definitions ground a question, so the answerability check knows a firm is a
Company. - Light by default, powerful on request. One
leveloption moves every capability from free and deterministic to LLM-backed. - Knows when it has no answer. An LLM-free answerability check, readiness lint, and certified facts tell an agent what the graph holds.
- No vector store. Retrieval walks the graph from keyword matches and returns the source passages. Embeddings are optional.
- Code too.
graph.code.indexputs a codebase in the graph: files, declarations, imports, and the calls it can resolve, each cited by file and line. - SDK, CLI, and MCP server over the same graph, in Python and TypeScript.
pip install selfgraph # Neo4j, Memgraph, and HydraDB
pip install "selfgraph[all]" # plus LLM extraction, Kuzu, FalkorDB, spaCy, tiktoken, MCP, OpenTelemetry, and code parsingEvery extra is listed in install. For TypeScript, see typescript/README.md.
Start with SelfGraph (or SyncSelfGraph) and a store such as KuzuStore, HydraDBStore,
or Neo4jStore. Use Schema when you want to define entity and relation types, and
Extraction when you want to construct structured facts as a model. Resource methods
return typed results. Import the other models, protocols, and helpers directly when you need them.
No server and no LLM, with pip install "selfgraph[kuzu]":
import asyncio
from selfgraph import KuzuStore, SelfGraph
async def main() -> None:
async with SelfGraph(store=KuzuStore("graph.kuzu")) as graph:
await graph.insert.facts(
{
"entities": [
{"type": "Person", "name": "Jane Doe"},
{"type": "Company", "name": "Acme"},
],
"relations": [
{"from_entity": "person:jane-doe", "type": "WORKS_AT", "to_entity": "company:acme"},
],
}
)
result = await graph.retrieve("who works at Acme")
print(result.context)
asyncio.run(main())These entities derive the ids person:jane-doe and company:acme from their
type and name. See Ids for the id contract and explicit ids.
With an LLM and a server:
from selfgraph import LLMConfig, Neo4jStore, SelfGraph
async with SelfGraph(
store=Neo4jStore("bolt://localhost:7687", auth=("neo4j", "password")),
llm=LLMConfig(provider="anthropic", model="claude-sonnet-5-5"),
) as graph:
await graph.insert.text("Soham prefers HydraDB. The team picked it for temporal history.")
result = await graph.retrieve("which database and why")
print(result.context)SyncSelfGraph has the same API without await. Without an LLM, insert.text falls back to spaCy or a simple regex pass; see inserting.
Every capability is a ladder of tiers, and level sets them all. The default, balanced, is the strongest tier that is free and deterministic.
| Capability | light |
balanced (default) |
max |
|---|---|---|---|
| Extraction | regex | spaCy, else regex | LLM |
| Entity resolution | exact |
default |
llm |
| Contradictions | warn on schema limits | warn on schema limits | LLM-judged, no schema needed |
| Retrieval seeds | BM25 | BM25 plus schema synonyms | plus embeddings, with your embedder |
| Traversal | BFS | BFS | PageRank |
graph = SelfGraph(store=store, llm=llm, level="max") # everything on
graph = SelfGraph(store=store, llm=llm, contradiction="llm") # one capability
graph = SelfGraph(store=store, llm=llm, level="max", max_tier="balanced") # cap: no LLM calls
print(graph.tiers)- Passing
llm=turns on LLM extraction only. Every other LLM tier is opt-in. - A higher tier runs the lower ones first and sends only the undecided cases up, so cost follows the hard cases.
- Every tier writes the same ids and encoding. Changing a tier needs no migration.
- Each result reports the tiers that produced it in
result.tiers.
See tiers.
A newer fact can retire an older one. Set from.max_count: 1 on WORKS_AT in the schema
to keep one employer per person with supersede:
schema = {
"relations": [
{"type": "WORKS_AT", "from": {"types": ["Person"], "max_count": 1}, "to": {"types": ["Company"]}},
],
}
graph = SelfGraph(store=store, schema=schema, contradiction="supersede")
await graph.relations.create("person:ann", "WORKS_AT", "company:acme", event_time="2020-01-01")
await graph.relations.create("person:ann", "WORKS_AT", "company:globex", event_time="2022-01-01")
await graph.retrieve("where does Ann work") # Globex
await graph.retrieve("where does Ann work", as_of="2021-06-01") # AcmeThe retired relation keeps its history and records what replaced it. Run the supersede lesson to create the entities and run the full example. See contradictions. graph.diff(since, until) lists what the graph stored between two known times: relations added, revised, retired, and certified, preference versions, decision writes, merges and unmerges, and source versions (changes between known times).
A schema can carry synonyms, certified definitions, and where each term's data lives. check_answerable then grounds a question in those terms before an agent answers:
schema = {
"entities": [
{
"name": "Company",
"synonyms": ["employer", "firm"],
"definitions": [{"name": "headcount", "expression": "count(Person)", "synonyms": ["staff size"]}],
}
]
}
graph = SelfGraph(store=store, schema=schema)
await graph.insert.facts({"entities": [{"name": "Acme", "type": "Company"}]})
report = await graph.check_answerable("What is the staff size of the firm Acme by ad spend?")
report.missing # ["ad", "spend"]
await graph.retrieve("which employers") # seeds Company entities through the synonymSchema.from_tables drafts a schema from table and column metadata, with no database connection. See ontology.
HydraDB requires version 0.5.0 or later. See Run HydraDB locally.
from selfgraph import CypherStore, FalkorDBStore, HydraDBStore, KuzuStore, Neo4jStore
Neo4jStore("bolt://localhost:7687", auth=("neo4j", "password"))
CypherStore("bolt://localhost:7687", auth=("user", "password")) # Memgraph and other Bolt engines
FalkorDBStore(host="localhost", port=6379)
KuzuStore("graph.kuzu") # embedded
HydraDBStore("bolt://127.0.0.1:7687", auth=("neo4j", "<token>"))See backends to configure from settings or add your own store.
export SELFGRAPH_AUTH=neo4j:password
selfgraph --store neo4j --uri bolt://localhost:7687 insert text "Jane runs Acme." --source-id notes
selfgraph --store neo4j --uri bolt://localhost:7687 retrieve "who runs Acme" --context-onlyselfgraph mcp serves the same API as MCP tools. Stdio clients do not pass your shell environment, so set the connection in env:
{
"mcpServers": {
"selfgraph": {
"command": "selfgraph",
"args": ["mcp"],
"env": {
"SELFGRAPH_STORE": "neo4j",
"SELFGRAPH_URI": "bolt://localhost:7687",
"SELFGRAPH_AUTH": "neo4j:password"
}
}
}
}Start with the documentation index for concepts, the hands-on tutorial, and API reference for both SDKs.
Contributions start with an approved issue; see CONTRIBUTING.md. Join us on Discord.
Apache-2.0.
