diff --git a/.env.example b/.env.example index 903b08c..96f602a 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,15 @@ # Copy to .env — FLASK_SECRET_KEY is auto-generated on first run if omitted. FLASK_SECRET_KEY= -# LLM provider (leave blank to use stub estimation) -# Supported: gemini +# LLM provider for the optional pass 4 review (leave blank to skip it) +# Supported: gemini, ollama LLM_PROVIDER= # Gemini (required when LLM_PROVIDER=gemini) # Install: pip install -e '.[gemini]' (from repo root) GEMINI_API_KEY= GEMINI_MODEL=gemini-2.0-flash + +# Ollama (used when LLM_PROVIDER=ollama) +OLLAMA_MODEL=qwen2.5:7b +OLLAMA_HOST=http://localhost:11434 diff --git a/CLAUDE.md b/CLAUDE.md index 5bf57a7..4615143 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ PhysCom (Physical Combinatorics) — innovation discovery engine that generates ## Commands - **Install**: `pip install -e ".[dev,web]"` (editable install with test and web deps) -- **Tests (all)**: `python -m pytest tests/ -q` (134 tests, ~2 min). Run after every change. +- **Tests (all)**: `python -m pytest tests/ -q` (~130 tests, ~2 min). Run after every change. - **Single test file**: `python -m pytest tests/test_scorer.py -q` - **Single test**: `python -m pytest tests/test_scorer.py::test_score_combination -q` - **Web dev server**: `python -m physcom_web` @@ -27,17 +27,20 @@ src/physcom/ # Core library (no web dependency) engine/combinator.py # Cartesian product of entities across dimensions engine/constraint_resolver.py # Pass 1: requires/excludes/mutex/range/force checks engine/scorer.py # Pass 3: log-normalize raw→0-1, weighted geometric mean composite + engine/formula.py # Safe AST evaluator for domain-authored pass-2 formulas engine/pipeline.py # Orchestrator: combo-first loop, incremental saves, resume, cancel - llm/base.py # LLMProvider ABC (estimate_physics, review_plausibility) - llm/providers/mock.py # MockLLMProvider for tests - seed/transport_example.py # 9 platforms + 9 power sources, 2 domains + llm/base.py # LLMProvider ABC (review_plausibility — pass 4 only) + llm/registry.py # build_llm_provider() from LLM_PROVIDER env / web form + llm/providers/ # gemini.py, ollama.py, mock.py (tests) + seed/transport_example.py # 11 platforms × 15 actuators × 18 energy storages, 5 domains src/physcom_web/ # Flask web UI app.py # App factory, get_repo(), DB path resolution routes/pipeline.py # Background thread pipeline execution, HTMX status/cancel endpoints routes/results.py # Results browse, detail view, human review submission routes/entities.py # Entity CRUD - routes/domains.py # Domain listing + routes/domains.py # Domain CRUD: metrics, free variables, formulas + routes/admin.py # Reseed, wipe, JSON snapshot export/import templates/ # Jinja2, extends base.html, uses HTMX for polling static/style.css # Single stylesheet @@ -62,12 +65,12 @@ tests/ # pytest, uses seeded_repo fixture from conftest.py 1. **Pass 1 — Constraints**: `ConstraintResolver.resolve()` → blocked/conditional/valid. Blocked combos get a result row and `continue`. 2. **Pass 2 — Estimation**: `_estimate_physics()` (deterministic physics engine; estimator-only, no LLM) → raw metric values. Saved immediately via `save_raw_estimates()` (normalized_score=NULL). 3. **Pass 3 — Scoring**: `Scorer.score_combination()` → log-normalized scores + weighted geometric mean composite. Saves via `save_scores()` + `save_result()`. -4. **Pass 4 — LLM Review**: Only for above-threshold combos with an LLM provider. No real provider yet (only `MockLLMProvider`). +4. **Pass 4 — LLM Review**: Only for above-threshold combos with an LLM provider (Gemini or Ollama, via `llm/registry.py`). 5. **Pass 5 — Human Review**: Manual via web UI results page. ## Testing -- Tests use `seeded_repo` fixture (in-memory SQLite with transport seed data: 9 platforms, 9 power sources, 2 domains). There's also a bare `repo` fixture for tests that seed their own data. +- Tests use `seeded_repo` fixture (in-memory SQLite with the transport seed data). There's also a bare `repo` fixture for tests that seed their own data. - Individual entity fixtures (walking, bicycle, spaceship, solar_sail, etc.) are defined in `conftest.py`. ## Conventions diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index f9ee4ea..ca0881a 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -1,624 +1,60 @@ -# Physical Combinatorics — Implementation Plan +# Implementation Plan — Public Release -## Context +Goal: make PhysCom presentable on the internet, both as a **public GitHub repo** and as a **hosted demo site**. The core engine is done: a 5-pass pipeline with 132 passing tests, a web UI with full CRUD, and Gemini and Ollama providers for pass 4. What's left is safety, packaging and presentation. -This project systematically generates novel concepts by computing the Cartesian product of real-world attribute dimensions (platforms, power sources, and future dimensions), then filters the combinatorial explosion through a multi-pass viability pipeline. The goal is to surface "bizarre but plausible" innovations (like hydrogen-powered bicycles) while eliminating the vast majority of nonsensical pairings. The core insight is that attributes are real things — the risk isn't bad input, it's how much noise survives the filters. - -**Stack:** Python, SQLite, abstract LLM interface, CLI-first. +Phases are ordered by risk. **Phase 1 blocks any public deployment.** Phases 2–3 block a good first impression. Phase 4 is optional. --- -## 1. Project Structure +## Phase 1 — Make it safe to expose (blocker) -``` -physicalCombinatorics/ -├── README.md -├── IMPLEMENTATION_PLAN.md -├── pyproject.toml # Package config, dependencies -├── src/ -│ └── physcom/ -│ ├── __init__.py -│ ├── cli.py # CLI entry point (argparse/click) -│ ├── db/ -│ │ ├── __init__.py -│ │ ├── schema.py # DDL, table creation, migrations -│ │ └── repository.py # CRUD operations for all entities -│ ├── models/ -│ │ ├── __init__.py -│ │ ├── entity.py # Entity, Dependency dataclasses -│ │ ├── domain.py # Domain, MetricWeight dataclasses -│ │ └── combination.py # Combination, Score dataclasses -│ ├── engine/ -│ │ ├── __init__.py -│ │ ├── combinator.py # Cartesian product generator -│ │ ├── constraint_resolver.py # Dependency contradiction detection -│ │ ├── scorer.py # Multiplicative logarithmic scoring -│ │ └── pipeline.py # Multi-pass orchestrator -│ ├── llm/ -│ │ ├── __init__.py -│ │ ├── base.py # Abstract LLM interface -│ │ ├── prompts.py # Prompt templates for physics/social passes -│ │ └── providers/ # Concrete implementations (future) -│ │ └── __init__.py -│ └── seed/ -│ └── transport_example.py # Seed data from the README example -├── tests/ -│ ├── test_constraint_resolver.py -│ ├── test_scorer.py -│ ├── test_combinator.py -│ ├── test_pipeline.py -│ └── test_repository.py -└── data/ - └── physcom.db # SQLite database (gitignored) -``` +The Docker image today runs Flask's **dev server with `debug=True` bound to `0.0.0.0`**. The Werkzeug debugger allows remote code execution, so the current container must never be reachable from the internet. + +| # | Task | Where | Notes | +|---|------|-------|-------| +| 1.1 | Serve with gunicorn, debug off | `Dockerfile`, `pyproject.toml` (`web` extra) | `gunicorn -w 1 --threads 8 "physcom_web.app:create_app()"`. Use one worker because pipeline runs are background threads inside the web process. Keep `python -m physcom_web` as the localhost-only dev entry point. Only turn on `debug=True` when `FLASK_DEBUG=1`. | +| 1.2 | Read-only public mode | `app.py`, a `before_request` hook | Add a `PHYSCOM_ADMIN_TOKEN` env var. If it's unset, only localhost can write. On a public host, every non-GET request and the `/admin`, `/pipeline`, entity/domain edit and review routes need a session flag set by a one-field `/login?token=` form. Browsing results, entities, domains and the result "explore" panel stays public. There's no user system: one admin is enough for a demo. | +| 1.3 | CSRF | `app.py` | With 1.2, only the admin can write. Set `SESSION_COOKIE_SAMESITE="Lax"`, `SESSION_COOKIE_SECURE=True` and `SESSION_COOKIE_HTTPONLY=True`; Lax already blocks cross-site POSTs. Only add Flask-WTF if public writes are ever allowed. | +| 1.4 | Check that "explore" is safe to leave public | `routes/results.py:91` | It's a POST that re-runs the estimator for one combo. Confirm it writes nothing, and cap its cost with a request timeout or small rate limit (a per-IP token bucket in memory is enough). If it does write, put it behind the admin check. | +| 1.5 | Persistent secret key | `app.py:36` | Today it falls back to a random key on each start, which logs the admin out on every restart and breaks sessions if there's ever more than one worker. In public mode, refuse to start without `FLASK_SECRET_KEY`. | +| 1.6 | Hardened container | `Dockerfile` | Run as a non-root user, add a `HEALTHCHECK` against `/`, and pin the base image digest. | +| 1.7 | Untrack local config | `.claude/settings.local.json` | It's committed today. `git rm --cached` it and add it to `.gitignore`. Check the git history for anything sensitive before making the repo public. | +| 1.8 | Tests | `tests/test_web_access.py` (new, one file) | Using the Flask test client: anonymous GET of results → 200; anonymous POST to `/admin/wipe` → 403; request with the token → allowed; debug off by default. | + +**Done when:** the container runs gunicorn, anonymous visitors can browse but can't change anything, and 1.8 passes. + +## Phase 2 — Public repo polish + +| # | Task | Notes | +|---|------|-------| +| 2.1 | `LICENSE` | Choose one (MIT is the usual default) and set `license` in `pyproject.toml`. Check with the employer first, since the repo lives under a corporate OneDrive. | +| 2.2 | Rewrite `README.md` | Keep the transport pitch at the top. It still lists the old metrics (safety and availability were removed from scoring) and still says 9×9 = 81 combos; the seed is now 11 × 15 × 18 across 5 domains. Replace the "a few notes" brainstorm at the bottom with a short **How it works** section (the 5 passes, emergent guardrails, log-normalized geometric mean) that links to `LOGIC DOCS/`. Add 2–3 screenshots (results list, combo detail, explore panel) and a link to the live demo. | +| 2.3 | CI | `.github/workflows/test.yml`: `pip install -e ".[dev,web]"` then `pytest -q` on Python 3.11 and 3.13. Add a badge to the README. | +| 2.4 | `pyproject.toml` metadata | Change `requires-python` from `>=3.10` to `>=3.11` (CLAUDE.md says 3.11+). Add authors, `readme`, `license`, `urls`. | +| 2.5 | Compose parity | Add `OLLAMA_MODEL` and `OLLAMA_HOST` to `docker-compose.yml` (only the Gemini vars are there now). Delete the commented-out Postgres block (see Phase 4). | +| 2.6 | Web route smoke tests | Extend 1.8's file with a parametrized "every GET route returns 200 on the seeded DB" test. The only web tests today are the async-pipeline tests; entity, domain and result pages have no coverage. | + +## Phase 3 — Hosted demo + +| # | Task | Notes | +|---|------|-------| +| 3.1 | Ship precomputed results | A full run is CPU-heavy (about 11.7k optimizer calls per combo), and anonymous runs would invite DoS. Run all 5 domains offline, export with `physcom snapshot export`, and load that snapshot on first start when the DB is empty. That uses the existing snapshot import and needs no new code path. | +| 3.2 | Pick a host | Any single small container host with a persistent volume works (Fly.io, Railway, a small VPS with Caddy for TLS). Keep SQLite: the demo is read-mostly with one writer. | +| 3.3 | Pass-4 reviews | Pre-generate them into the snapshot with a local Ollama model (phi4 scored 8/8 on the labeled set). The public site then needs no LLM key and costs nothing per visitor. | +| 3.4 | Landing page | `home.html` currently shows counts. Add a 3-sentence pitch and a "top surprising combos" list (high composite score, unusual pairings) so first-time visitors see the interesting output without digging. | + +## Phase 4 — Optional, only if needed + +Skipped until something forces them: +- **Postgres**: not needed for a read-mostly demo. Revisit only if you need multiple writers or multiple web workers. +- **Numpy-vectorized optimizer**: see `LOGIC DOCS/003`. Only needed when a 4th dimension is added or runs get slow; GPU is ruled out below the stated threshold. +- **Anthropic provider**: one file in the pattern of `llm/providers/gemini.py`, plus a branch in `llm/registry.py`. Add it if you want Claude reviews. +- **Pass-4 rationale**: show the estimator's chosen mass allocation and free variables in the review prompt (see the `ponytail:` note in `llm/prompts.py`). Only needed if reviews misjudge combos because they can't see this. +- **Per-key overrun tolerance** (`constraint_resolver.py:58`): only if mass and footprint turn out to need different slack. +- **More seed domains or dimensions** beyond transport: this would show off the generic formula estimator, but it's new content rather than polish. --- -## 2. Database Schema +## Suggested order -### Table: `dimensions` -Defines attribute categories (e.g., "platform", "power_source"). Adding a new dimension is just inserting a row — no schema change needed. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `name` | TEXT UNIQUE NOT NULL | e.g., "platform", "power_source" | -| `description` | TEXT | Human-readable purpose | - -### Table: `entities` -Individual attributes within a dimension. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `dimension_id` | INTEGER FK → dimensions.id | Which dimension this belongs to | -| `name` | TEXT NOT NULL | e.g., "Bicycle", "Solar Sail" | -| `description` | TEXT | Longer description | -| UNIQUE | (dimension_id, name) | No duplicate names within a dimension | - -### Table: `dependencies` -The core metadata on every entity. Uses a flexible category/key/value/unit structure so any type of dependency can be expressed without schema changes. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `entity_id` | INTEGER FK → entities.id | Owner entity | -| `category` | TEXT NOT NULL | One of: "environment", "force", "material", "physical", "infrastructure" | -| `key` | TEXT NOT NULL | e.g., "requires_ground", "min_mass_kg", "force_output_watts" | -| `value` | TEXT NOT NULL | e.g., "true", "500", "vacuum" | -| `unit` | TEXT | Optional unit: "kg", "watts", "celsius", etc. | -| `constraint_type` | TEXT NOT NULL | One of: "requires", "provides", "range_min", "range_max", "excludes" | - -**Constraint types explained:** -- `requires` — this entity needs this condition to function (walking requires ground=true) -- `provides` — this entity supplies this condition (a sealed cabin provides atmosphere=true) -- `range_min` / `range_max` — numeric bounds (nuclear reactor: min_mass_kg=2000) -- `excludes` — this entity cannot coexist with this condition (solar sail excludes atmosphere=dense) - -### Table: `domains` -Context frames that define what "good" means. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `name` | TEXT UNIQUE NOT NULL | e.g., "urban_commuting", "interplanetary_travel" | -| `description` | TEXT | What this domain represents | - -### Table: `metrics` -The measurable dimensions of viability. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `name` | TEXT UNIQUE NOT NULL | e.g., "speed", "cost_efficiency", "safety" | -| `unit` | TEXT | e.g., "km/h", "usd/km", "score_0_1" | -| `description` | TEXT | What this measures | - -### Table: `domain_metric_weights` -Per-domain weighting and normalization bounds for each metric. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `domain_id` | INTEGER FK → domains.id | | -| `metric_id` | INTEGER FK → metrics.id | | -| `weight` | REAL NOT NULL | 0.0–1.0, weights within a domain should sum to 1.0 | -| `norm_min` | REAL | Lower bound for normalization (below this → score 0) | -| `norm_max` | REAL | Upper bound for normalization (above this → score 1) | -| UNIQUE | (domain_id, metric_id) | | - -### Table: `combinations` -Each generated combination of entities. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `hash` | TEXT UNIQUE NOT NULL | Deterministic hash of sorted entity IDs (dedup) | -| `status` | TEXT NOT NULL DEFAULT 'pending' | One of: "pending", "valid", "blocked", "scored", "reviewed" | -| `block_reason` | TEXT | If blocked, why (which dependencies contradicted) | -| `created_at` | TIMESTAMP | | - -### Table: `combination_entities` -Junction table linking combinations to their constituent entities. - -| Column | Type | Notes | -|---|---|---| -| `combination_id` | INTEGER FK → combinations.id | | -| `entity_id` | INTEGER FK → entities.id | | -| PRIMARY KEY | (combination_id, entity_id) | | - -### Table: `combination_scores` -Per-metric scores for each combination within a domain. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `combination_id` | INTEGER FK → combinations.id | | -| `domain_id` | INTEGER FK → domains.id | | -| `metric_id` | INTEGER FK → metrics.id | | -| `raw_value` | REAL | The estimated raw metric value (e.g., 40.0 km/h) | -| `normalized_score` | REAL | 0.0–1.0 after log-normalization against domain bounds | -| `estimation_method` | TEXT | "physics_calc", "llm_estimate", "human_input" | -| `confidence` | REAL | 0.0–1.0 confidence in the estimate | -| UNIQUE | (combination_id, domain_id, metric_id) | | - -### Table: `combination_results` -Final composite viability scores per domain. - -| Column | Type | Notes | -|---|---|---| -| `id` | INTEGER PK | Auto-increment | -| `combination_id` | INTEGER FK → combinations.id | | -| `domain_id` | INTEGER FK → domains.id | | -| `composite_score` | REAL | Weighted geometric mean of normalized metric scores | -| `novelty_flag` | TEXT | "novel", "exists", "researched", or NULL | -| `llm_review` | TEXT | LLM-generated plausibility summary | -| `human_notes` | TEXT | Human reviewer notes | -| `pass_reached` | INTEGER | Highest pass this combination survived (1–5) | -| UNIQUE | (combination_id, domain_id) | | - -### Indexes -```sql -CREATE INDEX idx_deps_entity ON dependencies(entity_id); -CREATE INDEX idx_deps_category_key ON dependencies(category, key); -CREATE INDEX idx_combo_status ON combinations(status); -CREATE INDEX idx_scores_combo_domain ON combination_scores(combination_id, domain_id); -CREATE INDEX idx_results_domain_score ON combination_results(domain_id, composite_score DESC); -``` - ---- - -## 3. Entity & Dependency Data Model (Python) - -```python -@dataclass -class Dependency: - category: str # "environment", "force", "material", "physical", "infrastructure" - key: str # "requires_ground", "force_output_watts", "min_mass_kg" - value: str # "true", "75", "vacuum" - unit: str | None # "kg", "watts", etc. - constraint_type: str # "requires", "provides", "range_min", "range_max", "excludes" - -@dataclass -class Entity: - id: int | None - dimension: str # "platform", "power_source" - name: str # "Bicycle" - description: str - dependencies: list[Dependency] - -@dataclass -class Combination: - id: int | None - entities: list[Entity] # One per dimension - status: str # "pending" → "valid"/"blocked" → "scored" → "reviewed" - block_reason: str | None -``` - -### Example: Entities with Full Dependencies - -```python -Entity( - name="Solar Sail", - dimension="power_source", - description="Propulsion via radiation pressure from a star", - dependencies=[ - Dependency("environment", "atmosphere", "vacuum_or_thin", None, "requires"), - Dependency("environment", "star_proximity", "true", None, "requires"), - Dependency("physical", "surface_area", "100", "m^2", "range_min"), - Dependency("force", "force_output_watts", "0.001", "N", "provides"), - Dependency("force", "thrust_profile", "continuous_low", None, "provides"), - ] -) - -Entity( - name="Walking", - dimension="platform", - description="Bipedal locomotion", - dependencies=[ - Dependency("environment", "ground_surface", "true", None, "requires"), - Dependency("environment", "gravity", "true", None, "requires"), - Dependency("physical", "max_mass_kg", "150", "kg", "range_max"), - Dependency("force", "force_output_watts", "75", "watts", "provides"), - Dependency("infrastructure", "fuel_infrastructure", "none", None, "requires"), - ] -) - -Entity( - name="Modular Nuclear Reactor", - dimension="power_source", - description="Small-scale fission reactor for sustained high power output", - dependencies=[ - Dependency("physical", "min_mass_kg", "2000", "kg", "range_min"), - Dependency("material", "radiation_shielding", "true", None, "requires"), - Dependency("material", "coolant_system", "true", None, "requires"), - Dependency("force", "force_output_watts", "1000000", "watts", "provides"), - Dependency("infrastructure", "nuclear_fuel", "enriched_uranium", None, "requires"), - Dependency("infrastructure", "regulatory_approval", "nuclear", None, "requires"), - ] -) - -Entity( - name="Bicycle", - dimension="platform", - description="Two-wheeled human-scale vehicle", - dependencies=[ - Dependency("environment", "ground_surface", "true", None, "requires"), - Dependency("environment", "atmosphere", "standard", None, "requires"), - Dependency("physical", "max_mass_kg", "30", "kg", "range_max"), - Dependency("physical", "max_payload_kg", "120", "kg", "range_max"), - Dependency("force", "force_required_watts", "50", "watts", "range_min"), - Dependency("force", "force_required_watts", "500", "watts", "range_max"), - ] -) -``` - -Note how **Bicycle + Nuclear Reactor** is caught by Rule 3: the reactor's `min_mass_kg=2000` exceeds the bicycle's `max_mass_kg=30`. Meanwhile **Bicycle + Human Pedalling** passes all checks — the force ranges overlap, the mass is compatible, and no environmental contradictions exist. - ---- - -## 4. Constraint Resolution Engine - -**File:** `src/physcom/engine/constraint_resolver.py` - -The resolver takes a `Combination` (a set of entities, one per dimension) and checks all dependencies for contradictions. It returns `VALID`, `BLOCKED`, or `CONDITIONAL` with reasons. - -### Contradiction Rules - -**Rule 1: Requires vs. Excludes** -If entity A `requires` key=X and entity B `excludes` key=X → BLOCKED. - -> Walking requires `ground_surface=true`; if a hypothetical power source excluded ground operation, the combination is impossible. - -**Rule 2: Mutual Exclusion** -If entity A `requires` key=X and entity B `requires` key=Y where X and Y are mutually exclusive values of the same key → BLOCKED. - -> Solar sail requires `atmosphere=vacuum_or_thin`; a ground platform requires `atmosphere=standard` → contradiction on the `atmosphere` key. - -This requires a mutual exclusion registry: - -```python -MUTEX_VALUES = { - "atmosphere": [{"vacuum", "vacuum_or_thin"}, {"dense", "standard"}], - "medium": [{"ground"}, {"water"}, {"air"}, {"space"}], -} -``` - -**Rule 3: Range Incompatibility** -If entity A has `range_min` for key=K at value V1 and entity B has `range_max` for the same key at value V2, and V1 > V2 → BLOCKED. - -> Nuclear reactor `range_min` mass=2000kg vs. Bicycle `range_max` mass=30kg → the reactor cannot physically fit on the bicycle. - -**Rule 4: Force Scale Mismatch** -A specialized range check on force-related keys. If a platform requires a minimum force that the power source cannot provide, or the power source outputs force orders of magnitude beyond what the platform can structurally handle → flag. This may be a soft constraint (CONDITIONAL with warning) rather than hard BLOCKED, since some edge cases are debatable. - -**Rule 5: Unmet Requirements** -If entity A `requires` key=K but no other entity in the combination `provides` that key, AND it is not an ambient environmental assumption → `CONDITIONAL`. The combination works only if the missing requirement is externally supplied. - -> A hydrogen engine requires `fuel_infrastructure=hydrogen_station`. If no other entity provides it, the combination is conditionally viable — it works where hydrogen stations exist. - -### Resolver Interface - -```python -@dataclass -class ConstraintResult: - status: str # "valid", "blocked", "conditional" - violations: list[str] # Human-readable descriptions of hard blocks - warnings: list[str] # Soft constraint notes - -class ConstraintResolver: - def __init__(self, mutex_registry: dict): ... - def resolve(self, combination: Combination) -> ConstraintResult: ... -``` - ---- - -## 5. Scoring Pipeline - -**File:** `src/physcom/engine/scorer.py` - -### Normalization — Logarithmic Scaling - -Raw metric values are normalized to 0.0–1.0 against domain-specific bounds. The log scale reflects the expected behavior: most combinations cluster near 0 (useless) or near 1 (fully competitive) within a given domain. - -```python -def normalize(raw_value: float, norm_min: float, norm_max: float) -> float: - """Log-normalize a raw value to 0-1 within domain bounds. - - Values at or below norm_min → 0.0 - Values at or above norm_max → 1.0 - Values between are log-interpolated. - """ - if raw_value <= norm_min: - return 0.0 - if raw_value >= norm_max: - return 1.0 - log_min = math.log1p(norm_min) - log_max = math.log1p(norm_max) - log_val = math.log1p(raw_value) - return (log_val - log_min) / (log_max - log_min) -``` - -### Composite Score — Weighted Geometric Mean - -Scores are **multiplied**, not averaged. This is the key design decision: a single near-zero metric kills the overall viability, filtering out "technically possible but completely pointless in practice" concepts. - -```python -def composite_score(scores: list[float], weights: list[float]) -> float: - """Weighted geometric mean. Any score near 0 drives the result toward 0. - - composite = product(score_i ^ weight_i) for all metrics i - """ - result = 1.0 - for score, weight in zip(scores, weights): - result *= score ** weight - return result -``` - -**Properties:** -- If any `score = 0.0` → composite = 0.0 regardless of other scores -- If all scores = 1.0 → composite = 1.0 -- The resulting distribution is heavily skewed toward 0 — this is intended as the primary noise filter -- A person pushing a car: speed ≈ 0 in ground transport domain → composite ≈ 0 → eliminated -- A rocket-powered car: speed ≈ 1 in ground transport domain, but safety ≈ 0 → composite ≈ 0 → also eliminated -- Only combinations that score reasonably across ALL metrics survive - -### Scorer Interface - -```python -class Scorer: - def __init__(self, domain: Domain): ... - def score_combination(self, combination: Combination, - raw_metrics: dict[str, float]) -> ScoredResult: ... -``` - ---- - -## 6. Domain System - -**File:** `src/physcom/models/domain.py` - -Domains define the context in which combinations are evaluated. The same combination may be viable in one domain and worthless in another. - -```python -@dataclass -class MetricBound: - metric_name: str - weight: float # 0.0–1.0, all weights in a domain sum to 1.0 - norm_min: float # Below this = score 0 in this domain - norm_max: float # Above this = score 1 in this domain - -@dataclass -class Domain: - name: str - description: str - metric_bounds: list[MetricBound] -``` - -### Example Domains - -**Urban Commuting** (daily city travel, 1–50km): -| Metric | Weight | Min (score=0) | Max (score=1) | -|---|---|---|---| -| speed | 0.25 | 5 km/h | 120 km/h | -| cost_efficiency | 0.25 | $0.01/km | $2.00/km | -| safety | 0.25 | 0.0 | 1.0 | -| availability | 0.15 | 0.0 | 1.0 | -| range_fuel | 0.10 | 5 km | 500 km | - -**Interplanetary Travel** (between planets in a solar system): -| Metric | Weight | Min (score=0) | Max (score=1) | -|---|---|---|---| -| speed | 0.30 | 1,000 km/s | 300,000 km/s | -| range_fuel | 0.30 | 1M km | 10B km | -| safety | 0.20 | 0.0 | 1.0 | -| cost_efficiency | 0.10 | $1K/km | $1B/km | -| range_degradation | 0.10 | 100 days | 36,500 days | - -A car at 100 km/h scores ~0.83 for speed in urban commuting but ~0.0 in interplanetary travel. This is by design — domain context determines relevance. - ---- - -## 7. Multi-Pass Pipeline - -**File:** `src/physcom/engine/pipeline.py` - -``` - All Combinations (Cartesian product) - │ - Pass 1: Constraint Resolution (hard physics, deterministic) - │ filter: BLOCKED removed - ▼ - Valid + Conditional Combinations - │ - Pass 2: Physics Estimation (compute or LLM-assisted) - │ estimates raw metric values per combination - ▼ - Estimated Combinations - │ - Pass 3: Scoring & Ranking (per domain) - │ filter: composite_score < threshold removed - ▼ - High-Scoring Shortlist - │ - Pass 4: LLM Review (social factors, novelty, plausibility) - │ annotates with natural-language assessment - ▼ - Annotated Shortlist - │ - Pass 5: Human Review (manual, via CLI) - │ human adds notes, approves/rejects - ▼ - Final Curated Concepts -``` - -### Design Notes - -- **Pass 1 is deterministic and cheap.** It prunes the bulk of the combinatorial explosion using only dependency logic. No LLM calls, no estimation. This is the first and most aggressive filter. -- **Pass 2 is the most expensive.** Physics estimation (whether formula-based or LLM-assisted) runs only on combinations that survived Pass 1. For the initial transport example (81 combinations, many blocked), this might mean ~20–40 surviving combinations need estimation. -- **Pass 3 applies the multiplicative filter.** The logarithmic scoring distribution means most estimated combinations still score near 0. Only a handful survive the threshold. -- **Passes 4–5 are human-scale.** By the time concepts reach LLM review and human review, the list should be small enough for thoughtful individual assessment. - -### Pipeline Interface - -```python -class Pipeline: - def __init__(self, db: Repository, resolver: ConstraintResolver, - scorer: Scorer, llm: LLMProvider | None): ... - - def run(self, domain: Domain, dimensions: list[str], - score_threshold: float = 0.1, - passes: list[int] = [1, 2, 3, 4, 5]) -> PipelineResult: ... -``` - -The `passes` parameter allows partial runs (e.g., `[1, 2, 3]` skips LLM and human review). - ---- - -## 8. LLM Interface (Abstract) - -**File:** `src/physcom/llm/base.py` - -```python -from abc import ABC, abstractmethod - -class LLMProvider(ABC): - """Provider-agnostic LLM interface.""" - - @abstractmethod - def estimate_physics(self, combination_description: str, - metrics: list[str]) -> dict[str, float]: - """Estimate raw metric values for a combination using - order-of-magnitude physics reasoning. - Returns {metric_name: estimated_value}.""" - ... - - @abstractmethod - def review_plausibility(self, combination_description: str, - scores: dict[str, float]) -> str: - """Return a natural-language assessment of plausibility, - novelty, social viability, and practical barriers.""" - ... -``` - -**File:** `src/physcom/llm/prompts.py` - -Structured prompt templates for: -- `PHYSICS_ESTIMATION_PROMPT` — asks for order-of-magnitude metric estimates with reasoning -- `PLAUSIBILITY_REVIEW_PROMPT` — asks for social viability, barriers, novelty, and prior art - -A `MockLLMProvider` is included for deterministic testing. Concrete providers (Anthropic, OpenAI, local) are implemented in `src/physcom/llm/providers/` and registered by name. - ---- - -## 9. CLI Interface - -**File:** `src/physcom/cli.py` - -``` -physcom init # Create database, initialize schema -physcom seed # Load seed data (e.g., "transport") -physcom entity add # Add an entity interactively -physcom entity list [--dimension X] # List entities with dependencies -physcom domain add # Add a domain interactively -physcom domain list # List domains with metric weights -physcom run [--passes 1,2,3] [--threshold 0.1] -physcom results [--top N] # View ranked results -physcom review # Interactive human review -physcom export --format md # Export to markdown report -``` - ---- - -## 10. Implementation Phases - -### Phase A: Foundation (database + models) -1. Set up `pyproject.toml` with dependencies (`click` for CLI, `sqlite3` stdlib) -2. Implement `db/schema.py` — all table DDL, `init_db()` function, indexes -3. Implement `models/` — all dataclasses (`Entity`, `Dependency`, `Domain`, `Combination`, etc.) -4. Implement `db/repository.py` — CRUD for entities, dependencies, domains, metrics -5. Implement `seed/transport_example.py` — the README example with full dependency metadata on all 18 entities -6. Implement `cli.py` — `init` and `seed` commands -7. **Verify:** Create DB, load seed, query entities, confirm all dependency data persists correctly - -### Phase B: Constraint Engine -1. Implement `engine/combinator.py` — Cartesian product generator across N dimensions -2. Implement mutual exclusion registry (dict initially, DB table later) -3. Implement `engine/constraint_resolver.py` — all five contradiction rules -4. Wire Pass 1 into the pipeline and CLI -5. **Verify:** Solar sail + walking → BLOCKED (atmosphere contradiction). Hydrogen engine + bicycle → VALID. Nuclear reactor + bicycle → BLOCKED (mass range). Confirm expected blocked/valid counts for full 81-combination transport example. - -### Phase C: Scoring -1. Implement `engine/scorer.py` — log normalization + weighted geometric mean -2. Implement domain metric weights in the database -3. Wire Pass 2 with stub physics estimates (hardcoded for the transport seed) -4. Wire Pass 3 into the pipeline -5. **Verify:** Score distribution is heavily logarithmic. A single zero-metric kills composite score. Domain bounds shift rankings (same combination scores differently across domains). - -### Phase D: LLM Integration -1. Implement `llm/base.py` — abstract interface -2. Implement `llm/prompts.py` — prompt templates -3. Implement `MockLLMProvider` for testing -4. Wire Pass 2 to fall back to LLM when no hardcoded estimate exists -5. Wire Pass 4 (plausibility review) -6. **Verify:** Mock provider returns structured data. Pipeline processes LLM output correctly. Full pipeline runs end-to-end with mock. - -### Phase E: Human Review & Output -1. Implement Pass 5 — interactive CLI review workflow -2. Implement `export` command — markdown report generation -3. Implement `results` and `review` CLI commands -4. **Verify:** Full pipeline from seed data through all 5 passes to final curated output. - -### Phase F: Extension & Refinement -1. Add new attribute dimensions (terrain, passenger count, cargo type) -2. Add new evaluation domains (military logistics, recreational, emergency services) -3. Refine dependency metadata based on pipeline output analysis -4. Implement a concrete LLM provider -5. Optional: Streamlit dashboard for interactive exploration - ---- - -## 11. Testing Strategy - -| Test Type | Scope | Purpose | -|---|---|---| -| **Unit** | Each engine module | Constraint rules, scoring math, combinator logic | -| **Integration** | Full pipeline with seed + mock LLM | End-to-end data flow | -| **Property-based** | Scorer | Multiplicative zero-kill, score bounds [0,1], geometric mean identity | -| **Snapshot** | Transport example | Known combinations produce known constraint/score results | -| **Interface contract** | LLM providers | Structured output schema compliance (not output quality) | - -LLM output quality is inherently non-deterministic and is NOT tested. Only the interface contract (correct types, valid JSON, expected keys) is validated. - ---- - -## 12. Verification Checkpoints - -After each phase, run: - -1. `python -m pytest tests/` — all tests green -2. `physcom init && physcom seed transport` — seed loads without error -3. `physcom run urban_commuting --passes 1` — constraint pass produces expected blocked/valid split -4. `physcom run urban_commuting --passes 1,2,3 --threshold 0.05` — scoring produces a ranked shortlist -5. `physcom results urban_commuting --top 10` — top concepts are plausible, not nonsense -6. **Manual smell test:** Do obviously-absurd combinations survive? If so, dependency metadata or constraint rules need refinement — that's where the real signal-to-noise quality lives. +1.1 → 1.5 → 1.2 → 1.3 → 1.4 → 1.6 → 1.7 → 1.8 → 2.3 → 2.1 → 2.4 → 2.5 → 2.6 → 3.1 → 3.3 → 2.2 (screenshots need the final UI) → 3.4 → 3.2. diff --git a/README.md b/README.md index cf097bb..198afb5 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,10 @@ python -m pytest tests/ -q ### LLM integration (optional) -By default the pipeline uses stub estimation. To enable Gemini: +Pass 2 (physics estimation) is always the deterministic estimator — no LLM. +An LLM is only used for the optional pass 4 plausibility review. + +Gemini: ```bash pip install -e ".[gemini]" @@ -86,6 +89,15 @@ export GEMINI_API_KEY=your_key_here physcom run urban_commuting --passes 1,2,3,4 ``` +Local models via [Ollama](https://ollama.com) (no extra install): + +```bash +export LLM_PROVIDER=ollama +# export OLLAMA_MODEL=qwen2.5:7b # default +# export OLLAMA_HOST=http://localhost:11434 # default +physcom run urban_commuting --passes 1,2,3,4 +``` + Copy `.env.example` to `.env` and fill in your key for persistent configuration. --- diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index ece929f..0000000 --- a/STATUS.md +++ /dev/null @@ -1,140 +0,0 @@ -# PhysCom — Project Status - -## Architecture Overview - -``` -src/ -├── physcom/ Core engine (CLI + SQLite + 5-pass pipeline) -│ ├── cli.py Click CLI: init, seed, entity, domain, run, results, review, export -│ ├── db/ -│ │ ├── schema.py DDL — 9 tables, 4 indexes -│ │ └── repository.py Data-access layer (24 methods) -│ ├── engine/ -│ │ ├── combinator.py Cartesian product generator -│ │ ├── constraint_resolver.py Pass 1 — requires/provides/excludes/range matching -│ │ ├── scorer.py Pass 3 — weighted geometric mean normalizer -│ │ └── pipeline.py Orchestrator for passes 1–5 -│ ├── llm/ -│ │ ├── base.py Abstract LLMProvider interface (2 methods) -│ │ ├── prompts.py Prompt templates for passes 2 and 4 -│ │ └── providers/ -│ │ └── mock.py Deterministic stub for tests -│ ├── models/ Dataclasses: Entity, Dependency, Domain, MetricBound, Combination, Score -│ └── seed/ -│ └── transport_example.py 9 platforms + 9 power sources + 2 domains -│ -├── physcom_web/ Flask web UI -│ ├── app.py App factory, per-request DB connection -│ ├── routes/ -│ │ ├── entities.py Entity + dependency CRUD (9 routes, HTMX) -│ │ ├── domains.py Domain listing (1 route) -│ │ ├── pipeline.py Run form + execution (2 routes) -│ │ └── results.py Browse, detail, human review (4 routes) -│ ├── templates/ Jinja2 + HTMX — 11 templates -│ └── static/style.css -│ -tests/ 37 passing tests -Dockerfile Single-stage Python 3.13-slim -docker-compose.yml web + cli services, shared volume -``` - -## What Works - -| Area | Status | Notes | -|------|--------|-------| -| Database schema | Done | 9 tables, WAL mode, foreign keys | -| Entity/dependency CRUD | Done | CLI + web UI | -| Domain + metric weights | Done | CLI seed + web read-only | -| Pass 1 — constraint resolution | Done | requires/provides/excludes/range logic | -| Pass 2 — physics estimation | Done | Stub heuristic (force/mass-based); LLM path exists but no real provider | -| Pass 3 — scoring + ranking | Done | Weighted geometric mean with min/max normalization | -| Pass 4 — LLM plausibility review | Wired | Pipeline calls `self.llm.review_plausibility()` when `llm` is not None; only MockLLMProvider exists | -| Pass 5 — human review | Done | CLI interactive + web HTMX form | -| Web UI | Done | Entity CRUD, domain view, pipeline run, results browse + review | -| Docker | Done | Compose with web + cli services, named volume | -| Tests | 37/37 passing | Repository, combinator, constraints, scorer, pipeline | - -## What's Missing - -### LLM provider — no real implementation yet - -The `LLMProvider` abstract class defines two methods: - -```python -class LLMProvider(ABC): - def estimate_physics(self, combination_description: str, metrics: list[str]) -> dict[str, float]: ... - def review_plausibility(self, combination_description: str, scores: dict[str, float]) -> str: ... -``` - -**Pass 2** (`estimate_physics`) — given a combination description like *"platform: Bicycle + power_source: Hydrogen Combustion Engine"*, return estimated metric values (speed, cost_efficiency, safety, etc.) as floats. - -**Pass 4** (`review_plausibility`) — given a combination description and its normalized scores, return a 2–4 sentence plausibility assessment. - -Prompt templates already exist in `src/physcom/llm/prompts.py`. The pipeline already checks `if self.llm:` and skips gracefully when None. - -### To enable LLM reviews, you need to: - -1. **Create a real provider** at `src/physcom/llm/providers/.py` that subclasses `LLMProvider`. For example, an Anthropic provider: - - ```python - # src/physcom/llm/providers/anthropic.py - import json - from anthropic import Anthropic - from physcom.llm.base import LLMProvider - from physcom.llm.prompts import PHYSICS_ESTIMATION_PROMPT, PLAUSIBILITY_REVIEW_PROMPT - - class AnthropicProvider(LLMProvider): - def __init__(self, model: str = "claude-sonnet-4-20250514"): - self.client = Anthropic() # reads ANTHROPIC_API_KEY from env - self.model = model - - def estimate_physics(self, description: str, metrics: list[str]) -> dict[str, float]: - prompt = PHYSICS_ESTIMATION_PROMPT.format( - description=description, - metrics=", ".join(metrics), - ) - resp = self.client.messages.create( - model=self.model, - max_tokens=256, - messages=[{"role": "user", "content": prompt}], - ) - return json.loads(resp.content[0].text) - - def review_plausibility(self, description: str, scores: dict[str, float]) -> str: - prompt = PLAUSIBILITY_REVIEW_PROMPT.format( - description=description, - scores=json.dumps(scores, indent=2), - ) - resp = self.client.messages.create( - model=self.model, - max_tokens=512, - messages=[{"role": "user", "content": prompt}], - ) - return resp.content[0].text - ``` - -2. **Add the dependency** to `pyproject.toml`: - ```toml - [project.optional-dependencies] - llm = ["anthropic>=0.40"] - ``` - -3. **Wire it into the CLI** — in `cli.py`'s `run` command, instantiate the provider when an `--llm` flag is passed and include pass 4 in the pass list. - -4. **Wire it into the web UI** — in `routes/pipeline.py`, same logic: read a config flag or env var (`PHYSCOM_LLM_PROVIDER`), instantiate the provider, pass it to `Pipeline(...)`. - -5. **Set the API key** — `ANTHROPIC_API_KEY` env var (or equivalent for your chosen provider). In Docker, add it to `docker-compose.yml`: - ```yaml - environment: - - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} - ``` - -The same pattern works for OpenAI, Databricks, or any other provider — just subclass `LLMProvider` and implement the two methods. - -### Other future work - -- **Domain creation via web UI** — currently seed-only -- **Database upgrade** — SQLite → Postgres (docker-compose has a commented placeholder) -- **Async pipeline runs** — currently synchronous; fine for 81 combos, may need background tasks at scale -- **Export from web UI** — currently CLI-only (`physcom export`) -- **Authentication** — no auth on the web UI diff --git a/src/physcom/llm/base.py b/src/physcom/llm/base.py index 1f0e875..1e0428b 100644 --- a/src/physcom/llm/base.py +++ b/src/physcom/llm/base.py @@ -4,7 +4,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from physcom.models.domain import Domain, MetricBound +from physcom.models.domain import Domain class LLMRateLimitError(Exception): @@ -20,19 +20,7 @@ class LLMRateLimitError(Exception): class LLMProvider(ABC): - """Abstract LLM interface for physics estimation and plausibility review.""" - - @abstractmethod - def estimate_physics( - self, combination_description: str, metrics: list[MetricBound] - ) -> dict[str, float]: - """Given a natural-language description of a combination, - estimate raw metric values. `metrics` carries each metric's unit and - expected norm_min/norm_max so the estimate lands in the right - magnitude — a bare metric name gives no hint that "cost_efficiency" - means dollars per meter in the 1e-5 range, not a 0-1 score. - Returns {metric_name: estimated_value}.""" - ... + """Abstract LLM interface for plausibility review.""" @abstractmethod def review_plausibility( diff --git a/src/physcom/llm/parsing.py b/src/physcom/llm/parsing.py index 23daf86..1ecde54 100644 --- a/src/physcom/llm/parsing.py +++ b/src/physcom/llm/parsing.py @@ -2,11 +2,8 @@ from __future__ import annotations -import json import re -from physcom.models.domain import MetricBound - def parse_verdict(text: str) -> bool: """Extract VERDICT: PLAUSIBLE/IMPLAUSIBLE from response; default to True.""" @@ -22,16 +19,3 @@ def parse_rating(text: str) -> str | None: m = re.search(r"RATING:\s*(LOW|MEDIUM|HIGH)", text, re.IGNORECASE) return m.group(1).upper() if m else None - -def parse_metric_json(text: str, metrics: list[MetricBound]) -> dict[str, float]: - """Strip markdown fences and parse JSON; fall back to each metric's own - norm_min/norm_max midpoint on error — a flat constant like 0.5 is - guaranteed wrong-magnitude for at least some metrics regardless of unit. - """ - names = {mb.metric_name for mb in metrics} - text = re.sub(r"```(?:json)?\s*", "", text).strip().rstrip("`").strip() - try: - data = json.loads(text) - return {k: float(v) for k, v in data.items() if k in names} - except (json.JSONDecodeError, ValueError, TypeError): - return {mb.metric_name: (mb.norm_min + mb.norm_max) / 2 for mb in metrics} diff --git a/src/physcom/llm/prompts.py b/src/physcom/llm/prompts.py index 4a4b07e..5f88169 100644 --- a/src/physcom/llm/prompts.py +++ b/src/physcom/llm/prompts.py @@ -8,18 +8,6 @@ if TYPE_CHECKING: from physcom.models.domain import MetricBound -def format_metrics_for_prompt(metrics: list["MetricBound"]) -> str: - """Render each metric with its unit and expected range, so the model - anchors on the right order of magnitude instead of a generic decimal.""" - lines = [] - for mb in metrics: - unit = mb.unit or "dimensionless" - lines.append( - f"- {mb.metric_name} ({unit}): typical range {mb.norm_min:g} to {mb.norm_max:g}" - ) - return "\n".join(lines) - - def format_scores_for_prompt( raw_metrics: dict[str, float], normalized_scores: dict[str, float], @@ -73,24 +61,14 @@ match that magnitude, don't guess a generically "reasonable-looking" decimal. {{"some_metric": , "another_metric": }} — no explanatory text. """ -# ponytail: pass 4 used to see only pass 2's normalized scores, not the raw -# physical numbers or any reasoning behind them. Fixed the raw-value half of -# that gap: format_scores_for_prompt() now shows both, since a correct raw -# estimate can look damning once log-normalized against a scale built for a -# different kind of vehicle (a cyclist's real ~5 W/kg reads as "0.159" next -# to a car's 2000 W/kg ceiling) -- gemma2:27b did exactly this on a real -# bicycle combo, citing "extremely low power density (0.159)" as grounds for -# IMPLAUSIBLE while never reasoning from the actual (correct) 5 W/kg. The -# reasoning-text half of the gap is still open: estimate_physics() doesn't -# return a per-metric rationale, so pass 4 still can't see WHY pass 2 landed -# on a number, only what the number is. Upgrade path if the raw value alone -# isn't enough in practice: have estimate_physics() also return a short -# per-metric reason, persist it alongside raw_value (new nullable column), -# and feed it into this prompt. Deferred because it needs a schema/interface -# change across LLMProvider + both providers + pipeline + scorer + -# repository, and more generated tokens per combo. -# -# If we plan to LLM-review every p2 pass then maybe p2 and p4 should be combined. +# ponytail: pass 4 sees raw values + normalized scores (format_scores_for_prompt), +# since a correct raw estimate can look damning once log-normalized against a +# scale built for a different kind of vehicle (a cyclist's real ~5 W/kg reads +# as "0.159" next to a car's 2000 W/kg ceiling) -- gemma2:27b did exactly this +# on a real bicycle combo, citing "extremely low power density (0.159)" as +# grounds for IMPLAUSIBLE. It still can't see WHY pass 2 landed on a number. +# Upgrade path if raw values aren't enough: show the deterministic +# estimator's chosen mass allocation / free-variable values in this prompt. # # Calibration history: the original wording asked the model to weigh "novelty" # and "genuinely interesting innovation or nonsense" as part of the verdict, diff --git a/src/physcom/llm/providers/gemini.py b/src/physcom/llm/providers/gemini.py index bf106bb..168b626 100644 --- a/src/physcom/llm/providers/gemini.py +++ b/src/physcom/llm/providers/gemini.py @@ -6,14 +6,12 @@ import re import math from physcom.llm.base import LLMProvider, LLMRateLimitError -from physcom.llm.parsing import parse_metric_json, parse_verdict +from physcom.llm.parsing import parse_verdict from physcom.llm.prompts import ( - PHYSICS_ESTIMATION_PROMPT, PLAUSIBILITY_REVIEW_PROMPT, - format_metrics_for_prompt, format_scores_for_prompt, ) -from physcom.models.domain import Domain, MetricBound +from physcom.models.domain import Domain class GeminiLLMProvider(LLMProvider): @@ -29,23 +27,6 @@ class GeminiLLMProvider(LLMProvider): self._client = genai.Client(api_key=api_key) self._model = model - def estimate_physics( - self, combination_description: str, metrics: list[MetricBound] - ) -> dict[str, float]: - prompt = PHYSICS_ESTIMATION_PROMPT.format( - description=combination_description, - metrics=format_metrics_for_prompt(metrics), - ) - try: - response = self._client.models.generate_content( - model=self._model, contents=prompt - ) - except Exception as exc: - if "429" in str(exc) or "RESOURCE_EXHAUSTED" in str(exc): - raise LLMRateLimitError(str(exc), self._parse_retry_after(exc)) from exc - raise - return parse_metric_json(response.text, metrics) - def review_plausibility( self, combination_description: str, diff --git a/src/physcom/llm/providers/mock.py b/src/physcom/llm/providers/mock.py index f94e8a9..9f0d0f5 100644 --- a/src/physcom/llm/providers/mock.py +++ b/src/physcom/llm/providers/mock.py @@ -3,23 +3,12 @@ from __future__ import annotations from physcom.llm.base import LLMProvider -from physcom.models.domain import Domain, MetricBound +from physcom.models.domain import Domain class MockLLMProvider(LLMProvider): """Returns deterministic stub responses for testing.""" - def __init__(self, default_estimates: dict[str, float] | None = None) -> None: - self._defaults = default_estimates or {} - - def estimate_physics( - self, combination_description: str, metrics: list[MetricBound] - ) -> dict[str, float]: - result = {} - for mb in metrics: - result[mb.metric_name] = self._defaults.get(mb.metric_name, 0.5) - return result - def review_plausibility( self, combination_description: str, diff --git a/src/physcom/llm/providers/ollama.py b/src/physcom/llm/providers/ollama.py index 517c907..6c2c115 100644 --- a/src/physcom/llm/providers/ollama.py +++ b/src/physcom/llm/providers/ollama.py @@ -7,14 +7,12 @@ import urllib.error import urllib.request from physcom.llm.base import LLMProvider -from physcom.llm.parsing import parse_metric_json, parse_verdict +from physcom.llm.parsing import parse_verdict from physcom.llm.prompts import ( - PHYSICS_ESTIMATION_PROMPT, PLAUSIBILITY_REVIEW_PROMPT, - format_metrics_for_prompt, format_scores_for_prompt, ) -from physcom.models.domain import Domain, MetricBound +from physcom.models.domain import Domain class OllamaLLMProvider(LLMProvider): @@ -24,16 +22,6 @@ class OllamaLLMProvider(LLMProvider): self._model = model self._host = host.rstrip("/") - def estimate_physics( - self, combination_description: str, metrics: list[MetricBound] - ) -> dict[str, float]: - prompt = PHYSICS_ESTIMATION_PROMPT.format( - description=combination_description, - metrics=format_metrics_for_prompt(metrics), - ) - text = self._generate(prompt, json_mode=True) - return parse_metric_json(text, metrics) - def review_plausibility( self, combination_description: str, @@ -48,13 +36,11 @@ class OllamaLLMProvider(LLMProvider): domain_name=domain.name, domain_description=domain.description, ) - text = self._generate(prompt, json_mode=False).strip() + text = self._generate(prompt).strip() return (text, parse_verdict(text)) - def _generate(self, prompt: str, json_mode: bool) -> str: + def _generate(self, prompt: str) -> str: payload = {"model": self._model, "prompt": prompt, "stream": False} - if json_mode: - payload["format"] = "json" req = urllib.request.Request( f"{self._host}/api/generate", data=json.dumps(payload).encode("utf-8"), diff --git a/tests/test_llm_parsing.py b/tests/test_llm_parsing.py index c6e2342..249d390 100644 --- a/tests/test_llm_parsing.py +++ b/tests/test_llm_parsing.py @@ -2,26 +2,7 @@ from __future__ import annotations -from physcom.llm.parsing import parse_metric_json, parse_verdict -from physcom.models.domain import MetricBound - - -def _bounds(): - return [ - MetricBound("power_density", weight=0.5, norm_min=1, norm_max=2000, unit="W/kg"), - MetricBound("safety", weight=0.5, norm_min=0.0, norm_max=1.0, unit="0-1"), - ] - - -def test_parse_metric_json_strips_fences(): - text = '```json\n{"power_density": 500.0, "safety": 0.7}\n```' - result = parse_metric_json(text, _bounds()) - assert result == {"power_density": 500.0, "safety": 0.7} - - -def test_parse_metric_json_falls_back_to_range_midpoint_on_invalid(): - result = parse_metric_json("not json", _bounds()) - assert result == {"power_density": 1000.5, "safety": 0.5} +from physcom.llm.parsing import parse_verdict def test_parse_verdict_plausible(): diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 209f830..77fb015 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -43,10 +43,7 @@ def test_pass4_with_mock_llm(seeded_repo): domain = seeded_repo.get_domain("urban_commuting") resolver = ConstraintResolver() scorer = Scorer(domain) - mock_llm = MockLLMProvider(default_estimates={ - "power_density": 500.0, "cost_efficiency": 5e-4, "safety": 0.6, - "availability": 0.7, "range_fuel": 200000.0, - }) + mock_llm = MockLLMProvider() pipeline = Pipeline(seeded_repo, resolver, scorer, llm=mock_llm) result = pipeline.run(