add remote winnow support
This commit is contained in:
1 parent
17f16a6bfc
commit
ee7700275c
10 files changed
+674
-29
No files matched your search
+41
-3
@@ -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}"
|
||||
|
||||
+71
-6
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user