Skip to content

API Reference

PaulTiffany edited this page Nov 12, 2025 · 2 revisions

API Reference: Core Modules and Entry Points

Quick-Scan Infobox

Aspect Details
Target User Developers and educators integrating Compitum into workflows; basic Python familiarity assumed.
Core Goal Quick access to submodule functions for routing queries, computing signals, and building custom loops.
Time to First Import 2 mins: import compitum.router → Route a sample prompt.
Key Analogy Like a toolkit in a workshop: Each module a specialized tool—grab router for the heavy lifts, energy for fine-tuning.
Primary Resource Full auto-generated docs: API Site (built from source via Sphinx).

Core Principles Layer (Technical Backbone)

Compitum's API centers on a modular design, exposing entry points for each computational pillar: from query routing under constraints to stability controls. Imports are namespace-organized (compitum.<submodule>), with classes/functions designed for composability—e.g., chain predictors outputs into energy scalars for free-energy minimization.

Key entry points (with formal sketches):

  • compitum.router: Orchestrates model selection and certificate generation. Core: Router class handles embedding-based routing with SPD metrics.

    • route(prompt: str, context: Optional[dict] = None) → Certificate: Selects feasible model via utility maximization; returns JSON-like cert with traces. Params: max_steps: int = 10 (iteration cap).
    • Purpose: Bounded optimization over candidate embeddings.
  • compitum.energy: Computes free-energy scalars from utility components (quality, latency, etc.).

    • free_energy(components: dict) → float: Weighted sum: ( E = \alpha q - \beta l - \gamma c ), where ( q ) is quality, ( l ) latency, etc.
    • UtilityComponents dataclass: Encapsulates predictions (e.g., quality: float, coherence: float).
  • compitum.constraints: Feasibility checks and duality-based shadow prices.

    • feasible(models: List[Model], A: np.ndarray, b: np.ndarray) → List[bool]: Filters via ( A \cdot x \leq b ).
    • shadow_prices(optimal: float, relaxations: dict) → List[float]: Approximates ( \partial U / \partial b_i ) via finite differences.
  • compitum.boundary: Diagnostics for decision ties (gap/entropy).

    • is_boundary(utilities: List[float], threshold: float = 0.05) → bool: Flags if gap < threshold or softmax entropy > log(2).
    • Integrates with predictors for uncertainty-aware checks.
  • compitum.control: Trust-region and drift management.

    • SRMFController(trust_radius: float = 1.0): Updates radius via EMA of distance signals: ( r_{t+1} = \min(r_t + I_t, \max_r) ), with integral ( I ) for error accumulation.
    • drift_signal(history: List[float]) → float: Detects Lyapunov drift in energy trajectories.
  • compitum.metric: Low-rank SPD metric learning for embeddings.

    • learn_spd(X: np.ndarray, rank: int = 4) → SPDMatrix: Fits ( M = U \Lambda U^T ) via Riemannian optimization.
    • Defines distances: ( d(x,y) = \sqrt{(x-y)^T M (x-y)} ).
  • compitum.predictors: Calibrated models for utility/latency forecasts.

    • CalibratedPredictor (sklearn wrapper): Fits on historical traces; predict(X: np.ndarray) → np.ndarray.
    • Supports Thompson sampling for exploration.
  • compitum.cli: Command-line interface entry.

    • main(): Parses args, invokes router.route(). Flags: --prompt, --trace, --config.

Why modular? Mirrors quadratic geometry: Each submodule a bounded observer, querying the global space without overload—ensures scalable extensions.

Code Dive: Sample Routing Loop (Collapsible for Tinkerers)

Runnable notebook version (GitHub-rendered)

Pro Tip: Pipe cert.to_json() to files for classroom analysis—teach kids to spot high shadow prices as "bottlenecks."

Approachable Layer (Relatable Hooks for Educators)

Think of the API as a lesson plan's backbone: router is your facilitator (picks the right activity), energy the scorecard (balances fun vs. time), and constraints the ground rules (keeps things fair). No need to master Riemannian geometry upfront—start with CLI, then layer in modules like building a skill tree.

  • Classroom Tie-In: Use predictors in a debate sim: Forecast "coherence" scores for student arguments, routing to peer reviewers—turns abstract metrics into tangible feedback.
  • Analogy Echo: Like a GPS app: metric recalibrates your map (embeddings), control prevents veering off-route (drift), all while boundary warns of "construction zones" (ambiguities).
  • Common Hurdle: Overwhelmed by params? Defaults are educator-tuned—e.g., rank=4 keeps metrics lightweight for laptops.

Quick-Reference Toolkit (Module Overview)

Module Primary Class/Func Key Params Use Case
router Router.route() prompt: str, max_steps: int Core query handling; cert generation.
energy free_energy() components: dict Scalar optimization; plot utilities.
constraints feasible(), shadow_prices() A: ndarray, b: ndarray Filter models; sensitivity analysis.
boundary is_boundary() utilities: List[float] Detect ties; uncertainty checks.
control SRMFController trust_radius: float Stability tuning; EMA smoothing.
metric learn_spd() X: ndarray, rank: int Custom distances; embedding fits.
predictors CalibratedPredictor model: sklearn Forecast utilities; exploration.
cli main() --prompt, --trace Scripted runs; no-code entry.
Gotchas Table (Collapsible: Integration Snags)
Issue Symptom Fix Analogy
Import Error Module not found. pip install -e .[dev] in root. Missing toolbox—grab the full kit.
Nan Energies Inf/NaN in scalars. Check predictor calibration; clip inputs. Overflowing coffee—stir in bounds.
Slow Routing >10s per query. Lower D=35 to 16; batch predicts. Traffic jam—take side streets.

Next Steps: Your Loop

  • Dive Deeper: Build a custom router in Cookbook recipes.
  • Extend It: Subclass Router for domain-specific constraints (e.g., K-12 safety filters).
  • Feedback: Docs auto-update on commits—PR tweaks to docs/conf.py for Sphinx.

See also: Usage-Guide for CLI examples; Configuration for YAML tuning; Glossary for terms like "SPDMatrix."

Clone this wiki locally