llm: add the loaded semif engine as a text-generation provider
Restore SemIfEngine.generate (autoregressive sampling from the loaded llama.cpp context) and wrap it in provider.SemIfEngineClient, a non-HTTP sibling of OpenAICompatClient with the same chat() surface. llm.SemIfLLMClient keeps the LLMError contract so the scheduler's graceful draft_failed path and the LLM bridge's 502 path are unchanged. llm.provider now selects "semif" (the in-process decision model, no endpoint or model needed), "opencode", or the default "ollama"; build_llm_client owns the choice (build_scheduler delegates). Knobs live under llm.semif (temperature 0 = greedy, max_tokens). bootstrap skips the ollama llm warn/pull/probe when provider is semif. Only the llm task supports it; codegen still needs a real code model.
This commit is contained in:
1 parent
1dc0550659
commit
e426998cf7
9 files changed
+305
-26
No files matched your search
+30
-11
@@ -29,7 +29,7 @@ from .console import (
|
||||
)
|
||||
from .decisions import DecisionRequest, Option
|
||||
from .engine import EngineConfig, EngineUnavailable, SemIfEngine
|
||||
from .llm import LLMClient
|
||||
from .llm import LLMClient, SemIfLLMClient
|
||||
from .log import DecisionLog
|
||||
from .scheduler import Scheduler
|
||||
from .skills import tree_summary
|
||||
@@ -231,14 +231,28 @@ def build_codegen_client(config: dict) -> CodegenClient:
|
||||
)
|
||||
|
||||
|
||||
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
engine = SemIfEngine(build_engine_config(config))
|
||||
def build_llm_client(config: dict, engine):
|
||||
"""Build the `llm` title/description client from the `llm` config block.
|
||||
|
||||
`provider` selects the backend: `"semif"` drives the already-loaded SemIf
|
||||
engine model in-process (the GGUF is the model — no endpoint or `model` is
|
||||
needed), `"opencode"` the hosted Console client, and anything else the
|
||||
default ollama-compatible `LLMClient`. Shared by `build_scheduler` and tests
|
||||
so both exercise the configured provider rather than assuming ollama.
|
||||
"""
|
||||
llm_cfg = config.get("llm", {}) or {}
|
||||
llm_provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
|
||||
llm_cls = ConsoleLLMClient if llm_provider == "opencode" else LLMClient
|
||||
llm_endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
|
||||
llm = llm_cls(
|
||||
base_url=llm_endpoint["base_url"],
|
||||
provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
|
||||
if provider == "semif":
|
||||
semif_cfg = llm_cfg.get("semif", {}) or {}
|
||||
return SemIfLLMClient(
|
||||
engine,
|
||||
temperature=float(semif_cfg.get("temperature", 0.0)),
|
||||
max_tokens=int(semif_cfg.get("max_tokens", 256)),
|
||||
)
|
||||
llm_cls = ConsoleLLMClient if provider == "opencode" else LLMClient
|
||||
endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
|
||||
return llm_cls(
|
||||
base_url=endpoint["base_url"],
|
||||
model=_required_model(llm_cfg, "llm"),
|
||||
timeout=float(llm_cfg.get("timeout", 600.0)),
|
||||
stream=bool(llm_cfg.get("stream", False)),
|
||||
@@ -250,10 +264,15 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
presence_penalty=_opt_float(llm_cfg.get("presence_penalty")),
|
||||
frequency_penalty=_opt_float(llm_cfg.get("frequency_penalty")),
|
||||
disable_thinking=bool(llm_cfg.get("disable_thinking", True)),
|
||||
api_key=llm_endpoint["api_key"],
|
||||
extra_headers=llm_endpoint["extra_headers"],
|
||||
user_agent=llm_endpoint["user_agent"],
|
||||
api_key=endpoint["api_key"],
|
||||
extra_headers=endpoint["extra_headers"],
|
||||
user_agent=endpoint["user_agent"],
|
||||
)
|
||||
|
||||
|
||||
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
engine = SemIfEngine(build_engine_config(config))
|
||||
llm = build_llm_client(config, engine)
|
||||
log = DecisionLog(config.get("log", "data/decisions.jsonl"))
|
||||
trace = TraceLog(config.get("trace", "data/runs.jsonl"))
|
||||
codegen_cfg = config.get("codegen", {})
|
||||
|
||||
@@ -95,3 +95,64 @@ class SemIfEngine:
|
||||
},
|
||||
)
|
||||
|
||||
def generate(
|
||||
self,
|
||||
messages: list[dict],
|
||||
temperature: float = 0.0,
|
||||
max_tokens: int = 256,
|
||||
) -> str:
|
||||
"""Drive the pinned decision model in the normal way: text generation.
|
||||
|
||||
SemIf scoring reads option logits directly; this instead autoregressively
|
||||
samples from the same llama.cpp context, e.g. for skill-tree authoring.
|
||||
Generation decodes the chat template through the backend's low-level
|
||||
context (there is no high-level chat-completion object on the CPU
|
||||
backend), stopping at the tokenizer's eos token. The KV cache is cleared
|
||||
at the start, so interleaving scoring and generation on one model is safe.
|
||||
|
||||
It shares `self._lock` with `call`, so a generation serializes against
|
||||
decisions on the one loaded model — short JSON replies are seconds of
|
||||
contention, and there is only ever one copy of the GGUF.
|
||||
"""
|
||||
with self._lock:
|
||||
model, tokenizer, metadata = self._ensure_loaded()
|
||||
try:
|
||||
import numpy
|
||||
|
||||
engine = model.engine
|
||||
prompt_text = tokenizer.apply_chat_template(
|
||||
messages,
|
||||
tokenize=False,
|
||||
add_generation_prompt=True,
|
||||
enable_thinking=False,
|
||||
)
|
||||
prompt_ids = tokenizer.encode(prompt_text, add_special_tokens=False)
|
||||
engine.clear()
|
||||
logits = engine._decode(prompt_ids, 0, 0, True)
|
||||
generated: list[int] = []
|
||||
rng = numpy.random.default_rng()
|
||||
for position in range(max_tokens):
|
||||
token = _sample_token(logits, temperature, rng)
|
||||
if token == tokenizer.eos_token_id:
|
||||
break
|
||||
generated.append(token)
|
||||
logits = engine._decode([token], len(prompt_ids) + position, 0, True)
|
||||
return tokenizer.decode(generated).strip()
|
||||
except EngineUnavailable:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise EngineUnavailable(f"generation failed: {exc}") from exc
|
||||
|
||||
|
||||
def _sample_token(logits, temperature: float, rng) -> int:
|
||||
"""Pick the next token from next-position logits: greedy or temperature."""
|
||||
import numpy
|
||||
|
||||
if temperature <= 0.0:
|
||||
return int(numpy.argmax(logits))
|
||||
scaled = numpy.asarray(logits, dtype=numpy.float64) / max(temperature, 1e-6)
|
||||
scaled = scaled - scaled.max()
|
||||
probabilities = numpy.exp(scaled)
|
||||
probabilities /= probabilities.sum()
|
||||
return int(rng.choice(probabilities.size, p=probabilities))
|
||||
|
||||
+15
-1
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from .provider import OpenAICompatClient, ProviderError
|
||||
from .provider import OpenAICompatClient, ProviderError, SemIfEngineClient
|
||||
|
||||
|
||||
class LLMError(ProviderError):
|
||||
@@ -102,3 +102,17 @@ class LLMClient(OpenAICompatClient):
|
||||
if start != -1 and end != -1:
|
||||
text = text[start : end + 1]
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
class SemIfLLMClient(SemIfEngineClient):
|
||||
"""`llm` authoring backed by the loaded SemIf engine model.
|
||||
|
||||
The `llm.provider = "semif"` option: the same in-process GGUF the decision
|
||||
engine already loaded generates the title/description (and any other `llm`
|
||||
text) instead of calling an HTTP endpoint. Same `chat(...)` surface, same
|
||||
graceful error contract — raises `LLMError` so the scheduler traces a
|
||||
`draft_failed` and the LLM bridge reports 502 rather than crashing.
|
||||
"""
|
||||
|
||||
error_class = LLMError
|
||||
label = "semif:llm"
|
||||
@@ -8,6 +8,11 @@ provider logic once; subclasses set `base_url`/`model`, their sampler
|
||||
parameters, and the error classes they raise so existing callers keep catching
|
||||
their own types.
|
||||
|
||||
It also holds `SemIfEngineClient`, the non-HTTP sibling that generates text
|
||||
from the in-process SemIf engine model (`engine.SemIfEngine.generate`) behind
|
||||
the same ``chat(...)`` surface, so the `llm` task can be served by the loaded
|
||||
decision model instead of an HTTP endpoint.
|
||||
|
||||
Stdlib-only and imports nothing from the agent's own modules, so `codegen.py`
|
||||
(which imports `skills.py`, which imports `llm.py`) can depend on it without a
|
||||
cycle.
|
||||
@@ -633,3 +638,66 @@ class OpenAICompatClient:
|
||||
if sock is None:
|
||||
sock = getattr(response, "sock", None)
|
||||
return sock
|
||||
|
||||
|
||||
class SemIfEngineClient:
|
||||
"""Text generation backed by the in-process SemIf engine model.
|
||||
|
||||
A drop-in sibling of `OpenAICompatClient` for the small `llm` task: instead
|
||||
of speaking HTTP to an ollama/Console endpoint it drives the already-loaded
|
||||
decision GGUF through `engine.generate(...)`. It exposes the same
|
||||
``chat(messages, max_tokens=..., temperature=..., ...)`` surface every `llm`
|
||||
caller uses, so the provider choice is invisible to callers — title/
|
||||
description authoring, gateway result cleanup, and the LLM bridge all reuse
|
||||
it unchanged.
|
||||
|
||||
The engine is duck-typed (any object with ``generate(messages, temperature,
|
||||
max_tokens)``); this module stays free of imports from the agent's own
|
||||
modules, so subclasses in `llm.py` set the `LLMError` contract without a
|
||||
cycle. Sampler/`timeout`/`degeneration_check` arguments are accepted for
|
||||
signature compatibility and ignored: the engine generation is bounded by
|
||||
`max_tokens` and serializes on the engine's own lock.
|
||||
|
||||
Any engine failure (`EngineUnavailable`, a missing GGUF, a sampling error)
|
||||
is re-raised as `error_class` so the scheduler's graceful `draft_failed`
|
||||
path and the LLM bridge's 502 path keep their existing contracts.
|
||||
"""
|
||||
|
||||
error_class = ProviderError
|
||||
label = "semif"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine,
|
||||
temperature: float = 0.0,
|
||||
max_tokens: int = 256,
|
||||
disable_thinking: bool = True,
|
||||
):
|
||||
self.engine = engine
|
||||
self.temperature = temperature
|
||||
self.max_tokens = max_tokens
|
||||
# The engine's `generate` always decodes with thinking disabled; the knob
|
||||
# is accepted so the class mirrors the other providers' constructors.
|
||||
self.disable_thinking = disable_thinking
|
||||
|
||||
def chat(
|
||||
self,
|
||||
messages: list[dict],
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
top_p: float | None = None,
|
||||
presence_penalty: float | None = None,
|
||||
frequency_penalty: float | None = None,
|
||||
timeout: float | None = None,
|
||||
degeneration_check: Callable[[str], str | None] | None = None,
|
||||
) -> str:
|
||||
resolved_max = self.max_tokens if max_tokens is None else max_tokens
|
||||
resolved_temp = self.temperature if temperature is None else temperature
|
||||
try:
|
||||
return self.engine.generate(
|
||||
messages, temperature=resolved_temp, max_tokens=resolved_max
|
||||
)
|
||||
except Exception as exc: # EngineUnavailable and anything the engine raises
|
||||
raise self.error_class(
|
||||
f"{self.label} generation failed: {exc}"
|
||||
) from exc
|
||||
Reference in new issue
Block a user