Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 59 additions & 7 deletions llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import base64
import json
import os
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -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):
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"}
Expand Down
22 changes: 21 additions & 1 deletion scripts/check.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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"(?<![\w.])input\(", code):
Expand Down Expand Up @@ -306,7 +326,7 @@ def problems(root: Path) -> 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:
Expand Down