113 lines
14 KiB
Markdown
113 lines
14 KiB
Markdown
# Architecture & Economic Plan: Optimizing Python LLM Token Spend via Marginal Procedure-Step Variance ($\sigma^2_{\text{step}}$) & Tiered API Routing (`v2.0.0`)
|
||
|
||
- **Document ID:** `PLAN-LLM-TOKEN-ECONOMIZER-AND-VARIANCE-ROUTING` (`v2.0.0`)
|
||
- **Target Module in `hyperstitionstudio-core`:** `hyperstitionstud_io.economizer` (`hs-route-job` CLI & Python router API)
|
||
- **Core Optimization Principle:** Never spend LLM tokens on steps with zero marginal procedure-step variance ($\sigma^2_{\text{step}} = 0$), and route non-zero-variance steps (`Tier 1` Economy Flash -> `Tier 2` Mid-Tier Workhorse -> `Tier 3` Frontier Reasoning) using a deterministic 5-factor composite complexity score ($J_{\text{score}} \in [0, 100]$) paired with Python oracle verification gates.
|
||
|
||
---
|
||
|
||
## 1. Defining Marginal Procedure-Step Variance ($\sigma^2_{\text{step}}$) Across Pipeline Workflows
|
||
|
||
Every workflow in the `hyperstitionstud.io` workspace decomposes into a directed sequence of procedure steps $J = (s_1, s_2, \dots, s_m)$. At each step $s_k$, the **marginal procedure-step variance** $\sigma^2_{\text{step}}(s_k \mid s_{k-1}, \text{Spec})$ measures the dispersion of valid outputs given the prior step's output and the formal specification:
|
||
|
||
$$\sigma^2_{\text{step}}(s_k) \propto H\!\left(Y_k \;\middle|\; Y_{k-1},\; \text{Constraints}(s_k)\right)$$
|
||
|
||
| Variance Regime | $\sigma^2_{\text{step}}$ Range | Mathematical Characterization | Qualified Compute / API Tier | Representative Cost per 1M Input / Output Tokens |
|
||
| :--- | :--- | :--- | :--- | :--- |
|
||
| **Regime 0: Deterministic / Algorithmic** | $\sigma^2_{\text{step}} = 0.00$ | Output $Y_k = f(Y_{k-1})$ is uniquely determined by arithmetic, phonetic lookup, regex, graph topology, or schema rules. | **Tier 0: Local Python Only (`hyperstitionstud_io.*`) — Zero LLM Calls** | **`$0.00 / $0.00`** (`0` tokens consumed) |
|
||
| **Regime 1: Constrained Selection & Tagging** | $0.00 < \sigma^2_{\text{step}} \le 0.15$ | Python pre-computes a small finite candidate set ($N \le 10$ valid equations or enum tags); step $s_k$ only selects the most natural candidate index or confirms a state gate. | **Tier 1: Economy / Flash-Lite Model** (e.g., `gemini-2.5-flash-lite`, `gpt-4o-mini`, `claude-3-5-haiku`, or local quantized `14B`) | **`~$0.07 / $0.30`** (`85–95%` savings vs. mid-tier; `98%` vs. frontier) |
|
||
| **Regime 2: Template-Bound Expository Synthesis** | $0.15 < \sigma^2_{\text{step}} \le 0.50$ | All numerical locks, `G1–G6` vectors, and `[n]` citation quotes are pre-locked in a compact JSON brief; step $s_k$ drafts register-specific prose around those fixed anchors. | **Tier 2: Mid-Tier Structured Workhorse** (e.g., `gemini-2.5-flash`, `claude-3-7-sonnet` non-thinking, `gpt-4o`) + **Prompt Caching** | **`~$0.30 / $1.50`** (with `75–90%` cache discount on static system prefix) |
|
||
| **Regime 3: High-Variance Architectural & Theoretical Design** | $\sigma^2_{\text{step}} > 0.50$ | Open-ended multi-constraint system architecture, novel Landian-Deleuzean theoretical synthesis, or root-cause debugging across unindexed failure modes. | **Tier 3: Frontier Reasoning Model** (e.g., `gemini-4-argon` / `claude-opus` / `o3`) — restricted strictly to the design/synthesis step | **`$2.50–$15.00 / $10.00–$75.00`** (invoked only when $J_{\text{score}} > 65$) |
|
||
|
||
---
|
||
|
||
## 2. Five-Factor Qualification Model for API Tier Selection ($J_{\text{score}} \in [0, 100]$)
|
||
|
||
Marginal procedure-step variance ($\sigma^2_{\text{step}}$) is the primary driver, but four additional structural factors determine whether a low-cost API can safely execute a step without quality degradation or retry loops. `hyperstitionstud_io.economizer` evaluates a deterministic 5-factor score:
|
||
|
||
$$J_{\text{score}} = \text{round}\!\left(0.35 \cdot V_{\text{step}} + 0.25 \cdot D_{\text{verif}} + 0.15 \cdot C_{\text{ctx}} + 0.15 \cdot S_{\text{struct}} + 0.10 \cdot R_{\text{blast}}\right)$$
|
||
|
||
*(With the hard override: if $V_{\text{step}} == 0$, then $J_{\text{score}} = 0 \implies \textbf{Tier 0 Local Python}$).*
|
||
|
||
### The Five Qualification Factors
|
||
|
||
1. **`V_step` (`0–100`, Weight `0.35`) — Marginal Procedure-Step Variance:**
|
||
- `0`: Pure calculation, lookup, formatting, graph build, PDF/PNG compilation, or schema validation.
|
||
- `15–25`: Selecting the best 3 pre-verified equations from a Python-generated candidate list of 12, or classifying a headline into `S1–S6` / `M1–M6`.
|
||
- `45–60`: Writing a 3-paragraph dossier exegesis, barstool glossary entry, or 5-voice podcast dialogue turn from a structured JSON outline.
|
||
- `80–100`: Designing a new cross-repository architecture or formulating a novel philosophical thesis across unseen texts.
|
||
2. **`D_verif` (`0–100`, Weight `0.25`) — Absence of a Deterministic Python Verification Oracle ("Oracle Discount"):**
|
||
- **Crucial Economic Insight:** When Python has a fast, deterministic pass/fail oracle—such as `ci_provision_ingglish.py` (4-Gate CI check), `sources.py verify --evidence` (citation & verbatim quote check), or `build_encyclopedia_knowledge_graph.py --verify-only` (6-Gate graph check)—a **cheap Tier 1 or Tier 2 model can be tried first (`D_verif = 10`)**, because Python catches any formatting or citation error in `5 ms` for `$0.00`!
|
||
- Conversely, when no deterministic verifier exists for the output's semantic correctness (`D_verif = 85`), a higher-tier model is justified on the first pass to avoid undetected subtle errors.
|
||
3. **`C_ctx` (`0–100`, Weight `0.15`) — Effective Input Context Complexity & Cross-Hop Reasoning:**
|
||
- `10`: Single-item or pre-filtered 1-hop ego-network JSON payload (`< 1,500` tokens).
|
||
- `50`: Multi-story daily wire harvest synthesis (`3,000–8,000` tokens).
|
||
- `90`: Cross-repository architectural audit requiring multi-hop reasoning across 5+ modules.
|
||
4. **`S_struct` (`0–100`, Weight `0.15`) — Output Structural Freedom:**
|
||
- `10`: Constrained JSON Schema output (`enum`, boolean flags, integer array of selected equation IDs).
|
||
- `50`: Markdown table or section following a fixed dossier/proposal template.
|
||
- `90`: Free-form multi-file code refactor or philosophical essay.
|
||
5. **`R_blast` (`0–100`, Weight `0.10`) — Error Blast Radius & Reversibility:**
|
||
- `0`: Sidecar execution protected by `ReadOnlyIsolationGuard` and `.tmp -> os.replace()` atomic rollback.
|
||
- `80`: Modifying shared library APIs or public deployment configurations.
|
||
|
||
---
|
||
|
||
## 3. Concrete Audit of All Workspace Jobs Under the Economizer Rubric
|
||
|
||
Applying the 5-factor rubric across our actual workspace pipelines shows how **splitting monolithic LLM tasks into `Tier 0` Python pre/post-stages + minimal `Tier 1/2` LLM micro-steps cuts total LLM token expenditure by `88%–96%`**:
|
||
|
||
| Workspace Job / Pipeline Step | `V_step` | `D_verif` | `C_ctx` | `S_struct` | `R_blast` | $J_{\text{score}}$ | Assigned Tier & Token-Saving Mechanism |
|
||
| :--- | :-: | :-: | :-: | :-: | :-: | :-: | :--- |
|
||
| **1. Base-36 `AQ`, `Ingglish` G2P, Prime Ranks & `G1–G6` Locks** | `0` | `0` | `0` | `0` | `0` | **`0`** | **`Tier 0` (100% Python `hyperstitionstud_io`):** Never ask an LLM to compute `AQ` sums or translate Ingglish in-prompt (`$0.00`). |
|
||
| **2. Candidate `333 / 666 / 777` Equation Search & Gate 1–4 CI Filtering** | `0` | `0` | `0` | `0` | `0` | **`0`** | **`Tier 0` (100% Python Combinatorial Solver):** Python pre-solves exact `333/666/777` sums from headline/guild pools and filters for `dict_hits >= 0.40 * nw` before any LLM call (`$0.00`). |
|
||
| **3. Knowledge Graph Build (`388` Nodes, `1,282` Edges), Atlas PNGs & PDF Compilation** | `0` | `0` | `0` | `0` | `0` | **`0`** | **`Tier 0` (100% Python `build_encyclopedia_knowledge_graph.py` & `hs-pdf-build`):** Zero LLM tokens used for layout, XML/Canvas export, or ReportLab PDF generation (`$0.00`). |
|
||
| **4. Selecting Top 3 Natural Equations from Pre-Solved Python Candidates & Tagging `M1–M6` State** | `20` | `10` | `15` | `10` | `10` | **`14`** | **`Tier 1` (Economy Flash-Lite API):** Python sends only 10 pre-verified equations (`~400` input tokens); model returns JSON `{selected_ids: [0, 3, 7], state_gate: "M1"}` (`~40` output tokens). |
|
||
| **5. Daily `00:00 GMT` News Wire & `21:30 GMT` Quant Dossier Prose Synthesis** | `45` | `15` | `40` | `45` | `15` | **`34`** | **`Tier 2` (Mid-Tier Workhorse + Prompt Caching + Batch API):** Python supplies pre-verified locks; model writes Markdown prose; Python immediately verifies via `ci_provision_ingglish.py`. |
|
||
| **6. Stakeholder Proposal Translation (`Fund Manager` / `Board` / `Fantasy` Registers)** | `40` | `10` | `35` | `45` | `15` | **`30`** | **`Tier 1 -> Tier 2` Cascade with `sources.py verify --evidence` Oracle:** Try Tier 1/2 with cached style guide; Python `verify_draft()` validates 100% of `[n]` citations and verbatim quotes. |
|
||
| **7. Multi-Voice Podcast Script Act Generation (`< 90 min` `edge-tts` pipeline)** | `50` | `20` | `45` | `50` | `10` | **`38`** | **`Tier 2` (Mid-Tier Workhorse):** Python extracts exact Division/Volume article JSON cards (`~1,200` tokens per act); Tier 2 writes dialogue; `Tier 0` `edge-tts` + `ffmpeg` + `mutagen` synthesizes audio (`$0.00` LLM audio cost). |
|
||
| **8. Novel Cross-Repo Architecture & New `M7+` Philosophical Operator Discovery** | `85` | `70` | `80` | `80` | `60` | **`77`** | **`Tier 3` (Frontier Reasoning API):** Reserved strictly for high-variance architectural planning and novel theoretical discovery. |
|
||
|
||
---
|
||
|
||
## 4. Six Concrete Token-Economizing Techniques Built Into `hyperstitionstud_io.economizer`
|
||
|
||
### 4.1 Technique 1: Python Pre-Computation of All Combinatorial Search Spaces (`Zero-Math-in-Prompt`)
|
||
LLMs are notoriously expensive and error-prone when asked to search for phrases whose character values sum to `333`, `666`, or `777` (burning thousands of reasoning tokens on trial-and-error arithmetic).
|
||
- **Rule:** Python (`hyperstitionstud_io.ciphers`) **always** executes the combinatorial sum search locally in `< 20 ms` (`$0.00`), filters out candidates that would fail Gate 2 (`dict_hits < 0.40 * nw`), and passes only a numbered list of already-valid equations (`[0]..[9]`) to the LLM. The LLM's output token budget drops from `~4,000` reasoning tokens to a `25`-token JSON array `{"picked": [1, 4, 8]}`.
|
||
|
||
### 4.2 Technique 2: 1-Hop Sub-Graph & `CIDv1` Delta Slicing (`98%` Input Token Reduction)
|
||
Never feed full workspace registries (`glossary-registry.json` = `~28,000` tokens; `encyclopedia-graph.json` = `~65,000` tokens) into an LLM context window.
|
||
- **Rule:** Use `hs_query_knowledge_graph(query)` or `hyperstitionstud_io.ipld` `CIDv1` diffing to extract **only** the modified entries or the 1-hop ego-network (`~350–600` tokens) relevant to the current task.
|
||
|
||
### 4.3 Technique 3: "Cascade with Oracle" (Try `Tier 1` First Whenever `D_verif <= 20`)
|
||
Because `hyperstitionstud_io` includes three deterministic verification oracles:
|
||
1. `ci_provision_ingglish.py` (verifies equation formatting, `normalize_caps`, `classify_candidates`, and `AQ` math),
|
||
2. `sources.py verify --evidence` (verifies `[n]` citation IDs, URLs, and verbatim quotes), and
|
||
3. `build_encyclopedia_knowledge_graph.py --verify-only` (verifies 6 graph & SHA-256 isolation gates),
|
||
`hyperstitionstud_io.economizer.run_with_oracle_cascade()` can dispatch structured drafting tasks to **Tier 1 (`~$0.10/1M`)** first, run the Python oracle (`$0.00`, `5 ms`), and escalate to **Tier 2 or Tier 3** *only* on the rare subset of items where the oracle returns a non-zero exit code.
|
||
|
||
### 4.4 Technique 4: Immutable Prompt-Prefix Ordering for `75%–90%` Prompt Cache Discounts
|
||
Modern LLM APIs (OpenRouter, Anthropic, Google Gemini, OpenAI) apply automatic or explicit prompt-cache discounts (`75%–90%` off input token pricing) when the leading prefix of a prompt (`>= 1,024` tokens) is byte-for-byte identical across calls.
|
||
- **Rule in `hyperstitionstud_io.economizer.build_cached_messages()`:**
|
||
1. **Message 0 (Immutable System Prefix):** Static cipher rules, `S1–S6` / `M1–M6` coordinate table, and output JSON Schema (byte-identical across all calls -> **cached after Call #1**).
|
||
2. **Message 1 (Variable Task Tail):** Only the current headline or delta-sliced JSON payload (`< 500` tokens).
|
||
|
||
### 4.5 Technique 5: Compact Index-Reference Output Schemas (Eliminating Echoed Input Tokens)
|
||
Output tokens cost **`3x to 5x` more per token** than input tokens across almost every commercial LLM API.
|
||
- **Rule:** Never ask an LLM to re-emit full equation strings, long URLs, or verbatim quotes that Python already holds in memory. Have the LLM emit **integer indices** (`{"selected_eq_indices": [2, 5], "citation_ids": [3, 8]}`), and let Python's `render_sources()` and dossier formatter expand those indices into the final Markdown and PDF documents for `$0.00`.
|
||
|
||
### 4.6 Technique 6: Asynchronous Provider Batch APIs (`50%` Discount) for Scheduled Cron Harvests
|
||
The `21:30 GMT` US market closing-bell harvest and the `00:00 GMT` daily wire news harvest are non-interactive background jobs (`cronjob_manage`). Routing their Tier 1/2 narrative synthesis calls through provider Batch APIs (or OpenRouter economy routing with `max_price` caps) halves per-token cost again.
|
||
|
||
---
|
||
|
||
## 5. Planned Implementation in `/workspace/hyperstitionstudio-core` (`Phases 1–2`)
|
||
|
||
### Phase 1: Implement `src/hyperstitionstud_io/economizer/__init__.py` & `hs-route-job` CLI
|
||
1. Implement `JobProfile`, `score_job_complexity()`, `select_api_tier()`, `build_cached_messages()`, and `estimate_token_cost()` in `src/hyperstitionstud_io/economizer/__init__.py`.
|
||
2. Register `hs-route-job` in `pyproject.toml` so scripts, cron pipelines, and MCP clients can query the exact `Tier 0..3` assignment, recommended model slug, and estimated USD cost before making any API call.
|
||
|
||
### Phase 2: Add Pre-Solved Candidate Menus to `collect_news_aq.py` & `collect_financial_quant_aq.py`
|
||
1. Ensure both periodic collectors pre-solve and pre-filter candidate `333 / 666 / 777` equations in `Tier 0` Python so downstream LLM synthesis operates strictly on pre-verified index menus (`Regime 1 / Regime 2`).
|