Skip to main content

Chaos Cypher Cortex - Full-featured knowledge graph platform (processing center)

Project description

ChaosCypher Cortex

Full-featured knowledge graph backend API - Processing center

Cortex is the main backend API for ChaosCypher, providing comprehensive CRUD operations, workflow execution, document source processing, AI-powered chat, and knowledge graph management using Vertical Slice Architecture (VSA).

Features

  • ๐Ÿ“Š Knowledge Graph Management: Full CRUD for nodes, edges, and templates
  • ๐Ÿ’ฌ AI Chat: Conversational interface with RAG and tool use
  • ๐Ÿ“ Document Source Processing: Process PDFs, text files, CSVs into knowledge graphs
  • ๐Ÿ”„ Workflow Engine: Execute multi-step AI research workflows with triggers
  • ๐Ÿ” Search: FTS5 full-text + sqlite-vec vector search; multi-hop GraphRAG retrieval
  • ๐Ÿ”Œ MCP Server: Expose graph operations as Model Context Protocol tools
  • โš™๏ธ Settings Management: Configure LLM providers, databases, and system settings
  • ๐Ÿ” Single-User Auth: nginx auth_request gates every API call (no admin/user split)
  • ๐Ÿ—„๏ธ Multi-Database: Isolated workspaces with independent graphs

Architecture

Cortex is part of the ChaosCypher neural architecture:

  • Core - Brain (business logic)
  • Cortex - Processing center (full backend) ๐Ÿ‘ˆ You are here
  • Neuron - Worker cells (background processing)
  • Interface - Interaction layer (UI)

Vertical Slice Architecture (VSA)

Cortex uses VSA with self-contained feature slices. Each slice contains its own routes, service logic, and Pydantic models. The authoritative list is the set of directories under packages/cortex/src/chaoscypher_cortex/features/:

packages/cortex/src/chaoscypher_cortex/
โ”œโ”€โ”€ api/                      # API composition
โ”‚   โ””โ”€โ”€ v1/router.py          # Router registration (mounts all feature routers)
โ”œโ”€โ”€ features/                 # VSA slices (chats, sources, nodes, edges,
โ”‚                             # templates, search, llm, queue, settings,
โ”‚                             # settings_public, workflows, triggers, tools,
โ”‚                             # dashboard, graph, graph_snapshot, mcp, lexicon,
โ”‚                             # backup, export, quality, counts, health,
โ”‚                             # diagnostics, logs, pause, upgrade, edition,
โ”‚                             # databases, local_auth, admin_plugins)
โ”œโ”€โ”€ shared/                   # Shared infrastructure
โ”‚   โ”œโ”€โ”€ api/                 # Auth dependencies, error handling, pagination
โ”‚   โ”œโ”€โ”€ database/            # Database session
โ”‚   โ”œโ”€โ”€ llm/                 # LLM factory
โ”‚   โ””โ”€โ”€ queue/               # Queue utilities
โ”œโ”€โ”€ app_factory.py            # create_app() โ€” FastAPI app assembly
โ”œโ”€โ”€ boot.py                   # Startup orchestration
โ”œโ”€โ”€ lifespan.py               # Lifespan (startup/shutdown) wiring
โ”œโ”€โ”€ middleware.py             # Middleware stack
โ”œโ”€โ”€ shutdown.py               # Graceful shutdown
โ””โ”€โ”€ main.py                   # Thin CLI entrypoint

Each feature slice contains:

  • models.py - Pydantic DTOs (Request/Response)
  • repository.py - Data access layer
  • service.py - Business logic
  • api.py - REST endpoints + DI factory
  • __init__.py - Barrel exports

Installation

# From source (workspace sync โ€” installs core + cortex + all dev tools)
uv sync --all-packages --extra dev

# Single-package mode (cortex + its core dep only)
uv sync --package chaoscypher-cortex

The repo uses uv workspaces (see pyproject.toml [tool.uv.workspace]); pip install -e is no longer the supported install path. Install uv via the official installer before running these commands.

Usage

Standalone

# Start Cortex server
cc-cortex start

# Custom host/port
cc-cortex start --host 0.0.0.0 --port 8080

# With environment variables
QUEUE_HOST=localhost QUEUE_PORT=6379 cc-cortex start

Docker

# Development
docker compose -f packages/docker/multi-container/docker-compose.dev.yml up cortex

# Production
docker run -p 8080:8080 -e QUEUE_HOST=valkey -e QUEUE_PORT=6379 chaoscypher-cortex

Programmatic

from chaoscypher_cortex.main import create_app

app = create_app()

# Run with uvicorn
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8080)

Configuration

Configure via environment variables or settings.yaml in the data directory (/data/settings.yaml inside the app-data volume under Docker; the platform data dir, e.g. ~/.local/share/chaoscypher, when running bare):

# Queue (Valkey)
QUEUE_HOST=localhost
QUEUE_PORT=6379

# Database
CHAOSCYPHER_DATA_DIR=~/.local/share/chaoscypher
CHAOSCYPHER_CONFIG_DIR=~/.config/chaoscypher

# Logging
LOG_LEVEL=INFO
USE_JSON_LOGGING=false

# LLM Provider (provider only โ€” models are configured in the Settings UI
# or via settings.yaml llm.* keys)
CHAOSCYPHER_LLM_PROVIDER=ollama   # ollama | openai | anthropic | gemini

# API Keys (if using cloud providers)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...

API Endpoints

