From d32cc14bab38f8bec4130dc1d1f7cd27cea5e2c9 Mon Sep 17 00:00:00 2001 From: Param Harrison Date: Thu, 3 Dec 2026 10:46:50 +0200 Subject: [PATCH] fix: a wrong key or a rate limit gets a clear error and a retry The gateway retries by itself, keeps a tool's strict flag for Claude, and the check refuses a model field named thinking. Copied from the shared workshop kit. Co-Authored-By: Claude Sonnet 5.5 --- llm.py | 66 +++++++++++++++++++++++++++++++++++++++++++----- scripts/check.py | 22 +++++++++++++++- 2 files changed, 80 insertions(+), 8 deletions(-) diff --git a/llm.py b/llm.py index 466d9bd..ad1bb79 100644 --- a/llm.py +++ b/llm.py @@ -4,6 +4,7 @@ import base64 import json import os +import time from dataclasses import dataclass from pathlib import Path from typing import Any @@ -33,6 +34,15 @@ } DEFAULT_CAP_USD = 1.00 +TRIES = 3 +# Errors that a short wait can fix. LiteLLM's own num_retries needs one more package, so the loop is here. +PASSING = ( + litellm.RateLimitError, + litellm.InternalServerError, + litellm.ServiceUnavailableError, + litellm.APIConnectionError, + litellm.Timeout, +) class SpendCapReached(RuntimeError): @@ -47,6 +57,37 @@ class Refused(RuntimeError): pass +def _keeping_strict(mapper): + def wrapper(config, tool): + mapped, server = mapper(config, tool) + if mapped is not None and tool.get("function", {}).get("strict"): + mapped["strict"] = True + return mapped, server + + wrapper.keeps_strict = True + return wrapper + + +def _patch_strict() -> bool: + """LiteLLM drops a tool's `strict` flag on the way to Claude. Put it back. + + This reaches into a private LiteLLM function. An upgrade can move it, and then + a strict tool raises SetupError instead of losing the flag without a word. + """ + try: + from litellm.llms.anthropic.chat.transformation import AnthropicConfig + + mapper = AnthropicConfig._map_tool_helper + except (ImportError, AttributeError): + return False + if not getattr(mapper, "keeps_strict", False): + AnthropicConfig._map_tool_helper = _keeping_strict(mapper) + return True + + +STRICT_PATCHED = _patch_strict() + + @dataclass class Usage: calls: int = 0 @@ -221,13 +262,18 @@ def _send(call, request: dict) -> Any: raise SetupError("No key found. Run: cp env.example .env then paste your key into it.") if model.startswith("openrouter/") and not os.getenv("OPENROUTER_API_KEY"): raise SetupError("This step needs OPENROUTER_API_KEY in your settings file.") - try: - return call(num_retries=2, timeout=90, **request) - except (litellm.NotFoundError, litellm.AuthenticationError) as error: - raise SetupError( - f"The provider refused the model '{model}' or your key. " - "Check the model and the key in your settings file." - ) from error + for attempt in range(1, TRIES + 1): + try: + return call(timeout=90, **request) + except (litellm.NotFoundError, litellm.AuthenticationError) as error: + raise SetupError( + f"The provider refused the model '{model}' or your key. " + "Check the model and the key in your settings file." + ) from error + except PASSING: + if attempt == TRIES: + raise + time.sleep(2**attempt) def _cached(usage: Any) -> int: @@ -267,6 +313,12 @@ def wrapper(*args: Any, **request: Any) -> Any: # Current Claude models reject sampling settings. request.pop("temperature", None) request.pop("top_p", None) + tools = request.get("tools") or [] + if not STRICT_PATCHED and any(t.get("function", {}).get("strict") for t in tools): + raise SetupError( + "This LiteLLM version would drop the strict flag of your tool. " + "Run uv sync to get the locked version." + ) if model == HAIKU and not request.keys() & {"thinking", "reasoning_effort"}: # Short answers, low cost. The other Claude models reject this setting. request["thinking"] = {"type": "disabled"} diff --git a/scripts/check.py b/scripts/check.py index 9b39347..abeecd0 100644 --- a/scripts/check.py +++ b/scripts/check.py @@ -1,6 +1,7 @@ """The one offline gate for a workshop repo: plain English, one model file, a page that matches.""" # Copied from curriculum/workshop-kit. Edit it there, then sync it. +import ast import fnmatch import json import re @@ -175,11 +176,30 @@ def code_problems(code: str) -> list[str]: return found +def field_problems(code: str) -> list[str]: + """Claude refuses a structured answer with a field named thinking beside a step-by-step prompt.""" + try: + tree = ast.parse(re.sub(r"^\s*[%!].*$", "", code, flags=re.M)) + except SyntaxError: + return [] + shapes = ( + node for node in ast.walk(tree) + if isinstance(node, ast.ClassDef) and any("BaseModel" in ast.unparse(base) for base in node.bases) + ) + named = any( + isinstance(line, ast.AnnAssign) and getattr(line.target, "id", "") == "thinking" + for shape in shapes for line in shape.body + ) + return ['a model field named "thinking": Claude can refuse it, so name it "reasoning"'] if named else [] + + def notebook_problems(path: Path) -> list[str]: metadata, cells = cells_of(path) code = "\n".join(source for kind, source, _ in cells if kind == "code") pages = "\n\n".join(source for kind, source, _ in cells if kind == "markdown") found = english_problems(pages) + code_problems(code) + # one cell at a time: a cell that does not parse must not hide the others + found += sorted({p for kind, source, _ in cells if kind == "code" for p in field_problems(source)}) if re.search(r"^\s*[%!]\s*(?:uv\s+)?pip\s", code, re.M): found.append("pip install cell: add the package to pyproject.toml instead") if re.search(r"(? list[str]: if path.suffix == ".md": here += english_problems(text) + link_problems(root, path, text) if path.suffix == ".py" and relative not in ("llm.py", "scripts/check.py"): - here += code_problems(text) + here += code_problems(text) + field_problems(text) if path.suffix == ".ipynb": text = "\n".join(source for _, source, _ in cells_of(path)[1]) if path.suffix in (".md", ".py", ".ipynb") and relative != "scripts/check.py" and EM_DASH in text: