Make provider sampler params opt-in; drop escalation preset
Sampler parameters (temperature/top_p/presence_penalty/frequency_penalty) now default to None and are omitted from the request payload when unset, so the server's model/Modelfile default applies. The provider no longer guesses values on the user's behalf; callers opt in via config or a per-chat override. - provider.OpenAICompatClient / llm.LLMClient: default the four params to None and only include them in the payload when set (max_tokens/reasoning_effort already behaved this way). - cli.build_scheduler: pass None when the config key is absent via _opt_float, instead of hardcoded numeric fallbacks. - codegen: remove ESCALATED_SAMPLER and its use on retries (body, elicitation, testgen, regen). The retry ladder keeps the fresh short prompt but reuses the configured/omitted sampler; appropriate values can't be known in advance for arbitrary user models. - console: no functional change; the hosted Console API now receives no sampler params by default. - Tests cover omit-by-default, send-when-configured, per-call override, and the no-escalation retry. - Docs: config.example.json comments, provider/llm/codegen/console docstrings, AGENTS.md.
This commit is contained in:
1 parent
8afb488dc4
commit
5747ad2fa6
11 files changed
+223
-105
No files matched your search
@@ -601,8 +601,9 @@ CLI, unit tests (24) + box integration tests (2).
|
||||
the free models, …), and give `api_key` (literal) or `api_key_env` (env var
|
||||
name — preferred). `build_scheduler` maps `"opencode"` → `ConsoleLLMClient` /
|
||||
`ConsoleCodegenClient`, which keep the existing error contracts
|
||||
(`LLMError` / `CodegenError` / `DegenerationError`) and the same sampler
|
||||
defaults. The `OpenAICompatClient` transport already speaks the Console's SSE
|
||||
(`LLMError` / `CodegenError` / `DegenerationError`) and the same opt-in
|
||||
sampler behavior (none sent unless configured). The `OpenAICompatClient`
|
||||
transport already speaks the Console's SSE
|
||||
shape (`delta.content` + `delta.reasoning_content` + `include_usage` +
|
||||
`[DONE]`); the Console subclass adds bearer auth, defaults the base URL to
|
||||
`https://opencode.ai/inference/openai/v1`, and sets `query_context=False` so no
|
||||
@@ -799,21 +800,21 @@ CLI, unit tests (24) + box integration tests (2).
|
||||
total wall-clock `timeout` is enforced while the stream is live (a
|
||||
continuously-streaming runaway is cut off), not only during idle gaps. The
|
||||
budget is a safety net, not the loop cure: qwen38-iq3s's reasoning routinely
|
||||
exceeds even the relaxed cap before it settles on a body, which is why the
|
||||
sampler (below) is the real fix.
|
||||
- **Sampler params + escalation.** `codegen.temperature` (default 0.7),
|
||||
`top_p` (0.85), `presence_penalty` (1.5), `frequency_penalty` (0.2) are the
|
||||
Qwen3.8 model card's instruct-mode preset used as an anti-repetition sampler,
|
||||
not to toggle reasoning — a high `presence_penalty`, not greedy temperature,
|
||||
is the loop cure, and the model's thinking-mode preset
|
||||
(`presence_penalty=0.0`) is exactly what it loops under. Those four are
|
||||
the only sampler knobs reachable via ollama's OpenAI-compat API;
|
||||
`repeat_penalty`/`min_p`/`top_k` are Modelfile-only, so the per-request
|
||||
`presence_penalty` (which overrides the Modelfile) is what actually stops the
|
||||
loop and no Modelfile edit is needed. A rejected body retries with the
|
||||
escalated sampler (presence 2.0 / temp 0.5) and a fresh short prompt that
|
||||
resets the context to SMART; `max_attempts` (default 3) bounds the ladder,
|
||||
then a graceful stub. Degeneration does **not** retry: the watchdog raises
|
||||
exceeds even the relaxed cap before it settles on a body.
|
||||
- **Sampler params (opt-in).** `temperature`/`top_p`/`presence_penalty`/
|
||||
`frequency_penalty` are **not sent by default**: a `None`/absent value is
|
||||
omitted from the request so the server's model/Modelfile default applies. The
|
||||
provider never guesses a value for the user — set one in the `llm`/`codegen`
|
||||
config block (or per `chat` call) only when you know the right value for the
|
||||
model. `config.example.json` ships explicit values as a starting point, so a
|
||||
provisioned box still sends them. When configured, a high `presence_penalty`
|
||||
(not greedy temperature) is the anti-repetition loop cure for qwen38-iq3s, and
|
||||
those four are the only sampler knobs reachable via ollama's OpenAI-compat
|
||||
API (`repeat_penalty`/`min_p`/`top_k` are Modelfile-only). There is **no
|
||||
escalated preset**: a rejected body retries with a fresh short prompt that
|
||||
resets the context to SMART and reuses the same (configured or omitted)
|
||||
sampler params; `max_attempts` (default 3) bounds the ladder, then a graceful
|
||||
stub. Degeneration does **not** retry: the watchdog raises
|
||||
`DegenerationError(CodegenError)`, which propagates straight to the graceful
|
||||
stub (retry-on-degeneration is left as an open decision).
|
||||
- **Degeneration watchdog.** `codegen.degeneration.{enabled, threshold=0.9,
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@
|
||||
"threads": 8
|
||||
},
|
||||
"llm": {
|
||||
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap 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. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).",
|
||||
"_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. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).",
|
||||
"provider": "ollama",
|
||||
"base_url": "http://localhost:11434/v1",
|
||||
"model": "qwen3.5:4b",
|
||||
@@ -41,7 +41,7 @@
|
||||
"disable_thinking": true
|
||||
},
|
||||
"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 title/description 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<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty follow the Qwen3.8 model card's instruct-mode anti-repetition guidance (high presence_penalty, not greedy temperature); generate_skill_body escalates to presence 2.0 / temp 0.5 on retries (max_attempts attempts, fresh short prompt each time). elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
|
||||
"_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 title/description 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<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
|
||||
"provider": "ollama",
|
||||
"base_url": "http://localhost:11434/v1",
|
||||
"model": "qwen38-iq3s",
|
||||
|
||||
+18
-8
@@ -66,6 +66,16 @@ def _resolve_api_key(cfg: dict) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _opt_float(value) -> float | None:
|
||||
"""Config number for an opt-in provider parameter.
|
||||
|
||||
A missing/`null` key yields `None`, which the provider omits from the
|
||||
request so the server's model default applies. A present value is coerced
|
||||
to `float`.
|
||||
"""
|
||||
return None if value is None else float(value)
|
||||
|
||||
|
||||
def _provider_endpoint(cfg: dict, default_base: str) -> dict:
|
||||
"""Endpoint kwargs shared by the llm/codegen clients.
|
||||
|
||||
@@ -123,10 +133,10 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
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)),
|
||||
temperature=_opt_float(llm_cfg.get("temperature")),
|
||||
top_p=_opt_float(llm_cfg.get("top_p")),
|
||||
presence_penalty=_opt_float(llm_cfg.get("presence_penalty")),
|
||||
frequency_penalty=_opt_float(llm_cfg.get("frequency_penalty")),
|
||||
disable_thinking=bool(llm_cfg.get("disable_thinking", True)),
|
||||
api_key=llm_endpoint["api_key"],
|
||||
extra_headers=llm_endpoint["extra_headers"],
|
||||
@@ -161,10 +171,10 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
degeneration_interval=int(deg_cfg.get("interval", 8000)),
|
||||
degeneration_window=int(deg_cfg.get("window", 2000)),
|
||||
degeneration_min_chars=int(deg_cfg.get("min_chars", 4000)),
|
||||
temperature=float(codegen_cfg.get("temperature", 0.7)),
|
||||
top_p=float(codegen_cfg.get("top_p", 0.85)),
|
||||
presence_penalty=float(codegen_cfg.get("presence_penalty", 1.5)),
|
||||
frequency_penalty=float(codegen_cfg.get("frequency_penalty", 0.2)),
|
||||
temperature=_opt_float(codegen_cfg.get("temperature")),
|
||||
top_p=_opt_float(codegen_cfg.get("top_p")),
|
||||
presence_penalty=_opt_float(codegen_cfg.get("presence_penalty")),
|
||||
frequency_penalty=_opt_float(codegen_cfg.get("frequency_penalty")),
|
||||
max_attempts=int(codegen_cfg.get("max_attempts", 3)),
|
||||
api_key=codegen_endpoint["api_key"],
|
||||
extra_headers=codegen_endpoint["extra_headers"],
|
||||
|
||||
+14
-33
@@ -479,14 +479,6 @@ def integration_findings(integration: dict, source: str, code: str) -> list[str]
|
||||
return findings
|
||||
|
||||
|
||||
ESCALATED_SAMPLER = {
|
||||
"temperature": 0.5,
|
||||
"top_p": 0.85,
|
||||
"presence_penalty": 2.0,
|
||||
"frequency_penalty": 0.3,
|
||||
}
|
||||
|
||||
|
||||
def _retry_prompt(
|
||||
request: Request,
|
||||
category: str,
|
||||
@@ -495,7 +487,7 @@ def _retry_prompt(
|
||||
error: Exception,
|
||||
requirements: dict[str, str] | None = None,
|
||||
) -> list[dict]:
|
||||
"""Fresh short prompt for an escalated retry.
|
||||
"""Fresh short prompt for a corrective retry.
|
||||
|
||||
Not a growing conversation: the context resets to SMART (new request, tiny
|
||||
prompt) and the model is told in one line to stop looping and emit the
|
||||
@@ -538,16 +530,15 @@ def generate_skill_body(
|
||||
degeneration_check: Callable[[str], str | None] | None = None,
|
||||
requirements: dict[str, str] | None = None,
|
||||
) -> str:
|
||||
"""Author a skill body with the big model; escalate up to `max_attempts`.
|
||||
"""Author a skill body with the big model; retry up to `max_attempts`.
|
||||
|
||||
Attempt 1 uses the client's sampler defaults. Attempts >= 2 use the
|
||||
escalated sampler (higher presence_penalty to suppress repeated thinking,
|
||||
lower temperature for a decisive final answer) plus a fresh short prompt
|
||||
that resets the context to SMART and tells the model to emit the final
|
||||
Python now. Only an invalid parse (ValueError) escalates; a
|
||||
DegenerationError or other CodegenError propagates immediately so the
|
||||
scheduler can stub out gracefully. `requirements` (elicitation answers) are
|
||||
fed to the first-attempt prompt only.
|
||||
Every attempt uses the client's configured sampler parameters (or omits
|
||||
them when unset). A rejected parse (ValueError) retries with a fresh short
|
||||
prompt that resets the context to SMART and tells the model to emit the
|
||||
final Python now. Only an invalid parse retries; a DegenerationError or
|
||||
other CodegenError propagates immediately so the scheduler can stub out
|
||||
gracefully. `requirements` (elicitation answers) are fed to the
|
||||
first-attempt prompt only.
|
||||
"""
|
||||
contract_text = contract if contract is not None else read_skill_contract()
|
||||
if client.stream:
|
||||
@@ -573,7 +564,6 @@ def generate_skill_body(
|
||||
messages,
|
||||
max_tokens=max_tokens,
|
||||
degeneration_check=degeneration_check,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
return parse_skill_body(raw)
|
||||
except ValueError as exc:
|
||||
@@ -734,7 +724,7 @@ def generate_elicitation(
|
||||
"""Propose implementation questions + an integration hint with the big model.
|
||||
|
||||
Returns an empty result when the model produced none or the reply failed to
|
||||
parse after the escalation ladder — elicitation must never block authoring.
|
||||
parse after the retry ladder — elicitation must never block authoring.
|
||||
"""
|
||||
attempts = max(client.max_attempts, 1)
|
||||
last_error: Exception | None = None
|
||||
@@ -748,10 +738,7 @@ def generate_elicitation(
|
||||
request, category, draft, tree, last_error, max_questions=max_questions
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
raw = client.chat(messages)
|
||||
result = parse_elicitation_result(raw)
|
||||
return ElicitationResult(
|
||||
result.questions[: max(0, max_questions)], result.integration
|
||||
@@ -977,10 +964,7 @@ def generate_skill_tests(
|
||||
target=target,
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
raw = client.chat(messages)
|
||||
return parse_skill_test(raw)
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
@@ -1058,7 +1042,7 @@ def regenerate_skill_body(
|
||||
"""Rewrite a skill body whose test, review, or real run failed.
|
||||
|
||||
Fresh prompt (context resets) carrying the raw evidence bundle and the
|
||||
previous body; escalation ladder identical to generate_skill_body.
|
||||
previous body; retry ladder identical to generate_skill_body.
|
||||
`reason_kind` labels the corrective context (`test`, `fidelity`, or
|
||||
`run_failure`). The bundle is handed through as-is — the caller includes
|
||||
requirements and the raw failure fields, never a paraphrase. A
|
||||
@@ -1076,10 +1060,7 @@ def regenerate_skill_body(
|
||||
attempt_evidence, reason_kind=reason_kind,
|
||||
)
|
||||
try:
|
||||
raw = client.chat(
|
||||
messages,
|
||||
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||
)
|
||||
raw = client.chat(messages)
|
||||
return parse_skill_body(raw)
|
||||
except ValueError as exc:
|
||||
last_error = exc
|
||||
|
||||
@@ -47,7 +47,8 @@ class OpenCodeConsoleClient(OpenAICompatClient):
|
||||
Pins the Console defaults: bearer auth, the Console base URL, a Console
|
||||
label, and ``query_context = False`` (no ollama ``/api/show`` probe). The
|
||||
endpoint subclasses below reuse it via cooperative multiple inheritance so
|
||||
they also keep ``LLMClient``/``CodegenClient`` sampler defaults.
|
||||
they also keep ``LLMClient``/``CodegenClient`` sampler parameters (opt-in:
|
||||
none are sent unless configured).
|
||||
|
||||
A default ``User-Agent`` is always sent: the Console gateway rejects
|
||||
urllib's default ``Python-urllib/<ver>`` with HTTP 403. Pass ``user_agent``
|
||||
@@ -91,9 +92,9 @@ class OpenCodeConsoleClient(OpenAICompatClient):
|
||||
class ConsoleLLMClient(OpenCodeConsoleClient, LLMClient):
|
||||
"""Console-backed `llm` author (skill/category title + description).
|
||||
|
||||
Same conservative sampler defaults as ``LLMClient``; the Console transport
|
||||
adds the bearer key and skips the ollama probe. Raises ``LLMError``
|
||||
(unchanged contract).
|
||||
Same opt-in sampler behavior as ``LLMClient`` (none sent unless configured);
|
||||
the Console transport adds the bearer key and skips the ollama probe. Raises
|
||||
``LLMError`` (unchanged contract).
|
||||
|
||||
``disable_thinking`` is forced **off**: `LLMClient` sends
|
||||
``reasoning_effort: "none"`` (an ollama-compat knob) and the Console
|
||||
|
||||
+11
-9
@@ -5,8 +5,8 @@ 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.
|
||||
model, sampler parameters, and error type. `_parse_json` is also borrowed by
|
||||
the authoring parsers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,9 +23,11 @@ class LLMError(ProviderError):
|
||||
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`.
|
||||
Short JSON replies, so the timeout is modest and generation is single-shot.
|
||||
No sampler parameters are sent unless the `llm` block in `config.json` sets
|
||||
them: an unset `temperature`/`top_p`/`presence_penalty`/`frequency_penalty`
|
||||
is omitted so the server's model default applies. Every value is overridable
|
||||
from config.
|
||||
|
||||
`disable_thinking` defaults **on**: the small local model is often a
|
||||
reasoning model (e.g. `qwen3.5:4b`) whose hidden chain-of-thought consumes
|
||||
@@ -57,10 +59,10 @@ class LLMClient(OpenAICompatClient):
|
||||
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,
|
||||
temperature: float | None = None,
|
||||
top_p: float | None = None,
|
||||
presence_penalty: float | None = None,
|
||||
frequency_penalty: float | None = None,
|
||||
disable_thinking: bool = True,
|
||||
api_key: str = "",
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
|
||||
+23
-18
@@ -4,9 +4,9 @@ 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.
|
||||
provider logic once; subclasses set `base_url`/`model`, their sampler
|
||||
parameters, and the error classes they raise so existing callers keep catching
|
||||
their own types.
|
||||
|
||||
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
|
||||
@@ -49,7 +49,7 @@ class TokenBudget(NamedTuple):
|
||||
class OpenAICompatClient:
|
||||
"""OpenAI-compatible chat provider shared by the authoring clients.
|
||||
|
||||
Subclasses set `base_url`/`model` (and their sampler defaults) and the
|
||||
Subclasses set `base_url`/`model` (and their sampler parameters) 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.
|
||||
@@ -80,14 +80,13 @@ class OpenAICompatClient:
|
||||
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 are the Qwen3.8 card's instruct-mode preset
|
||||
(unsloth/Qwen3.8-27B-GGUF) used as an anti-repetition sampler, not to
|
||||
toggle reasoning: a high `presence_penalty` is the loop cure, while the
|
||||
prototype thinking-mode preset (`presence_penalty=0.0`) is what this
|
||||
codegen model loops under. `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).
|
||||
Sampler parameters are **opt-in**: `temperature`/`top_p`/
|
||||
`presence_penalty`/`frequency_penalty` default to `None` and a `None`
|
||||
parameter is omitted from the request payload entirely, so the server's
|
||||
model/Modelfile default applies. A caller that knows the right value for its
|
||||
model sets it (constructor or per-`chat` override); this provider never
|
||||
guesses a value on the user's behalf. `max_tokens` and `reasoning_effort`
|
||||
work the same way: sent only when explicitly set.
|
||||
|
||||
`disable_thinking` sends `reasoning_effort: "none"` so a reasoning model
|
||||
answers directly instead of spending the (short) reply budget on hidden
|
||||
@@ -129,10 +128,10 @@ class OpenAICompatClient:
|
||||
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,
|
||||
temperature: float | None = None,
|
||||
top_p: float | None = None,
|
||||
presence_penalty: float | None = None,
|
||||
frequency_penalty: float | None = None,
|
||||
max_attempts: int = 3,
|
||||
disable_thinking: bool = False,
|
||||
api_key: str = "",
|
||||
@@ -202,6 +201,13 @@ class OpenAICompatClient:
|
||||
payload: dict = {
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"stream": True,
|
||||
"stream_options": {"include_usage": True},
|
||||
}
|
||||
# Sampler parameters are opt-in: a per-call override wins, otherwise the
|
||||
# constructor value; a None value is omitted entirely so the server's
|
||||
# model/Modelfile default applies.
|
||||
sampler = {
|
||||
"temperature": self.temperature if temperature is None else temperature,
|
||||
"top_p": self.top_p if top_p is None else top_p,
|
||||
"presence_penalty": (
|
||||
@@ -210,9 +216,8 @@ class OpenAICompatClient:
|
||||
"frequency_penalty": (
|
||||
self.frequency_penalty if frequency_penalty is None else frequency_penalty
|
||||
),
|
||||
"stream": True,
|
||||
"stream_options": {"include_usage": True},
|
||||
}
|
||||
payload.update({k: v for k, v in sampler.items() if v is not None})
|
||||
if self.disable_thinking:
|
||||
payload["reasoning_effort"] = "none"
|
||||
if max_tokens is not None:
|
||||
|
||||
@@ -12,7 +12,7 @@ import time
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.cli import build_scheduler, load_config
|
||||
from semif_agent.cli import _opt_float, build_scheduler, load_config
|
||||
from semif_agent.codegen import (
|
||||
CodegenClient,
|
||||
generate_skill_body,
|
||||
@@ -306,6 +306,10 @@ def test_generate_skill_body_codegen(tmp_path):
|
||||
model=codegen_cfg.get("model", "qwen38-iq3s"),
|
||||
timeout=float(codegen_cfg.get("timeout", 1200.0)),
|
||||
stream=True,
|
||||
temperature=_opt_float(codegen_cfg.get("temperature")),
|
||||
top_p=_opt_float(codegen_cfg.get("top_p")),
|
||||
presence_penalty=_opt_float(codegen_cfg.get("presence_penalty")),
|
||||
frequency_penalty=_opt_float(codegen_cfg.get("frequency_penalty")),
|
||||
)
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(
|
||||
|
||||
+48
-10
@@ -1267,12 +1267,35 @@ def _sequenced_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
|
||||
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
|
||||
|
||||
|
||||
def test_chat_payload_carries_sampler_defaults():
|
||||
def test_chat_omits_sampler_params_by_default():
|
||||
"""Sampler parameters are opt-in: an unset value is never sent, so the
|
||||
server's model/Modelfile default applies."""
|
||||
httpd, base = _fake_server(GOOD_BODY)
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
client.chat([{"role": "user", "content": "hi"}])
|
||||
body = httpd.RequestHandlerClass.received[0]
|
||||
for key in ("temperature", "top_p", "presence_penalty", "frequency_penalty"):
|
||||
assert key not in body
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_chat_sends_configured_sampler_params():
|
||||
httpd, base = _fake_server(GOOD_BODY)
|
||||
try:
|
||||
client = CodegenClient(
|
||||
base_url=base,
|
||||
model="test",
|
||||
timeout=10,
|
||||
temperature=0.7,
|
||||
top_p=0.85,
|
||||
presence_penalty=1.5,
|
||||
frequency_penalty=0.2,
|
||||
)
|
||||
client.chat([{"role": "user", "content": "hi"}])
|
||||
body = httpd.RequestHandlerClass.received[0]
|
||||
assert body["temperature"] == 0.7
|
||||
assert body["top_p"] == 0.85
|
||||
assert body["presence_penalty"] == 1.5
|
||||
@@ -1282,9 +1305,22 @@ def test_chat_payload_carries_sampler_defaults():
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_skill_body_escalates_sampler_on_retry(tmp_path):
|
||||
"""An invalid first parse must retry with the escalated sampler and a fresh
|
||||
corrective prompt (context resets to SMART, no growing conversation)."""
|
||||
def test_chat_per_call_override_wins_over_client_default():
|
||||
httpd, base = _fake_server(GOOD_BODY)
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10, temperature=0.7)
|
||||
client.chat([{"role": "user", "content": "hi"}], temperature=0.1)
|
||||
body = httpd.RequestHandlerClass.received[0]
|
||||
assert body["temperature"] == 0.1
|
||||
assert "presence_penalty" not in body
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_generate_skill_body_retries_with_fresh_prompt(tmp_path):
|
||||
"""An invalid first parse must retry with a fresh corrective prompt (context
|
||||
resets to SMART, no growing conversation) and no sampler override."""
|
||||
httpd, base = _sequenced_server(["this is not python at all", GOOD_BODY])
|
||||
try:
|
||||
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||
@@ -1297,12 +1333,14 @@ def test_generate_skill_body_escalates_sampler_on_retry(tmp_path):
|
||||
reqs = httpd.RequestHandlerClass.received
|
||||
assert len(reqs) == 2, "one retry after the rejected first attempt"
|
||||
first, second = reqs
|
||||
assert first["temperature"] == 0.7
|
||||
assert first["presence_penalty"] == 1.5
|
||||
assert second["temperature"] == 0.5
|
||||
assert second["top_p"] == 0.85
|
||||
assert second["presence_penalty"] == 2.0
|
||||
assert second["frequency_penalty"] == 0.3
|
||||
for body in (first, second):
|
||||
for key in (
|
||||
"temperature",
|
||||
"top_p",
|
||||
"presence_penalty",
|
||||
"frequency_penalty",
|
||||
):
|
||||
assert key not in body
|
||||
retry_user = second["messages"][1]["content"]
|
||||
assert "You are looping" in retry_user
|
||||
assert "probe" in retry_user
|
||||
|
||||
+41
-3
@@ -33,6 +33,7 @@ class _FakeConsole(BaseHTTPRequestHandler):
|
||||
reply: str = "{}"
|
||||
models: list = ["kimi-k2.7-code", "glm-5.3"]
|
||||
calls: list = []
|
||||
bodies: list = []
|
||||
|
||||
def _record(self) -> None:
|
||||
type(self).calls.append(
|
||||
@@ -52,7 +53,11 @@ class _FakeConsole(BaseHTTPRequestHandler):
|
||||
|
||||
def do_POST(self) -> None:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.rfile.read(length)
|
||||
raw = self.rfile.read(length)
|
||||
try:
|
||||
type(self).bodies.append(json.loads(raw.decode("utf-8")))
|
||||
except ValueError:
|
||||
pass
|
||||
self._record()
|
||||
body = (
|
||||
_sse_frame({"choices": [{"delta": {"content": self.reply}}]})
|
||||
@@ -69,7 +74,7 @@ class _FakeConsole(BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def _server(reply: str = "{}", models: list | None = None):
|
||||
attrs = {"reply": reply, "calls": []}
|
||||
attrs = {"reply": reply, "calls": [], "bodies": []}
|
||||
if models is not None:
|
||||
attrs["models"] = models
|
||||
handler = type("Handler", (_FakeConsole,), attrs)
|
||||
@@ -101,7 +106,8 @@ def test_console_codegen_pins_defaults_and_error_contract():
|
||||
assert client.error_class is CodegenError
|
||||
assert client.degeneration_error_class is DegenerationError
|
||||
assert client.query_context is False
|
||||
assert client.presence_penalty == 1.5 # CodegenClient sampler default preserved
|
||||
# Sampler params are opt-in: unset means None, never sent to the Console.
|
||||
assert client.presence_penalty is None
|
||||
|
||||
|
||||
def test_console_error_is_provider_error():
|
||||
@@ -123,6 +129,38 @@ def test_chat_sends_bearer_and_skips_ollama_probe():
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_console_chat_omits_sampler_params_by_default():
|
||||
httpd, base = _server(reply="{}")
|
||||
try:
|
||||
ConsoleLLMClient(base_url=base, api_key="k", model="m", timeout=10).chat(
|
||||
[{"role": "user", "content": "hi"}]
|
||||
)
|
||||
body = httpd.RequestHandlerClass.bodies[0]
|
||||
for key in ("temperature", "top_p", "presence_penalty", "frequency_penalty"):
|
||||
assert key not in body
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_console_chat_sends_configured_sampler_params():
|
||||
httpd, base = _server(reply="{}")
|
||||
try:
|
||||
ConsoleCodegenClient(
|
||||
base_url=base,
|
||||
api_key="k",
|
||||
model="m",
|
||||
timeout=10,
|
||||
presence_penalty=1.5,
|
||||
).chat([{"role": "user", "content": "hi"}])
|
||||
body = httpd.RequestHandlerClass.bodies[0]
|
||||
assert body["presence_penalty"] == 1.5
|
||||
assert "temperature" not in body
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_plain_llm_without_key_sends_no_auth_header():
|
||||
httpd, base = _server(reply="{}")
|
||||
try:
|
||||
|
||||
@@ -123,6 +123,44 @@ def test_generate_skill_via_provider():
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_llm_omits_sampler_params_by_default():
|
||||
"""No sampler params are sent unless the `llm` config sets them, so the
|
||||
server's model default applies."""
|
||||
httpd, base = _fake_server('{"title": "x", "description": "y"}')
|
||||
try:
|
||||
LLMClient(base_url=base, model="test", timeout=10).chat(
|
||||
[{"role": "user", "content": "name this"}]
|
||||
)
|
||||
body = httpd.RequestHandlerClass.received[0]
|
||||
for key in ("temperature", "top_p", "presence_penalty", "frequency_penalty"):
|
||||
assert key not in body
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_llm_sends_configured_sampler_params():
|
||||
httpd, base = _fake_server('{"title": "x", "description": "y"}')
|
||||
try:
|
||||
LLMClient(
|
||||
base_url=base,
|
||||
model="test",
|
||||
timeout=10,
|
||||
temperature=0.2,
|
||||
top_p=0.9,
|
||||
presence_penalty=0.0,
|
||||
frequency_penalty=0.0,
|
||||
).chat([{"role": "user", "content": "name this"}])
|
||||
body = httpd.RequestHandlerClass.received[0]
|
||||
assert body["temperature"] == 0.2
|
||||
assert body["top_p"] == 0.9
|
||||
assert body["presence_penalty"] == 0.0
|
||||
assert body["frequency_penalty"] == 0.0
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_llm_disables_thinking_by_default():
|
||||
"""The title/description author sends reasoning_effort:none so a reasoning
|
||||
model answers the short JSON directly (its CoT otherwise eats the 128-token
|
||||
|
||||
Reference in new issue
Block a user