Routes live under /api/v1/ and are gated by nginx auth_request (no register/login flow inside Cortex). The full surface includes:

  • Knowledge graph โ€” /nodes, /edges, /templates, /graph
  • Sources โ€” /sources (upload, list, extract, commit, citations, chunks). SourceResponse exposes user upload-time choices via the nested upload_options object (auto_analyze, enable_normalization, enable_vision, content_filtering, filtering_mode, extraction_depth, forced_domain), per-stage drop / merge counters via quality_metrics (40+ typed counters + companion fields like loader_encoding_used), and search-index health via quality_metrics.vector_indexing_status (pending / indexed / degraded / failed). New persisted upload settings must round-trip through upload_options, never as siblings on SourceResponse โ€” see packages/docs/docs/reference/api/sources.md.
  • Search โ€” /search (FTS5, vector, hybrid, GraphRAG)
  • Chat โ€” /chats, /chats/{id}/messages, /chats/{id}/send + /chats/{id}/events (SSE), plus /cancel, /retry, /regenerate, /export
  • Workflows โ€” /workflows, /workflows/{id}/executions, /triggers, /tools
  • Settings โ€” /settings, /settings/reset (plus scoped /settings/reset/{scope} variants)
  • Queue โ€” /queue/tasks, /queue/stats
  • Operations โ€” /llm/stats, /llm/tasks (Ollama instance management lives under /settings/ollama), /databases, /exports, /backup
  • Diagnostics โ€” /health, /diagnostics, /logs, /edition, plus pause/resume under /sources/{id}/... and /system/processing/...
  • MCP โ€” /mcp (Streamable HTTP transport: POST for JSON-RPC, GET for the SSE stream, DELETE to end a session)

The complete reference (request/response shapes, query params, error envelopes) is in packages/docs/docs/reference/api/ and at the live OpenAPI page http://localhost:8080/docs (disabled by default โ€” start Cortex with ENABLE_API_DOCS=true to enable /docs, /redoc, and /openapi.json).

Development

Project Structure

packages/cortex/
โ”œโ”€โ”€ src/chaoscypher_cortex/
โ”‚   โ”œโ”€โ”€ api/                # Router registration (api/v1/router.py)
โ”‚   โ”œโ”€โ”€ features/           # VSA feature slices
โ”‚   โ”œโ”€โ”€ shared/             # Shared infrastructure
โ”‚   โ””โ”€โ”€ main.py             # Thin CLI entrypoint
โ”œโ”€โ”€ tests/                  # Test suite
โ”œโ”€โ”€ Dockerfile              # Production image
โ”œโ”€โ”€ Dockerfile.dev          # Development image
โ””โ”€โ”€ pyproject.toml          # Package configuration

Adding New Features

  1. Create directory: features/{feature}/
  2. Define DTOs: {feature}/models.py
  3. Create repository: {feature}/repository.py
  4. Create service: {feature}/service.py
  5. Create API + factory: {feature}/api.py
  6. Export: {feature}/__init__.py
  7. Register router in api/v1/router.py

Example:

# features/my_feature/models.py
from pydantic import BaseModel

class MyFeatureRequest(BaseModel):
    name: str

class MyFeatureResponse(BaseModel):
    id: str
    name: str

# features/my_feature/service.py
class MyFeatureService:
    def create(self, data: dict) -> dict:
        # Business logic
        return {"id": "123", "name": data["name"]}

# features/my_feature/api.py
from fastapi import APIRouter, Depends

router = APIRouter(prefix="/api/v1/my-feature", tags=["My Feature"])

def get_service() -> MyFeatureService:
    return MyFeatureService()

@router.post("/", response_model=MyFeatureResponse)
def create_item(
    request: MyFeatureRequest,
    service: Annotated[MyFeatureService, Depends(get_service)]
):
    return service.create(request.model_dump())

Testing

# Run all tests
pytest

# Unit tests only
pytest -m unit

# With coverage
pytest --cov=chaoscypher_cortex --cov-report=html

Hot-Reload Development

# Using watchdog (not a workspace dependency โ€” uv adds it for this run;
# it is preinstalled only in the dev Docker image)
uv run --with watchdog watchmedo auto-restart -d src -p "*.py" -- cc-cortex start

# Using Docker
docker compose -f packages/docker/multi-container/docker-compose.dev.yml up cortex

Dependencies

  • Core: chaoscypher-core - Business logic
  • FastAPI: Web framework
  • SQLModel: Database ORM
  • Valkey (via chaoscypher_core.queue): Background task queue
  • Structlog: Structured logging
  • Pydantic: Data validation

License

AGPL-3.0 License - See LICENSE file for details

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chaoscypher_cortex-0.2.0.tar.gz (271.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chaoscypher_cortex-0.2.0-py3-none-any.whl (363.1 kB view details)

Uploaded Python 3

File details

Details for the file chaoscypher_cortex-0.2.0.tar.gz.

File metadata

  • Download URL: chaoscypher_cortex-0.2.0.tar.gz
  • Upload date:
  • Size: 271.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.20 {"installer":{"name":"uv","version":"0.11.20","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for chaoscypher_cortex-0.2.0.tar.gz
Algorithm Hash digest
SHA256 ca9be532fd2d22b68fa4aca7145a5a29b328c22823f2effcf1c349aeea7aab7b
MD5 c24499412e75703a6d0634e9a3ed4577
BLAKE2b-256 9792020bb26a1d45b29272efdc969df86c0bad30d9b5c2ed5446fa80637c293f

See more details on using hashes here.

File details

Details for the file chaoscypher_cortex-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: chaoscypher_cortex-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 363.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.20 {"installer":{"name":"uv","version":"0.11.20","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for chaoscypher_cortex-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 10fa1b81a52d48937d32791eebfe618dae3fd1dac684c751cee21b4e4b00c05a
MD5 612c4f80caa38ae219b1ad0f7d89d62e
BLAKE2b-256 d3f4f7037d4a510c410b0dc773588be240eba9b2ee1074903818560b71bbb9e4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page