Contributing to Deriva¶
Thanks for your interest in contributing to Deriva!
Python 3.14+ is required. The project uses modern Python features and is developed with 3.14 in mind.
Tooling: We use uv for package management, Ruff for linting/formatting, and ty for type checking. Pydantic AI is used for interacting with LLMs, DuckDB for storing configurations and settings. For testing we use pytest and codecov for CI test coverage reporting.
Development Setup¶
# Clone the repo
git clone https://github.com/StevenBtw/deriva.git
cd Deriva
# Copy environment template
cp .env.example .env
# Edit .env with your configuration (LLM keys, etc.)
# Install all three packages (editable) and the development tools
uv sync
# Run the studio (build the front end once: cd studio && npm install && npm run build)
uv run deriva
# Run linter
uv run ruff check .
# Run type checker
uv run ty check .
Workspace and packages¶
The repository is a uv workspace that builds three packages, released together with one version number. They share one Python namespace, deriva (a namespace package: there is no deriva/__init__.py).
| Package | Source | Holds |
|---|---|---|
deriva-cli |
the root, deriva/ |
adapters, modules, common, services and the CLI |
deriva-studio |
packages/deriva-studio/src/deriva/studio/ |
the studio backend and its built front end (static/, from studio/) |
deriva-dev |
packages/deriva-dev/src/deriva/bench/ |
benchmarking, with its CLI commands and its studio API |
uv sync installs all three as editable, so a checkout always has benchmarking. The CLI and the studio load deriva.bench only when it is installed (deriva.services.about.features()); without it, deriva-cli benchmark says how to install deriva-dev.
Build the packages the way users get them:
cd studio && npm ci && npm run build && cd ..
uv build --all-packages --no-sources # dist/: three wheels and three sdists
--no-sources builds without the local overrides in [tool.uv.sources], as uv recommends before publishing. tests/test_packaging.py builds the wheels and checks that each holds exactly its own files.
To try a build as a user would, install it as a tool with every workspace wheel by path; uv otherwise reuses a cached build of the same version number:
uv tool install --python 3.14 dist/deriva_studio-<version>-py3-none-any.whl --with dist/deriva_cli-<version>-py3-none-any.whl
Point DERIVA_HOME at an empty folder to see a first start.
To release, set the same version in the three pyproject.toml files and in the two pins between them (deriva-studio pins deriva-cli==<version>, deriva-dev pins deriva-studio==<version>), then push the tag v<version>. The release workflow checks the versions and pins, builds and smoke tests the packages, publishes them to PyPI with trusted publishing and attaches constraints.txt to the GitHub release.
Architecture¶
Deriva follows a layered architecture with strict separation of concerns:
- studio/ (FastAPI + React): Local web UI for running the pipeline, the graphs, the model and configuration
- cli/cli.py: Headless CLI for automation and scripting
- Services: Shared orchestration layer with
PipelineSessionas the unified API - Adapters: Stateful services for I/O, persistence, connections
- Modules: Pure functions for business logic transformations
Key Principle: Both the studio and the CLI use PipelineSession from the services layer. This provides a unified API for lifecycle management, queries, and orchestration. Configuration lives in DuckDB (single source of truth). Data flows through pure transformations, with I/O isolated to adapters.
Architectural Boundaries (Enforced by Ruff)¶
CLI → services only (PipelineSession is the API)
App → services only (PipelineSession is the API)
Bench → services, adapters, modules, common (deriva-dev; only the CLI and studio entry points load it)
Services → adapters, modules, common
Adapters → common only (NOT modules or services)
Modules → common only (NOT adapters or services)
Common → stdlib and third-party only
These boundaries are enforced at lint time via Ruff's TID251 rule with per-layer ruff.toml files.
The same rule keeps third-party libraries where their package declares them (extend-banned-api in pyproject.toml, inherited by every layer): the heavy engines (pydantic-ai, spaCy, CTranslate2, DuckDB, grafeo, lxml, tree-sitter) only in adapters/, the web stack (FastAPI, Starlette, uvicorn, the widgets) only in the studio and bench, and packages no Deriva package declares (requests, anywidget, ipywidgets, marimo) nowhere.
Architecture Overview
### Component Hierarchyderiva/
├── studio/
│ ├── app.py - FastAPI app factory (studio layer, services only)
│ ├── routers/ - API routes (repositories, configs, graph, model, runs, grafeo)
│ └── static/ - Built React front end (from studio/ at the repo root)
├── cli/
│ └── cli.py - Headless CLI + uses PipelineSession
│
├── services/ (Shared orchestration layer)
│ ├── session.py - PipelineSession: unified API for the CLI and the studio
│ ├── config.py - Config CRUD (read/write DuckDB settings)
│ ├── extraction.py - Run extraction step
│ ├── derivation.py - Run derivation step
│ ├── pipeline.py - Orchestrate full pipeline
│ └── benchmarking.py - Multi-model benchmarking and analysis
│
├── common/ (Shared utilities)
│ ├── types.py - Shared TypedDicts, Protocols, ProgressReporter
│ ├── logging.py - Pipeline logging with structlog (JSON Lines output)
│ ├── chunking.py - File chunking with overlap support
│ └── utils.py - File encoding, helpers
│
├── adapters/ (Stateful I/O services)
│ ├── database/ - DuckDB configuration storage
│ ├── grafeo/ - Embedded graph database (grafeo)
│ ├── repository/ - Git operations
│ ├── graph/ - Graph CRUD (namespace: Graph)
│ ├── archimate/ - ArchiMate CRUD (namespace: Model)
│ └── llm/ - LLM provider abstraction (Azure, OpenAI, Anthropic, Ollama)
│
└── modules/ (Pure business logic)
└── analysis/
├── consistency.py - Model consistency checks
├── deviation.py - Deviation analysis
└── types.py - Shared analysis types
└── extraction/
├── base.py - Shared extraction utilities (ID generation, deduplication)
├── classification.py - File type classification
├── repository.py - Repository node extraction
├── directory.py - Directory node extraction
├── file.py - File node extraction (with type/subtype)
├── edges.py - Unified edge extraction (IMPORTS, CALLS, REFERENCES, etc.)
├── type_definition.py - Classes/functions (AST for Python, LLM for others)
├── method.py - Methods within type definitions
├── business_concept.py - Domain concepts (LLM)
├── technology.py - Frameworks/libraries detection
├── external_dependency.py - External dependencies
├── test.py - Test definitions
├── ast_extraction.py - Python AST parsing
└── input_sources.py - Input source filtering
└── derivation/
├── base.py - Shared utilities (prompts, parsing, graph filtering)
├── element_base.py - HybridDerivation base class for all element modules
├── application_component.py - ApplicationComponent derivation
├── application_interface.py - ApplicationInterface derivation
├── application_service.py - ApplicationService derivation
├── business_actor.py - BusinessActor derivation
├── business_event.py - BusinessEvent derivation
├── business_function.py - BusinessFunction derivation
├── business_object.py - BusinessObject derivation
├── business_process.py - BusinessProcess derivation
├── data_object.py - DataObject derivation
├── device.py - Device derivation
├── node.py - Node derivation
├── system_software.py - SystemSoftware derivation
└── technology_service.py - TechnologyService derivation
┌─────────────────┐ ┌─────────────────┐
│ Studio │ │ CLI │
│ (web UI) │ │ (headless) │
└────────┬────────┘ └────────┬────────┘
│ │
└───────────┬───────────────┘
│
┌──────▼──────┐
│ PipelineSession │ ← unified API
└──────┬──────┘
│
┌──────▼──────┐
│ Services │ ← orchestration functions
└──────┬──────┘
│
┌───────────┼───────────┐
│ │ │
┌──────▼──────┐ ┌──▼───┐ ┌─────▼─────┐
│ Adapters │ │Modules│ │ Common │
│ (I/O) │ │(pure) │ │ (shared) │
└─────────────┘ └──────┘ └───────────┘
User clicks "Run" in the studio OR runs `deriva-cli run` in the CLI
↓
┌─────────────────────────────────────────────────────────────┐
│ PIPELINESESSION (unified API for the CLI and the studio) │
├─────────────────────────────────────────────────────────────┤
│ with PipelineSession() as session: │
│ session.run_extraction(repo_name="my-repo") │
│ session.run_derivation() │
│ session.export_model("output.xml") │
│ │
│ # For the studio (one session per process): │
│ stats = session.get_graph_stats() │
│ elements = session.get_archimate_elements() │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ EXTRACTION (inside services.extraction) │
├─────────────────────────────────────────────────────────────┤
│ Phases: classify → parse │
│ 1. Load config from DuckDB via services.config │
│ 2. Get repos from RepositoryManager │
│ 3. Classify: modules.extraction.classification [PURE] │
│ 4. Parse: modules.extraction.structural/* [PURE] │
│ 5. Parse: modules.extraction.llm/* [PURE + LLM] │
│ 6. Persist via GraphManager.add_node() [I/O] │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ DERIVATION (inside services.derivation) │
├─────────────────────────────────────────────────────────────┤
│ Phases: prep → generate → refine │
│ 1. Prep: Graph enrichment (PageRank, communities, k-core) │
│ 2. Generate: Query candidates with enrichment data [I/O] │
│ 3. Generate: Call modules.derivation.{element}.generate() │
│ 4. Generate: Persist via ArchimateManager.add_element() │
│ 5. Relationship: Derive relationships per-element or batch │
└─────────────────────────────────────────────────────────────┘
↓
Export via ArchimateManager.export_to_xml() [I/O]
↓
Studio: streams progress and shows results | CLI: prints summary to stdout
Code Style¶
Naming at a Glance¶
| Element | Convention | Example |
|---|---|---|
| Files/modules | snake_case |
file_utils.py, manager.py |
| Classes | PascalCase |
GraphManager, ExtractionResult |
| Functions/methods | snake_case |
read_file_with_encoding() |
| Variables | snake_case |
file_path, element_type |
| Constants | UPPER_SNAKE_CASE |
DEFAULT_TIMEOUT, MAX_RETRIES |
| Private | _prefix |
_internal_cache, _serialize_value() |
| TypedDicts | PascalCase |
PipelineResult, LLMDetails |
| Protocols | PascalCase + descriptive |
ExtractionFunction, Serializable |
Architectural Rules¶
- Adapters: Stateful, own schemas, provide CRUD, raise exceptions
- Modules: Pure functions, no I/O, return data/errors as dicts
- app/app.py: Orchestration only, no business logic
- Single config source: All configuration in
.env(no YAML)
File Structure¶
Every Python file follows this structure:
"""Module-level docstring explaining what this module does."""
from __future__ import annotations # Always include
# Standard library
import json
from pathlib import Path
from typing import Any, Protocol, TypedDict
# Third-party
from pydantic import BaseModel
# Local imports
from common.types import PipelineResult
from .models import RepositoryNode
# Module constants
DEFAULT_TIMEOUT = 30
# Public API
__all__ = ["process_file", "FileProcessor"]
# =============================================================================
# Section Header (for longer files)
# =============================================================================
class FileProcessor:
"""Class implementation..."""
pass
Module Organization¶
Package style (directory with multiple files) - use when a module has related files:
adapters/graph/
├── __init__.py # Re-exports: from .manager import GraphManager
├── manager.py # Main class
├── models.py # Data models
└── queries.py # Complex queries (if needed)
Flat style (single file) - use for standalone utilities:
Rule of thumb: Start flat, graduate to a package when you need models.py or other supporting files.
Import Rules¶
- Always start with
from __future__ import annotations - Group imports: stdlib → third-party → local (blank line between groups)
- Relative imports for same-package:
from .models import Node - Absolute imports for cross-package:
from common.types import Result - Multi-line imports when 3+ items from same module
Type Hints
#### Modern Syntax (Python 3.10+)# Unions - use | not Optional or Union
def get_user(id: int) -> User | None:
...
# Collections - use lowercase builtins
items: list[str] = []
mapping: dict[str, int] = {}
class LLMDetails(TypedDict, total=False):
"""Tracks LLM call metadata for observability."""
prompt: str
response: str
tokens_in: int
tokens_out: int
cache_used: bool
Docstrings
**Core principle:** Explain the *why*, not the *what*. The code shows what happens; docstrings explain why it matters. #### Module Docstrings Brief. What is this module's job?"""JSON parsing utilities for Deriva.
Handles the messy reality of LLM output that's almost-but-not-quite valid JSON.
"""
class GraphManager:
"""
High-level interface for graph database operations.
Wraps grafeo complexity and provides domain-specific operations
like "add repository" rather than raw graph queries.
"""
def read_file_with_encoding(file_path: Path) -> str | None:
"""
Read a file with automatic encoding detection.
Handles the encoding mess you find in real codebases: UTF-8 with/without
BOM, UTF-16 variants, and falls back to Latin-1 for binary-ish text files.
Returns None rather than raising - caller decides how to handle.
Args:
file_path: Path to the file
Returns:
File content as string, or None if reading fails
"""
Comments
Comments explain **why**, not **what**. #### Good Comments# BOM markers indicate encoding - check before trying UTF-8
if raw.startswith(b'\xff\xfe'):
return raw.decode('utf-16-le')
# MERGE needs deterministic IDs to avoid duplicates
node_id = f"Repository_{repo_name}"
# LLMs sometimes return markdown-wrapped JSON
content = content.strip().removeprefix("```json").removesuffix("```")
Error Handling
#### Be Specific# Good - catch what you expect
try:
data = json.loads(content)
except json.JSONDecodeError as e:
return ParseResult(success=False, error=f"Invalid JSON: {e}")
# Bad - catches everything
try:
data = json.loads(content)
except Exception:
return None
def read_file(path: Path) -> str | None:
"""Returns None if file can't be read."""
try:
return path.read_text()
except (OSError, UnicodeDecodeError):
return None
def connect(self) -> None:
"""Raises ConnectionError if connection fails."""
try:
self._db = get_database()
except Exception as e:
raise ConnectionError(f"Failed to connect: {e}") from e
Python 3.14 Features
Since we're on Python 3.14, use these modern features: #### Deferred Annotations (PEP 649) No need to quote forward references: #### Exception Groups (PEP 654) Handle multiple exceptions with exception groups:# Exception groups (Python 3.11+)
try:
async_operations()
except* TimeoutError:
handle_timeout()
except* ConnectionRefusedError:
handle_connection_error()
Formatting
#### String Quotes Use double quotes consistently: #### Line Length 180 characters max (configured in `pyproject.toml`). But prefer shorter when readable. #### Checklist Before Committing - [ ] `from __future__ import annotations` at top - [ ] Imports organized: stdlib → third-party → local - [ ] Type hints on all public functions - [ ] Docstrings on all public classes and functions - [ ] No `print()` statements (use logging) - [ ] Double quotes for strings - [ ] `__all__` defined for modules with public API - [ ] `ruff check` passesAdapter Rules
### Purpose - Complex, stateful services that manage persistence and external systems - Own their schemas, metamodels, and validation logic - Provide CRUD operations for their domain - Do **NOT** contain business logic (that's in modules) ### Lifecycle - **One instance per session**: `PipelineSession` creates the adapters and keeps them for its lifetime - Maintain **persistent connections** for session lifetime - Support **auto-reconnect** with retry logic (max 3 attempts, exponential backoff) - Cleanup via `__del__` or `__exit__` methods ### Configuration - **Read .env** in `__init__` using `python-dotenv` - **Cache** config values (don't re-read on every operation) - Provide **defaults** for optional settings ### Dependencies - Can import **infrastructure adapters** (e.g., GraphManager ← GrafeoConnection) - **Cannot** import other domain adapters (e.g., GraphManager ✗← ArchimateManager) - **Cannot** import modules ### Error Handling - **Raise exceptions** with clear messages - Use **custom exception classes** (e.g., `GraphError`, `ArchimateError`) - Retry transient errors (connection issues) - Do **NOT** catch and silence errors ### Interface - Export via `__init__.py` (e.g., `from .manager import GraphManager`) - Consistent method naming: `add_*`, `get_*`, `update_*`, `delete_*`, `query_*` - Return **data** (dicts, lists, dataclasses), not side effects - Accept **parameters** from the services (don't read global state) ### Adapter Structureadapters/{name}/
├── __init__.py # Re-export manager class and models
├── manager.py # Main manager class with all CRUD logic
└── models.py # Data models with generate_id() methods
LLM Manager
### Overview The LLM adapter (`adapters/llm/`) provides a unified interface for multiple LLM providers using **pydantic-ai** for agent-based LLM interactions with automatic retries, caching, and structured output support. **Supported Providers:** - **Azure OpenAI** - Enterprise Azure deployments - **OpenAI** - Direct OpenAI API - **Anthropic** - Claude models - **Mistral** - Mistral AI models - **Ollama** - Local LLM inference (no API key required) ### Basic Usagefrom adapters.llm import LLMManager
llm = LLMManager() # Reads provider config from .env
response = llm.query("What is Python?")
if response.response_type == "live":
print(response.content)
elif response.response_type == "cached":
print(f"From cache: {response.content}")
else:
print(f"Error: {response.error}")
from pydantic import BaseModel, Field
from adapters.llm import LLMManager
class BusinessConcept(BaseModel):
name: str = Field(description="Concept name")
type: str = Field(description="actor, service, process, etc.")
description: str = Field(description="Brief description")
llm = LLMManager()
result = llm.query(
prompt="Extract the main business concept from: ...",
response_model=BusinessConcept
)
# result is a validated BusinessConcept instance
print(result.name) # Type-safe, IDE autocomplete works
# Use local Ollama
LLM_PROVIDER=ollama
LLM_OLLAMA_MODEL=llama3.2
LLM_OLLAMA_API_URL=http://localhost:11434/api/chat
# Use Azure OpenAI
LLM_PROVIDER=azure
LLM_AZURE_API_URL=https://your-resource.openai.azure.com/...
LLM_AZURE_API_KEY=your-key
LLM_AZURE_MODEL=gpt-4o-mini
from adapters.llm import create_provider, ProviderConfig
config = ProviderConfig(
api_url="http://localhost:11434/api/chat",
api_key=None,
model="llama3.2"
)
provider = create_provider("ollama", config)
result = provider.complete(
messages=[{"role": "user", "content": "Hello"}],
temperature=0.7
)
print(result.content)
Module Rules
### Purpose - **Pure business logic** - data transformations only - Abstracts complex operations away from the services and the UI - Do **NOT** manage state, connections, or I/O ### Purity - **Pure functions**: Same input → same output - **No side effects**: Don't write to files, databases, network - **No state**: No class variables, no module-level state - Return **data** (dicts, lists, dataclasses), never `None` - **No adapter imports** (receive adapter data via parameters) - **No I/O operations** (the services do I/O through adapters) ### Dependencies - Can import **Python stdlib** (pathlib, json, re, typing, dataclasses, etc.) - Can import **each other** (e.g., orchestration ← classification) - Can use **external libs** if pure (e.g., polars for data transforms) - **Cannot** import adapters - **Cannot** import UI libraries ### Error Handling - Return **error data** in results (e.g., `{'errors': [...]}`) - Use **type hints** for clarity - Do **NOT** raise exceptions (return errors as data) ### Result StructureModule Pattern
### Shared Types (`common/types.py`) All pipeline modules use shared TypedDicts and Protocols for consistent interfaces:from common.types import (
# Base result type - all modules return this structure
BaseResult, # success, errors, stats
LLMDetails, # prompt, response, tokens_in, tokens_out, cache_used
# Extraction types
ExtractionResult, # BaseResult + data: {nodes, edges} + llm_details
BatchExtractionResult,
# Derivation types
DerivationResult, # BaseResult + data: {elements_created, issues} + llm_details
DerivationConfig, # step_name, phase, input_graph_query, instruction, example
# Function protocols for type safety
ExtractionFunction,
DerivationFunction,
)
# services/derivation.py
def _load_element_module(element_type: str) -> Any:
"""Lazily load element generation module."""
if element_type == "ApplicationComponent":
from deriva.modules.derivation import application_component as module
elif element_type == "BusinessObject":
from deriva.modules.derivation import business_object as module
# ... other element types
return module
def generate_element(graph_manager, archimate_manager, llm_query_fn, element_type, ...):
"""Route to appropriate module based on element_type."""
module = _load_element_module(element_type)
return module.generate(graph_manager, archimate_manager, ...)
"""Contract element derivation."""
from __future__ import annotations
from deriva.modules.derivation.base import (
Candidate, GenerationResult, batch_candidates, build_derivation_prompt,
build_element, get_enrichments, parse_derivation_response, query_candidates,
DERIVATION_SCHEMA,
)
def generate(
graph_manager, archimate_manager, engine, llm_query_fn,
query: str, instruction: str, example: str,
max_candidates: int, batch_size: int,
temperature: float | None = None, max_tokens: int | None = None,
) -> GenerationResult:
# 1. Get enrichments from DuckDB
enrichments = get_enrichments(engine)
# 2. Query candidates using the graph query
candidates = query_candidates(graph_manager, query, enrichments)
# 3. Filter/limit candidates
candidates = candidates[:max_candidates]
# 4. Batch and process with LLM
# ... (see existing modules for full pattern)
return GenerationResult(success=True, elements_created=count, ...)
Module Reference
### Core Modules #### `extraction/classification.py` **Goal:** Classify files by type based on the file type registry.def classify_files(
file_paths: List[str],
file_type_registry: List[Dict[str, str]]
) -> Dict[str, Any]:
"""
Returns: {
'classified': [...], # Files with known types
'undefined': [...], # Files with unknown extensions
'stats': {...},
'errors': [...]
}
"""
class LogLevel(int, Enum):
PHASE = 1 # High-level: classification, extraction, derivation
STEP = 2 # Steps: Repository, Directory, File, etc.
DETAIL = 3 # Item-level: each file, node, edge
class RunLogger:
"""Structured logger using structlog for JSON Lines output."""
def phase_start(self, phase: str, message: str = "") -> None
def phase_end(self, phase: str, message: str = "") -> None
def step(self, step_name: str) -> StepContext # Context manager
def get_entries(self, min_level: int = 1) -> List[LogEntry]
def read_file_with_encoding(file_path: Path) -> Optional[str]:
"""Auto-detect encoding (UTF-8, UTF-16, Latin-1 fallback)."""
# Build a single node
def build_{node_type}_node(data: Dict) -> Dict[str, Any]
# Extract from files (structural) or via LLM (semantic)
def extract_{node_type}s(...) -> Dict[str, Any]:
"""
Returns: {
'nodes': [...],
'edges': [...],
'stats': {...},
'errors': [...]
}
"""
# Each LLM module exports:
def build_user_prompt(file_content: str, file_path: str, example: str, ...) -> str # Dynamic content
def build_extraction_prompt(...) -> str # Legacy combined format for backward compatibility
def parse_llm_response(response: str) -> List[Dict]
{NODE_TYPE}_SCHEMA: Dict # JSON schema for validation
{NODE_TYPE}_MULTI_SCHEMA: Dict # Schema for multi-file batch extraction
# Single file extraction
def extract_{type}s(file_path, content, repo_name, llm_query_fn, config) -> Dict[str, Any]
# Multi-file batch extraction (for token efficiency)
def extract_{type}s_multi(files: List[Dict], repo_name, llm_query_fn, config) -> Dict[str, Any]
from deriva.modules.extraction.edges import extract_edges_batch, EdgeType
# Extract all edge types (default)
result = extract_edges_batch(files, repo_name, repo_path)
# Extract specific edge types only
result = extract_edges_batch(
files, repo_name, repo_path,
edge_types={EdgeType.IMPORTS, EdgeType.CALLS}
)
def parse_input_sources(config: Dict) -> Dict[str, List[str]]
def filter_files_by_input_sources(files: List, specs: List[str]) -> List
def has_file_sources(config: Dict) -> bool
def has_node_sources(config: Dict) -> bool
from deriva.modules.derivation.element_base import HybridDerivation
class ApplicationComponentDerivation(HybridDerivation):
ELEMENT_TYPE = "ApplicationComponent"
OUTBOUND_RULES = [...] # Relationships FROM this element
INBOUND_RULES = [...] # Relationships TO this element
# Optional: customize filtering behavior via class constants
USE_COMMUNITY_ROOTS = True # Prioritize community root nodes
MIN_PAGERANK = 0.001 # Filter low-importance nodes
COMMUNITY_ROOT_RATIO = 0.6 # 60% community roots in results
from deriva.modules.derivation import (
Candidate, # Dataclass for candidate nodes with enrichment data
query_candidates, # Run the graph query and return enriched candidates
batch_candidates, # Split candidates into batches for LLM
build_derivation_prompt, # Build LLM prompt for elements
build_unified_relationship_prompt, # Build LLM prompt for relationships
parse_derivation_response, # Parse LLM element response
build_element, # Build ArchiMate element from LLM output
DERIVATION_SCHEMA, # JSON schema for element derivation
RELATIONSHIP_SCHEMA, # JSON schema for relationship derivation
)
def generate(
graph_manager: GraphManager,
archimate_manager: ArchimateManager,
engine: Any, # DuckDB connection for enrichment
llm_query_fn: Callable,
query: str, # Graph query for candidates
instruction: str, # LLM derivation instructions
example: str, # Example output
max_candidates: int,
batch_size: int,
temperature: float | None = None,
max_tokens: int | None = None,
) -> GenerationResult:
"""Returns GenerationResult with success, elements_created, created_elements, errors."""
Configuration Pattern
### Configuration Principle: "Who Changes It" Deriva splits configuration by **ownership** - who needs to change it and why: | Category | Location | Owner | Examples | | --------------------- | ---------- | ---------- | -------------------------------------------- | | **Secrets & Keys** | `.env` | Ops/Deploy | API keys, passwords | | **Infrastructure** | `.env` | Ops/Deploy | Connection URIs, paths, provider URLs | | **Provider Settings** | `.env` | Ops/Deploy | LLM rate limits, timeouts, model definitions | | **Algorithm Tuning** | Database | Users | PageRank damping, Louvain resolution | | **Quality Thresholds**| Database | Users | Confidence thresholds, batch sizes | | **Pipeline Configs** | Database | Users | Extraction/derivation prompts, patterns | **Rationale:** - **`.env`** = deployment-specific, rarely changes, requires restart - **Database** = tunable during optimization, versioned for rollback, UI-editable ### Two Configuration Systems 1. **Environment variables (`.env`)** - Infrastructure and provider settings 2. **Database configs (DuckDB)** - Pipeline behavior and tuning parameters ### .env File (Adapter Configuration) - Lives in the Deriva home folder (`deriva/common/paths.py`): the repository root in a checkout, `~/.deriva` for an installed tool, or the folder in `DERIVA_HOME` - **Read in one place**: `deriva/common/settings.py` merges the `.env` file with the process environment (a variable set in the environment wins) and offers typed groups (`LlmSettings`, `GrafeoSettings`, `GraphSettings`, `ArchimateSettings`, `NlpSettings`, `RepositorySettings`); `tests/test_common/test_no_cwd_paths.py` fails on any other `os.getenv`, `os.environ` or `load_dotenv` in the three packages - Each field of a group has a default; an empty number or switch counts as unset (the `LLM_{NAME}_*` model blocks are read by name, `settings.model_configs()`) - Values **cached** by adapters on init (not re-read on every call) - `.env.example` is the template - **No YAML files** for configuration - **Never commit** .env to git (keep in .gitignore) ### Environment Variables - Naming: `{MANAGER}_{CATEGORY}_{SETTING}` (e.g., `GRAFEO_DB_DIR`) - Provide **sensible defaults** in code if env var missing - Comma-separated for lists (e.g., `ARCHIMATE_ELEMENT_TYPES=Component,Service`) - Boolean as string: `true`/`false` (case-insensitive) ### Pattern# adapters/some_adapter/manager.py
from deriva.common.settings import GrafeoSettings
class SomeManager:
def __init__(self):
grafeo = GrafeoSettings()
self.slow_query_ms = grafeo.slow_query_ms
# Read all config in __init__
# Cache values as instance variables
Progress Tracking
### Overview The CLI provides visual progress tracking for pipeline and benchmark operations using the [Rich](https://rich.readthedocs.io/) library. This is implemented as an optional dependency with graceful fallback. ### Installation ### Features - **Progress bars** with ETA, elapsed time, and completion counts - **Spinner animations** for indeterminate operations - **Phase/step hierarchy** for multi-stage pipelines (extraction → derivation) - **Benchmark matrix display** showing current run context (repository, model, iteration) ### CLI Usage# Default: progress bars shown (if Rich installed)
deriva-cli run all --repo my-repo
# Quiet mode: disable progress display
deriva-cli run all --repo my-repo -q
# Verbose mode: detailed text output (also disables progress bar)
deriva-cli run all --repo my-repo -v
# Benchmark with progress
deriva-cli benchmark run --repos my-repo --models my-model -n 3
# Benchmark quiet mode
deriva-cli benchmark run --repos my-repo --models my-model -n 3 -q
class ProgressReporter(Protocol):
"""UI-agnostic progress reporting protocol."""
def start_phase(self, name: str, total_steps: int) -> None: ...
def start_step(self, name: str, total_items: int | None = None) -> None: ...
def update(self, current: int | None = None, message: str = "") -> None: ...
def advance(self, amount: int = 1) -> None: ...
def complete_step(self, message: str = "") -> None: ...
def complete_phase(self, message: str = "") -> None: ...
def log(self, message: str, level: str = "info") -> None: ...
class BenchmarkProgressReporter(Protocol):
"""Extended protocol for benchmark operations."""
# Includes all ProgressReporter methods plus:
def start_benchmark(self, session_id: str, total_runs: int, ...) -> None: ...
def start_run(self, run_number: int, repository: str, model: str, ...) -> None: ...
def complete_run(self, status: str, stats: dict | None = None) -> None: ...
def complete_benchmark(self, runs_completed: int, runs_failed: int, ...) -> None: ...
from deriva.common.types import ProgressReporter
def my_service_function(
...,
progress: ProgressReporter | None = None,
) -> dict:
if progress:
progress.start_phase("my_operation", total_steps=3)
# Step 1
if progress:
progress.start_step("Processing items", total_items=len(items))
for item in items:
process(item)
if progress:
progress.advance()
if progress:
progress.complete_step("Done")
# ... more steps ...
if progress:
progress.complete_phase("Operation complete")
return result
Benchmarking System
### Overview The benchmarking system enables multi-model comparison for evaluating LLM performance on the ArchiMate derivation pipeline. **Key Components:** - `deriva/bench/benchmarking.py` (in `packages/deriva-dev/src/`) - `BenchmarkOrchestrator` for running benchmarks, `BenchmarkAnalyzer` for analysis - OCEL 2.0 event logging for process mining analysis ### ArchitectureBenchmarkConfig
↓
BenchmarkOrchestrator
├── Clears graph/model between runs
├── Switches LLM provider per run
├── Executes pipeline stages
├── Logs events in OCEL format
└── Tracks runs in DuckDB
↓
BenchmarkAnalyzer
├── Intra-model consistency (stability)
├── Inter-model consistency (agreement)
└── Inconsistency localization (hotspots)
Naming Conventions¶
Use consistent naming across all components:
- snake_case everywhere (variables, functions, files)
- Verb-based function names:
add_*,get_*,build_*,validate_* - Predicate functions:
is_*,has_*,can_* - Short names when obvious:
x,y,i,j,n,m
Naming Details
### Variables & Functions# snake_case everywhere
parse_input, build_graph, max_iterations
# Short names when obvious
x, y, i, j, n, m # coordinates, indices, counts
xs, ys, vals # plurals for collections
# Verb-based functions
add_node(), build_graph(), get_neighbors()
# Predicate functions
is_valid(), can_place(), has_cycle()
Studio¶
The studio is the local web UI: packages/deriva-studio/src/deriva/studio/ (FastAPI backend, a top layer that imports deriva.services only, enforced by its ruff.toml) and studio/ at the repo root (React 19, Vite, TypeScript, CodeMirror 6, own CSS).
Running it¶
uv run deriva # API + built front end on http://127.0.0.1:8765
cd studio && npm run dev # front-end development; Vite forwards /api, /grafeo, /widgets to 8765
# open http://localhost:5173/api/auth?token=<the token deriva printed>
DERIVA_STUDIO_API=http://127.0.0.1:9000 npm run dev # the same for a studio started with --port 9000
npm test && npm run lint && npm run typecheck
npm run build # writes packages/deriva-studio/src/deriva/studio/static/ (git-ignored, shipped in the wheel)
Backend rules¶
- One
PipelineSessionper process, behind a lock (SessionProvider); request handlers and the run worker take it (the worker once per pipeline step). A database held by another process answers 503 with the holder's PID. - Step config edits go through the versioned service functions only (
save_extraction_config,save_derivation_config), never in-place updates. Model configs are not versioned: they live in.env(save_model_config). - Free-form graph queries (the widget's query bar) run read-only: a write guard plus a grafeo transaction that is always rolled back.
- Tests inject a fake session (
tests/test_studio/conftest.py); they never open the real databases.
Widgets¶
The studio mounts anywidget-graph and anywidget-archimate without Jupyter, through studio/src/widgets/host.ts (the model API a widget's front-end module expects). The backend serves each widget's module from the installed Python package (/widgets/<name>/index.js). anywidget-graph runs in grafeo server mode against /grafeo (health, query, schema), answered from the embedded databases.
Testing¶
Tests should mirror the source structure. When adding tests, use this organization:
tests/
├── test_adapters/ # Adapter integration tests
│ ├── test_database.py
│ ├── test_graph.py
│ └── ...
├── test_modules/ # Module unit tests
│ ├── extraction/
│ ├── derivation/
│ └── ...
└── test_services/ # Service tests
Running Tests¶
# Run all tests
uv run pytest
# Run specific test file
uv run pytest tests/test_modules/extraction/test_classification.py -v
# Run with coverage
uv run pytest --cov=.
Module Tests (Pure Functions)¶
# tests/test_modules/extraction/test_classification.py
def test_classify_files():
files = [{'path': 'deriva/main.py', 'content': '...'}]
registry = {'py': 'python'}
result = classification.classify_files(files, registry)
assert result[0]['type'] == 'python'
Module tests should be unit tests only - no external dependencies, mock data only.
Adapter Tests (Integration)¶
# tests/test_adapters/test_graph.py
def test_add_and_get_node():
manager = GraphManager()
node = {'id': 'test1', 'type': 'Repository'}
manager.add_node(node)
retrieved = manager.get_node('test1')
assert retrieved['id'] == 'test1'
Adapter tests may require external services (DuckDB) - use fixtures for setup/teardown.
Anti-Patterns to Avoid¶
| Anti-Pattern | Why It's Bad | Do This Instead |
|---|---|---|
| Importing adapters in app.py or cli.py | Violates architectural boundaries | Use PipelineSession from services |
| Business logic in app.py or cli.py | Hard to test, violates separation | Move logic to modules |
| Adapters importing adapters | Creates coupling | Coordinate via services |
| Modules with I/O | Breaks purity, hard to test | Pass data as parameters |
| Direct .env access in modules | Violates purity | Receive config as parameters |
| YAML configuration files | Multiple config sources | Use .env for all config |
| Creating adapters in individual cells | Multiple instances, connection issues | Create PipelineSession once |
Related Documentation¶
This project includes several specialized documentation files:
| Document | Description |
|---|---|
| README.md | Project overview; install and usage are on docs.deriva.dev |
| Architecture | Layers, packages, the home folder and the settings layer |
| Benchmarking | User guide for running benchmarks and analyzing consistency |
| Optimization | Prompt engineering and the config optimization workflow |
| ArchiMate | ArchiMate elements, relationships and metamodel rules |
| Changelog | Version history and release notes |
| .github/SECURITY.md | Security policy and vulnerability reporting |
Component Documentation¶
| Component | README |
|---|---|
| CLI | deriva/cli/README.md |
| LLM Adapter | deriva/adapters/llm/README.md |
| Graph Adapter | deriva/adapters/graph/README.md |
| Database Adapter | deriva/adapters/database/README.md |
| Grafeo Adapter | deriva/adapters/grafeo/README.md |
| ArchiMate Adapter | deriva/adapters/archimate/README.md |
| Repository Adapter | deriva/adapters/repository/README.md |
| Studio | Studio |
Philosophy¶
- Working > perfect - ship it, iterate
- Readable > clever - clarity over cleverness
- Simple > general - solve today's problem
- Pure > stateful - isolate side effects to adapters