SelfGraph
Turn unstructured text into a queryable, versioned knowledge graph.
One graph API over any graph backend, in Python and TypeScript.
What's included
- Text-to-graph extraction with any LLM provider, or without an LLM via spaCy NER or a zero-dependency fallback.
- Typed CRUD over entities, relations, preferences, and decision traces, with bitemporal versioning, source provenance, and per-namespace isolation.
- An optional schema that guides extraction and validates every write (warn, strict, or off), with contradiction handling on
max_count: warn, or let the newer fact supersede the older one. - Optional entity resolution that merges duplicates on insert by external id, alias, or name similarity, with a reversible record of every merge.
- Retrieval from keyword seeds and bounded BFS, DFS, or personalized PageRank, returning source passages and relationships with no vector store, optionally as of a past time.
- Explicit maintenance: relevance decay, pruning, and merging duplicate relations, dry runs by default.
- Schema import and export in the Neo4j graph schema JSON that neo4j-graphrag uses.
- A CLI and an MCP server over the same API, and one storage interface across Neo4j, Memgraph, FalkorDB, embedded Kuzu, HydraDB, or a custom store.
- A pure TypeScript SDK in typescript/ that reads and writes the same graph.
Install
pip install selfgraph # core: Neo4j, the openCypher family, and HydraDB
pip install "selfgraph[llm]" # LLM text extraction for any provider
pip install "selfgraph[ner]" # LLM-free extraction via spaCy NER (then: python -m spacy download en_core_web_sm)
pip install "selfgraph[falkordb]" # the FalkorDB backend
pip install "selfgraph[kuzu]" # the embedded Kuzu backend
pip install "selfgraph[mcp]" # the MCP server
pip install "selfgraph[all]" # llm, tokenizer, ner, falkordb, kuzu, mcp
For TypeScript, npm install @hydradb/selfgraph; see typescript/README.md.
Quickstart
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.ontology(
{
"entities": [
{"id": "person:jane", "type": "Person", "name": "Jane Doe"},
{"id": "company:acme", "type": "Company", "name": "Acme"},
],
"relations": [
{"from_entity": "person:jane", "type": "WORKS_AT", "to_entity": "company:acme"},
],
}
)
result = await graph.retrieve("who works at Acme")
print(result.context)
asyncio.run(main())
async with initializes the store on entry and closes it on exit; a bare SelfGraph(...) also initializes lazily on first use. Closing a graph closes the store you passed in, so build a new store for each SelfGraph. SyncSelfGraph has the same API without await.
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", strategy="bfs", depth=3)
print(result.context)
Without llm=, insert.text extracts with spaCy NER (the ner extra and its model), which gives NER types such as Person and verb-lemma relation types, or else a regex fallback that types every entity Thing and links neighbours with RELATED_TO. Use an LLM for graphs that matter, or skip extraction with insert.ontology(...) or your own extractor=.
Ontology input
insert.ontology(...) and selfgraph insert ontology FILE take this JSON; unknown keys are rejected. Only type and name on an entity, and from_entity, type, and to_entity on a relation, are required. An omitted entity id is derived as type:name with the name canonicalized, so Acme Corp and Acme, Inc. both become company:acme; explicit ids follow the id rules. Decision steps are relation ids and default to []; relation_id("person:jane", "WORKS_AT", "company:acme") returns the one shown.
{
"entities": [
{"id": "person:jane", "type": "Person", "name": "Jane Doe", "aliases": ["Jane"],
"external_ids": {"crm": "c-42"}, "properties": {"role": "CEO"}},
{"type": "Company", "name": "Acme"}
],
"relations": [
{"from_entity": "person:jane", "type": "WORKS_AT", "to_entity": "company:acme",
"properties": {"title": "CEO"}, "event_time": "2024-01-15T00:00:00Z",
"evidence": [{"source_id": "notes", "quote": "Jane runs Acme."}]}
],
"preferences": [
{"subject_entity": "person:jane", "key": "database", "value_entity": "company:acme",
"kind": "preference", "strength": 0.9}
],
"decisions": [
{"title": "Joined Acme", "steps": ["relation:ec6ca7724d4851341629a9b9"], "actor_entity": "person:jane",
"rationale": "best offer", "outcome_entity": "company:acme"}
]
}
See inserting for inserts and schema for the schema format.
Helpers
| Helper | Import from | Returns |
|---|---|---|
entity_id(type, name), relation_id(from_entity, type, to_entity), preference_id(subject_entity, kind, key, value_entity), decision_id(actor_entity, title), profile_id(subject_entity) |
selfgraph |
The id an insert derives. |
normalize_rel_type(type) |
selfgraph |
The stored UPPER_SNAKE relation type. |
chunk_text(text, max_tokens=, overlap_tokens=) |
selfgraph.extraction |
The Chunks extraction would read. |
count_tokens(text) |
selfgraph.extraction.chunking |
Tokens through tiktoken, or an estimate without it. |
Warnings go to the standard selfgraph logger (logging.getLogger("selfgraph")).
Configuration
The constructor SelfGraph(store, ...) takes objects: llm (an LLMConfig or an LLMClient), instructions, prompts, extractor, namespace, schema, schema_mode, resolver (a mode or an EntityResolver), and contradiction. SelfGraph.connect(...) and SelfGraph.from_env(...) take flat settings instead, the same ones the CLI flags and SELFGRAPH_* variables set: store, uri, auth, database, namespace, llm_provider, llm_model, llm_api_key, llm_base_url, llm_timeout, llm_concurrency, schema, instructions, prompts (each a dict, inline JSON, or a file path), schema_mode, resolver, and contradiction. Any other key raises ValidationError.
LLMConfig(
provider,
model,
api_key=None,
base_url=None,
temperature=0.0,
max_retries=3,
timeout=120, # seconds per LLM call, None waits forever
concurrency=4, # chunks extracted at once
)
class LLMClient(Protocol): # used for extraction and resolver="llm"
async def generate(self, *, system: str, user: str, output: type[T]) -> T: ... # output is a pydantic model
class EntityResolver(Protocol): # target_id None keeps the candidate separate
async def resolve(self, candidate: EntityInput, existing: Sequence[Entity]) -> ResolutionDecision: ...
class Extractor(Protocol): # replaces LLM, spaCy, and regex extraction
async def extract(self, document: ParsedDocument) -> Ontology: ... # whole text, "text/plain", call metadata
instructions = {"entities": "...", "relations": "...", "preferences": "...", "decisions": "..."} # any subset
prompts = {"entities": {"system": "...", "user": "... {text} ...", "version": "v1"}} # per pass
A prompt override needs system, user, and version, and its user must contain {text}. instructions and prompts also apply per call on insert.text (custom prompts).
Backends
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, graph="selfgraph")
KuzuStore("graph.kuzu") # embedded; no path opens ./selfgraph_kuzu
HydraDBStore("bolt://127.0.0.1:17687", auth=("neo4j", "<token>")) # HydraDB 0.4.0 or newer
All logic lives in the SDK and a store only implements graph primitives, so the same graph runs on any backend; implement GraphStore to add one. With no store and no URI, connect(), from_env(), the CLI, and MCP use ~/.selfgraph/default.kuzu; with a URI and no store they use HydraDB, so a .kuzu path also needs store="kuzu". Kuzu allows one process at a time per database. See backends for auth shapes, concurrency, and what run_cypher() sees on each backend.
CLI and MCP
export SELFGRAPH_AUTH=neo4j:password # secrets in the environment, not flags, which ps shows
selfgraph --store neo4j --uri bolt://localhost:7687 insert text "..." --source-id notes
selfgraph --store neo4j --uri bolt://localhost:7687 retrieve "who works at Acme" --context-only
The CLI covers the library and adds init, version, mcp, schema import and export, and a query that can write. The MCP server has 34 tools that mirror the library; its run_cypher is read-only. Neither raw Cypher path is scoped to the namespace. Stdio MCP clients do not pass your shell environment, so set the connection in the client's env block:
{
"mcpServers": {
"selfgraph": {
"command": "selfgraph",
"args": ["mcp"],
"env": {
"SELFGRAPH_STORE": "neo4j",
"SELFGRAPH_URI": "bolt://localhost:7687",
"SELFGRAPH_AUTH": "neo4j:password"
}
}
}
}
Documentation
Full docs are in docs/: install, quickstart, inserting, schema, entity resolution, resources, retrieval, maintenance, backends, CLI, MCP, errors, and TypeScript.
Contributing
Issues and pull requests are welcome. Contributions start with an approved issue; see CONTRIBUTING.md. Join the community on Discord.
License
Apache-2.0.
Metadata
Release files for selfgraph 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| selfgraph-0.1.0.tar.gz | 273.5 kB | Without provenance | Details for selfgraph-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| selfgraph-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for selfgraph-0.1.0-py3-none-any.whl |
Total release size: 459.3 kB
Release files / selfgraph-0.1.0.tar.gz
| Download URL | selfgraph-0.1.0.tar.gz |
|---|---|
| Size | 273.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
75186d524b00a03386c621940d67851a10b0492fb9c846ebcc6b29bea0523d63
|
|
BLAKE2b-256 checksum How to use checksums |
1476c4ac18f28fc8b203d4a2b42e6b6d004ccacfde537a9c37cb9adf73e6b5f4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / selfgraph-0.1.0-py3-none-any.whl
| Download URL | selfgraph-0.1.0-py3-none-any.whl |
|---|---|
| Size | 185.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cb75b39e5975e6ffee459f3c936c13a214c808e4416bec7285deab66f3ff640f
|
|
BLAKE2b-256 checksum How to use checksums |
b84da277bcd5bf2aba36a893493cb8736024669aa733db51b5e28af0e370646c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for selfgraph 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.