From ee7700275c443eaf2a77821160307dede71e7e61 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Wed, 7 Oct 2026 08:12:45 +0000 Subject: [PATCH] add remote winnow support --- AGENTS.md | 45 +++++- config.example.json | 17 +- semif_agent/cli.py | 44 +++++- semif_agent/engine.py | 77 ++++++++- semif_agent/scheduler.py | 4 +- semif_agent/skills.py | 14 +- semif_agent/winnow.py | 240 +++++++++++++++++++++++++++++ tests/integration/test_pipeline.py | 13 +- tests/test_engine_config.py | 36 ++++- tests/test_winnow_engine.py | 213 +++++++++++++++++++++++++ 10 files changed, 674 insertions(+), 29 deletions(-) create mode 100644 semif_agent/winnow.py create mode 100644 tests/test_winnow_engine.py diff --git a/AGENTS.md b/AGENTS.md index 30deb18..bbe2778 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,10 +147,20 @@ timers.py in-process timer/alarm service (TimerService) owned by the the gateway routes it to the originating chat, the dashboard shows pending/fired). Real local compute (`compute` transport), per-process, and deliberately NOT persisted across restarts. -engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import); - call() scores a decision, generate() autoregressively samples - text from the same loaded model (shares the engine lock, clears - the KV cache) — backs the `semif` llm provider +engine.py DecisionEngine (the pluggable contract: call/warm/loaded/ + generate) + SemIfEngine, the default local provider -> + semif_phase1.llamacpp_backend (lazy import); call() scores a + decision, generate() autoregressively samples text from the + same loaded model (shares the engine lock, clears the KV cache) + — backs the `semif` llm provider. Selected per machine by + `engine.provider` (mirrors llm.provider/codegen.provider). +winnow.py WinnowEngine -> a remote Winnow `/v1/systemone` typed-decision + HTTP API (`engine.provider == "winnow"`): maps DecisionRequest + to a `choice` question (options -> criteria), validates and + normalizes the returned distribution over exactly those option + ids, and generate() via /v1/chat/completions. stdlib urllib; an + internal lock serializes on the single-slot server; every + failure raises EngineUnavailable (fatal, like the local engine) codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill bodies against CODEGEN.md (real actions via stdlib transports, data from the runner via ctx.config, never embedded; bodies @@ -561,6 +571,33 @@ CLI, unit tests (24) + integration tests (2). ## Constraints & gotchas (learned the hard way) +### Decision engine (providers) +- The decision engine is **pluggable**, selected per machine by `engine.provider` + in config.json — the same provider pattern as `llm`/`codegen`. `"semif"` + (default) is the local llama.cpp GGUF (`SemIfEngine`); `"winnow"` is a remote + Winnow `/v1/systemone` typed-decision API (`semif_agent.winnow.WinnowEngine`, + configured by the nested `engine.winnow` block). `cli.build_engine` picks the + class; `SemIfEngine`/`WinnowEngine` both satisfy `engine.DecisionEngine` + (`call`/`warm`/`loaded`/`generate`). +- **The engine is always real and every `EngineUnavailable` is fatal**, + whichever provider is selected: `WinnowEngine` converts every network, HTTP, + and malformed/unnormalized-distribution failure into `EngineUnavailable` so + the scheduler's fatal path (and the codegen watchdog / LLM bridge's graceful + paths) behave identically to the local engine. There is no fallback model. +- The agent's flat decision (`state` + `question` + typed `options`) maps onto + Winnow's `choice` question type (`options` -> `criteria` id->description, + `question` -> `instructions`); the returned distribution is validated against + exactly the requested option ids and normalized. `generate` goes through the + same server's `/v1/chat/completions`, so `llm.provider == "semif"` keeps + working when the decision engine is Winnow. +- Swapping the decision model changes routing/assessment behaviour and the + decision-log distribution; that is the intended per-machine choice. The + decision log and `dream` cost are unchanged because `DecisionResult` is the + same contract. +- Context differs by provider (the local engine's `engine.context_tokens` vs the + remote server's own `--ctx-size`); a state that overflows is a fatal + `EngineUnavailable`, the same class as the local token limit. + ### Environment - The core is pure stdlib and runs anywhere Python does. Never pip-install heavy deps on a thin client; a full install belongs on a provisioned host. diff --git a/config.example.json b/config.example.json index edb49a6..229ac91 100644 --- a/config.example.json +++ b/config.example.json @@ -15,12 +15,25 @@ "engine": { "_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.", "_gpu_comment": "gpu_layers: 0 keeps the CPU-only default, -1 offloads every layer, a positive count offloads that many. Requires a llama-cpp-python built with a GPU backend (bootstrap detects Vulkan/ROCm/CUDA). gpu_device picks the llama.cpp device index and gpu_split sets its split mode (0 = none).", + "_provider_comment": "provider selects the decision engine, exactly like llm.provider/codegen.provider: \"semif\" (default) is the local llama.cpp GGUF described below; \"winnow\" is a remote /v1/systemone typed-decision API configured by the `winnow` block (a different model, e.g. Winnow-12B on a ROCm host). The engine is always real: a provider that cannot be reached raises EngineUnavailable, which is fatal — there is no fallback model. The decision log and `dream` cost work unchanged either way.", + "provider": "semif", "backend": "llamacpp", "context_tokens": 4096, "threads": 8, "gpu_layers": 0, "gpu_device": null, - "gpu_split": 0 + "gpu_split": 0, + "winnow": { + "_comment": "Settings for provider == \"winnow\": a remote Winnow typed-decision server (`winnow-server`, ROCm/HIP on a dedicated GPU host) exposing POST /v1/systemone (choice questions) and /v1/chat/completions (text, used by llm.provider == \"semif\"). base_url is the server root; model is required (no default). timeout bounds each request; retries is the number of transient-failure retries before the engine is declared unavailable (0 = a single attempt; an unreachable engine is fatal by contract). api_key/api_key_env add a bearer token (usually unset on a LAN); extra_headers/user_agent pass through for custom setups. The Winnow model holds the whole GPU, so it cannot be resident alongside a large codegen model — stop one before starting the other.", + "base_url": "http://127.0.0.1:8091", + "model": "", + "api_key": "", + "api_key_env": "", + "timeout": 120, + "retries": 0, + "user_agent": "semif-agent", + "extra_headers": {} + } }, "llm": { "_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show), \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).", @@ -144,7 +157,7 @@ "_comment": "Messenger COMMAND intake — and nothing else. `python -m semif_agent.cli gateway` runs one or more platforms (`--platform simplex,lxmf` or `all`) in a SINGLE process sharing one scheduler/skill store — never run two gateway processes over one store. Each platform feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. It must never read a contact's history, show/create invite links, or compose on the user's behalf — that is the independent bridge services' job (`bridges`). home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). reply_prefix is prepended to every reply. text_batch_delay concatenates rapid-fire messages from one contact.", "humanize": { "_comment": "Optional LLM cleanup of a skill's result line for chat replies. Off by default. When enabled, a completed result is unwrapped from the scheduler's `: — ` bookkeeping and rewritten by the scheduler's `llm` client into one grounded, friendly sentence; it never decides success/failure and always falls back to the raw result on any error. `timeout`/`max_tokens`/`max_chars` bound the auxiliary call (a slow cleanup must not hold the gateway). A platform turns it on/off with its own `humanize` key (bool or `{enabled: ...}`), overriding this global default; `timeout`/`max_tokens`/`max_chars` are global. Only result lines are cleaned — questions, repair/approval notices, and status chatter are untouched.", - "enabled": false, + "enabled": true, "timeout": 20.0, "max_tokens": 200, "max_chars": 600 diff --git a/semif_agent/cli.py b/semif_agent/cli.py index 0314cdf..f5b99f4 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -28,7 +28,8 @@ from .console import ( ConsoleLLMClient, ) from .decisions import DecisionRequest, Option -from .engine import EngineConfig, EngineUnavailable, SemIfEngine +from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine +from .winnow import WinnowConfig, WinnowEngine from .llm import LLMClient, SemIfLLMClient from .log import DecisionLog from .scheduler import Scheduler @@ -38,6 +39,8 @@ from .trace import TraceLog REPO_ROOT = Path(__file__).resolve().parent.parent +DEFAULT_WINNOW_URL = "http://127.0.0.1:8091" + _PATH_KEYS = ( "skill_seeds", "skill_bodies", @@ -191,6 +194,41 @@ def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig: ) +def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine: + """Build the decision engine from the `engine` config block. + + `provider` selects the implementation, mirroring `llm`/`codegen`: + + * ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built + from the per-machine `engine` knobs + the pinned refs in pins.json. + * ``"winnow"`` — a remote `/v1/systemone` typed-decision API + (`WinnowEngine`), configured by the nested `engine.winnow` block + (`base_url`/`model`/`api_key`/`timeout`/`retries`). + + The engine is always real: a provider that cannot be reached raises + `EngineUnavailable` at call time, which the scheduler treats as fatal. The + `winnow` model is required (no default) exactly as `llm.model`/`codegen.model` + are, so a misconfigured endpoint fails as an actionable config error. + """ + eng = config.get("engine", {}) or {} + provider = str(eng.get("provider", "semif") or "semif").lower() + if provider == "winnow": + win = eng.get("winnow", {}) or {} + endpoint = _provider_endpoint(win, DEFAULT_WINNOW_URL) + return WinnowEngine( + WinnowConfig( + base_url=endpoint["base_url"], + model=_required_model(win, "engine.winnow"), + timeout=float(win.get("timeout", 120.0)), + retries=int(win.get("retries", 0)), + api_key=endpoint["api_key"], + extra_headers=endpoint["extra_headers"], + user_agent=str(win.get("user_agent") or "semif-agent"), + ) + ) + return SemIfEngine(build_engine_config(config, pins)) + + def build_codegen_client(config: dict) -> CodegenClient: """Build the codegen client from the `codegen` config block. @@ -275,7 +313,7 @@ def build_llm_client(config: dict, engine): def build_scheduler(config: dict) -> tuple[Scheduler, dict]: - engine = SemIfEngine(build_engine_config(config)) + engine = build_engine(config) llm = build_llm_client(config, engine) log = DecisionLog(config.get("log", "data/decisions.jsonl")) trace = TraceLog(config.get("trace", "data/runs.jsonl")) @@ -374,7 +412,7 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]: def try_warm(scheduler: Scheduler) -> str: try: - scheduler.engine._ensure_loaded() + scheduler.engine.warm() return "decision engine loaded." except EngineUnavailable as exc: return f"decision engine unavailable: {exc}" diff --git a/semif_agent/engine.py b/semif_agent/engine.py index 2aec781..0ceeada 100644 --- a/semif_agent/engine.py +++ b/semif_agent/engine.py @@ -1,17 +1,21 @@ -"""Real SemIf decision engine (no mocking). +"""The decision-engine contract and the local SemIf implementation. -Wraps the SemIf package (`semif_phase1`). The import and model load happen +`DecisionEngine` is the pluggable contract every provider satisfies; the +provider is selected per machine by `engine.provider` in config.json, exactly +like `llm.provider` / `codegen.provider`. `SemIfEngine` is the default: it wraps +the SemIf package (`semif_phase1`). The import and model load happen lazily so the rest of the agent is pure stdlib and testable without SemIf installed. The shipped llama.cpp backend scores a local GGUF; it runs on CPU by default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a machine with SemIf and the pinned GGUF available; elsewhere calls raise -EngineUnavailable. +EngineUnavailable. The remote alternative lives in `semif_agent.winnow`. """ from __future__ import annotations import threading +from abc import ABC, abstractmethod from dataclasses import dataclass from pathlib import Path @@ -19,7 +23,58 @@ from .decisions import DecisionRequest, DecisionResult class EngineUnavailable(RuntimeError): - """SemIf is not installed or the configured model is missing.""" + """The decision engine is not installed, not reachable, or failed. + + This is the one error a decision engine raises. It is fatal by contract: + the scheduler records it (`_mark_fatal`) and the front ends exit, because + the agent cannot make decisions without a real engine. + """ + + +class DecisionEngine(ABC): + """The pluggable decision-engine contract. + + A decision engine answers a `DecisionRequest` (state + question + typed + options) with a `DecisionResult` (probabilities over exactly those options). + It is selected per machine by `engine.provider` in config.json, mirroring + `llm.provider` / `codegen.provider`: + + * ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`). + * ``"winnow"`` — a remote ``/v1/systemone`` typed-decision API + (`semif_agent.winnow.WinnowEngine`). + + The engine is always real: any failure to produce a decision raises + `EngineUnavailable`, which the scheduler treats as fatal. `generate` is the + optional text-generation face of the same model (used by + `llm.provider == "semif"`); an engine that cannot generate text raises + `EngineUnavailable` there rather than inventing a reply. + """ + + label: str = "engine" + + @property + @abstractmethod + def loaded(self) -> bool: + """Whether the underlying model is loaded/warm.""" + + @abstractmethod + def warm(self) -> None: + """Load/warm the model, raising `EngineUnavailable` on failure.""" + + @abstractmethod + def call(self, request: DecisionRequest) -> DecisionResult: + """Score one decision, raising `EngineUnavailable` on failure.""" + + def generate( + self, + messages: list[dict], + temperature: float = 0.0, + max_tokens: int = 256, + ) -> str: + """Autoregressively generate text from the same model, if supported.""" + raise EngineUnavailable( + f"{self.label} engine does not support text generation" + ) @dataclass @@ -93,8 +148,14 @@ def _offloading_params(original, config: EngineConfig): return offloading -class SemIfEngine: - """One pinned SemIf model, loaded once and used for every decision.""" +class SemIfEngine(DecisionEngine): + """One pinned SemIf model, loaded once and used for every decision. + + The default `engine.provider`: the local llama.cpp GGUF. Text generation + from the same model backs `llm.provider == "semif"`. + """ + + label = "semif" def __init__(self, config: EngineConfig): self.config = config @@ -153,6 +214,10 @@ class SemIfEngine: def loaded(self) -> bool: return self._model is not None + def warm(self) -> None: + """Load the model (idempotent), raising `EngineUnavailable` on failure.""" + self._ensure_loaded() + def call(self, request: DecisionRequest) -> DecisionResult: with self._lock: model, tokenizer, metadata = self._ensure_loaded() diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 9c25faa..459bdfe 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -33,7 +33,7 @@ from .codegen import ( skill_contract_ref, ) from .decisions import DecisionRequest, Option, Request -from .engine import EngineUnavailable, SemIfEngine +from .engine import DecisionEngine, EngineUnavailable from .llm import LLMClient from .log import DecisionLog from .provider import ProviderError @@ -224,7 +224,7 @@ class SchedulerReply: class Scheduler: def __init__( self, - engine: SemIfEngine, + engine: DecisionEngine, llm: LLMClient, log: DecisionLog, config: dict, diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 40263e1..82bf692 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -22,7 +22,7 @@ from pathlib import Path from typing import Callable from .decisions import DecisionRequest, Option, Request -from .engine import SemIfEngine +from .engine import DecisionEngine from .llm import LLMClient from .log import DecisionLog from .timers import TimerService @@ -41,7 +41,7 @@ class ActionResult: @dataclass class ActionContext: - engine: SemIfEngine + engine: DecisionEngine config: dict timers: TimerService | None = None # The scheduler, exposed to built-in meta skills (housekeeping) so they can @@ -1117,7 +1117,7 @@ def merge_registry(tree: dict[str, list[Skill]], categories: dict[str, dict]) -> def _navigate_canned( - engine: SemIfEngine, + engine: DecisionEngine, log: DecisionLog, trace: TraceLog, request: Request, @@ -1160,7 +1160,7 @@ def _navigate_canned( def navigate( - engine: SemIfEngine, + engine: DecisionEngine, log: DecisionLog, trace: TraceLog, request: Request, @@ -1340,7 +1340,7 @@ def navigate( def confirm_category_fit( - engine: SemIfEngine, + engine: DecisionEngine, log: DecisionLog, trace: TraceLog, request: Request, @@ -1405,7 +1405,7 @@ def confirm_category_fit( def confirm_non_action( - engine: SemIfEngine, + engine: DecisionEngine, log: DecisionLog, trace: TraceLog, request: Request, @@ -1468,7 +1468,7 @@ def confirm_non_action( def confirm_skill_fit( - engine: SemIfEngine, + engine: DecisionEngine, log: DecisionLog, trace: TraceLog, request: Request, diff --git a/semif_agent/winnow.py b/semif_agent/winnow.py new file mode 100644 index 0000000..6fa8f09 --- /dev/null +++ b/semif_agent/winnow.py @@ -0,0 +1,240 @@ +"""Remote Winnow decision engine: a `/v1/systemone` typed-decision HTTP API. + +An alternative to the local SemIf llama.cpp engine (`engine.SemIfEngine`), +selected per machine with ``engine.provider == "winnow"`` in config.json — the +same provider pattern as ``llm`` / ``codegen``. The agent's flat decision +contract (state + question + typed options) maps onto Winnow's ``choice`` +question type: the options become the question's ``criteria`` (id -> description) +and the question becomes its ``instructions``; the server returns a probability +over exactly those keys. + +Winnow runs as its own process (``winnow-server``); see ``local/ENVIRONMENT.md`` +for the guppy deployment. The engine is real: any network, HTTP, or distribution +failure raises `EngineUnavailable`, which the scheduler treats as fatal — there +is no fallback model and no fabricated reply. +""" + +from __future__ import annotations + +import json +import math +import threading +import time +import urllib.error +import urllib.request +from dataclasses import dataclass + +from .decisions import DecisionRequest, DecisionResult +from .engine import DecisionEngine, EngineUnavailable + + +@dataclass +class WinnowConfig: + """Per-machine settings for the remote Winnow engine (`engine.winnow`).""" + + base_url: str = "http://127.0.0.1:8091" + model: str = "Winnow-12B" + timeout: float = 120.0 + # Transient-failure retries before declaring the engine unavailable. 0 means + # a single attempt: an unreachable remote engine is fatal by contract. + retries: int = 0 + api_key: str = "" + extra_headers: dict | None = None + user_agent: str = "semif-agent" + + +class WinnowEngine(DecisionEngine): + """One Winnow `/v1/systemone` endpoint, used for every decision. + + Scoring maps `DecisionRequest` -> a single ``choice`` question and reads the + returned distribution back over the requested option ids. The endpoint is a + single-slot server, so calls serialize on an internal lock exactly as + `SemIfEngine` serializes on its llama.cpp context. + """ + + label = "winnow" + + def __init__(self, config: WinnowConfig): + self.config = config + self._lock = threading.Lock() + self._loaded = False + + @property + def loaded(self) -> bool: + return self._loaded + + # ---- transport ---- + + def _headers(self) -> dict: + headers = { + "content-type": "application/json", + "accept": "application/json", + } + if self.config.user_agent: + headers["user-agent"] = self.config.user_agent + if self.config.api_key: + headers["authorization"] = f"Bearer {self.config.api_key}" + for key, value in (self.config.extra_headers or {}).items(): + headers[str(key)] = str(value) + return headers + + def _post(self, path: str, payload: dict) -> dict: + """POST JSON, returning the parsed object or raising `EngineUnavailable`.""" + url = self.config.base_url.rstrip("/") + path + data = json.dumps(payload).encode("utf-8") + attempts = max(0, int(self.config.retries)) + 1 + last: Exception | None = None + for attempt in range(attempts): + request = urllib.request.Request( + url, data=data, method="POST", headers=self._headers() + ) + try: + with urllib.request.urlopen( + request, timeout=self.config.timeout + ) as response: + body = response.read().decode("utf-8", errors="replace") + parsed = json.loads(body) + if not isinstance(parsed, dict): + raise EngineUnavailable( + f"Winnow response from {url} is not a JSON object" + ) + return parsed + except urllib.error.HTTPError as exc: + detail = "" + try: + detail = exc.read().decode("utf-8", errors="replace")[:300] + except Exception: + pass + last = EngineUnavailable( + f"HTTP {exc.code} from {url}: {detail}".strip() + ) + # A 4xx (except 429) will not succeed on retry. + if 400 <= exc.code < 500 and exc.code != 429: + break + except EngineUnavailable: + raise + except Exception as exc: # URLError, timeout, socket, JSONDecodeError + last = exc + if attempt + 1 < attempts: + time.sleep(min(2.0**attempt, 5.0)) + if isinstance(last, EngineUnavailable): + raise last + raise EngineUnavailable( + f"Winnow request to {url} failed: {type(last).__name__}: {last}" + ) + + # ---- DecisionEngine ---- + + def warm(self) -> None: + """Verify the endpoint is reachable (`GET /health`), else raise.""" + url = self.config.base_url.rstrip("/") + "/health" + request = urllib.request.Request(url, method="GET", headers=self._headers()) + try: + with urllib.request.urlopen( + request, timeout=self.config.timeout + ) as response: + if getattr(response, "status", 200) != 200: + raise EngineUnavailable( + f"Winnow health check returned HTTP {response.status}" + ) + except EngineUnavailable: + raise + except Exception as exc: + raise EngineUnavailable(f"Winnow unreachable at {url}: {exc}") from exc + self._loaded = True + + def call(self, request: DecisionRequest) -> DecisionResult: + option_ids = [option.id for option in request.options] + payload = { + "state": request.state, + "model": self.config.model, + "questions": { + "decision": { + "type": "choice", + "instructions": request.question, + "criteria": { + option.id: option.description for option in request.options + }, + } + }, + } + with self._lock: + started = time.perf_counter() + body = self._post("/v1/systemone", payload) + elapsed = time.perf_counter() - started + + answers = body.get("answers") + answer = answers.get("decision") if isinstance(answers, dict) else None + if not isinstance(answer, dict): + raise EngineUnavailable("Winnow response is missing answers.decision") + if answer.get("type") not in (None, "choice"): + raise EngineUnavailable( + f"Winnow answer type {answer.get('type')!r} is not 'choice'" + ) + raw = answer.get("probabilities") + if not isinstance(raw, dict): + raise EngineUnavailable("Winnow answer is missing probabilities") + if set(raw) != set(option_ids): + raise EngineUnavailable( + "Winnow probabilities do not match the requested options: " + f"{sorted(raw)} != {sorted(option_ids)}" + ) + try: + values = [float(raw[option_id]) for option_id in option_ids] + except (TypeError, ValueError) as exc: + raise EngineUnavailable( + f"Winnow probabilities are not numeric: {exc}" + ) from exc + if any((not math.isfinite(value)) or value < 0.0 or value > 1.0 for value in values): + raise EngineUnavailable( + "Winnow returned a non-finite or out-of-range probability" + ) + total = sum(values) + if total <= 0.0: + raise EngineUnavailable("Winnow returned an all-zero distribution") + probabilities = [value / total for value in values] + usage = body.get("usage") if isinstance(body.get("usage"), dict) else {} + self._loaded = True + return DecisionResult( + request=request, + option_ids=option_ids, + probabilities=probabilities, + extra={ + "input_tokens": usage.get("input_tokens"), + "output_tokens": usage.get("output_tokens"), + "forward_seconds": elapsed, + "total_seconds": elapsed, + "raw_probability_sum": total, + "served_model": body.get("model"), + "confidence": answer.get("confidence"), + }, + ) + + def generate( + self, + messages: list[dict], + temperature: float = 0.0, + max_tokens: int = 256, + ) -> str: + """Text generation via the same server's `/v1/chat/completions`. + + Backs `llm.provider == "semif"` when the decision engine is Winnow. + """ + payload = { + "model": self.config.model, + "messages": messages, + "max_tokens": max_tokens, + "temperature": temperature, + } + with self._lock: + body = self._post("/v1/chat/completions", payload) + choices = body.get("choices") + if not isinstance(choices, list) or not choices: + raise EngineUnavailable("Winnow chat response has no choices") + first = choices[0] + message = first.get("message") if isinstance(first, dict) else None + content = message.get("content") if isinstance(message, dict) else None + if not isinstance(content, str): + raise EngineUnavailable("Winnow chat response has no message content") + self._loaded = True + return content.strip() diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index 9521bb6..fd21046 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -350,13 +350,18 @@ def test_busy_queue_path(tmp_path): scheduler.idle() -def test_engine_scoring_only(tmp_path): - """The pinned decision model scores (makes decisions); it no longer writes - free text. Text authoring is the `llm` provider's job.""" +def test_engine_is_pluggable(tmp_path): + """The configured decision engine satisfies the `DecisionEngine` contract + (`call` + `warm` + `generate`), whether the local `semif` provider or a + remote `winnow` one. The engine is selected by `engine.provider`.""" config = load_config() require_real(config) scheduler, config = build_scheduler(config) - assert not hasattr(scheduler.engine, "generate") + from semif_agent.engine import DecisionEngine + + assert isinstance(scheduler.engine, DecisionEngine) + assert hasattr(scheduler.engine, "call") + assert hasattr(scheduler.engine, "generate") def test_generate_category(tmp_path): diff --git a/tests/test_engine_config.py b/tests/test_engine_config.py index ce9a234..6dd257d 100644 --- a/tests/test_engine_config.py +++ b/tests/test_engine_config.py @@ -9,12 +9,17 @@ from __future__ import annotations from types import SimpleNamespace -from semif_agent.cli import build_engine_config +import pytest + +from semif_agent.cli import build_engine, build_engine_config from semif_agent.engine import ( + DecisionEngine, EngineConfig, + SemIfEngine, _install_gpu_state_reset, _offloading_params, ) +from semif_agent.winnow import WinnowEngine PINS = { "engine": { @@ -77,3 +82,32 @@ def test_gpu_state_reset_clears_cache_data(): _install_gpu_state_reset(SimpleNamespace(engine=engine)) engine.clear() assert calls == [("mem", True)] + + +def test_build_engine_defaults_to_the_local_semif_provider(): + engine = build_engine({"engine": {"backend": "llamacpp"}}, PINS) + assert isinstance(engine, SemIfEngine) + assert isinstance(engine, DecisionEngine) + assert engine.label == "semif" + + +def test_build_engine_selects_the_winnow_provider(): + engine = build_engine( + { + "engine": { + "provider": "winnow", + "winnow": {"base_url": "http://example:8091", "model": "Winnow-12B"}, + } + }, + PINS, + ) + assert isinstance(engine, WinnowEngine) + assert isinstance(engine, DecisionEngine) + assert engine.label == "winnow" + assert engine.config.base_url == "http://example:8091" + assert engine.config.model == "Winnow-12B" + + +def test_build_engine_winnow_requires_a_model(): + with pytest.raises(SystemExit): + build_engine({"engine": {"provider": "winnow", "winnow": {}}}, PINS) diff --git a/tests/test_winnow_engine.py b/tests/test_winnow_engine.py new file mode 100644 index 0000000..f6e1cd6 --- /dev/null +++ b/tests/test_winnow_engine.py @@ -0,0 +1,213 @@ +"""Pure-stdlib tests for the remote Winnow decision engine provider. + +The engine is exercised over a real loopback HTTP server (the transport is not +mocked): the handler records the request body and returns a canned +``/v1/systemone`` response, so the tests prove the decision-contract mapping and +the strict distribution validation. No model, no GGUF, no external network. +""" + +from __future__ import annotations + +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +from semif_agent.decisions import DecisionRequest, Option +from semif_agent.engine import EngineUnavailable +from semif_agent.winnow import WinnowConfig, WinnowEngine + + +class _Handler(BaseHTTPRequestHandler): + def log_message(self, *args): # keep the test output quiet + pass + + def _read(self) -> dict: + length = int(self.headers.get("content-length", 0) or 0) + raw = self.rfile.read(length) if length else b"{}" + return json.loads(raw or b"{}") + + def _send(self, status: int, payload: dict) -> None: + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + status = self.server.state.get("health_status", 200) + self._send(status, {"status": "ok"} if status == 200 else {"error": "down"}) + else: + self._send(404, {"error": "not found"}) + + def do_POST(self): + body = self._read() + self.server.state.setdefault("requests", []).append( + (self.path, body, {k.lower(): v for k, v in self.headers.items()}) + ) + if self.path == "/v1/systemone": + status = self.server.state.get("systemone_status", 200) + response = self.server.state.get("systemone_response") + if response is None: + response = _default_systemone(body) + self._send(status, response) + elif self.path == "/v1/chat/completions": + self._send( + 200, + {"choices": [{"message": {"role": "assistant", "content": " hello "}}]}, + ) + else: + self._send(404, {"error": "not found"}) + + +def _default_systemone(body: dict) -> dict: + criteria = body["questions"]["decision"]["criteria"] + keys = list(criteria) + probs = { + key: (0.9 if index == 0 else 0.1 / max(len(keys) - 1, 1)) + for index, key in enumerate(keys) + } + # Return the keys in REVERSE order to prove the engine aligns by id, not by + # position in the returned object. + return { + "model": "Winnow-12B", + "answers": { + "decision": { + "type": "choice", + "probabilities": dict(reversed(list(probs.items()))), + "confidence": 0.9, + "choice": keys[0], + } + }, + "usage": {"input_tokens": 42, "output_tokens": 0}, + } + + +@pytest.fixture() +def winnow(): + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + server.state = {} + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + base = f"http://127.0.0.1:{server.server_address[1]}" + yield server, base + server.shutdown() + server.server_close() + + +def _engine(base: str, **cfg) -> WinnowEngine: + return WinnowEngine( + WinnowConfig(base_url=base, model="Winnow-12B", timeout=5.0, **cfg) + ) + + +def _decision(*option_ids: str) -> DecisionRequest: + return DecisionRequest( + state="the user said hello", + question="Which category handles this request?", + options=[Option(oid, f"description for {oid}") for oid in option_ids], + ) + + +def test_call_maps_decision_to_a_choice_question(winnow): + server, base = winnow + engine = _engine(base) + result = engine.call(_decision("response", "calendar")) + + assert result.option_ids == ["response", "calendar"] + assert result.prob("response") == pytest.approx(0.9) + assert result.prob("calendar") == pytest.approx(0.1) + assert result.selected == "response" + assert result.extra["input_tokens"] == 42 + + path, body, _ = server.state["requests"][-1] + assert path == "/v1/systemone" + assert body["model"] == "Winnow-12B" + assert body["state"] == "the user said hello" + question = body["questions"]["decision"] + assert question["type"] == "choice" + assert question["instructions"] == "Which category handles this request?" + assert question["criteria"] == { + "response": "description for response", + "calendar": "description for calendar", + } + + +def test_call_normalizes_an_unnormalized_distribution(winnow): + server, base = winnow + server.state["systemone_response"] = { + "answers": {"decision": {"type": "choice", "probabilities": {"a": 0.4, "b": 0.4}}} + } + result = _engine(base).call(_decision("a", "b")) + assert result.probs == pytest.approx({"a": 0.5, "b": 0.5}) + + +def test_call_rejects_mismatched_probability_keys(winnow): + server, base = winnow + server.state["systemone_response"] = { + "answers": {"decision": {"type": "choice", "probabilities": {"a": 1.0}}} + } + with pytest.raises(EngineUnavailable): + _engine(base).call(_decision("a", "b")) + + +def test_call_rejects_all_zero_distribution(winnow): + server, base = winnow + server.state["systemone_response"] = { + "answers": {"decision": {"type": "choice", "probabilities": {"a": 0.0, "b": 0.0}}} + } + with pytest.raises(EngineUnavailable): + _engine(base).call(_decision("a", "b")) + + +def test_call_rejects_http_error(winnow): + server, base = winnow + server.state["systemone_status"] = 500 + with pytest.raises(EngineUnavailable): + _engine(base).call(_decision("a", "b")) + + +def test_call_rejects_missing_answer(winnow): + server, base = winnow + server.state["systemone_response"] = {"answers": {}} + with pytest.raises(EngineUnavailable): + _engine(base).call(_decision("a", "b")) + + +def test_call_sends_bearer_token(winnow): + server, base = winnow + _engine(base, api_key="secret").call(_decision("a", "b")) + _, _, headers = server.state["requests"][-1] + assert headers.get("authorization") == "Bearer secret" + + +def test_generate_uses_chat_completions(winnow): + server, base = winnow + text = _engine(base).generate([{"role": "user", "content": "hi"}], max_tokens=16) + assert text == "hello" + path, body, _ = server.state["requests"][-1] + assert path == "/v1/chat/completions" + assert body["max_tokens"] == 16 + + +def test_warm_checks_health_and_marks_loaded(winnow): + server, base = winnow + engine = _engine(base) + assert engine.loaded is False + engine.warm() + assert engine.loaded is True + + server.state["health_status"] = 503 + with pytest.raises(EngineUnavailable): + _engine(base).warm() + + +def test_unreachable_endpoint_raises_engine_unavailable(): + engine = WinnowEngine( + WinnowConfig(base_url="http://127.0.0.1:1", model="Winnow-12B", timeout=1.0) + ) + with pytest.raises(EngineUnavailable): + engine.call(_decision("a", "b"))