cortexdb

package module
v2.92.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 0 Imported by: 0

README

CortexDB

Go Reference CI codecov

A pure-Go, single-file AI memory and knowledge graph. One SQLite file holds vectors, hybrid RAG search, scoped agent memory, an RDF/SPARQL knowledge graph, a Palantir-style ontology, and 60+ agent tools — embedded in your Go program, or installed as a shared brain for Claude Code / Codex. Works with no embedder (lexical mode, no API key) or any OpenAI-compatible embeddings endpoint. No service to run.

go get github.com/liliang-cn/cortexdb/v2

The live 3D view of a CortexDB brain

The same brain under Orbit

serve_graph_3d on a real shared brain — the one behind an OpenClaw cluster: 2000 entities, 5953 relations, node types the agents wrote themselves. Served from inside the MCP server handling the calls, so the graph lights up as tools touch it. (Orbit, as MP4)

db, _ := cortexdb.Open(cortexdb.DefaultConfig("brain.db"))
defer db.Close()
brain := db.KnowledgeMemory()
_, _ = brain.Remember(ctx, cortexdb.KnowledgeMemoryRememberRequest{Content: "Alice prefers tabs.", Scope: "user"})
rec, _ := brain.Recall(ctx, cortexdb.KnowledgeMemoryRecallRequest{Query: "what does Alice prefer?"})
fmt.Println(rec.ContextPack.Text) // paste-ready context pack with source attribution

What's inside

  • KnowledgeMemory brain facadeRecall / Remember / Reflect / Consolidate / PromoteToKnowledge / context packs; fused retrieval across episodic memory, durable knowledge, and GraphRAG chunks; relational answers returned as graph facts (Alice —uses→ Apollo) read from edges, reliable even with no embedder; deterministic no-LLM extract_conversation; memories can carry inline entities/relations so one call stores and graphs them.
  • Composable retrievalcortex_query: vector / lexical / hybrid / graph prefetch lanes fused by RRF, weighted RRF, or DBSF, with metadata filters and per-source score debugging; an Authorize callback gates every candidate (RBAC/ABAC at the retrieval layer); pluggable reranker.
  • Vector + lexical engine — FTS5, HNSW / IVF / Flat indexes, scalar & binary quantization, geospatial indexing, semantic query routing.
  • External retrieval lanes — a search cluster you already run (Meilisearch, Weaviate, …) can be one fused lane via QuerySource, without becoming the storage: it names candidate ids, the brain still owns the content, and a stale id is dropped rather than fabricated.
  • Swappable storage — SQLite by default; a postgres:// DSN moves the same brain to PostgreSQL + pgvector, with vectors, hybrid search, memory and the RDF graph all running on either. Compile-time backend registry, not a plugin system (storage is the hot path). 104 opt-in PostgreSQL tests, mostly parity: one test body, both databases, same answer required.
  • Knowledge graph — RDF triples/quads on the same file: a practical SPARQL subset (updates, OPTIONAL/UNION/VALUES, aggregates, subqueries, property paths), RDFS-lite materialized inference, SHACL-lite validation, N-Triples/Turtle/TriG I/O; property-graph apply_inference materializes two-hop relation compositions with provenance; entities track asserting documents, and delete_document_graph is deletion shaped like ingest.
  • Ontology (Palantir-style) — typed object/link/interface types with primary keys and cardinality, an object-set algebra (union / intersect / filter / search_around), governed action types with audit trail, generated typed agent tools, and a breaking-change schema diff; strict or vocabulary enforcement.
  • Pipelinesmemoryflow (transcript → recall → wake-up → promotion), graphflow (corpus → graph → HTML report), importflow (CSV / SQL dumps / live Postgres-MySQL → RAG + KG), connector (PII masking, signed plans, reversible vault, CDC sync).
  • Tools & MCP — 60+ tools with the same names in-process and over MCP, plus render_graph_html, an interactive graph view.
  • Quality, measuredpkg/eval runs a labeled query set through the real retrieval path with recall@k / nDCG regression floors in CI; FTS5 / SPARQL / SQL-dump parsers are fuzz-tested.

Claude Code / Codex plugin & shared brain

/plugin marketplace add liliang-cn/cortexdb   →   /plugin install cortexdb@cortexdb      (Claude Code)
codex plugin marketplace add liliang-cn/cortexdb && codex plugin add cortexdb@cortexdb   (Codex)

Lexical mode by default, one global brain at ~/.cortexdb/cortexdb.db, slash commands (/remember, /recall, /cortexdb-graph) and an auto-recall hook. Point many agents and machines at one cortexdb-grpc (CORTEXDB_REMOTE=host:port + token) and Claude Code, Codex, OpenClaw and Hermes share the same memory and graph. Typed clients: cargo add cortexdb-client · pip install cortexdb-client · npm install cortexdb-client.

