diff --git a/config.example.json b/config.example.json index 687c2b1..079a37f 100644 --- a/config.example.json +++ b/config.example.json @@ -13,13 +13,20 @@ }, "llm": {"base_url": "http://localhost:11434/v1", "model": "qwen3.5:4b"}, "codegen": { - "_comment": "OpenAI-compatible model that writes runnable skill bodies. Larger/slower than the decision or self-assessment model. No max_tokens cap: qwen38-iq3s reasons extensively (~7 min) before emitting the body; reasoning is filtered automatically. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream in minutes instead of blocking on the total timeout.", + "_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 tuple[Scheduler, dict]: stream=bool(codegen_cfg.get("stream", False)), idle_warn=float(codegen_cfg.get("idle_warn", 60.0)), idle_timeout=float(codegen_cfg.get("idle_timeout", 180.0)), + context_window=float(codegen_cfg.get("context_window", 0.0)), + smart_limit=int(codegen_cfg.get("smart_limit", 100000)), + warn_limit=int(codegen_cfg.get("warn_limit", 200000)), + max_fill_ratio=float(codegen_cfg.get("max_fill_ratio", 0.8)), + warn_fill_ratio=float(codegen_cfg.get("warn_fill_ratio", 0.5)), + max_output=float(codegen_cfg.get("max_output", 0.25)), + chars_per_token=float(codegen_cfg.get("chars_per_token", 4.0)), ) log = DecisionLog(config.get("log", "data/decisions.jsonl")) trace = TraceLog(config.get("trace", "data/runs.jsonl")) diff --git a/semif_agent/codegen.py b/semif_agent/codegen.py index ff737e6..a208043 100644 --- a/semif_agent/codegen.py +++ b/semif_agent/codegen.py @@ -18,17 +18,35 @@ import time import urllib.error import urllib.request from pathlib import Path +from typing import NamedTuple from .decisions import Request from .skills import SkillDraft, tree_summary DEFAULT_CONTRACT = Path(__file__).resolve().parent.parent / "SKILL.md" +DEFAULT_CONTEXT_WINDOW = 100000 class CodegenError(RuntimeError): """The codegen 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 + + def read_skill_contract(path: str | None = None) -> str: contract = Path(path) if path else DEFAULT_CONTRACT if not contract.is_file(): @@ -39,18 +57,24 @@ def read_skill_contract(path: str | None = None) -> str: class CodegenClient: """Minimal OpenAI-compatible chat client for writing skill bodies. - No token cap by default: Qwen3-style models reason first and the cap - truncates the hidden reasoning, leaving `content` empty. Omit `max_tokens` - so the model runs to completion; the reasoning is filtered automatically - because only `content` is read. + 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. - With `stream=True` the response is read as an SSE token stream and echoed - to stdout as it arrives — including the chain-of-thought — so a long - body write shows live progress. Echoing is console-only; 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. + `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`. """ def __init__( @@ -61,6 +85,13 @@ class CodegenClient: stream: bool = False, idle_warn: float = 60.0, idle_timeout: float = 180.0, + context_window: float = 0.0, + smart_limit: int = 100000, + warn_limit: int = 200000, + max_fill_ratio: float = 0.8, + warn_fill_ratio: float = 0.5, + max_output: float = 0.25, + chars_per_token: float = 4.0, ): self.base_url = base_url.rstrip("/") self.model = model @@ -68,6 +99,14 @@ class CodegenClient: 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._window: int | None = None def chat( self, @@ -75,12 +114,15 @@ class CodegenClient: max_tokens: int | None = None, temperature: float = 0.0, ) -> 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": temperature, - "stream": self.stream, + "stream": True, } if max_tokens is not None: payload["max_tokens"] = max_tokens @@ -90,9 +132,7 @@ class CodegenClient: ) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: - if self.stream: - return self._read_stream(response) - payload = json.loads(response.read().decode("utf-8")) + return self._read_stream(response, budget) except urllib.error.URLError as exc: raise CodegenError( f"codegen endpoint unreachable at {url}: {exc}. Is your local server running?" @@ -101,10 +141,118 @@ class CodegenClient: raise CodegenError( f"codegen request timed out after {self.timeout}s at {url}" ) from exc - return payload["choices"][0]["message"]["content"] - def _read_stream(self, response) -> str: - """Read an OpenAI-compatible SSE stream, echo tokens to stdout. + 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") or {} + num_ctx = params.get("num_ctx") + if isinstance(num_ctx, int) and 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 _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) -> 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 @@ -117,17 +265,20 @@ class CodegenClient: 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. 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 total budget). + 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). """ parts: list[str] = [] sock = self._stream_socket(response) if sock is None: - return self._read_stream_blocking(response) + return self._read_stream_blocking(response, budget) start = time.monotonic() last_activity = start warned = False + warned_fill = False + out_chars = 0 while True: if time.monotonic() - start >= self.timeout: raise CodegenError( @@ -157,56 +308,79 @@ class CodegenClient: if not raw: break last_activity = time.monotonic() - if not self._consume_frame(raw.decode("utf-8").strip(), parts): + continues, text, reasoning = self._consume_frame( + raw.decode("utf-8").strip() + ) + 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) + warned_fill = self._enforce_budget(budget, out_chars, warned_fill) + if not continues: break - if parts: + if parts and self.stream: sys.stdout.write("\n") sys.stdout.flush() return "".join(parts) - def _read_stream_blocking(self, response) -> str: + def _read_stream_blocking(self, response, budget: TokenBudget) -> 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` in the loop, - or a continuously-streaming runaway would never be cut short. + 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 for raw in response: if time.monotonic() - start >= self.timeout: raise CodegenError( f"codegen request exceeded {self.timeout:.0f}s total budget" ) - if not self._consume_frame(raw.decode("utf-8").strip(), parts): + continues, text, reasoning = self._consume_frame( + raw.decode("utf-8").strip() + ) + 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) + warned_fill = self._enforce_budget(budget, out_chars, warned_fill) + if not continues: break - if parts: + if parts and self.stream: sys.stdout.write("\n") sys.stdout.flush() return "".join(parts) @staticmethod - def _consume_frame(line: str, parts: list[str]) -> bool: - """Process one SSE line. Returns False on [DONE] (stop reading).""" + def _consume_frame(line: str) -> tuple[bool, str, str]: + """Process one SSE line. + + Returns (continue, content, reasoning). `content` feeds the returned + body; `reasoning` is only ever echoed. (False, "", "") on [DONE]. + """ if not line.startswith("data:"): - return True + return True, "", "" data = line[len("data:") :].strip() if data == "[DONE]": - return False + return False, "", "" try: chunk = json.loads(data) except ValueError: - return True + return True, "", "" choice = chunk.get("choices", [{}])[0] delta = choice.get("delta", {}) or {} text = delta.get("content") or "" reasoning = delta.get("reasoning_content") or delta.get("reasoning") or "" - if text or reasoning: - sys.stdout.write(text + reasoning) - sys.stdout.flush() - parts.append(text) - return True + return True, text, reasoning @staticmethod def _stream_socket(response): diff --git a/tests/test_codegen.py b/tests/test_codegen.py index 3646e02..dd32343 100644 --- a/tests/test_codegen.py +++ b/tests/test_codegen.py @@ -163,17 +163,41 @@ def test_merge_skill_bodies_creates_missing_category(tmp_path): assert tree["brand_new"][0].name == "ping" +def _respond_show(handler, body: dict | None = None) -> bool: + """Serve the ollama `/api/show` reply; returns True if handled.""" + if not handler.path.endswith("/api/show"): + return False + encoded = json.dumps( + body if body is not None else {"parameters": {"num_ctx": 4242}} + ).encode("utf-8") + handler.send_response(200) + handler.send_header("Content-Type", "application/json") + handler.send_header("Content-Length", str(len(encoded))) + handler.end_headers() + handler.wfile.write(encoded) + return True + + class _FakeOpenAI(BaseHTTPRequestHandler): + """Single-shot SSE server: the reply arrives as one content delta. The + `/api/show` window query is answered too (default num_ctx 4242) but never + recorded in `received`, so chat-payload assertions stay unambiguous.""" + reply: str = GOOD_BODY received: list = [] 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).received.append(json.loads(raw)) - body = json.dumps({"choices": [{"message": {"content": self.reply}}]}).encode("utf-8") + body = ( + _sse_frame({"choices": [{"delta": {"content": self.reply}}]}) + + "data: [DONE]\n\n" + ).encode("utf-8") self.send_response(200) - self.send_header("Content-Type", "application/json") + self.send_header("Content-Type", "text/event-stream") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -228,7 +252,9 @@ class _SilentOpenAI(BaseHTTPRequestHandler): def do_POST(self): length = int(self.headers.get("Content-Length") or 0) - self.rfile.read(length) + raw = self.rfile.read(length).decode("utf-8") + if _respond_show(self): + return time.sleep(5) def log_message(self, format, *args): @@ -241,7 +267,9 @@ class _StalledStreamOpenAI(BaseHTTPRequestHandler): def do_POST(self): length = int(self.headers.get("Content-Length") or 0) - self.rfile.read(length) + raw = self.rfile.read(length).decode("utf-8") + if _respond_show(self): + return self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() @@ -331,7 +359,9 @@ class _RunawayStreamOpenAI(BaseHTTPRequestHandler): def do_POST(self): length = int(self.headers.get("Content-Length") or 0) - self.rfile.read(length) + raw = self.rfile.read(length).decode("utf-8") + if _respond_show(self): + return self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.end_headers() @@ -351,6 +381,40 @@ class _RunawayStreamOpenAI(BaseHTTPRequestHandler): pass +class _CapTripOpenAI(BaseHTTPRequestHandler): + """Streams forever but reports an empty `/api/show` (no num_ctx), so the + client falls back to its `context_window` config — deterministic budget + tests at tiny windows.""" + + 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 + 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 _cap_trip_server() -> tuple[ThreadingHTTPServer, str]: + handler = type("Handler", (_CapTripOpenAI,), {}) + 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_stream_total_budget_fires_while_streaming(): """A continuously-streaming runaway must be cut short by the total budget, not loop forever. idle_timeout (0.5s) < timeout (1.0s) makes the @@ -394,15 +458,99 @@ def test_read_stream_blocking_enforces_total_budget(): """The blocking fallback must enforce the total budget too — its per-read socket timeout bounds individual reads, not the whole stream.""" client = CodegenClient( - base_url="http://unused", model="test", timeout=0.5, stream=True + base_url="http://127.0.0.1:1/v1", model="test", timeout=0.5, stream=True ) + budget = client._compute_budget([{"role": "user", "content": "hi"}]) started = time.monotonic() with pytest.raises(CodegenError, match="total budget"): - client._read_stream_blocking(_ForeverFrames()) + client._read_stream_blocking(_ForeverFrames(), budget) elapsed = time.monotonic() - started assert elapsed < 5.0, f"blocking fallback should fail fast, took {elapsed:.1f}s" +def test_output_cap_trips_at_fraction_of_window(): + """max_output in (0,1) caps at a fraction of the detected window; the cap + must abort a runaway stream in real time.""" + httpd, base = _cap_trip_server() + try: + client = CodegenClient( + base_url=base, + model="test", + timeout=10, + stream=True, + context_window=100, + max_output=0.25, + idle_timeout=30, + ) + started = time.monotonic() + with pytest.raises(CodegenError, match="token budget"): + client.chat([{"role": "user", "content": "hi"}]) + assert time.monotonic() - started < 8.0 + finally: + httpd.shutdown() + httpd.server_close() + + +def test_output_cap_trips_at_absolute_tokens(): + """max_output >= 1 is an absolute token cap, independent of the window.""" + httpd, base = _cap_trip_server() + try: + client = CodegenClient( + base_url=base, + model="test", + timeout=10, + stream=True, + context_window=100, + max_output=8, + idle_timeout=30, + ) + with pytest.raises(CodegenError, match="token budget"): + client.chat([{"role": "user", "content": "hi"}]) + finally: + httpd.shutdown() + httpd.server_close() + + +def test_budget_warns_near_fill_threshold(capsys): + """The one-shot fill warning fires (before the cap aborts) when the total + fill estimate crosses warn_point.""" + httpd, base = _cap_trip_server() + try: + client = CodegenClient( + base_url=base, + model="test", + timeout=10, + stream=True, + context_window=100, + max_output=0.5, + warn_fill_ratio=0.2, + idle_timeout=30, + ) + with pytest.raises(CodegenError, match="token budget"): + client.chat([{"role": "user", "content": "hi"}]) + captured = capsys.readouterr().out + assert "total fill" in captured + assert "near the" in captured + finally: + httpd.shutdown() + httpd.server_close() + + +def test_budget_start_line_printed(capsys): + httpd, base = _streaming_server() + try: + client = CodegenClient(base_url=base, model="test", timeout=10, stream=True) + out = client.chat([{"role": "user", "content": "hi"}]) + assert out == GOOD_BODY + captured = capsys.readouterr().out + assert captured.startswith("[codegen] context window") + assert "output cap" in captured + assert "peak total fill" in captured + finally: + httpd.shutdown() + httpd.server_close() + + class _StreamingOpenAI(BaseHTTPRequestHandler): """Replies with an OpenAI-compatible SSE token stream (COT then content). @@ -418,6 +566,8 @@ class _StreamingOpenAI(BaseHTTPRequestHandler): 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).received.append(json.loads(raw)) self.send_response(200) self.send_header("Content-Type", "text/event-stream") @@ -475,7 +625,22 @@ def test_chat_stream_verbose_echoes_tokens(reasoning_key, capsys): out = client.chat([{"role": "user", "content": "hi"}]) assert out == GOOD_BODY captured = capsys.readouterr().out - assert captured == _StreamingOpenAI.reasoning + GOOD_BODY + "\n" + assert captured.startswith("[codegen] context window") + assert captured.endswith(_StreamingOpenAI.reasoning + GOOD_BODY + "\n") + finally: + httpd.shutdown() + httpd.server_close() + + +def test_chat_stream_false_returns_content_without_echo(capsys): + """`stream: false` must still return the full content (transport always + streams) but print nothing beyond the request — no token echo.""" + httpd, base = _streaming_server() + try: + client = CodegenClient(base_url=base, model="test", timeout=10, stream=False) + out = client.chat([{"role": "user", "content": "hi"}]) + assert out == GOOD_BODY + assert capsys.readouterr().out == "" finally: httpd.shutdown() httpd.server_close() @@ -500,6 +665,88 @@ def test_chat_includes_max_tokens_when_set(): client.chat([{"role": "user", "content": "hi"}], max_tokens=512) body = httpd.RequestHandlerClass.received[0] assert body["max_tokens"] == 512 + finally: + httpd.shutdown() + httpd.server_close() + + +class _ShowOpenAI(BaseHTTPRequestHandler): + """Answers `/api/show` with a configurable body and counts the calls.""" + + show: dict = {"parameters": {"num_ctx": 4242}} + show_calls: int = 0 + show_requests: list = [] + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length).decode("utf-8") + type(self).show_calls += 1 + type(self).show_requests.append(json.loads(raw)) + body = json.dumps(type(self).show).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) + + def log_message(self, format, *args): + pass + + +def _show_server(show: dict) -> tuple[ThreadingHTTPServer, str]: + handler = type( + "Handler", + (_ShowOpenAI,), + {"show": show, "show_calls": 0, "show_requests": []}, + ) + 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_context_window_from_num_ctx(): + httpd, base = _show_server({"parameters": {"num_ctx": 4096}}) + try: + client = CodegenClient(base_url=base, model="test") + assert client._context_window() == 4096 + assert httpd.RequestHandlerClass.show_requests[0] == {"model": "test"} + finally: + httpd.shutdown() + httpd.server_close() + + +def test_context_window_from_model_info(): + httpd, base = _show_server({"model_info": {"qwen35.context_length": 262144}}) + try: + client = CodegenClient(base_url=base, model="test") + assert client._context_window() == 262144 + finally: + httpd.shutdown() + httpd.server_close() + + +def test_context_window_falls_back_to_config(): + httpd, base = _show_server({}) + try: + client = CodegenClient(base_url=base, model="test", context_window=2048) + assert client._context_window() == 2048 + finally: + httpd.shutdown() + httpd.server_close() + + +def test_context_window_falls_back_to_default(): + client = CodegenClient(base_url="http://127.0.0.1:1/v1", model="test") + assert client._context_window() == 100000 + + +def test_context_window_is_cached(): + httpd, base = _show_server({"parameters": {"num_ctx": 4242}}) + try: + client = CodegenClient(base_url=base, model="test") + assert client._context_window() == 4242 + assert client._context_window() == 4242 + assert httpd.RequestHandlerClass.show_calls == 1 finally: httpd.shutdown() httpd.server_close() \ No newline at end of file