diff --git a/AGENTS.md b/AGENTS.md index 43754a0..cf948bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,23 +68,26 @@ scheduler.py no up-front gate: every input is dispatched -> choice(tau) -> score -> queue; preempt + requeue; a skill run paused for input (needs_input) keeps `current` busy; `answer` routes straight to the pending run, bypassing - gate/score/navigation; skill-body authoring is an ASYNC single-slot - worker (stub authored sync, write queued, gate stays free, the - original request is re-queued and re-runs the new leaf when the - body lands); the worker runs the full pipeline: elicitation -> + gate/score/navigation; draft authoring (title+description by the + small `llm` provider) AND skill-body authoring (codegen) are ASYNC + single-slot workers: a create_category/create_skill request is + queued, the gate stays free, the category job chains into its + skill job, and the original request is re-queued and re-runs the + new leaf when the body lands; the body worker runs the full + pipeline: elicitation -> codegen body -> fidelity gate -> data contract -> test -> auto-run test (3-option SemIf regen ladder on failure); config search auto-populates the skill config from global/category - config; elicitation asks implementation questions (REPL inline; - dashboard deferred via the question queue, `wait_timeout`); a + config; elicitation asks implementation questions (all front ends + defer via the question queue, `wait_timeout`); a failed real run triggers a logged SemIf repair choice (retry/repair_skill/ask_user/no_repair) surfaced to the user queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0 skills.py tree + registry (hardcoded built-ins: the closed `response` canned tree only), navigation = SemIf choices per level (logged), create_category - and create_skill author + register stubs via the decision model - in generation mode; SkillStore persists one folder per skill + and create_skill author + register stubs via the small `llm` + provider (separate from codegen); SkillStore persists one folder per skill (skill.py, skill.test.py, contract.json, config.json) and materialize_skill / merge_skill_store hot-load runnable skills from data/skills/; @@ -124,9 +127,14 @@ codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill test: inline fixtures, loopback http.server for HTTP bodies, no external network, no mock_data.json); run_skill_test executes the test as a subprocess -llm.py dormant OpenAI-compatible client (stdlib urllib); the small - LLM is out of every decision path — assessment/fidelity are - SemIf — only `_parse_json` is still borrowed by the parsers +llm.py small OpenAI-compatible provider (LLMClient) that authors a + new category/skill title + description — its own endpoint/model, + deliberate separate from codegen; provider logic (SSE/budget/idle) + is shared from provider.py; `_parse_json` is also borrowed by the + authoring parsers +provider.py shared OpenAI-compatible chat transport (OpenAICompatClient: + SSE stream, token budget, idle watchdog, degeneration hook) + subclassed by llm.LLMClient and codegen.CodegenClient log.py decisions.jsonl rows {state, question, options, predicted_probs, selected, observed_outcome, label_source} trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/ @@ -199,7 +207,7 @@ Integration tests run on the staging machine `jarvis` (see "### jarvis (staging) Machine split (Sep 2026): **guppy** hosts the remote **codegen** model (the 12G `qwen38-iq3s`) only; **jarvis** is the staging/test target (semif-agent + SemIf engine + deps) and runs its **own local ollama** serving the small -self-assessment model (`qwen3.5:4b`). Only codegen traffic travels to guppy. +title/description model (`qwen3.5:4b`). Only codegen traffic travels to guppy. Provision jarvis with `scripts/bootstrap.sh` (see "### jarvis (staging)"). **Connecting to jarvis (`ssh jarvis@192.168.8.130`)**: this is a plain `ssh` @@ -258,9 +266,10 @@ CLI, unit tests (24) + box integration tests (2). validate (accuracy/ECE on a held-out slice, prompt-hash regression), swap the pinned model revision. GPU offload: train on a beefier GPU; the running agent keeps a frozen inference revision until a swap validates. -- `create_skill` branch: live, mirroring `create_category`. The decision - model, driven in normal generation mode via `SemIfEngine.generate`, proposes a - specific skill title + description for the chosen category; the stub is +- `create_skill` branch: live, mirroring `create_category`. The small `llm` + provider (a dedicated endpoint/model, separate from `codegen`; production may + point both at the same host) proposes a specific skill title + description for + the chosen category; the stub is persisted to `data/categories.json` (under that category's `skills` list) and merged into the running tree as a leaf. Since Sep 2026 the leaf also gets a real runnable body via the async authoring pipeline: a larger @@ -268,13 +277,17 @@ CLI, unit tests (24) + box integration tests (2). `predict`/`act` code against `SKILL.md`, then a contract + test (against `TESTGEN.md`) are generated and the test is auto-run before the leaf is declared ready — all persisted to a folder in `data/skills/` and - hot-loaded. Authoring is **asynchronous**: the stub is created and the gate - freed immediately, the body write runs on a single-slot background worker, and + hot-loaded. Authoring is **asynchronous**: the draft is authored by a + single-slot `llm` worker, the stub is created and the gate + freed immediately, the body write runs on a separate single-slot codegen + worker, and once the body lands the request that prompted creation is re-queued and re-runs navigation onto the new leaf (an empty/in-progress leaf can be restarted via `restart ` or the dashboard). A request that prompted a whole new category runs the same chain deterministically: `create_category` → - `create_skill` → async body → re-dispatch. Authoring is still a single pass — + `create_skill` → async body → re-dispatch. An unreachable `llm` endpoint is + graceful (traced `draft_failed`, user notified, request not re-dispatched); + only SemIf availability is fatal. Authoring is still a single pass — validating/reusing written bodies across runs is future work. **Create-branch confidence gate** (Sep 2026): `create_skill`/`create_category` compete in a softmax with the real options, so a weak plurality win is not @@ -300,7 +313,7 @@ CLI, unit tests (24) + box integration tests (2). - **Real integrations, implementation questions, fidelity + repair** (Sep 2026): elicitation is on by default and asks implementation questions (which service/account, how to connect, where the credential comes from, what success - looks like); the REPL asks inline, the dashboard defers via the question queue + looks like); every front end defers via the question queue (`/api/questions`, worker waits `codegen.elicitation.wait_timeout`). Bodies must perform the real action via stdlib transports with values from `ctx.config` and declare `INTEGRATION` (service/transport/config_vars); a @@ -381,7 +394,7 @@ CLI, unit tests (24) + box integration tests (2). llama.cpp **CPU** backend (its llamacpp backend forces `n_gpu_layers=0`), so the GPU is NOT used by the decision engine — it IS used by ollama. - **jarvis box**: runs the agent and its **own local ollama** serving the small - self-assessment model (`qwen3.5:4b`). `config.json` `llm.base_url` points at + title/description model (`qwen3.5:4b`). `config.json` `llm.base_url` points at `http://127.0.0.1:11434/v1`; only `codegen.base_url` points at guppy. - The SemIf tokenizer is fetched from HF (`Qwen/Qwen3.5-4B` at the pinned revision), cached under each checkout's `.runtime/hf` (`HF_HOME`). @@ -426,7 +439,7 @@ CLI, unit tests (24) + box integration tests (2). (`sudo systemctl restart ollama`) — the ROCm runner can wedge. - **jarvis = local small model.** Runs its own ollama (`/usr/local/bin/ollama`, systemd `ollama.service`, `127.0.0.1:11434`) serving `qwen3.5:4b` for - self-assessment (assess/elicitation/fidelity, ~3s). `bootstrap.sh` ensures + new-skill title/description authoring (~3s). `bootstrap.sh` ensures that model is pulled; `config.json` `llm.base_url` points here. - `bootstrap.sh` installs **no ollama**: it expects the target box to already run one for `llm` (and pulls `llm.model` into it), while codegen is remote. @@ -503,9 +516,9 @@ CLI, unit tests (24) + box integration tests (2). ### codegen (skill bodies, box) - Skill **bodies** are written by a separate OpenAI-compatible model, configured under `codegen` in config.json (default model `qwen38-iq3s`, the 12G 27B - IQ3_S GGUF — huge/slow). Title + description for new skills still come from - the **small** decision model (`engine.generate`); only the runnable code body - uses codegen. + IQ3_S GGUF — huge/slow). Title + description for new skills come from the + separate small `llm` provider (its own endpoint/model, shared transport in + `provider.py`); only the runnable code body uses codegen. - **Do NOT cap `max_tokens`** on the codegen call. qwen38-iq3s reasons first and a cap truncates the hidden reasoning, leaving `content` empty (`finish_reason: length`) and the body write fails with "skill body is @@ -553,14 +566,14 @@ CLI, unit tests (24) + box integration tests (2). as a module and its `predict`/`act` run in-process; `skill.test.py` runs as a subprocess in the skill folder). The box is the intended target; treat the endpoint as trusted. -- Flow in `scheduler._dispatch_skill`: small model authors title+description → - stub registered + hot-merged into the tree (navigable immediately) → trace - `skill_writing` (dashboard shows title/description + a "writing skill body…" - badge) → the body write is queued to a **single-slot background worker** (the - 12G codegen model can't run twice), the gate stays free for new input. The - worker runs the full authoring pipeline: +- Flow in `scheduler._dispatch_skill`: the request is queued to the **single-slot + `llm` draft worker** (small model authors title+description) → stub registered + + hot-merged into the tree → the body write is queued to a **separate + single-slot codegen worker** (the 12G codegen model can't run twice), the gate + stays free for new input. A category request chains the same way in one worker. + The codegen worker runs the full authoring pipeline: 1. **elicitation** (`generate_elicitation`): implementation questions + - integration hint. REPL asks inline at dispatch; the dashboard sets + integration hint. Every front end (REPL, dashboard, gateway) sets `defer_questions` and the worker posts to the question queue and waits (`codegen.elicitation.wait_timeout`) for answers. 2. **codegen body** (`generate_skill_body` / `regenerate_skill_body` on @@ -613,8 +626,8 @@ CLI, unit tests (24) + box integration tests (2). - **Requirements elicitation (implementation questions, default on).** `codegen.elicitation.enabled` asks the product owner how the new skill should connect (which service/account, how to connect, where the credential comes - from, what success looks like, how failure should behave). The REPL asks - inline at dispatch; the dashboard defers — the single-slot worker posts + from, what success looks like, how failure should behave). Every front end + defers — the single-slot worker posts questions to `scheduler.questions` (`GET/POST /api/questions`) and waits up to `codegen.elicitation.wait_timeout` seconds, then proceeds with whatever answers arrived (`questions_timeout` trace). Answers ride on the draft into @@ -897,7 +910,7 @@ The bridge read path (`simplex.next_message`) and contact-link lookup up the stdlib HTTP server on an ephemeral port with the engine never loaded; `tests/test_codegen.py` for prompt/parse/validate, integration extraction/findings, and body store round-trips; and `tests/test_llm.py` for - the retained `_parse_json` helper. `tests/conftest.py``s `ScriptedEngine` + the `_parse_json` helper and the LLMClient provider. `tests/conftest.py``s `ScriptedEngine` drives scheduling mechanics (assessment is now a SemIf decision) without a GGUF. - `tests/integration/` — jarvis only (staging); requires real SemIf + real diff --git a/README.md b/README.md index 4679a28..c77492e 100644 --- a/README.md +++ b/README.md @@ -148,17 +148,18 @@ observe baseline → predict → act → observe outcome → assess ### Authoring a new skill -When navigation chooses a create branch, `scheduler._dispatch_skill` runs the -authoring pipeline. It is **asynchronous** and single-slot, so the gate stays -free while the big codegen model thinks: +When navigation chooses a create branch, the scheduler queues the draft to a +single-slot `llm` worker and the body write to a separate single-slot codegen +worker. It is **asynchronous**, so the gate stays free while either model thinks: -1. **Stub.** The small decision model (`SemIfEngine.generate`) authors a title + - description. The stub is registered and hot-merged into the running tree - immediately (navigable right away); a `skill_writing` trace event is emitted. +1. **Stub.** The small `llm` provider (`generate_skill`) authors a title + + description on its own worker. The stub is registered and hot-merged into the + running tree as + soon as it lands; a `skill_writing` trace event is emitted. 2. **Elicitation** (`generate_elicitation`, default on): implementation questions — which service/account, how to connect, where the credential - comes from, what success looks like. The REPL asks inline; the dashboard - defers to a question queue and the worker waits + comes from, what success looks like. Every front end (REPL, dashboard, + gateway) defers to a question queue and the worker waits (`codegen.elicitation.wait_timeout`). 3. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes `predict`/`act` against `SKILL.md`, @@ -285,8 +286,9 @@ semif_agent/ create gates, intent guard, tiered config resolution codegen.py OpenAI-compatible client; body/elicitation/contract/test generation; parse/validate; INTEGRATION extraction; test runner + provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog) engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import) - llm.py dormant OpenAI-compatible client (`_parse_json` is reused) + llm.py small OpenAI-compatible provider; authors new title + description log.py decisions.jsonl rows {state, question, options, probs, ...} trace.py runs.jsonl lifecycle events keyed by run_id dream.py NLL / weighted CE / accuracy / ECE cost report @@ -323,11 +325,11 @@ machines: - **`codegen`** — the large model that writes skill bodies (e.g. `qwen38-iq3s`, a 27B IQ3_S GGUF). This is slow and ideally on a beefier host. -- **`llm`** — an OpenAI-compatible endpoint retained but **dormant**: assessment, - fidelity and requeue are SemIf decisions now, so the LLM is out of every - decision path (only its `_parse_json` helper is borrowed by the authoring - parsers). It is configured for backlogged retirement; skill titles and - descriptions come from the SemIf decision model itself, not this endpoint. +- **`llm`** — a small, fast model (e.g. `qwen3.5:4b`) that authors the title + + description of a newly created category/skill. Deliberately its own + endpoint/model, so it can stay local even when `codegen` is remote; it uses + the same provider transport (`provider.py`) and an unreachable endpoint is + graceful (the request is not re-dispatched), never fatal. The **decision engine is separate** and runs via llama.cpp CPU (or Vulkan if your build enables it), not ollama. @@ -391,7 +393,7 @@ Key blocks: | Block | What it controls | | --- | --- | | `engine` | SemIf source/revision, GGUF path, context, threads | -| `llm` | dormant OpenAI-compatible endpoint (out of every decision path) | +| `llm` | small model endpoint that authors new category/skill title + description | | `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget | | `navigation` | create-gate `create_tau` / `create_margin` | | `tau` | decision threshold; `max_reentries` requeue bound | diff --git a/config.example.json b/config.example.json index ddccff7..a7a3b91 100644 --- a/config.example.json +++ b/config.example.json @@ -21,12 +21,21 @@ "threads": 8 }, "llm": { - "_comment": "Dormant OpenAI-compatible endpoint. Assessment and fidelity are SemIf decisions now, so the LLM is out of every decision path; this block is retained for backlogged retirement and only `_parse_json` is still borrowed by the authoring parsers. Runs on THIS machine's local ollama; bootstrap sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. Only codegen travels to a remote host.", + "_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 sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies, so the sampler defaults are conservative (low temperature, no presence penalty). 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.", "base_url": "http://localhost:11434/v1", - "model": "qwen3.5:4b" + "model": "qwen3.5:4b", + "timeout": 600, + "stream": false, + "idle_warn": 30, + "idle_timeout": 120, + "context_window": 0, + "temperature": 0.2, + "top_p": 0.9, + "presence_penalty": 0.0, + "frequency_penalty": 0.0 }, "codegen": { - "_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap sets base_url from --codegen-url, default guppy http://192.168.8.181:11434); the local small model is `llm` above. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or self-assessment model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0=1 absolute tokens, 0 tuple[Scheduler, dict]: threads=config.get("engine", {}).get("threads"), ) ) + llm_cfg = config.get("llm", {}) or {} llm = LLMClient( - base_url=config.get("llm", {}).get("base_url", "http://localhost:11434/v1"), - model=config.get("llm", {}).get("model", "qwen2.5:3b"), + base_url=llm_cfg.get("base_url", "http://localhost:11434/v1"), + model=llm_cfg.get("model", "qwen2.5:3b"), + timeout=float(llm_cfg.get("timeout", 600.0)), + stream=bool(llm_cfg.get("stream", False)), + idle_warn=float(llm_cfg.get("idle_warn", 30.0)), + idle_timeout=float(llm_cfg.get("idle_timeout", 120.0)), + context_window=float(llm_cfg.get("context_window", 0.0)), + temperature=float(llm_cfg.get("temperature", 0.2)), + top_p=float(llm_cfg.get("top_p", 0.9)), + presence_penalty=float(llm_cfg.get("presence_penalty", 0.0)), + frequency_penalty=float(llm_cfg.get("frequency_penalty", 0.0)), ) log = DecisionLog(config.get("log", "data/decisions.jsonl")) trace = TraceLog(config.get("trace", "data/runs.jsonl")) @@ -238,7 +248,7 @@ def _fatal_exit(scheduler: Scheduler) -> int | None: def repl(scheduler: Scheduler, config: dict) -> int: - scheduler.asker = lambda question: input(f"{question} ") + scheduler.defer_questions = True print(try_warm(scheduler)) print( "type a request, or one of: busy | idle | status | skills | dream | " @@ -246,6 +256,7 @@ def repl(scheduler: Scheduler, config: dict) -> int: "repairs | repair [action] | quit" ) while True: + _answer_questions(scheduler) try: line = input("> ").strip() except (EOFError, KeyboardInterrupt): diff --git a/semif_agent/codegen.py b/semif_agent/codegen.py index 9957eb4..e13a5d4 100644 --- a/semif_agent/codegen.py +++ b/semif_agent/codegen.py @@ -1,11 +1,10 @@ """Skill code-body generation through an OpenAI-compatible API. -The decision engine authors a skill's title + description with the small model -(engine.generate). Writing the runnable body is a separate step: a larger -OpenAI-compatible model (e.g. qwen38-iq3s on ollama) is prompted with the -SKILL.md contract plus the request and the existing tree, and must reply with -valid Python implementing `predict` / `act`. Stdlib-only HTTP, mirroring -`llm.py`. +The small `llm` provider authors a skill's title + description; writing the +runnable body is a separate step: a larger OpenAI-compatible model (e.g. +qwen38-iq3s on ollama) is prompted with the SKILL.md contract plus the request +and the existing tree, and must reply with valid Python implementing `predict` / +`act`. The shared provider transport lives in `provider.py`. """ from __future__ import annotations @@ -13,24 +12,20 @@ from __future__ import annotations import ast import json import re -import select import subprocess import sys -import time -import urllib.error -import urllib.request from pathlib import Path from typing import Callable, NamedTuple -from .decisions import Request -from .skills import SkillDraft, tree_summary from .bridges.registry import describe_bridges +from .decisions import Request +from .provider import OpenAICompatClient, ProviderError +from .skills import SkillDraft, tree_summary DEFAULT_CONTRACT = Path(__file__).resolve().parent.parent / "SKILL.md" -DEFAULT_CONTEXT_WINDOW = 100000 -class CodegenError(RuntimeError): +class CodegenError(ProviderError): """The codegen endpoint could not be reached.""" @@ -43,22 +38,6 @@ class DegenerationError(CodegenError): """ -class TokenBudget(NamedTuple): - """Per-request token limits derived from the detected context window. - - `total_limit` caps prompt + output; `output_limit` caps just the streamed - output (the enforced one — it already bakes in the prompt estimate); - `warn_point` is the total fill at which a one-shot console warning fires. - An `output_limit` of 0 means no cap is configured. - """ - - window: int - total_limit: int - output_limit: int - warn_point: int | None - prompt_est: int - - def read_skill_contract(path: str | None = None) -> str: contract = Path(path) if path else DEFAULT_CONTRACT if not contract.is_file(): @@ -105,514 +84,18 @@ def skill_contract_ref(path: str | None = None) -> dict: return {"ref": ref, "dirty": dirty} -class CodegenClient: - """Minimal OpenAI-compatible chat client for writing skill bodies. +class CodegenClient(OpenAICompatClient): + """OpenAI-compatible chat client that writes skill bodies. - The transport always reads the response as an SSE token stream so the - layered token budget, the idle watchdog, and the total wall-clock budget - can abort a runaway generation in real time — never via a server-side - `max_tokens` cap, because Qwen3-style models reason first and a cap - truncates the hidden reasoning, leaving `content` empty. - - `stream=True` additionally echoes tokens (including the chain-of-thought) - to stdout as they arrive; echo is console-only and the returned content - is identical either way. A silent stream (no bytes for `idle_warn` - seconds) prints a warning, and one that stays silent for `idle_timeout` - seconds raises CodegenError instead of blocking on the total timeout — a - wedged generation is surfaced in minutes, not ~20. - - The context window is lazily queried once from ollama's `/api/show` - (`parameters.num_ctx`, falling back to `model_info..context_length`, - then the `context_window` config, then 100000); the per-request budget - caps output at `max_output` (absolute tokens if >= 1, else a fraction of - the window) and total fill at `smart_limit`/`warn_limit`. - - An optional `degeneration_check` callback (passed per `chat` call) is fed - the last `degeneration_window` chars of content+reasoning every - `degeneration_interval` chars once `degeneration_min_chars` have - accumulated; a non-None return aborts the stream with DegenerationError. - It lets a SemIf continue/stop decision cut off a generation that is - looping instead of converging, before it fills the context window. - - Sampler defaults follow the Qwen3.8 model card's instruct-mode guidance - (unsloth/Qwen3.8-27B-GGUF): the anti-repetition cure is a high - `presence_penalty`, not greedy temperature. `temperature`/`top_p`/ - `presence_penalty`/`frequency_penalty` are per-`chat` overridable; the - `generate_skill_body` escalation ladder bumps presence toward the card's - max (2.0) and lowers temperature on retries. `max_attempts` bounds that - ladder (default 3). + The provider machinery (real SSE transport, layered token budget, idle + watchdog, degeneration hook, `/api/show` context detection) lives in + `provider.OpenAICompatClient`; this subclass pins the codegen error types + and console label. See the base class docstring for full behavior. """ - def __init__( - self, - base_url: str, - model: str, - timeout: float = 1200.0, - stream: bool = False, - idle_warn: float = 60.0, - idle_timeout: float = 180.0, - context_window: float = 0.0, - smart_limit: int = 250000, - warn_limit: int = 500000, - max_fill_ratio: float = 0.9, - warn_fill_ratio: float = 0.7, - max_output: float = 0.85, - chars_per_token: float = 4.0, - degeneration_interval: int = 8000, - degeneration_window: int = 2000, - degeneration_min_chars: int = 4000, - temperature: float = 0.7, - top_p: float = 0.85, - presence_penalty: float = 1.5, - frequency_penalty: float = 0.2, - max_attempts: int = 3, - ): - self.base_url = base_url.rstrip("/") - self.model = model - self.timeout = timeout - self.stream = stream - self.idle_warn = idle_warn - self.idle_timeout = idle_timeout - self.context_window = context_window - self.smart_limit = smart_limit - self.warn_limit = warn_limit - self.max_fill_ratio = max_fill_ratio - self.warn_fill_ratio = warn_fill_ratio - self.max_output = max_output - self.chars_per_token = chars_per_token - self.degeneration_interval = degeneration_interval - self.degeneration_window = degeneration_window - self.degeneration_min_chars = degeneration_min_chars - self.temperature = temperature - self.top_p = top_p - self.presence_penalty = presence_penalty - self.frequency_penalty = frequency_penalty - self.max_attempts = max_attempts - self._window: int | None = None - - 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, - degeneration_check: Callable[[str], str | None] | None = None, - ) -> str: - budget = self._compute_budget(messages) - if self.stream: - self._print_budget(budget) - url = f"{self.base_url}/chat/completions" - payload: dict = { - "model": self.model, - "messages": messages, - "temperature": self.temperature if temperature is None else temperature, - "top_p": self.top_p if top_p is None else top_p, - "presence_penalty": ( - self.presence_penalty if presence_penalty is None else presence_penalty - ), - "frequency_penalty": ( - self.frequency_penalty if frequency_penalty is None else frequency_penalty - ), - "stream": True, - "stream_options": {"include_usage": True}, - } - if max_tokens is not None: - payload["max_tokens"] = max_tokens - body = json.dumps(payload).encode("utf-8") - request = urllib.request.Request( - url, data=body, headers={"Content-Type": "application/json"} - ) - try: - with urllib.request.urlopen(request, timeout=self.timeout) as response: - return self._read_stream(response, budget, degeneration_check) - except urllib.error.URLError as exc: - raise CodegenError( - f"codegen endpoint unreachable at {url}: {exc}. Is your local server running?" - ) from exc - except TimeoutError as exc: - raise CodegenError( - f"codegen request timed out after {self.timeout}s at {url}" - ) from exc - - def _native_base_url(self) -> str: - """Ollama's `/api/show` lives on the native API, not the /v1 compat.""" - if self.base_url.endswith("/v1"): - return self.base_url[: -len("/v1")] - return self.base_url - - def _query_context_window(self) -> int | None: - """POST /api/show {model} for the runtime context window. Any failure - (unreachable, non-ollama endpoint, malformed reply) returns None so the - caller falls back to config or the default. Uses a short request - timeout so a slow show endpoint never wedges the actual generation.""" - url = f"{self._native_base_url()}/api/show" - request = urllib.request.Request( - url, - data=json.dumps({"model": self.model}).encode("utf-8"), - headers={"Content-Type": "application/json"}, - ) - try: - with urllib.request.urlopen( - request, timeout=min(self.timeout, 10.0) - ) as response: - data = json.loads(response.read().decode("utf-8")) - except (urllib.error.URLError, TimeoutError, ValueError, KeyError): - return None - params = data.get("parameters") - if isinstance(params, dict): - num_ctx = params.get("num_ctx") - if isinstance(num_ctx, int) and num_ctx > 0: - return num_ctx - elif isinstance(params, str): - # ollama serves parameters as modelfile text, not a dict: - # "num_ctx 100000\n..." — pull the num_ctx line if present. - for line in params.splitlines(): - parts = line.split() - if len(parts) == 2 and parts[0] == "num_ctx": - try: - num_ctx = int(parts[1]) - except ValueError: - break - if num_ctx > 0: - return num_ctx - model_info = data.get("model_info") or {} - for key, value in model_info.items(): - if key.endswith(".context_length") and isinstance(value, int) and value > 0: - return value - return None - - def _context_window(self) -> int: - """Detected context window, queried once and cached.""" - if self._window is not None: - return self._window - window = self._query_context_window() - if window is None: - window = ( - int(self.context_window) - if self.context_window > 0 - else DEFAULT_CONTEXT_WINDOW - ) - self._window = window - return window - - def _compute_budget(self, messages: list[dict]) -> TokenBudget: - window = self._context_window() - max_out = ( - int(self.max_output) - if self.max_output >= 1 - else int(self.max_output * window) - ) - total_limit = int(min(self.smart_limit, window * self.max_fill_ratio)) - prompt_est = int( - sum(len(str(m.get("content") or "")) for m in messages) - / self.chars_per_token - ) - if total_limit > 0 and prompt_est >= total_limit: - raise CodegenError( - f"codegen prompt (~{prompt_est} tokens) already exceeds the " - f"total budget of {total_limit} tokens" - ) - if total_limit > 0 and max_out > 0: - output_limit = min(max_out, total_limit - prompt_est) - else: - output_limit = 0 - warn_point = None - if self.warn_limit > 0 and self.warn_fill_ratio > 0: - warn_point = min(self.warn_limit, int(window * self.warn_fill_ratio)) - return TokenBudget(window, total_limit, output_limit, warn_point, prompt_est) - - def _print_budget(self, budget: TokenBudget) -> None: - if budget.window and budget.output_limit > 0: - print( - f"[codegen] context window {budget.window} tokens · " - f"output cap {budget.output_limit} tokens " - f"({budget.output_limit / budget.window * 100:.0f}%) · " - f"peak total fill ~{budget.total_limit} tokens" - ) - elif budget.window: - print( - f"[codegen] context window {budget.window} tokens · " - f"peak total fill ~{budget.total_limit} tokens" - ) - sys.stdout.flush() - - def _log_usage(self, budget: TokenBudget, usage: dict) -> None: - """Report exact token usage once `include_usage` yields a usage chunk. - - Logs real prompt/completion/total tokens, % of the detected window, and - the zone (SMART < smart_limit, WARN < warn_limit, else DUMB) measured - against absolute total-token thresholds. - """ - prompt = usage.get("prompt_tokens") - completion = usage.get("completion_tokens") - total = usage.get("total_tokens") - if not isinstance(total, int): - return - if not isinstance(prompt, int): - prompt = total - (completion if isinstance(completion, int) else 0) - if not isinstance(completion, int): - completion = total - prompt - pct = total / budget.window * 100 if budget.window else 0.0 - if self.smart_limit > 0 and total < self.smart_limit: - zone = "SMART" - elif self.warn_limit > 0 and total < self.warn_limit: - zone = "WARN" - else: - zone = "DUMB" - print( - f"[codegen] usage: prompt {prompt} · completion {completion} · " - f"total {total} tokens · {pct:.0f}% of window · {zone}" - ) - sys.stdout.flush() - - def _enforce_budget(self, budget: TokenBudget, out_chars: int, warned: bool) -> bool: - """Abort when the output cap is exceeded; one-shot warn near the fill - threshold. Returns the updated warned state.""" - output_est = out_chars / self.chars_per_token - if budget.output_limit > 0 and output_est >= budget.output_limit: - raise CodegenError( - f"codegen output exceeded {budget.output_limit} token budget " - f"(~{out_chars} chars at {self.chars_per_token:g} chars/token)" - ) - if budget.warn_point is not None and not warned: - total = budget.prompt_est + output_est - if total >= budget.warn_point: - sys.stdout.write( - f"\n[codegen] total fill ~{int(total)} tokens — " - f"near the {budget.output_limit} token output budget\n" - ) - sys.stdout.flush() - return True - return warned - - def _read_stream( - self, - response, - budget: TokenBudget, - degeneration_check: Callable[[str], str | None] | None = None, - ) -> str: - """Read an OpenAI-compatible SSE stream; echo tokens if `stream`. - - Only `content` deltas are accumulated into the returned body; - reasoning (chain-of-thought) is echoed to the console but never part - of the result. Backends disagree on the field name: ollama streams it - as `reasoning`, DeepSeek/vllm-style as `reasoning_content`, so read both. - - Reads are gated by `select` so the socket never blocks-and-times-out: - a socket that delivers no bytes for `idle_warn` seconds prints a - warning, and `idle_timeout` seconds of silence raises CodegenError. - The total wall-clock budget `self.timeout` is enforced against the - whole stream and checked on every loop iteration, so even a - continuously-streaming generation that never sends `[DONE]` is cut - short. The token budget aborts as soon as the output cap is reached. - Thresholds <= 0 disable the idle checks. If the underlying socket - can't be reached, falls back to a plain blocking read - (`_read_stream_blocking`, which enforces the same budgets). - - An optional `degeneration_check` (last `window` chars of content + - reasoning, every `interval` chars past `min_chars`) can abort a - generation that is looping instead of converging — a non-None return - is the abort reason. - """ - parts: list[str] = [] - sock = self._stream_socket(response) - if sock is None: - return self._read_stream_blocking(response, budget, degeneration_check) - start = time.monotonic() - last_activity = start - warned = False - warned_fill = False - out_chars = 0 - usage: dict | None = None - recent: list[str] = [] - recent_len = 0 - last_check: int | None = None - while True: - if time.monotonic() - start >= self.timeout: - raise CodegenError( - f"codegen request exceeded {self.timeout:.0f}s total budget" - ) - ready, _, _ = select.select([sock], [], [], 1.0) - now = time.monotonic() - if not ready: - idle = now - last_activity - if self.idle_warn > 0 and not warned and idle >= self.idle_warn: - sys.stdout.write( - f"\n[codegen] no tokens for {idle:.0f}s — still waiting, " - f"will fail after {self.idle_timeout:.0f}s of silence\n" - ) - sys.stdout.flush() - warned = True - if self.idle_timeout > 0 and idle >= self.idle_timeout: - raise CodegenError( - f"codegen stream stalled: no tokens for {idle:.0f}s " - f"(idle_timeout={self.idle_timeout:.0f}s)" - ) - continue - try: - raw = response.readline() - except OSError as exc: - raise CodegenError(f"codegen stream read failed: {exc}") from exc - if not raw: - break - last_activity = time.monotonic() - continues, text, reasoning, frame_usage = self._consume_frame( - raw.decode("utf-8").strip() - ) - if frame_usage is not None: - usage = frame_usage - if self.stream and (text or reasoning): - sys.stdout.write(text + reasoning) - sys.stdout.flush() - if text: - parts.append(text) - out_chars += len(text) + len(reasoning) - if text or reasoning: - recent.append(text + reasoning) - recent_len = self._trim_recent(recent, recent_len) - warned_fill = self._enforce_budget(budget, out_chars, warned_fill) - reason, last_check = self._check_degeneration( - degeneration_check, recent, out_chars, last_check - ) - if reason: - raise DegenerationError(f"codegen degeneration detected: {reason}") - if not continues: - break - if usage is not None: - self._log_usage(budget, usage) - if parts and self.stream: - sys.stdout.write("\n") - sys.stdout.flush() - return "".join(parts) - - def _read_stream_blocking( - self, - response, - budget: TokenBudget, - degeneration_check: Callable[[str], str | None] | None = None, - ) -> str: - """Fallback reader when the response socket can't be located. - - A plain blocking read relies on the per-read socket timeout for - silence, but that bounds individual reads, not the whole stream — so - enforce the same total wall-clock budget `self.timeout` and the token - budget in the loop, or a continuously-streaming runaway would never be - cut short. - """ - parts: list[str] = [] - start = time.monotonic() - warned_fill = False - out_chars = 0 - usage: dict | None = None - recent: list[str] = [] - recent_len = 0 - last_check: int | None = None - for raw in response: - if time.monotonic() - start >= self.timeout: - raise CodegenError( - f"codegen request exceeded {self.timeout:.0f}s total budget" - ) - continues, text, reasoning, frame_usage = self._consume_frame( - raw.decode("utf-8").strip() - ) - if frame_usage is not None: - usage = frame_usage - if self.stream and (text or reasoning): - sys.stdout.write(text + reasoning) - sys.stdout.flush() - if text: - parts.append(text) - out_chars += len(text) + len(reasoning) - if text or reasoning: - recent.append(text + reasoning) - recent_len = self._trim_recent(recent, recent_len) - warned_fill = self._enforce_budget(budget, out_chars, warned_fill) - reason, last_check = self._check_degeneration( - degeneration_check, recent, out_chars, last_check - ) - if reason: - raise DegenerationError(f"codegen degeneration detected: {reason}") - if not continues: - break - if usage is not None: - self._log_usage(budget, usage) - if parts and self.stream: - sys.stdout.write("\n") - sys.stdout.flush() - return "".join(parts) - - def _trim_recent(self, recent: list[str], recent_len: int) -> int: - """Keep the rolling (content+reasoning) buffer bounded. - - Only the last `degeneration_window + degeneration_interval` chars are - ever needed: the check runs every `interval` chars against the last - `window` chars, so older text can be dropped. Returns the new length. - """ - budget = self.degeneration_window + self.degeneration_interval - while recent and recent_len > budget: - recent_len -= len(recent.pop(0)) - return recent_len - - def _check_degeneration( - self, - check: Callable[[str], str | None] | None, - recent: list[str], - out_chars: int, - last_check: int | None, - ) -> tuple[str | None, int | None]: - """Run the degeneration callback on the last `window` chars of - content+reasoning, every `interval` chars once `min_chars` have - accumulated. Returns (reason, new_last_check); a non-None reason means - the caller should abort.""" - if check is None or out_chars < self.degeneration_min_chars: - return None, last_check - if last_check is None or out_chars - last_check >= self.degeneration_interval: - window = self.degeneration_window or len(recent) - reason = check("".join(recent)[-window:]) - return reason, out_chars - return None, last_check - - @staticmethod - def _consume_frame(line: str) -> tuple[bool, str, str, dict | None]: - """Process one SSE line. - - Returns (continue, content, reasoning, usage). `content` feeds the - returned body; `reasoning` is only ever echoed; `usage` is the exact - token usage carried on the final chunk when `include_usage` was - requested (None otherwise). (False, "", "", None) on [DONE]. - """ - if not line.startswith("data:"): - return True, "", "", None - data = line[len("data:") :].strip() - if data == "[DONE]": - return False, "", "", None - try: - chunk = json.loads(data) - except ValueError: - return True, "", "", None - usage = chunk.get("usage") - if not isinstance(usage, dict): - usage = None - choices = chunk.get("choices") or [] - choice = choices[0] if choices else {} - delta = choice.get("delta", {}) or {} - text = delta.get("content") or "" - reasoning = delta.get("reasoning_content") or delta.get("reasoning") or "" - return True, text, reasoning, usage - - @staticmethod - def _stream_socket(response): - """Reach the underlying socket across Python-version response shapes.""" - fp = getattr(response, "fp", response) - raw = getattr(fp, "raw", None) - sock = getattr(raw, "_sock", None) if raw is not None else None - if sock is None: - sock = getattr(fp, "sock", None) - if sock is None: - sock = getattr(response, "sock", None) - return sock + error_class = CodegenError + degeneration_error_class = DegenerationError + label = "codegen" BODY_DIRECTIVES = ( diff --git a/semif_agent/engine.py b/semif_agent/engine.py index c3ea1a3..d7ec37e 100644 --- a/semif_agent/engine.py +++ b/semif_agent/engine.py @@ -95,59 +95,3 @@ 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. - """ - 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)) diff --git a/semif_agent/llm.py b/semif_agent/llm.py index cf4e98d..b6f76c9 100644 --- a/semif_agent/llm.py +++ b/semif_agent/llm.py @@ -1,41 +1,82 @@ -"""OpenAI-compatible LLM client — retained but dormant. +"""OpenAI-compatible provider for skill title + description authoring. -Decision-making (assessment, requeue, fidelity) now belongs to SemIf; this -client no longer participates in any decision path. The `llm` endpoint stays -configured for now (retirement is backlogged), so the class remains as the -stdlib transport plus `_parse_json`, which the authoring parsers borrow. Uses -only the stdlib HTTP client so the core stays dependency-free. +New categories and skills are named by a small, local OpenAI-compatible model +on the `llm` endpoint, deliberately separate from the larger `codegen` model +that writes runnable bodies. It uses the same provider machinery as +`CodegenClient` (`provider.OpenAICompatClient`): stdlib-only HTTP, a real SSE +stream, a token budget, and an idle watchdog — just with its own endpoint, +model, sampler defaults, and error type. `_parse_json` is also borrowed by the +authoring parsers. """ from __future__ import annotations import json -import urllib.error -import urllib.request + +from .provider import OpenAICompatClient, ProviderError -class LLMClient: - def __init__(self, base_url: str, model: str, timeout: float = 120.0): - self.base_url = base_url.rstrip("/") - self.model = model - self.timeout = timeout +class LLMError(ProviderError): + """The configured `llm` endpoint could not be reached or stalled.""" - def _chat(self, messages: list[dict], temperature: float = 0.0) -> str: - url = f"{self.base_url}/chat/completions" - body = json.dumps( - {"model": self.model, "messages": messages, "temperature": temperature} - ).encode("utf-8") - request = urllib.request.Request( - url, data=body, headers={"Content-Type": "application/json"} + +class LLMClient(OpenAICompatClient): + """Small-model author of skill/category titles + descriptions. + + Short JSON replies, so the defaults are conservative: low temperature, no + presence penalty, a modest timeout, and single-shot generation. Every value + is overridable from the `llm` block in `config.json`. + """ + + error_class = LLMError + degeneration_error_class = LLMError + label = "llm" + + def __init__( + self, + base_url: str, + model: str, + timeout: float = 600.0, + stream: bool = False, + idle_warn: float = 30.0, + idle_timeout: float = 120.0, + context_window: float = 0.0, + smart_limit: int = 250000, + warn_limit: int = 500000, + max_fill_ratio: float = 0.9, + warn_fill_ratio: float = 0.7, + max_output: float = 0.85, + chars_per_token: float = 4.0, + degeneration_interval: int = 8000, + degeneration_window: int = 2000, + degeneration_min_chars: int = 4000, + temperature: float = 0.2, + top_p: float = 0.9, + presence_penalty: float = 0.0, + frequency_penalty: float = 0.0, + ): + super().__init__( + base_url=base_url, + model=model, + timeout=timeout, + stream=stream, + idle_warn=idle_warn, + idle_timeout=idle_timeout, + context_window=context_window, + smart_limit=smart_limit, + warn_limit=warn_limit, + max_fill_ratio=max_fill_ratio, + warn_fill_ratio=warn_fill_ratio, + max_output=max_output, + chars_per_token=chars_per_token, + degeneration_interval=degeneration_interval, + degeneration_window=degeneration_window, + degeneration_min_chars=degeneration_min_chars, + temperature=temperature, + top_p=top_p, + presence_penalty=presence_penalty, + frequency_penalty=frequency_penalty, ) - try: - with urllib.request.urlopen(request, timeout=self.timeout) as response: - payload = json.loads(response.read().decode("utf-8")) - except urllib.error.URLError as exc: - raise RuntimeError( - f"LLM endpoint unreachable at {url}: {exc}. Is your local server running?" - ) from exc - return payload["choices"][0]["message"]["content"] @staticmethod def _parse_json(raw: str) -> dict: diff --git a/semif_agent/provider.py b/semif_agent/provider.py new file mode 100644 index 0000000..f04300e --- /dev/null +++ b/semif_agent/provider.py @@ -0,0 +1,565 @@ +"""Shared OpenAI-compatible chat provider. + +Both the small title/description author (`LLMClient` in `llm.py`) and the big +skill-body writer (`CodegenClient` in `codegen.py`) use the same transport +machinery: stdlib-only HTTP, a real SSE stream, a layered token budget, an idle +watchdog, and an optional SemIf degeneration hook. This module holds that +provider logic once; subclasses set `base_url`/`model`, their sampler defaults, +and the error classes they raise so existing callers keep catching their own +types. + +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. +""" + +from __future__ import annotations + +import json +import select +import sys +import time +import urllib.error +import urllib.request +from typing import Callable, NamedTuple + +DEFAULT_CONTEXT_WINDOW = 100000 + + +class ProviderError(RuntimeError): + """The configured OpenAI-compatible endpoint could not be reached.""" + + +class TokenBudget(NamedTuple): + """Per-request token limits derived from the detected context window. + + `total_limit` caps prompt + output; `output_limit` caps just the streamed + output (the enforced one — it already bakes in the prompt estimate); + `warn_point` is the total fill at which a one-shot console warning fires. + An `output_limit` of 0 means no cap is configured. + """ + + window: int + total_limit: int + output_limit: int + warn_point: int | None + prompt_est: int + + +class OpenAICompatClient: + """OpenAI-compatible chat provider shared by the authoring clients. + + Subclasses set `base_url`/`model` (and their sampler defaults) and the + error classes they raise: `error_class` for transport/parse/budget failures + and `degeneration_error_class` for a watchdog abort, so existing callers + keep catching their own types. `label` prefixes console diagnostics. + + The transport always reads the response as an SSE token stream so the + layered token budget, the idle watchdog, and the total wall-clock budget + can abort a runaway generation in real time — never via a server-side + `max_tokens` cap, because Qwen3-style models reason first and a cap + truncates the hidden reasoning, leaving `content` empty. + + `stream=True` additionally echoes tokens (including the chain-of-thought) + to stdout as they arrive; echo is console-only and the returned content + is identical either way. A silent stream (no bytes for `idle_warn` + seconds) prints a warning, and one that stays silent for `idle_timeout` + seconds raises CodegenError instead of blocking on the total timeout — a + wedged generation is surfaced in minutes, not ~20. + + The context window is lazily queried once from ollama's `/api/show` + (`parameters.num_ctx`, falling back to `model_info..context_length`, + then the `context_window` config, then 100000); the per-request budget + caps output at `max_output` (absolute tokens if >= 1, else a fraction of + the window) and total fill at `smart_limit`/`warn_limit`. + + An optional `degeneration_check` callback (passed per `chat` call) is fed + the last `degeneration_window` chars of content+reasoning every + `degeneration_interval` chars once `degeneration_min_chars` have + accumulated; a non-None return aborts the stream with DegenerationError. + It lets a SemIf continue/stop decision cut off a generation that is + looping instead of converging, before it fills the context window. + + Sampler defaults follow the Qwen3.8 model card's instruct-mode guidance + (unsloth/Qwen3.8-27B-GGUF): the anti-repetition cure is a high + `presence_penalty`, not greedy temperature. `temperature`/`top_p`/ + `presence_penalty`/`frequency_penalty` are per-`chat` overridable; the + `generate_skill_body` escalation ladder bumps presence toward the card's + max (2.0) and lowers temperature on retries. `max_attempts` bounds that + ladder (default 3). + """ + + error_class = ProviderError + degeneration_error_class = ProviderError + label = "provider" + + def __init__( + self, + base_url: str, + model: str, + timeout: float = 1200.0, + stream: bool = False, + idle_warn: float = 60.0, + idle_timeout: float = 180.0, + context_window: float = 0.0, + smart_limit: int = 250000, + warn_limit: int = 500000, + max_fill_ratio: float = 0.9, + warn_fill_ratio: float = 0.7, + max_output: float = 0.85, + chars_per_token: float = 4.0, + degeneration_interval: int = 8000, + degeneration_window: int = 2000, + degeneration_min_chars: int = 4000, + temperature: float = 0.7, + top_p: float = 0.85, + presence_penalty: float = 1.5, + frequency_penalty: float = 0.2, + max_attempts: int = 3, + ): + self.base_url = base_url.rstrip("/") + self.model = model + self.timeout = timeout + self.stream = stream + self.idle_warn = idle_warn + self.idle_timeout = idle_timeout + self.context_window = context_window + self.smart_limit = smart_limit + self.warn_limit = warn_limit + self.max_fill_ratio = max_fill_ratio + self.warn_fill_ratio = warn_fill_ratio + self.max_output = max_output + self.chars_per_token = chars_per_token + self.degeneration_interval = degeneration_interval + self.degeneration_window = degeneration_window + self.degeneration_min_chars = degeneration_min_chars + self.temperature = temperature + self.top_p = top_p + self.presence_penalty = presence_penalty + self.frequency_penalty = frequency_penalty + self.max_attempts = max_attempts + self._window: int | None = None + + 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, + degeneration_check: Callable[[str], str | None] | None = None, + ) -> str: + budget = self._compute_budget(messages) + if self.stream: + self._print_budget(budget) + url = f"{self.base_url}/chat/completions" + payload: dict = { + "model": self.model, + "messages": messages, + "temperature": self.temperature if temperature is None else temperature, + "top_p": self.top_p if top_p is None else top_p, + "presence_penalty": ( + self.presence_penalty if presence_penalty is None else presence_penalty + ), + "frequency_penalty": ( + self.frequency_penalty if frequency_penalty is None else frequency_penalty + ), + "stream": True, + "stream_options": {"include_usage": True}, + } + if max_tokens is not None: + payload["max_tokens"] = max_tokens + body = json.dumps(payload).encode("utf-8") + request = urllib.request.Request( + url, data=body, headers={"Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=self.timeout) as response: + return self._read_stream(response, budget, degeneration_check) + except urllib.error.URLError as exc: + raise self.error_class( + f"{self.label} endpoint unreachable at {url}: {exc}. Is your local server running?" + ) from exc + except TimeoutError as exc: + raise self.error_class( + f"{self.label} request timed out after {self.timeout}s at {url}" + ) from exc + + def _native_base_url(self) -> str: + """Ollama's `/api/show` lives on the native API, not the /v1 compat.""" + if self.base_url.endswith("/v1"): + return self.base_url[: -len("/v1")] + return self.base_url + + def _query_context_window(self) -> int | None: + """POST /api/show {model} for the runtime context window. Any failure + (unreachable, non-ollama endpoint, malformed reply) returns None so the + caller falls back to config or the default. Uses a short request + timeout so a slow show endpoint never wedges the actual generation.""" + url = f"{self._native_base_url()}/api/show" + request = urllib.request.Request( + url, + data=json.dumps({"model": self.model}).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen( + request, timeout=min(self.timeout, 10.0) + ) as response: + data = json.loads(response.read().decode("utf-8")) + except (urllib.error.URLError, TimeoutError, ValueError, KeyError): + return None + params = data.get("parameters") + if isinstance(params, dict): + num_ctx = params.get("num_ctx") + if isinstance(num_ctx, int) and num_ctx > 0: + return num_ctx + elif isinstance(params, str): + # ollama serves parameters as modelfile text, not a dict: + # "num_ctx 100000\n..." — pull the num_ctx line if present. + for line in params.splitlines(): + parts = line.split() + if len(parts) == 2 and parts[0] == "num_ctx": + try: + num_ctx = int(parts[1]) + except ValueError: + break + if num_ctx > 0: + return num_ctx + model_info = data.get("model_info") or {} + for key, value in model_info.items(): + if key.endswith(".context_length") and isinstance(value, int) and value > 0: + return value + return None + + def _context_window(self) -> int: + """Detected context window, queried once and cached.""" + if self._window is not None: + return self._window + window = self._query_context_window() + if window is None: + window = ( + int(self.context_window) + if self.context_window > 0 + else DEFAULT_CONTEXT_WINDOW + ) + self._window = window + return window + + def _compute_budget(self, messages: list[dict]) -> TokenBudget: + window = self._context_window() + max_out = ( + int(self.max_output) + if self.max_output >= 1 + else int(self.max_output * window) + ) + total_limit = int(min(self.smart_limit, window * self.max_fill_ratio)) + prompt_est = int( + sum(len(str(m.get("content") or "")) for m in messages) + / self.chars_per_token + ) + if total_limit > 0 and prompt_est >= total_limit: + raise self.error_class( + f"{self.label} prompt (~{prompt_est} tokens) already exceeds the " + f"total budget of {total_limit} tokens" + ) + if total_limit > 0 and max_out > 0: + output_limit = min(max_out, total_limit - prompt_est) + else: + output_limit = 0 + warn_point = None + if self.warn_limit > 0 and self.warn_fill_ratio > 0: + warn_point = min(self.warn_limit, int(window * self.warn_fill_ratio)) + return TokenBudget(window, total_limit, output_limit, warn_point, prompt_est) + + def _print_budget(self, budget: TokenBudget) -> None: + if budget.window and budget.output_limit > 0: + print( + f"[{self.label}] context window {budget.window} tokens · " + f"output cap {budget.output_limit} tokens " + f"({budget.output_limit / budget.window * 100:.0f}%) · " + f"peak total fill ~{budget.total_limit} tokens" + ) + elif budget.window: + print( + f"[{self.label}] context window {budget.window} tokens · " + f"peak total fill ~{budget.total_limit} tokens" + ) + sys.stdout.flush() + + def _log_usage(self, budget: TokenBudget, usage: dict) -> None: + """Report exact token usage once `include_usage` yields a usage chunk. + + Logs real prompt/completion/total tokens, % of the detected window, and + the zone (SMART < smart_limit, WARN < warn_limit, else DUMB) measured + against absolute total-token thresholds. + """ + prompt = usage.get("prompt_tokens") + completion = usage.get("completion_tokens") + total = usage.get("total_tokens") + if not isinstance(total, int): + return + if not isinstance(prompt, int): + prompt = total - (completion if isinstance(completion, int) else 0) + if not isinstance(completion, int): + completion = total - prompt + pct = total / budget.window * 100 if budget.window else 0.0 + if self.smart_limit > 0 and total < self.smart_limit: + zone = "SMART" + elif self.warn_limit > 0 and total < self.warn_limit: + zone = "WARN" + else: + zone = "DUMB" + print( + f"[{self.label}] usage: prompt {prompt} · completion {completion} · " + f"total {total} tokens · {pct:.0f}% of window · {zone}" + ) + sys.stdout.flush() + + def _enforce_budget(self, budget: TokenBudget, out_chars: int, warned: bool) -> bool: + """Abort when the output cap is exceeded; one-shot warn near the fill + threshold. Returns the updated warned state.""" + output_est = out_chars / self.chars_per_token + if budget.output_limit > 0 and output_est >= budget.output_limit: + raise self.error_class( + f"{self.label} output exceeded {budget.output_limit} token budget " + f"(~{out_chars} chars at {self.chars_per_token:g} chars/token)" + ) + if budget.warn_point is not None and not warned: + total = budget.prompt_est + output_est + if total >= budget.warn_point: + sys.stdout.write( + f"\n[{self.label}] total fill ~{int(total)} tokens — " + f"near the {budget.output_limit} token output budget\n" + ) + sys.stdout.flush() + return True + return warned + + def _read_stream( + self, + response, + budget: TokenBudget, + degeneration_check: Callable[[str], str | None] | None = None, + ) -> str: + """Read an OpenAI-compatible SSE stream; echo tokens if `stream`. + + Only `content` deltas are accumulated into the returned body; + reasoning (chain-of-thought) is echoed to the console but never part + of the result. Backends disagree on the field name: ollama streams it + as `reasoning`, DeepSeek/vllm-style as `reasoning_content`, so read both. + + Reads are gated by `select` so the socket never blocks-and-times-out: + a socket that delivers no bytes for `idle_warn` seconds prints a + warning, and `idle_timeout` seconds of silence raises CodegenError. + The total wall-clock budget `self.timeout` is enforced against the + whole stream and checked on every loop iteration, so even a + continuously-streaming generation that never sends `[DONE]` is cut + short. The token budget aborts as soon as the output cap is reached. + Thresholds <= 0 disable the idle checks. If the underlying socket + can't be reached, falls back to a plain blocking read + (`_read_stream_blocking`, which enforces the same budgets). + + An optional `degeneration_check` (last `window` chars of content + + reasoning, every `interval` chars past `min_chars`) can abort a + generation that is looping instead of converging — a non-None return + is the abort reason. + """ + parts: list[str] = [] + sock = self._stream_socket(response) + if sock is None: + return self._read_stream_blocking(response, budget, degeneration_check) + start = time.monotonic() + last_activity = start + warned = False + warned_fill = False + out_chars = 0 + usage: dict | None = None + recent: list[str] = [] + recent_len = 0 + last_check: int | None = None + while True: + if time.monotonic() - start >= self.timeout: + raise self.error_class( + f"{self.label} request exceeded {self.timeout:.0f}s total budget" + ) + ready, _, _ = select.select([sock], [], [], 1.0) + now = time.monotonic() + if not ready: + idle = now - last_activity + if self.idle_warn > 0 and not warned and idle >= self.idle_warn: + sys.stdout.write( + f"\n[{self.label}] no tokens for {idle:.0f}s — still waiting, " + f"will fail after {self.idle_timeout:.0f}s of silence\n" + ) + sys.stdout.flush() + warned = True + if self.idle_timeout > 0 and idle >= self.idle_timeout: + raise self.error_class( + f"{self.label} stream stalled: no tokens for {idle:.0f}s " + f"(idle_timeout={self.idle_timeout:.0f}s)" + ) + continue + try: + raw = response.readline() + except OSError as exc: + raise self.error_class(f"{self.label} stream read failed: {exc}") from exc + if not raw: + break + last_activity = time.monotonic() + continues, text, reasoning, frame_usage = self._consume_frame( + raw.decode("utf-8").strip() + ) + if frame_usage is not None: + usage = frame_usage + if self.stream and (text or reasoning): + sys.stdout.write(text + reasoning) + sys.stdout.flush() + if text: + parts.append(text) + out_chars += len(text) + len(reasoning) + if text or reasoning: + recent.append(text + reasoning) + recent_len = self._trim_recent(recent, recent_len) + warned_fill = self._enforce_budget(budget, out_chars, warned_fill) + reason, last_check = self._check_degeneration( + degeneration_check, recent, out_chars, last_check + ) + if reason: + raise self.degeneration_error_class(f"{self.label} degeneration detected: {reason}") + if not continues: + break + if usage is not None: + self._log_usage(budget, usage) + if parts and self.stream: + sys.stdout.write("\n") + sys.stdout.flush() + return "".join(parts) + + def _read_stream_blocking( + self, + response, + budget: TokenBudget, + degeneration_check: Callable[[str], str | None] | None = None, + ) -> str: + """Fallback reader when the response socket can't be located. + + A plain blocking read relies on the per-read socket timeout for + silence, but that bounds individual reads, not the whole stream — so + enforce the same total wall-clock budget `self.timeout` and the token + budget in the loop, or a continuously-streaming runaway would never be + cut short. + """ + parts: list[str] = [] + start = time.monotonic() + warned_fill = False + out_chars = 0 + usage: dict | None = None + recent: list[str] = [] + recent_len = 0 + last_check: int | None = None + for raw in response: + if time.monotonic() - start >= self.timeout: + raise self.error_class( + f"{self.label} request exceeded {self.timeout:.0f}s total budget" + ) + continues, text, reasoning, frame_usage = self._consume_frame( + raw.decode("utf-8").strip() + ) + if frame_usage is not None: + usage = frame_usage + if self.stream and (text or reasoning): + sys.stdout.write(text + reasoning) + sys.stdout.flush() + if text: + parts.append(text) + out_chars += len(text) + len(reasoning) + if text or reasoning: + recent.append(text + reasoning) + recent_len = self._trim_recent(recent, recent_len) + warned_fill = self._enforce_budget(budget, out_chars, warned_fill) + reason, last_check = self._check_degeneration( + degeneration_check, recent, out_chars, last_check + ) + if reason: + raise self.degeneration_error_class(f"{self.label} degeneration detected: {reason}") + if not continues: + break + if usage is not None: + self._log_usage(budget, usage) + if parts and self.stream: + sys.stdout.write("\n") + sys.stdout.flush() + return "".join(parts) + + def _trim_recent(self, recent: list[str], recent_len: int) -> int: + """Keep the rolling (content+reasoning) buffer bounded. + + Only the last `degeneration_window + degeneration_interval` chars are + ever needed: the check runs every `interval` chars against the last + `window` chars, so older text can be dropped. Returns the new length. + """ + budget = self.degeneration_window + self.degeneration_interval + while recent and recent_len > budget: + recent_len -= len(recent.pop(0)) + return recent_len + + def _check_degeneration( + self, + check: Callable[[str], str | None] | None, + recent: list[str], + out_chars: int, + last_check: int | None, + ) -> tuple[str | None, int | None]: + """Run the degeneration callback on the last `window` chars of + content+reasoning, every `interval` chars once `min_chars` have + accumulated. Returns (reason, new_last_check); a non-None reason means + the caller should abort.""" + if check is None or out_chars < self.degeneration_min_chars: + return None, last_check + if last_check is None or out_chars - last_check >= self.degeneration_interval: + window = self.degeneration_window or len(recent) + reason = check("".join(recent)[-window:]) + return reason, out_chars + return None, last_check + + @staticmethod + def _consume_frame(line: str) -> tuple[bool, str, str, dict | None]: + """Process one SSE line. + + Returns (continue, content, reasoning, usage). `content` feeds the + returned body; `reasoning` is only ever echoed; `usage` is the exact + token usage carried on the final chunk when `include_usage` was + requested (None otherwise). (False, "", "", None) on [DONE]. + """ + if not line.startswith("data:"): + return True, "", "", None + data = line[len("data:") :].strip() + if data == "[DONE]": + return False, "", "", None + try: + chunk = json.loads(data) + except ValueError: + return True, "", "", None + usage = chunk.get("usage") + if not isinstance(usage, dict): + usage = None + choices = chunk.get("choices") or [] + choice = choices[0] if choices else {} + delta = choice.get("delta", {}) or {} + text = delta.get("content") or "" + reasoning = delta.get("reasoning_content") or delta.get("reasoning") or "" + return True, text, reasoning, usage + + @staticmethod + def _stream_socket(response): + """Reach the underlying socket across Python-version response shapes.""" + fp = getattr(response, "fp", response) + raw = getattr(fp, "raw", None) + sock = getattr(raw, "_sock", None) if raw is not None else None + if sock is None: + sock = getattr(fp, "sock", None) + if sock is None: + sock = getattr(response, "sock", None) + return sock diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 561d9b2..541209f 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -34,6 +34,7 @@ from .decisions import DecisionRequest, Option, Request from .engine import EngineUnavailable, SemIfEngine from .llm import LLMClient from .log import DecisionLog +from .provider import ProviderError from .queue import UrgencyQueue from .skill import SkillRunner from .skills import ( @@ -107,11 +108,26 @@ class SkillWrite: repair_evidence: dict | None = None +@dataclass +class DraftAuthor: + """One queued async draft authoring (single-slot `llm` worker). + + `kind` is "category" (author a top-level category) or "skill" (author a + leaf inside `category`). A category job chains into its skill job so the + create_category -> create_skill order stays deterministic. + """ + + request: Request + category: str | None + weight: float + kind: str + + @dataclass class PendingQuestion: """A question waiting for the human (deferred elicitation or repair). - Posted by the codegen worker when no inline asker is wired; answered via + Posted by the codegen worker; answered via the dashboard (`/api/questions`) or `Scheduler.answer_question`. The worker waits (bounded by `codegen.elicitation.wait_timeout`) and continues with whatever answers arrived. @@ -159,9 +175,7 @@ class DispatchResult: summary: str skill: str | None = None decisions_logged: int = 0 - body_written: bool = False needs_input: str | None = None - draft: SkillDraft | None = None class Scheduler: @@ -179,7 +193,6 @@ class Scheduler: | None = None, regen_decision_factory: Callable[[str], Callable[[str], str] | None] | None = None, - asker: Callable[[str], str | None] | None = None, on_request_requeued: Callable[[str, str], None] | None = None, ): self.engine = engine @@ -195,7 +208,6 @@ class Scheduler: self.codegen = codegen self.degeneration_check_factory = degeneration_check_factory self.regen_decision_factory = regen_decision_factory - self.asker = asker self.on_request_requeued = on_request_requeued codegen_cfg = config.get("codegen", {}) or {} elicitation_cfg = codegen_cfg.get("elicitation", {}) or {} @@ -234,6 +246,9 @@ class Scheduler: self.current: Process | None = None self.pending: PendingRun | None = None self._lock = threading.RLock() + self._drafts: deque[DraftAuthor] = deque() + self._draft_notify = threading.Condition(self._lock) + self._draft_thread: threading.Thread | None = None self._writes: deque[SkillWrite] = deque() self._write_notify = threading.Condition(self._lock) self._write_thread: threading.Thread | None = None @@ -421,10 +436,7 @@ class Scheduler: create_margin=self.create_margin, ) if isinstance(navigation, CreateCategory): - created = self._create_category(request) - if created.kind != "create_category": - return created - return self._dispatch_skill(request, created.skill, weight) + return self._dispatch_create_category(request, weight) if isinstance(navigation, CreateSkill): if navigation.category in CANNED_CATEGORIES: fallback = self._canned_fallback(navigation.category) @@ -460,16 +472,34 @@ class Scheduler: return skill return skills[0] if skills else None + def _dispatch_create_category( + self, request: Request, weight: float = 0.0 + ) -> DispatchResult: + """Queue a new top-level category for the `llm` draft worker. + + The gate stays free: the small model authors the category in the + background and, once it lands, the same worker authors the skill leaf + inside it and hands off to the codegen body worker. On failure the + request is not re-dispatched and the user is told. + """ + self._queue_draft(request, None, "category", weight) + return DispatchResult( + kind="create_category", + summary=( + "authoring a new category in the background; the request will " + "re-run when it is ready" + ), + ) + def _dispatch_skill( self, request: Request, category: str, weight: float = 0.0 ) -> DispatchResult: - """create_skill in `category`, then launch an async body write. + """Queue a new skill leaf for the `llm` draft worker. - The stub is authored and registered synchronously so the leaf is - navigable immediately; the runnable body is written in the background - by the single-slot codegen worker. When the body lands, the original - request is re-queued and re-runs navigation onto the new leaf. A - re-dispatched request whose skill is still unwritten must not author a + The small model authors the title + description in the background, then + the codegen worker writes the runnable body; when the body lands the + original request is re-queued and re-runs navigation onto the new leaf. + A re-dispatched request whose skill is still unwritten must not author a second skill — it reports the pending write instead. """ pending = request.meta.get("awaiting_skill_body") @@ -483,70 +513,14 @@ class Scheduler: ), skill=name, ) - created = self._create_skill(request, category) - if created.kind != "create_skill" or created.draft is None: - return created - if self.asker is not None: - self._elicit_requirements(request, category, created.draft) - elif self.elicitation_enabled: - if self.defer_questions: - self.trace.append( - "requirements_deferred", - request.id, - category=category, - skill=created.draft.name, - ) - else: - self.trace.append( - "requirements_skipped", - request.id, - category=category, - skill=created.draft.name, - reason="no asker wired", - ) - self._start_skill_write(request, category, created.draft, weight) - return created - - def _elicit_requirements( - self, request: Request, category: str, draft: SkillDraft - ) -> None: - """Ask the product owner implementation questions before the body is written. - - Inline path (the REPL wires an asker): questions are generated and asked - synchronously at dispatch. The dashboard uses the deferred path instead — - the worker posts questions to `self.questions` and waits for answers. - Answers seed the draft's requirements and the intended integration. Any - failure degrades to no requirements — elicitation must never block - authoring. - """ - if not self.elicitation_enabled or self.codegen is None: - return - try: - elicited = generate_elicitation( - self.codegen, request, category, draft, self.tree, - max_questions=self.elicitation_max, - ) - except CodegenError: - return - if elicited.integration: - draft.integration = elicited.integration - for question in elicited.questions: - try: - answer = self.asker(question) - except Exception: - return - if answer is None or not answer.strip(): - return - draft.requirements[question] = answer.strip() - if draft.requirements or draft.integration: - self.trace.append( - "requirements", - request.id, - category=category, - skill=draft.name, - questions=list(draft.requirements.keys()), - integration=draft.integration or None, - ) + self._queue_draft(request, category, "skill", weight) + return DispatchResult( + kind="create_skill", + summary=( + f"authoring a new skill for {category} in the background; " + "the request will re-run when it is ready" + ), + ) def _run_skill(self, skill: Skill, request: Request) -> DispatchResult: if skill.writing: @@ -915,108 +889,146 @@ class Scheduler: requirements=dict(row.get("requirements") or {}), ) - def _create_category(self, request: Request) -> DispatchResult: - """Author a new category stub with the decision model in generation mode. + # ---- async draft authoring (single-slot `llm` worker) ---- - The engine is always real, so an EngineUnavailable is fatal: it is - recorded and re-raised for the caller to stop on. + def _queue_draft( + self, + request: Request, + category: str | None, + kind: str, + weight: float, + ) -> None: + """Queue a category or skill draft for the `llm` worker. + + The gate stays free: this returns immediately and one draft at a time is + authored in the background. A category job chains into its skill job; a + skill job hands off to the codegen body worker. """ + with self._lock: + self._drafts.append( + DraftAuthor( + request=request, category=category, weight=weight, kind=kind + ) + ) + if self._draft_thread is None or not self._draft_thread.is_alive(): + self._draft_thread = threading.Thread( + target=self._draft_worker, name="draft-author", daemon=True + ) + self._draft_thread.start() + self._draft_notify.notify() + target = category or "(new category)" + print( + f"[llm] queued {kind} authoring for {target}; " + "the request will re-run when it is ready." + ) + + def _draft_worker(self) -> None: + """Drain the draft queue one authoring call at a time.""" + while True: + with self._draft_notify: + while not self._drafts and self._fatal is None: + self._draft_notify.wait() + if self._fatal is not None: + return + job = self._drafts.popleft() + self._author_draft(job) + + def _author_draft(self, job: DraftAuthor) -> None: try: - draft = generate_category(self.engine, request, self.tree) - except EngineUnavailable as exc: - self._mark_fatal(exc) - raise - except ValueError as exc: - self.trace.append("error", request.id, phase="create_category", message=str(exc)) - return DispatchResult(kind="error", summary=f"create_category failed: {exc}") - if draft.name in self.tree: - self.trace.append( - "error", - request.id, - phase="create_category", - message=f"category {draft.name} already exists", - ) - return DispatchResult( - kind="error", - summary=f"create_category failed: {draft.name} already exists", - ) - self.registry.register(draft.name, draft.description) - self.tree[draft.name] = [] - self.trace.append( - "category_created", - request.id, - category=draft.name, - description=draft.description, - ) - return DispatchResult( - kind="create_category", - summary=f"created category {draft.name}: {draft.description}", - skill=draft.name, - ) + if job.kind == "category": + self._author_category(job) + else: + self._author_skill(job) + except (ProviderError, ValueError) as exc: + self._fail_draft(job, exc) - def _create_skill(self, request: Request, category: str) -> DispatchResult: - """Author a new skill leaf with the decision model in generation mode. + def _tree_snapshot(self) -> dict: + with self._lock: + return {category: list(skills) for category, skills in self.tree.items()} - The small model writes the title + description; the stub is registered - and merged into the tree so the leaf is navigable immediately. If - codegen is configured, the runnable body is written asynchronously (see - _start_skill_write) and the request is re-dispatched once the body - lands; the returned result carries the draft so _dispatch_skill can - launch that write. Without codegen the stub is final. The engine is - always real, so an EngineUnavailable is fatal: it is recorded and - re-raised for the caller to stop on. + def _author_category(self, job: DraftAuthor) -> None: + """Author a top-level category, then chain into its skill leaf. + + An `llm` failure is graceful: only the user is told, the request is not + re-dispatched — the decision engine stays the single fatal dependency. """ - try: - draft = generate_skill(self.engine, request, category, self.tree) - except EngineUnavailable as exc: - self._mark_fatal(exc) - raise - except ValueError as exc: - self.trace.append("error", request.id, phase="create_skill", message=str(exc)) - return DispatchResult(kind="error", summary=f"create_skill failed: {exc}") - existing = {s.name for s in self.tree.get(category, [])} - if draft.name in existing: + draft = generate_category(self.llm, job.request, self._tree_snapshot()) + with self._lock: + if draft.name in self.tree: + self.trace.append( + "error", + job.request.id, + phase="create_category", + message=f"category {draft.name} already exists", + ) + return + self.registry.register(draft.name, draft.description) + self.tree[draft.name] = [] self.trace.append( - "error", - request.id, - phase="create_skill", - category=category, - message=f"skill {draft.name} already exists", - ) - return DispatchResult( - kind="error", - summary=f"create_skill failed: {draft.name} already exists", - ) - - self.registry.register_skill( - category, draft.name, draft.description, request_text=request.text - ) - self.tree.setdefault(category, []).append( - Skill(name=draft.name, category=category, description=draft.description) - ) - if self.codegen is None: - self.trace.append( - "skill_created", - request.id, - category=category, - skill=draft.name, + "category_created", + job.request.id, + category=draft.name, description=draft.description, - body=None, - written=False, ) - return DispatchResult( - kind="create_skill", - summary=f"created stub {category}.{draft.name}: {draft.description} (no codegen configured)", - skill=draft.name, + self._queue_draft(job.request, draft.name, "skill", job.weight) + + def _author_skill(self, job: DraftAuthor) -> None: + """Author a skill leaf stub, then launch the codegen body write.""" + draft = generate_skill( + self.llm, job.request, job.category, self._tree_snapshot() + ) + with self._lock: + existing = {s.name for s in self.tree.get(job.category, [])} + if draft.name in existing: + self.trace.append( + "error", + job.request.id, + phase="create_skill", + category=job.category, + message=f"skill {draft.name} already exists", + ) + return + self.registry.register_skill( + job.category, + draft.name, + draft.description, + request_text=job.request.text, ) - return DispatchResult( - kind="create_skill", - summary=( - f"created stub {category}.{draft.name}: {draft.description} — " - "body writing in background; request will re-run when ready" - ), - skill=draft.name, - draft=draft, + self.tree.setdefault(job.category, []).append( + Skill( + name=draft.name, + category=job.category, + description=draft.description, + ) + ) + if self.codegen is None: + self.trace.append( + "skill_created", + job.request.id, + category=job.category, + skill=draft.name, + description=draft.description, + body=None, + written=False, + ) + if self.codegen is None: + return + self._start_skill_write(job.request, job.category, draft, job.weight) + + def _fail_draft(self, job: DraftAuthor, exc: Exception) -> None: + """Surface a failed draft authoring; the request is not re-dispatched.""" + target = job.category or "(new category)" + with self._lock: + self.trace.append( + "draft_failed", + job.request.id, + authoring=job.kind, + category=job.category, + message=str(exc), + ) + print( + f"[llm] {job.kind} authoring for {target} FAILED: {exc}. " + "The request was not re-dispatched." ) # ---- async skill-body writes (single-slot codegen worker) ---- @@ -1173,12 +1185,21 @@ class Scheduler: def _deferred_elicit(self, job: SkillWrite, tree: dict) -> None: """Generate questions in the background, post them, wait for answers. - The dashboard path: no inline asker exists, so the single-slot worker - itself asks. It pauses here for up to `elicitation.wait_timeout` while - the gate stays free and other requests proceed; whatever answers arrive - (possibly none) feed the body writer. + The single-slot worker itself asks: the REPL, dashboard, and gateway all + defer questions to `self.questions` now that authoring is async. It + pauses here for up to `elicitation.wait_timeout` while the gate stays + free and other requests proceed; whatever answers arrive (possibly none) + feed the body writer. """ if not (self.defer_questions and self.elicitation_enabled and self.codegen): + if self.elicitation_enabled and self.codegen is not None: + self.trace.append( + "requirements_skipped", + job.request.id, + category=job.category, + skill=job.draft.name, + reason="questions not deferred by this front end", + ) return try: elicited = generate_elicitation( diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 88d3d78..ba9481f 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -2,10 +2,10 @@ A skill is a leaf reached by a chain of SemIf choices (category -> skill). The category level carries a "create_category" branch and the leaf level a -"create_skill" branch. Both are live: the decision model is driven in normal -generation mode to propose a title + description — a broad new category or a -specific new skill leaf — which is persisted to a category registry and merged -into the running tree as a stub. +"create_skill" branch. Both are live: a small OpenAI-compatible model (`llm`, +separate from `codegen`) proposes a title + description — a broad new category +or a specific new skill leaf — which is persisted to a category registry and +merged into the running tree as a stub. Only the real skills live here; navigation uses the real decision engine. """ @@ -92,8 +92,8 @@ class Skill: class CreateSkill: """Suggestion that the current category needs a new skill. - Handled live, like CreateCategory: the decision model authors the new skill - stub, which is persisted and merged into the tree. `category` names the + Handled live, like CreateCategory: the small `llm` provider authors the new + skill stub, which is persisted and merged into the tree. `category` names the category that needs the new skill. """ @@ -104,8 +104,8 @@ class CreateSkill: class CreateCategory: """Suggestion that the request needs a brand-new top-level category. - Like CreateSkill this is handled live: the decision model is used in - normal generation mode to author the category stub. + Like CreateSkill this is handled live: the small `llm` provider authors the + category stub. """ @@ -894,10 +894,10 @@ def parse_category_draft(raw: str) -> CategoryDraft: def generate_category( - engine: SemIfEngine, request: Request, tree: dict[str, list[Skill]] + client: LLMClient, request: Request, tree: dict[str, list[Skill]] ) -> CategoryDraft: - """Author a new category stub with the decision model in generation mode.""" - raw = engine.generate(build_category_prompt(request, tree), max_tokens=128) + """Author a new category stub with the `llm` provider.""" + raw = client.chat(build_category_prompt(request, tree), max_tokens=128) return parse_category_draft(raw) @@ -945,8 +945,8 @@ def parse_skill_draft(raw: str) -> SkillDraft: def generate_skill( - engine: SemIfEngine, request: Request, category: str, tree: dict[str, list[Skill]] + client: LLMClient, request: Request, category: str, tree: dict[str, list[Skill]] ) -> SkillDraft: - """Author a new skill leaf stub with the decision model in generation mode.""" - raw = engine.generate(build_skill_prompt(request, category, tree), max_tokens=128) + """Author a new skill leaf stub with the `llm` provider.""" + raw = client.chat(build_skill_prompt(request, category, tree), max_tokens=128) return parse_skill_draft(raw) diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index 25deafb..52056e4 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -2,8 +2,9 @@ python -m pytest tests/integration -q -The decision engine is real (llamacpp GGUF) and self-assessment is a real -local LLM endpoint. If either is unavailable this fails loudly — no mocking. +The decision engine is real (llamacpp GGUF), and the `llm` and `codegen` +providers are real OpenAI-compatible endpoints. If any is unavailable this +fails loudly — no mocking. """ import json @@ -78,7 +79,7 @@ def _install_tracking_fixture(scheduler): The pipeline tests need a target whose flow is stable; the hardcoded email/tracking examples were removed because they faked their integrations. This injects a runnable tracking leaf instead — the decision engine, the - self-assessment LLM, and the decision log all remain real. + `llm`/`codegen` providers, and the decision log all remain real. """ def predict(ctx, request): @@ -240,29 +241,22 @@ def test_busy_choice_path(tmp_path): scheduler.idle() -def test_engine_generation_normal_mode(tmp_path): - """The pinned decision model must also generate text in the normal way.""" +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.""" config = load_config() require_real(config) scheduler, config = build_scheduler(config) - out = scheduler.engine.generate( - [ - {"role": "system", "content": "Reply with the single word ok."}, - {"role": "user", "content": "say ok"}, - ], - max_tokens=16, - ) - print(f"generation: {out!r}") - assert isinstance(out, str) and out.strip() + assert not hasattr(scheduler.engine, "generate") def test_generate_category(tmp_path): - """Authoring a category stub through the real decision model.""" + """Authoring a category stub through the real `llm` provider.""" config = load_config() require_real(config) scheduler, config = build_scheduler(config) draft = generate_category( - scheduler.engine, + scheduler.llm, Request("tell me if my package was delivered"), scheduler.tree, ) @@ -272,12 +266,12 @@ def test_generate_category(tmp_path): def test_generate_skill(tmp_path): - """Authoring a skill leaf stub through the real decision model.""" + """Authoring a skill leaf stub through the real `llm` provider.""" config = load_config() require_real(config) scheduler, config = build_scheduler(config) draft = generate_skill( - scheduler.engine, + scheduler.llm, Request("tell me if my package was delivered"), "tracking", scheduler.tree, @@ -481,8 +475,14 @@ def test_create_category_chain_runs_new_skill(tmp_path): status, detail = scheduler.submit("track my drone delivery in real time") print(f"[{status}] {detail}") assert status in ("running", "preempted", "queued", "rejected") - assert scheduler.current is None, "gate must be free again right after the stub is created" + assert scheduler.current is None, "gate must be free again right after the draft is queued" + draft_deadline = time.monotonic() + 10 * 60 + while time.monotonic() < draft_deadline: + kinds = [e["kind"] for e in scheduler.trace.read()] + if "category_created" in kinds and "skill_writing" in kinds: + break + time.sleep(5) kinds = [e["kind"] for e in scheduler.trace.read()] assert "category_created" in kinds, "category stub must be authored first" assert "skill_writing" in kinds, "the async body write must be launched" diff --git a/tests/test_llm.py b/tests/test_llm.py index dc24902..16117e5 100644 --- a/tests/test_llm.py +++ b/tests/test_llm.py @@ -1,11 +1,69 @@ -"""Pure-stdlib tests for the retained JSON helper on the dormant LLM client. +"""Pure-stdlib tests for the `llm` authoring provider. -The LLM no longer participates in any decision path (assessment and fidelity -are SemIf decisions), so only `_parse_json` — which the authoring parsers -borrow — is exercised here. +A throwaway stdlib HTTP server stands in for the OpenAI-compatible endpoint — +the LLMClient itself is real, not mocked. """ -from semif_agent.llm import LLMClient +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +from semif_agent.decisions import Request +from semif_agent.llm import LLMClient, LLMError +from semif_agent.skills import ( + CategoryDraft, + SkillDraft, + build_skills, + build_tree, + generate_category, + generate_skill, +) + + +def _sse_frame(payload: dict) -> str: + return f"data: {json.dumps(payload)}\n\n" + + +class _FakeOpenAI(BaseHTTPRequestHandler): + """Single-shot SSE server: the reply arrives as one content delta. The + `/api/show` window query is answered too but never recorded.""" + + reply: str = "" + received: list = [] + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length).decode("utf-8") + if self.path.rstrip("/").endswith("/api/show"): + body = json.dumps({"parameters": {"num_ctx": 32768}}).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + type(self).received.append(json.loads(raw)) + body = ( + _sse_frame({"choices": [{"delta": {"content": self.reply}}]}) + + "data: [DONE]\n\n" + ).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format, *args) -> None: + pass + + +def _fake_server(reply: str) -> tuple[ThreadingHTTPServer, str]: + handler = type("Handler", (_FakeOpenAI,), {"reply": reply, "received": []}) + httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" def test_parse_json_extracts_object_from_prose(): @@ -15,3 +73,57 @@ def test_parse_json_extracts_object_from_prose(): def test_parse_json_handles_bare_object(): assert LLMClient._parse_json('{"ok": true}') == {"ok": True} + + +def test_chat_returns_streamed_content(): + httpd, base = _fake_server('{"title": "track_live", "description": "Follow it."}') + try: + client = LLMClient(base_url=base, model="test", timeout=10) + out = client.chat([{"role": "user", "content": "name this"}]) + assert out == '{"title": "track_live", "description": "Follow it."}' + assert httpd.RequestHandlerClass.received[0]["model"] == "test" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_generate_category_via_provider(): + httpd, base = _fake_server( + '{"title": "Track Delivery", "description": "Track parcels end to end."}' + ) + try: + client = LLMClient(base_url=base, model="test", timeout=10) + draft = generate_category( + client, Request("where is my parcel?"), build_tree(build_skills({"skills": {}})) + ) + assert isinstance(draft, CategoryDraft) + assert draft.name == "track_delivery" + assert draft.description == "Track parcels end to end." + finally: + httpd.shutdown() + httpd.server_close() + + +def test_generate_skill_via_provider(): + httpd, base = _fake_server( + '{"title": "track.live", "description": "Follow a package in real time."}' + ) + try: + client = LLMClient(base_url=base, model="test", timeout=10) + draft = generate_skill( + client, + Request("track my drone delivery"), + "tracking", + build_tree(build_skills({"skills": {}})), + ) + assert isinstance(draft, SkillDraft) + assert draft.name == "track.live" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_unreachable_endpoint_raises_llm_error(): + client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2) + with pytest.raises(LLMError): + client.chat([{"role": "user", "content": "hi"}]) diff --git a/tests/test_skills.py b/tests/test_skills.py index ccd0a26..b43b5c8 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -19,12 +19,11 @@ import pytest from semif_agent.cli import REPO_ROOT, load_config from semif_agent.codegen import CodegenClient from semif_agent.decisions import Request -from semif_agent.engine import EngineConfig, EngineUnavailable, SemIfEngine -from semif_agent.llm import LLMClient +from semif_agent.engine import EngineConfig, SemIfEngine +from semif_agent.llm import LLMClient, LLMError from semif_agent.log import DecisionLog from semif_agent.skill import RunResult from semif_agent.scheduler import ( - DispatchResult, PendingQuestion, RepairOffer, Scheduler, @@ -280,16 +279,10 @@ def test_category_registry_roundtrip(tmp_path): assert loaded["delivery"]["skills"] == [] -def test_generate_category_without_engine_raises(): - engine = SemIfEngine(EngineConfig()) - with pytest.raises(EngineUnavailable): - generate_category(engine, Request("anything"), {}) - - -def test_generate_without_engine_raises(): - engine = SemIfEngine(EngineConfig()) - with pytest.raises(EngineUnavailable): - engine.generate([{"role": "user", "content": "hi"}]) +def test_generate_category_without_endpoint_raises(): + client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2) + with pytest.raises(LLMError): + generate_category(client, Request("anything"), {}) def test_build_tree_includes_registry_stubs(tmp_path): @@ -359,10 +352,10 @@ def test_parse_skill_draft_rejects_unclean_title(): parse_skill_draft('{"title": "ca$h!", "description": "nope"}') -def test_generate_skill_without_engine_raises(): - engine = SemIfEngine(EngineConfig()) - with pytest.raises(EngineUnavailable): - generate_skill(engine, Request("anything"), "tracking", {}) +def test_generate_skill_without_endpoint_raises(): + client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2) + with pytest.raises(LLMError): + generate_skill(client, Request("anything"), "tracking", {}) def test_category_registry_register_skill(tmp_path): @@ -796,12 +789,14 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path): scheduler.tree["simplex"] = [ Skill(name="next_message", category="simplex", description="Read the next SimpleX message."), ] - scheduler._create_skill = lambda request, category: DispatchResult( - kind="create_skill", summary="authoring requested", skill="send_message" + queued: list = [] + scheduler._queue_draft = lambda request, category, kind, weight: queued.append( + (category, kind) ) request = Request("send a simplex message to pepper") result = scheduler._dispatch(request) assert result.kind == "create_skill" + assert queued == [("simplex", "skill")] phases = [r["extra"].get("phase") for r in scheduler.log.read()] assert "navigate:intent" in phases @@ -832,14 +827,15 @@ def test_dispatch_intent_match_runs_skill(tmp_path): -def test_dispatch_create_category_without_engine_is_fatal(tmp_path): - """An empty tree short-circuits to CreateCategory; without an engine the - category authoring is fatal — the app is marked and the caller stops.""" +def test_dispatch_create_category_queues_draft_and_is_not_fatal(tmp_path): + """An empty tree short-circuits to CreateCategory; the `llm` draft is + queued asynchronously. An unreachable llm endpoint is graceful — traced and + the request is not re-dispatched — never fatal (only SemIf is fatal).""" log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) scheduler = Scheduler( engine=SemIfEngine(EngineConfig()), - llm=LLMClient(base_url="http://localhost:1/v1", model="test"), + llm=LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2), log=log, config={ "skills": {}, @@ -850,10 +846,16 @@ def test_dispatch_create_category_without_engine_is_fatal(tmp_path): trace=trace, ) scheduler.tree = {} - with pytest.raises(EngineUnavailable): - scheduler._dispatch(Request("anything")) - assert scheduler.fatal is not None - assert "not available" in scheduler.fatal + result = scheduler._dispatch(Request("anything")) + assert result.kind == "create_category" + assert scheduler.fatal is None + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if any(e["kind"] == "draft_failed" for e in trace.read()): + break + time.sleep(0.02) + assert any(e["kind"] == "draft_failed" for e in trace.read()) + assert scheduler.fatal is None def test_skill_status_reflects_writing_and_noop(): @@ -1077,20 +1079,34 @@ def test_unresolved_variables_respects_tiered_config(tmp_path): assert unresolved_variables(store, skill2, {}) == ["sender_address", "tag"] assert unresolved_variables(store, skill2, {}, answered={"tag": "per-fire"}) == ["sender_address"] -def test_elicit_requirements_asks_and_records(tmp_path): - """Opt-in elicitation asks the product owner refinement questions before - the body is written and rides the answers on the draft into the body prompt.""" +def test_deferred_elicitation_asks_and_records(tmp_path): + """Opt-in elicitation runs on the codegen worker (deferred): questions are + posted to the question queue, the worker waits, and the answers ride the + draft into the body prompt.""" httpd, base = _pipeline_codegen_server( ['{"questions": ["Draft or send?"]}', GOOD_BODY, "{}", GOOD_TEST] ) try: scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10)) + scheduler.defer_questions = True scheduler.elicitation_enabled = True - answers = [] - scheduler.asker = lambda q: (answers.append(q), "draft first")[1] + request = Request("track my package") draft = SkillDraft(name="track_live", description="Follow a package.") - scheduler._elicit_requirements(Request("track my package"), "tracking", draft) - assert answers == ["Draft or send?"] + job = SkillWrite(request=request, category="tracking", draft=draft, weight=0.5) + + def answerer() -> None: + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + pending = scheduler.pending_questions() + if pending: + scheduler.answer_question(pending[0]["id"], "draft first") + return + time.sleep(0.02) + + thread = threading.Thread(target=answerer) + thread.start() + scheduler._deferred_elicit(job, scheduler.tree) + thread.join() assert draft.requirements == {"Draft or send?": "draft first"} assert any(e["kind"] == "requirements" for e in scheduler.trace.read()) finally: @@ -1098,40 +1114,6 @@ def test_elicit_requirements_asks_and_records(tmp_path): httpd.server_close() -def test_elicit_requirements_disabled_skips(tmp_path): - httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_TEST]) - try: - scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10)) - scheduler.elicitation_enabled = False - scheduler.asker = lambda q: "answer" - draft = SkillDraft(name="track_live", description="Follow a package.") - scheduler._elicit_requirements(Request("track my package"), "tracking", draft) - assert draft.requirements == {} - assert httpd.RequestHandlerClass.chat_calls == 0 - finally: - httpd.shutdown() - httpd.server_close() - - -def test_elicit_requirements_asker_none_stops(tmp_path): - """An asker that stops answering (None) halts collection without error.""" - httpd, base = _pipeline_codegen_server( - ['{"questions": ["A?", "B?"]}', GOOD_BODY, "{}", GOOD_TEST] - ) - try: - scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10)) - scheduler.elicitation_enabled = True - asked = [] - scheduler.asker = lambda q: (asked.append(q), None)[1] - draft = SkillDraft(name="track_live", description="Follow a package.") - scheduler._elicit_requirements(Request("track my package"), "tracking", draft) - assert asked == ["A?"] - assert draft.requirements == {} - finally: - httpd.shutdown() - httpd.server_close() - - def test_async_skill_write_regen_ladder_on_failing_test(tmp_path): """A failing auto-run test triggers the regen decision (regen_test by default when no factory), regenerating the test until it passes."""