To keep that server up, deploy/ has a hardened systemd unit and a container image whose healthcheck is the server binary itself (cortexdb-grpc -health). Every port has a default and every default is overridable.

More

Full guide (layers, ontology details, shared-brain ops): docs/GUIDE.md · 16 runnable examples (go run ./examples/01_core16_ontology) · launch kit: docs/LAUNCH_KIT.md · 中文: README_CN.md

Embedded, inspectable, local-first — not a distributed vector database, not an enterprise RDF server.

Documentation

Overview

Package cortexdb is the public documentation entrypoint for CortexDB.

CortexDB is a pure-Go, single-file AI memory and knowledge graph library. It uses SQLite as the storage kernel and exposes vector search, lexical search, RAG knowledge storage, scoped agent memory, RDF/SPARQL/RDFS/SHACL knowledge graph features, corpus-to-graph workflows, and MCP-aligned tool APIs.

Architecture

The main packages are:

  • pkg/cortexdb: primary DB facade for vectors, text search, knowledge, memory, KnowledgeMemory recall, knowledge graph APIs, GraphRAG tools, and MCP.
  • pkg/memoryflow: agent memory workflow for transcript ingest, recall, wake-up layers, diary, transcript reconstruction, and promotion.
  • pkg/graphflow: corpus-to-graph workflow for extraction schema, build, analysis, report, JSON/Markdown/HTML export, and optional LLM extraction.
  • pkg/graph: low-level graph engine for property graph operations, RDF triples/quads, SPARQL, RDFS-lite inference, and SHACL-lite validation.
  • pkg/core: low-level SQLite storage, embeddings, FTS5, indexes, and chat/session primitives.

Use pkg/cortexdb first unless you need a workflow layer or low-level graph control.

Quick Start

import (
	"context"
	"github.com/liliang-cn/cortexdb/v2/pkg/cortexdb"
)

func main() {
	db, _ := cortexdb.Open(cortexdb.DefaultConfig("KnowledgeMemory.db"))
	defer db.Close()

	ctx := context.Background()
	quick := db.Quick()

	_, _ = quick.Add(ctx, []float32{0.1, 0.2, 0.9}, "SQLite is a single-file database.")
	_, _ = quick.Search(ctx, []float32{0.1, 0.2, 0.8}, 3)
}

Knowledge and Memory

Durable knowledge and scoped memory are available directly on DB:

_, _ = db.SaveKnowledge(ctx, cortexdb.KnowledgeSaveRequest{
	KnowledgeID: "apollo-plan",
	Title:       "Apollo launch plan",
	Content:     "Alice owns Apollo. Apollo ships on Friday.",
	Keywords:    nil,
})

_, _ = db.SearchKnowledge(ctx, cortexdb.KnowledgeSearchRequest{
	Query:         "Who owns Apollo?",
	Keywords:      []string{"Apollo", "Alice", "owns"},
	RetrievalMode: cortexdb.RetrievalModeLexical,
	TopK:          3,
})

_, _ = db.SaveMemory(ctx, cortexdb.MemorySaveRequest{
	MemoryID:  "style",
	UserID:    "user-1",
	Scope:     cortexdb.MemoryScopeUser,
	Namespace: "assistant",
	Content:   "User prefers concise status updates.",
})

Knowledge Graph

The high-level knowledge graph API supports RDF triples/quads, import/export, SPARQL, RDFS-lite inference, and SHACL-lite validation:

_, _ = db.UpsertKnowledgeGraph(ctx, cortexdb.KnowledgeGraphUpsertRequest{
	Triples: []cortexdb.KnowledgeGraphTriple{
		{
			Subject:   graph.NewIRI("https://example.com/alice"),
			Predicate: graph.NewIRI(graph.RDFType),
			Object:    graph.NewIRI("https://example.com/Person"),
		},
	},
})

_, _ = db.QueryKnowledgeGraph(ctx, cortexdb.KnowledgeGraphQueryRequest{
	Query: `SELECT ?o WHERE { <https://example.com/alice> ?p ?o . }`,
})

_, _ = db.RefreshKnowledgeGraphInference(ctx, cortexdb.KnowledgeGraphInferenceRefreshRequest{
	Mode: cortexdb.KnowledgeGraphInferenceRefreshModeIncremental,
})

SPARQL support is a practical embedded subset. It includes SELECT, ASK, CONSTRUCT, DESCRIBE, update forms, OPTIONAL, UNION, MINUS, VALUES, BIND, FILTER, EXISTS, NOT EXISTS, aggregates, subqueries, and constrained property paths such as ^pred, p|q, p+, and p*.

MemoryFlow

Use pkg/memoryflow for chat/session memory workflows:

