ship codegen sampler params + escalation ladder per Qwen3.8 card
CodegenClient now sends temperature/top_p/presence_penalty/frequency_penalty (card-endorsed high presence_penalty, temp 0.7 instead of greedy 0.0) and generate_skill_body escalates on invalid parse with an escalated sampler (temp 0.5/presence 2.0) and a fresh short corrective prompt, up to max_attempts. Degeneration aborts are a distinct DegenerationError(CodegenError) that propagates without retry; retry-on-degeneration is left open. Marks guardrail items 5/6 per the model card.
This commit is contained in:
1 parent
7c5cd2b685
commit
d18f0ccdb6
5 files changed
+363
-38
No files matched your search
@@ -238,10 +238,12 @@ unit tests (24) + box integration tests (2).
|
|||||||
|
|
||||||
Context learned 2026-09-24 on the box: qwen38-iq3s looped ~40 min on one skill
|
Context learned 2026-09-24 on the box: qwen38-iq3s looped ~40 min on one skill
|
||||||
body (1.5 MB streamed) with no guard firing. Root causes: (1) `CodegenClient`
|
body (1.5 MB streamed) with no guard firing. Root causes: (1) `CodegenClient`
|
||||||
sends `temperature 0.0` (greedy) and no penalties while the Modelfile has
|
sent `temperature 0.0` (greedy) and no penalties while the Modelfile has
|
||||||
`repeat_penalty 1` (off) + `presence_penalty 0`; (2) the total `timeout` check
|
`repeat_penalty 1` (off) + `presence_penalty 0` (now fixed: item 5 ships the
|
||||||
only runs inside the `if not ready:` branch of `_read_stream`, so a
|
card-endorsed high `presence_penalty` per-request); (2) the total `timeout`
|
||||||
continuously-streaming runaway never trips it. Known model facts: qwen38-iq3s
|
check only runs inside the `if not ready:` branch of `_read_stream`, so a
|
||||||
|
continuously-streaming runaway never trips it (fixed in item 1). Known model
|
||||||
|
facts: qwen38-iq3s
|
||||||
runtime window `num_ctx=100000` (native `qwen35.context_length=262144`);
|
runtime window `num_ctx=100000` (native `qwen35.context_length=262144`);
|
||||||
ollama OpenAI-compat `/v1/chat/completions` supports `temperature`, `top_p`,
|
ollama OpenAI-compat `/v1/chat/completions` supports `temperature`, `top_p`,
|
||||||
`presence_penalty`, `frequency_penalty`, `max_tokens`, `reasoning_effort`, and
|
`presence_penalty`, `frequency_penalty`, `max_tokens`, `reasoning_effort`, and
|
||||||
@@ -334,22 +336,41 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget
|
|||||||
verification pending**: run the codegen integration tests and watch the
|
verification pending**: run the codegen integration tests and watch the
|
||||||
`codegen` trace events + an abort fire on a real degenerating stream.
|
`codegen` trace events + an abort fire on a real degenerating stream.
|
||||||
|
|
||||||
- [ ] **5. Sampler params + 3-attempt escalation ladder** (`codegen.py`, `cli.py`)
|
- [x] **5. Sampler params + 3-attempt escalation ladder** (`codegen.py`, `cli.py`)
|
||||||
- Send `temperature`/`top_p`/`presence_penalty`/`frequency_penalty`
|
- Send `temperature`/`top_p`/`presence_penalty`/`frequency_penalty`.
|
||||||
(defaults `0.15`/`0.95`/`0.1`/`0.2`).
|
- `generate_skill_body` escalates on invalid parse: attempts 2–3 use the
|
||||||
- `generate_skill_body` escalates on degeneration or invalid parse:
|
escalated sampler + a corrective message ("You are looping; emit the final
|
||||||
attempts 2–3 use `temp 0.3 / presence 0.3 / freq 0.5` + a corrective
|
Python now."). Max 3 attempts (config `max_attempts`), then graceful stub.
|
||||||
message ("You are looping; emit the final Python now."). Max 3 attempts
|
Retry = fresh short prompt, i.e. context resets to SMART.
|
||||||
(config `max_attempts`), then graceful stub. Retry = fresh short prompt,
|
|
||||||
i.e. context resets to SMART.
|
|
||||||
- Tests: payload carries the params; retry uses escalated params.
|
- Tests: payload carries the params; retry uses escalated params.
|
||||||
|
- **Revised values after reading the Qwen3.8-27B model card
|
||||||
|
(unsloth/Qwen3.8-27B-GGUF, 2026-09-24):** the original spec (`temp 0.15 /
|
||||||
|
presence 0.1 / freq 0.2`) kept the model nearly greedy with a near-zero
|
||||||
|
presence penalty — the exact loop recipe already documented on the box.
|
||||||
|
The card's anti-repetition guidance is a HIGH `presence_penalty` ("adjust
|
||||||
|
between 0 and 2 to reduce endless repetition"), recommended
|
||||||
|
`temp 0.7 / top_p 0.80 / presence 1.5` in instruct mode. Implemented
|
||||||
|
defaults: `temperature 0.7, top_p 0.85, presence_penalty 1.5,
|
||||||
|
frequency_penalty 0.2`; escalated (attempts 2+): `temp 0.5, top_p 0.85,
|
||||||
|
presence_penalty 2.0, frequency_penalty 0.3`. `top_k`/`min_p`/`repeat_penalty`
|
||||||
|
from the card are NOT reachable via ollama OpenAI-compat, so they stay
|
||||||
|
unset. **Degeneration does NOT retry**: the item-4 watchdog raises a new
|
||||||
|
`DegenerationError(CodegenError)` subclass that propagates straight to the
|
||||||
|
scheduler's graceful-stub path — retry-on-degeneration is left as an open
|
||||||
|
decision. Unit-tested on the dev machine (payload defaults, escalated retry
|
||||||
|
payload + corrective prompt, max_attempts exhaustion, degeneration and
|
||||||
|
token-budget errors propagate without retry). **Box verification pending**:
|
||||||
|
confirm qwen38-iq3s converges faster / aborts via `codegen` trace events.
|
||||||
|
|
||||||
- [ ] **6. Box Modelfile anti-loop levers** (guppy; infra, not a code change)
|
- [ ] **6. Box Modelfile anti-loop levers** (guppy; infra, not a code change)
|
||||||
- `repeat_penalty`/`min_p` are not reachable via OpenAI-compat, so set them
|
- **Superseded by item 5.** The model card calls for `repetition_penalty 1.0`
|
||||||
server-side: edit the qwen38-iq3s Modelfile to `PARAMETER repeat_penalty 1.2`
|
(off) and `min_p 0.0` — the original `repeat_penalty 1.2 / min_p 0.05`
|
||||||
and `PARAMETER min_p 0.05`, then `ollama create qwen38-iq3s -f ...`.
|
plan contradicts it. The card-endorsed cure (high `presence_penalty`,
|
||||||
- Verify: `ollama show --modelfile qwen38-iq3s` shows the params; re-run
|
reachable per-request via OpenAI-compat) is already shipped in item 5, so
|
||||||
`test_generate_skill_body_codegen` and
|
no Modelfile edit is needed. Left as `[ ]` only for a box sanity check:
|
||||||
|
`ollama show --modelfile qwen38-iq3s` still shows `repeat_penalty 1` /
|
||||||
|
`presence_penalty 0`; confirm the per-request values override them, then
|
||||||
|
re-run `test_generate_skill_body_codegen` and
|
||||||
`test_create_category_chain_runs_new_skill`; confirm no long loop.
|
`test_create_category_chain_runs_new_skill`; confirm no long loop.
|
||||||
|
|
||||||
- [ ] **7. SKILL.md auditability** (`codegen.py`, `scheduler.py`, `static/app.js`)
|
- [ ] **7. SKILL.md auditability** (`codegen.py`, `scheduler.py`, `static/app.js`)
|
||||||
|
|||||||
+6
-1
@@ -13,7 +13,7 @@
|
|||||||
},
|
},
|
||||||
"llm": {"base_url": "http://localhost:11434/v1", "model": "qwen3.5:4b"},
|
"llm": {"base_url": "http://localhost:11434/v1", "model": "qwen3.5:4b"},
|
||||||
"codegen": {
|
"codegen": {
|
||||||
"_comment": "OpenAI-compatible model that writes runnable skill bodies. 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<x<1 fraction of window); chars_per_token converts chars to the token estimate.",
|
"_comment": "OpenAI-compatible model that writes runnable skill bodies. 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<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).",
|
||||||
"base_url": "http://localhost:11434/v1",
|
"base_url": "http://localhost:11434/v1",
|
||||||
"model": "qwen38-iq3s",
|
"model": "qwen38-iq3s",
|
||||||
"timeout": 1200,
|
"timeout": 1200,
|
||||||
@@ -27,6 +27,11 @@
|
|||||||
"warn_fill_ratio": 0.7,
|
"warn_fill_ratio": 0.7,
|
||||||
"max_output": 0.85,
|
"max_output": 0.85,
|
||||||
"chars_per_token": 4.0,
|
"chars_per_token": 4.0,
|
||||||
|
"temperature": 0.7,
|
||||||
|
"top_p": 0.85,
|
||||||
|
"presence_penalty": 1.5,
|
||||||
|
"frequency_penalty": 0.2,
|
||||||
|
"max_attempts": 3,
|
||||||
"degeneration": {
|
"degeneration": {
|
||||||
"_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.",
|
"_comment": "SemIf degeneration watchdog: while the body streams, a 2-option SemIf decision (continue/stop) is made every `interval` chars against the last `window` chars of content+reasoning (once `min_chars` have accumulated); P(stop) >= threshold aborts the write with a graceful stub. Recorded trace-only (kind `codegen`), never in the decision log. Disabled when no engine is available.",
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
|
|||||||
@@ -70,6 +70,11 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
|||||||
degeneration_interval=int(deg_cfg.get("interval", 8000)),
|
degeneration_interval=int(deg_cfg.get("interval", 8000)),
|
||||||
degeneration_window=int(deg_cfg.get("window", 2000)),
|
degeneration_window=int(deg_cfg.get("window", 2000)),
|
||||||
degeneration_min_chars=int(deg_cfg.get("min_chars", 4000)),
|
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)),
|
||||||
|
max_attempts=int(codegen_cfg.get("max_attempts", 3)),
|
||||||
)
|
)
|
||||||
|
|
||||||
def make_degeneration_check(run_id: str):
|
def make_degeneration_check(run_id: str):
|
||||||
|
|||||||
+108
-20
@@ -31,6 +31,15 @@ class CodegenError(RuntimeError):
|
|||||||
"""The codegen endpoint could not be reached."""
|
"""The codegen endpoint could not be reached."""
|
||||||
|
|
||||||
|
|
||||||
|
class DegenerationError(CodegenError):
|
||||||
|
"""A SemIf degeneration watchdog aborted the stream mid-generation.
|
||||||
|
|
||||||
|
Subclass of CodegenError so the scheduler's graceful-stub path catches it;
|
||||||
|
distinct so callers can choose to retry a degenerated stream later without
|
||||||
|
retrying genuine endpoint failures.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
class TokenBudget(NamedTuple):
|
class TokenBudget(NamedTuple):
|
||||||
"""Per-request token limits derived from the detected context window.
|
"""Per-request token limits derived from the detected context window.
|
||||||
|
|
||||||
@@ -79,9 +88,17 @@ class CodegenClient:
|
|||||||
An optional `degeneration_check` callback (passed per `chat` call) is fed
|
An optional `degeneration_check` callback (passed per `chat` call) is fed
|
||||||
the last `degeneration_window` chars of content+reasoning every
|
the last `degeneration_window` chars of content+reasoning every
|
||||||
`degeneration_interval` chars once `degeneration_min_chars` have
|
`degeneration_interval` chars once `degeneration_min_chars` have
|
||||||
accumulated; a non-None return aborts the stream. It lets a SemIf
|
accumulated; a non-None return aborts the stream with DegenerationError.
|
||||||
continue/stop decision cut off a generation that is looping instead of
|
It lets a SemIf continue/stop decision cut off a generation that is
|
||||||
converging, before it fills the context window.
|
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).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -102,6 +119,11 @@ class CodegenClient:
|
|||||||
degeneration_interval: int = 8000,
|
degeneration_interval: int = 8000,
|
||||||
degeneration_window: int = 2000,
|
degeneration_window: int = 2000,
|
||||||
degeneration_min_chars: int = 4000,
|
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.base_url = base_url.rstrip("/")
|
||||||
self.model = model
|
self.model = model
|
||||||
@@ -119,13 +141,21 @@ class CodegenClient:
|
|||||||
self.degeneration_interval = degeneration_interval
|
self.degeneration_interval = degeneration_interval
|
||||||
self.degeneration_window = degeneration_window
|
self.degeneration_window = degeneration_window
|
||||||
self.degeneration_min_chars = degeneration_min_chars
|
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
|
self._window: int | None = None
|
||||||
|
|
||||||
def chat(
|
def chat(
|
||||||
self,
|
self,
|
||||||
messages: list[dict],
|
messages: list[dict],
|
||||||
max_tokens: int | None = None,
|
max_tokens: int | None = None,
|
||||||
temperature: float = 0.0,
|
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,
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
budget = self._compute_budget(messages)
|
budget = self._compute_budget(messages)
|
||||||
@@ -135,7 +165,14 @@ class CodegenClient:
|
|||||||
payload: dict = {
|
payload: dict = {
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
"messages": messages,
|
"messages": messages,
|
||||||
"temperature": temperature,
|
"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": True,
|
||||||
}
|
}
|
||||||
if max_tokens is not None:
|
if max_tokens is not None:
|
||||||
@@ -365,7 +402,7 @@ class CodegenClient:
|
|||||||
degeneration_check, recent, out_chars, last_check
|
degeneration_check, recent, out_chars, last_check
|
||||||
)
|
)
|
||||||
if reason:
|
if reason:
|
||||||
raise CodegenError(f"codegen degeneration detected: {reason}")
|
raise DegenerationError(f"codegen degeneration detected: {reason}")
|
||||||
if not continues:
|
if not continues:
|
||||||
break
|
break
|
||||||
if parts and self.stream:
|
if parts and self.stream:
|
||||||
@@ -416,7 +453,7 @@ class CodegenClient:
|
|||||||
degeneration_check, recent, out_chars, last_check
|
degeneration_check, recent, out_chars, last_check
|
||||||
)
|
)
|
||||||
if reason:
|
if reason:
|
||||||
raise CodegenError(f"codegen degeneration detected: {reason}")
|
raise DegenerationError(f"codegen degeneration detected: {reason}")
|
||||||
if not continues:
|
if not continues:
|
||||||
break
|
break
|
||||||
if parts and self.stream:
|
if parts and self.stream:
|
||||||
@@ -564,6 +601,48 @@ def parse_skill_body(raw: str) -> str:
|
|||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
ESCALATED_SAMPLER = {
|
||||||
|
"temperature": 0.5,
|
||||||
|
"top_p": 0.85,
|
||||||
|
"presence_penalty": 2.0,
|
||||||
|
"frequency_penalty": 0.3,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _retry_prompt(
|
||||||
|
request: Request,
|
||||||
|
category: str,
|
||||||
|
draft: SkillDraft,
|
||||||
|
contract: str,
|
||||||
|
error: Exception,
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Fresh short prompt for an escalated 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
|
||||||
|
final Python.
|
||||||
|
"""
|
||||||
|
system = (
|
||||||
|
"You write runnable skill bodies for a local agent. The contract below "
|
||||||
|
"is authoritative: follow it exactly.\n\n"
|
||||||
|
f"{contract}"
|
||||||
|
)
|
||||||
|
user = (
|
||||||
|
f"The previous attempt to write the skill body for {category}.{draft.name} "
|
||||||
|
f"was rejected: {error}. You are looping; emit the final Python now.\n"
|
||||||
|
f"Request: {request.text}\n"
|
||||||
|
f"Category: {category}\n"
|
||||||
|
f"Skill name: {draft.name}\n"
|
||||||
|
f"Skill description: {draft.description}\n"
|
||||||
|
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
|
||||||
|
"no markdown fences, no JSON."
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{"role": "system", "content": system},
|
||||||
|
{"role": "user", "content": user},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def generate_skill_body(
|
def generate_skill_body(
|
||||||
client: CodegenClient,
|
client: CodegenClient,
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -574,29 +653,38 @@ def generate_skill_body(
|
|||||||
max_tokens: int | None = None,
|
max_tokens: int | None = None,
|
||||||
degeneration_check: Callable[[str], str | None] | None = None,
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Author a skill body with the big model; retries once on invalid output."""
|
"""Author a skill body with the big model; escalate 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.
|
||||||
|
"""
|
||||||
contract_text = contract if contract is not None else read_skill_contract()
|
contract_text = contract if contract is not None else read_skill_contract()
|
||||||
messages = build_skill_body_prompt(request, category, draft, tree, contract_text)
|
|
||||||
if client.stream:
|
if client.stream:
|
||||||
print(f"[codegen] writing body for {category}.{draft.name}...")
|
print(f"[codegen] writing body for {category}.{draft.name}...")
|
||||||
last_error: Exception | None = None
|
last_error: Exception | None = None
|
||||||
for attempt in range(2):
|
attempts = max(client.max_attempts, 1)
|
||||||
|
for attempt in range(1, attempts + 1):
|
||||||
|
if attempt == 1:
|
||||||
|
messages = build_skill_body_prompt(
|
||||||
|
request, category, draft, tree, contract_text
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
messages = _retry_prompt(
|
||||||
|
request, category, draft, contract_text, last_error
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
raw = client.chat(
|
raw = client.chat(
|
||||||
messages,
|
messages,
|
||||||
max_tokens=max_tokens,
|
max_tokens=max_tokens,
|
||||||
degeneration_check=degeneration_check,
|
degeneration_check=degeneration_check,
|
||||||
|
**(ESCALATED_SAMPLER if attempt > 1 else {}),
|
||||||
)
|
)
|
||||||
return parse_skill_body(raw)
|
return parse_skill_body(raw)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
last_error = exc
|
last_error = exc
|
||||||
messages = messages + [
|
raise ValueError(f"skill body rejected {attempts} times: {last_error}")
|
||||||
{
|
|
||||||
"role": "user",
|
|
||||||
"content": (
|
|
||||||
f"That was rejected: {exc}. Reply with ONLY the Python code "
|
|
||||||
"now — no prose, no fences, no JSON."
|
|
||||||
),
|
|
||||||
}
|
|
||||||
]
|
|
||||||
raise ValueError(f"skill body rejected twice: {last_error}")
|
|
||||||
@@ -16,6 +16,7 @@ import pytest
|
|||||||
from semif_agent.codegen import (
|
from semif_agent.codegen import (
|
||||||
CodegenClient,
|
CodegenClient,
|
||||||
CodegenError,
|
CodegenError,
|
||||||
|
DegenerationError,
|
||||||
build_skill_body_prompt,
|
build_skill_body_prompt,
|
||||||
generate_skill_body,
|
generate_skill_body,
|
||||||
parse_skill_body,
|
parse_skill_body,
|
||||||
@@ -894,3 +895,208 @@ def test_degeneration_disabled_no_callback_no_abort():
|
|||||||
finally:
|
finally:
|
||||||
httpd.shutdown()
|
httpd.shutdown()
|
||||||
httpd.server_close()
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
class _SequencedOpenAI(BaseHTTPRequestHandler):
|
||||||
|
"""Returns one reply per chat request, in order; counts chat calls.
|
||||||
|
|
||||||
|
`/api/show` is answered (default num_ctx 4242) and never counted, so chat
|
||||||
|
payload and retry-count assertions stay unambiguous.
|
||||||
|
"""
|
||||||
|
|
||||||
|
replies: list = []
|
||||||
|
received: list = []
|
||||||
|
chat_calls: int = 0
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
raw = self.rfile.read(length).decode("utf-8")
|
||||||
|
if _respond_show(self):
|
||||||
|
return
|
||||||
|
type(self).chat_calls += 1
|
||||||
|
type(self).received.append(json.loads(raw))
|
||||||
|
index = min(type(self).chat_calls - 1, len(type(self).replies) - 1)
|
||||||
|
reply = type(self).replies[index]
|
||||||
|
body = (
|
||||||
|
_sse_frame({"choices": [{"delta": {"content": 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):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _sequenced_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
|
||||||
|
handler = type(
|
||||||
|
"Handler",
|
||||||
|
(_SequencedOpenAI,),
|
||||||
|
{"replies": replies, "received": [], "chat_calls": 0},
|
||||||
|
)
|
||||||
|
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_chat_payload_carries_sampler_defaults():
|
||||||
|
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]
|
||||||
|
assert body["temperature"] == 0.7
|
||||||
|
assert body["top_p"] == 0.85
|
||||||
|
assert body["presence_penalty"] == 1.5
|
||||||
|
assert body["frequency_penalty"] == 0.2
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
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)."""
|
||||||
|
httpd, base = _sequenced_server(["this is not python at all", GOOD_BODY])
|
||||||
|
try:
|
||||||
|
client = CodegenClient(base_url=base, model="test", timeout=10)
|
||||||
|
tree = build_tree(build_skills({"skills": {}}))
|
||||||
|
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||||
|
code = generate_skill_body(
|
||||||
|
client, Request("is the service up?"), "tracking", draft, tree
|
||||||
|
)
|
||||||
|
assert "def predict" in code and "def act" in code
|
||||||
|
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
|
||||||
|
retry_user = second["messages"][1]["content"]
|
||||||
|
assert "You are looping" in retry_user
|
||||||
|
assert "probe" in retry_user
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_skill_body_exhausts_max_attempts(tmp_path):
|
||||||
|
httpd, base = _sequenced_server(["this is not python at all"])
|
||||||
|
try:
|
||||||
|
client = CodegenClient(base_url=base, model="test", timeout=10, max_attempts=3)
|
||||||
|
tree = build_tree(build_skills({"skills": {}}))
|
||||||
|
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||||
|
with pytest.raises(ValueError, match="rejected 3 times"):
|
||||||
|
generate_skill_body(
|
||||||
|
client, Request("is the service up?"), "tracking", draft, tree
|
||||||
|
)
|
||||||
|
assert httpd.RequestHandlerClass.chat_calls == 3
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
class _DegeneratingOpenAI(BaseHTTPRequestHandler):
|
||||||
|
"""Streams forever (degeneration bait) and counts chat requests; answers
|
||||||
|
`/api/show` with {} so the client falls back to its `context_window` config."""
|
||||||
|
|
||||||
|
chat_calls: int = 0
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
length = int(self.headers.get("Content-Length") or 0)
|
||||||
|
raw = self.rfile.read(length).decode("utf-8")
|
||||||
|
if _respond_show(self, {}):
|
||||||
|
return
|
||||||
|
type(self).chat_calls += 1
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "text/event-stream")
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.flush()
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
frame = _sse_frame({"choices": [{"delta": {"content": "x"}}]})
|
||||||
|
self.wfile.write(frame.encode("utf-8"))
|
||||||
|
self.wfile.flush()
|
||||||
|
time.sleep(0.01)
|
||||||
|
except (BrokenPipeError, ConnectionResetError, OSError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _degenerating_server() -> tuple[ThreadingHTTPServer, str]:
|
||||||
|
handler = type("Handler", (_DegeneratingOpenAI,), {"chat_calls": 0})
|
||||||
|
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_degeneration_error_propagates_without_retry():
|
||||||
|
"""A degeneration abort is a DegenerationError (CodegenError subclass) and
|
||||||
|
must NOT retry — retry is reserved for invalid parses, leaving degeneration
|
||||||
|
handling as an explicit choice."""
|
||||||
|
assert issubclass(DegenerationError, CodegenError)
|
||||||
|
httpd, base = _degenerating_server()
|
||||||
|
try:
|
||||||
|
client = CodegenClient(
|
||||||
|
base_url=base,
|
||||||
|
model="test",
|
||||||
|
timeout=10,
|
||||||
|
stream=True,
|
||||||
|
context_window=100000,
|
||||||
|
max_output=0.5,
|
||||||
|
idle_timeout=30,
|
||||||
|
degeneration_interval=1,
|
||||||
|
degeneration_window=20,
|
||||||
|
degeneration_min_chars=1,
|
||||||
|
max_attempts=3,
|
||||||
|
)
|
||||||
|
tree = build_tree(build_skills({"skills": {}}))
|
||||||
|
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||||
|
with pytest.raises(DegenerationError, match="degeneration detected"):
|
||||||
|
generate_skill_body(
|
||||||
|
client,
|
||||||
|
Request("is the service up?"),
|
||||||
|
"tracking",
|
||||||
|
draft,
|
||||||
|
tree,
|
||||||
|
degeneration_check=lambda recent: "looping",
|
||||||
|
)
|
||||||
|
assert httpd.RequestHandlerClass.chat_calls == 1, "degeneration must not retry"
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_codegen_error_does_not_retry():
|
||||||
|
"""A non-degeneration CodegenError (token budget) must propagate without
|
||||||
|
retrying either."""
|
||||||
|
httpd, base = _degenerating_server()
|
||||||
|
try:
|
||||||
|
client = CodegenClient(
|
||||||
|
base_url=base,
|
||||||
|
model="test",
|
||||||
|
timeout=10,
|
||||||
|
stream=True,
|
||||||
|
context_window=3000,
|
||||||
|
max_output=0.01,
|
||||||
|
idle_timeout=30,
|
||||||
|
max_attempts=3,
|
||||||
|
)
|
||||||
|
tree = build_tree(build_skills({"skills": {}}))
|
||||||
|
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||||
|
with pytest.raises(CodegenError, match="token budget"):
|
||||||
|
generate_skill_body(
|
||||||
|
client, Request("is the service up?"), "tracking", draft, tree
|
||||||
|
)
|
||||||
|
assert httpd.RequestHandlerClass.chat_calls == 1
|
||||||
|
finally:
|
||||||
|
httpd.shutdown()
|
||||||
|
httpd.server_close()
|
||||||
Reference in new issue
Block a user