flow, _ := memoryflow.New(db, planner, extractor)
_, _ = flow.IngestTranscript(ctx, memoryflow.IngestTranscriptRequest{...})
_, _ = flow.WakeUpLayers(ctx, memoryflow.WakeUpLayersRequest{...})

Hindsight can be used as an optional recall strategy plugin without replacing memoryflow:

flow, _ := memoryflow.New(
	db,
	planner,
	extractor,
	memoryflow.WithRecallStrategy(hindsight.NewStrategy(db, hindsight.StrategyOptions{
		BankID:      "apollo-agent",
		EntityNames: []string{"Apollo"},
		Keywords:    []string{"deadline"},
		UseKG:       true,
	})),
)

LLM-dependent parts are interfaces: QueryPlanner, SessionExtractor, and PromotionPolicy.

GraphFlow

Use pkg/graphflow for corpus-to-graph workflows:

// ExtractionResult can come from deterministic code or an LLM.
_, _ = graphflow.Build(ctx, db, []graphflow.ExtractionResult{extraction}, graphflow.BuildOptions{})
report, _ := graphflow.Analyze(ctx, db, graphflow.AnalyzeRequest{TopN: 10})
_, _ = graphflow.Export(ctx, db, graphflow.ExportRequest{OutputDir: "graphflow-out", Analysis: report})

LLM extraction depends only on graphflow.JSONGenerator. The example examples/05_graphflow demonstrates github.com/openai/openai-go/v3 with JSON Schema structured output.

Tools and MCP

In-process tool calling:

tools := db.GraphRAGTools()
defs := tools.Definitions()
resp, err := tools.Call(ctx, "knowledge_graph_query", payload)
_, _, _ = defs, resp, err

MCP:

server := db.NewMCPServer(cortexdb.MCPServerOptions{})
_ = server

Examples

The examples directory is organized by architecture:

go run ./examples/01_core
go run ./examples/02_rag
go run ./examples/03_memoryflow
go run ./examples/04_knowledge_graph
go run ./examples/05_graphflow
go run ./examples/06_tools_mcp

Index

Constants

View Source
const Version = "2.92.0"

Version represents the current version of the cortexdb library.

Variables

This section is empty.

Functions

This section is empty.

Types

This section is empty.

Directories

Path Synopsis
cmd
cortexdb-connector-mcp command
cortexdb-connector-mcp runs the data-connector tools (connector_introspect, connector_plan, connector_run, connector_unmask) as an MCP stdio server.
cortexdb-connector-mcp runs the data-connector tools (connector_introspect, connector_plan, connector_run, connector_unmask) as an MCP stdio server.
cortexdb-grpc command
Command cortexdb-grpc serves the pkg/cortexdb facade over gRPC.
Command cortexdb-grpc serves the pkg/cortexdb facade over gRPC.
examples
01_core command
02_rag command
03_memoryflow command
05_graphflow command
06_tools_mcp command
07_importflow command
08_self_knowledge_graph command
Dogfooding demo: turn docs/PROJECT_OVERVIEW.md (CortexDB's own project overview) into a knowledge graph using CortexDB's graphflow workflow, with an LLM extractor.
Dogfooding demo: turn docs/PROJECT_OVERVIEW.md (CortexDB's own project overview) into a knowledge graph using CortexDB's graphflow workflow, with an LLM extractor.
09_connector command
Demo: desensitize a CSV through the connector privacy gate, then import to RAG.
Demo: desensitize a CSV through the connector privacy gate, then import to RAG.
10_support_brain command
Customer-support "agent brain" — an end-to-end CortexDB demo over a REAL database (Postgres or MySQL).
Customer-support "agent brain" — an end-to-end CortexDB demo over a REAL database (Postgres or MySQL).
11_unified_brain command
Unified support brain — a complex, multi-source CortexDB application.
Unified support brain — a complex, multi-source CortexDB application.
12_incident_agent command
Incident-analysis agent — a complex CortexDB example that REQUIRES an LLM (a chat/generation model, not an embedding model).
Incident-analysis agent — a complex CortexDB example that REQUIRES an LLM (a chat/generation model, not an embedding model).
13_scale_analytics command
Scale + analytics — a comprehensive, larger-volume CortexDB example.
Scale + analytics — a comprehensive, larger-volume CortexDB example.
14_semantic_rag command
Semantic RAG — CortexDB with a real embedding model (vector search), plus an LLM answer.
Semantic RAG — CortexDB with a real embedding model (vector search), plus an LLM answer.
15_cortex_query command
Cortex Query — composable retrieval over one local CortexDB file.
Cortex Query — composable retrieval over one local CortexDB file.
16_ontology command
Command ontology demonstrates the Palantir-style ontology end to end: typed object types with mandatory primary keys, link types with per-side cardinality, interfaces for polymorphic retrieval, the composable object set algebra, governed writes through action types, typed tool generation, schema diffing, and the strict_actions write gate.
Command ontology demonstrates the Palantir-style ontology end to end: typed object types with mandatory primary keys, link types with per-side cardinality, interfaces for polymorphic retrieval, the composable object set algebra, governed writes through action types, typed tool generation, schema diffing, and the strict_actions write gate.
17_query_source command
Command query_source shows an external search engine acting as one retrieval lane inside CortexDB, without becoming CortexDB's storage.
Command query_source shows an external search engine acting as one retrieval lane inside CortexDB, without becoming CortexDB's storage.
kg_e2e command
Command kg_e2e is a runnable, fully-printed end-to-end walkthrough of the CortexDB RDF / Knowledge Graph stack through the public pkg/cortexdb facade.
Command kg_e2e is a runnable, fully-printed end-to-end walkthrough of the CortexDB RDF / Knowledge Graph stack through the public pkg/cortexdb facade.
internal
pgtest
Package pgtest gives a test its own PostgreSQL schema.
Package pgtest gives a test its own PostgreSQL schema.
testname
Package testname hands out the unique numbers that tests use to name the databases, schemas and files they create.
Package testname hands out the unique numbers that tests use to name the databases, schemas and files they create.
pkg
agentmem
Package agentmem is a SQL-backed agent memory store.
Package agentmem is a SQL-backed agent memory store.
authz
Package authz is the key and scope model behind CortexDB's gRPC server.
Package authz is the key and scope model behind CortexDB's gRPC server.
connector
Package connector turns live data sources into agent-usable knowledge with desensitization as a first-class step.
Package connector turns live data sources into agent-usable knowledge with desensitization as a first-class step.
core
Package core provides advanced search capabilities
Package core provides advanced search capabilities
cortexdb
Package cortexdb provides a lightweight SQLite-based vector database for Go AI projects
Package cortexdb provides a lightweight SQLite-based vector database for Go AI projects
eval
Package eval is a retrieval-quality evaluation harness for CortexDB.
Package eval is a retrieval-quality evaluation harness for CortexDB.
geo
Package geo provides geo-spatial indexing and search capabilities for cortexdb
Package geo provides geo-spatial indexing and search capabilities for cortexdb
graphflow
Package graphflow provides a library-first graph extraction/build/report/export pipeline over CortexDB's graph and RDF storage.
Package graphflow provides a library-first graph extraction/build/report/export pipeline over CortexDB's graph and RDF storage.
hindsight
Package hindsight: chat.go provides a thin wrapper around the cortexdb session/message API that optionally auto-triggers fact extraction.
Package hindsight: chat.go provides a thin wrapper around the cortexdb session/message API that optionally auto-triggers fact extraction.
httpapi
Package httpapi exposes the pkg/cortexdb facade over HTTP/JSON.
Package httpapi exposes the pkg/cortexdb facade over HTTP/JSON.
importflow
Package importflow imports external structured data (CSV, MySQL/PG SQL dumps) into CortexDB, building RAG (vector/FTS5) and knowledge-graph (RDF triple) foundations in a single pass.
Package importflow imports external structured data (CSV, MySQL/PG SQL dumps) into CortexDB, building RAG (vector/FTS5) and knowledge-graph (RDF triple) foundations in a single pass.
index
Package index provides vector indexing implementations
Package index provides vector indexing implementations
liveview
Package liveview serves a knowledge graph as a live, rotatable 3D page.
Package liveview serves a knowledge graph as a live, rotatable 3D page.
memoryflow
Package memoryflow provides a higher-level workflow facade on top of CortexDB's memory, knowledge, and KnowledgeMemory primitives.
Package memoryflow provides a higher-level workflow facade on top of CortexDB's memory, knowledge, and KnowledgeMemory primitives.
observability
Package observability gives CortexDB the three things an operator needs from a process that calls itself a service: counters, gauges and histograms that can be scraped, the same numbers on /debug/vars for a human with curl, and a tracing seam that some other module can fill in.
Package observability gives CortexDB the three things an operator needs from a process that calls itself a service: counters, gauges and histograms that can be scraped, the same numbers on /debug/vars for a human with curl, and a tracing seam that some other module can fill in.
quantization
Package quantization provides vector compression techniques
Package quantization provides vector compression techniques
rpcserver
Package rpcserver exposes the pkg/cortexdb facade over gRPC.
Package rpcserver exposes the pkg/cortexdb facade over gRPC.
semantic-router
Package semantic-router provides a semantic routing layer for LLM applications.
Package semantic-router provides a semantic routing layer for LLM applications.
sqldialect
Package sqldialect is the thin layer that lets one body of SQL run on both SQLite and PostgreSQL.
Package sqldialect is the thin layer that lets one body of SQL run on both SQLite and PostgreSQL.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL