diff --git a/.env.example b/.env.example index 4ad2ffc..10b0138 100644 --- a/.env.example +++ b/.env.example @@ -185,6 +185,10 @@ EMAIL= # in the stack: the rowing photo reader, the job posting reader and the email # pipeline's classifier. The backend no longer calls Claude itself. CLAUDE_API_KEY= +# Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5 +# (the default when blank) or claude-opus-5-5. Editable on the admin panel's +# Environment tab, which restarts the python service to apply it. +CLAUDE_MODEL= STEAM_API_KEY= STEAM_ID= diff --git a/CLAUDE.md b/CLAUDE.md index 58acee2..c4225d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,7 +58,7 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi. **Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode). -**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **Every Claude call in the stack lives here**, behind four internal routes: `/internal/rowing/read` (behind `POST /api/rowing`), `/internal/jobs/extract` (behind `POST /api/jobs/capture/extract`), `/internal/jobs/score` (behind the job-lead pipeline) and `/internal/email/classify` (behind the email sync). The Go backend calls them directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. Adding another is a short recipe in `python/README.md` ("Internal routes"). +**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **Every Claude call in the stack lives here**, behind four internal routes: `/internal/rowing/read` (behind `POST /api/rowing`), `/internal/jobs/extract` (behind `POST /api/jobs/capture/extract`), `/internal/jobs/score` (behind the job-lead pipeline) and `/internal/email/classify` (behind the email sync). The Go backend calls them directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting for all four, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), chosen on the admin panel's Environment tab; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes"). **Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 62c4074..5060456 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -260,7 +260,8 @@ Two distinct mechanisms read it, and services use both: `gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own convention for overriding `app.ini` keys), and `python` receives an explicit allow-list, so it never sees the database password or any API key other than -the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`). The Python service +the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`, plus `CLAUDE_MODEL`, +which picks the model). The Python service makes every Claude call in the stack — rowing photo reader, job posting reader, job lead scorer and email classifier — so it is the only container that reads `CLAUDE_API_KEY`; the backend receives it through `env_file` but no longer uses it. A new diff --git a/backend/services/env_registry.json b/backend/services/env_registry.json index c654803..d4bd476 100644 --- a/backend/services/env_registry.json +++ b/backend/services/env_registry.json @@ -1,5 +1,6 @@ [ {"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls, all made by the Python service: email classifier, rowing photo reader, job posting reader, job lead scorer", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://console.anthropic.com/settings/keys"}, + {"name": "CLAUDE_MODEL", "group": "API keys", "purpose": "Model for every Claude call: lead scoring, email classifier, posting reader, rowing photo reader. Blank uses claude-sonnet-5-5. Rough cost per million tokens in/out: Haiku $1/$5, Sonnet $2/$10, Opus $4/$20", "kind": "enum", "options": ["claude-haiku-4-5", "claude-sonnet-5-5", "claude-opus-5-5"], "editable": true, "services": ["python"]}, {"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"}, {"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]}, {"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"}, diff --git a/docker-compose.yml b/docker-compose.yml index f71ce8c..147e3b4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -416,6 +416,7 @@ services: - ROOT_PATH=/py - TFL_APP_KEY=${TFL_APP_KEY:-} - CLAUDE_API_KEY=${CLAUDE_API_KEY:-} + - CLAUDE_MODEL=${CLAUDE_MODEL:-} healthcheck: test: ["CMD", "python", "-c", "import urllib.request,os; urllib.request.urlopen(f\"http://localhost:{os.environ.get('PYTHON_PORT','8000')}/health\")"] interval: 30s diff --git a/python/README.md b/python/README.md index af96945..286fe20 100644 --- a/python/README.md +++ b/python/README.md @@ -98,7 +98,15 @@ They share their plumbing, in two places: with a string `detail`. The guard runs as a dependency, so a request from outside is a 404 before its body is validated. -All four use `claude-haiku-4-5` (`MODEL` in `claude.py`). The Go callers set +All four use one model, `MODEL` in `claude.py`: the `CLAUDE_MODEL` variable, +or `claude-sonnet-5-5` when it is blank. It is chosen on the admin panel's +Environment tab from `claude-haiku-4-5`, `claude-sonnet-5-5` and +`claude-opus-5-5`, and saving it there restarts this service. The request is +shaped per model by `_model_options`: a model that thinks gets +`output_config.effort: "low"` and 4,000 tokens of headroom on top of the +caller's `max_tokens`, because thinking is billed against it; Haiku 4.5 gets +neither, since it rejects the effort setting. A refusal (`stop_reason: +"refusal"`) is reported as the route's `failed` message. The Go callers set their own timeout above this side's (30s per attempt, two SDK retries), so they see this service's error rather than their own. @@ -237,7 +245,7 @@ braces version of the same thing. The internal deadlines in `travelodge.py` return partial results with `summary.truncated = true` instead of dying. Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, the optional -`TFL_APP_KEY` (see below), and `CLAUDE_API_KEY` for the four internal Claude routes. Dev mode mounts `python/app` and runs +`TFL_APP_KEY` (see below), and `CLAUDE_API_KEY` and `CLAUDE_MODEL` for the four internal Claude routes. Dev mode mounts `python/app` and runs uvicorn with `--reload`. ## Running locally diff --git a/python/app/claude.py b/python/app/claude.py index 44c100a..8232428 100644 --- a/python/app/claude.py +++ b/python/app/claude.py @@ -1,8 +1,8 @@ """The Anthropic client and the one call every Claude caller here makes. `rowing` (a photo in, three numbers out), `jobs` (page text in, a few fields -out) and `email_classify` (an email in, a verdict out) are the same shape of -call: one prompt asking for bare JSON, one reply to parse. That whole sequence +out), `job_score` (a posting and a profile in, a score out) and +`email_classify` (an email in, a verdict out) are the same shape of call: one prompt asking for bare JSON, one reply to parse. That whole sequence is `ask_json` below, so a caller is a prompt, a pydantic model and three error strings, and the handling around the call cannot drift between them. Also here: the lazily built client and the two exception types `main` maps to 502 @@ -23,7 +23,35 @@ log = logging.getLogger(__name__) T = TypeVar("T", bound=BaseModel) -MODEL = "claude-haiku-4-5" +# Which model every call uses. CLAUDE_MODEL is set from the admin panel's +# Environment tab (it is in backend/services/env_registry.json, whose `options` +# list is what the panel offers); changing it there recreates this container, +# which is why reading it once at import is enough. Blank means the default. +# +# The registry's options are the ids this module has been written for. Another +# id is passed through as it is, treated as a model that thinks (see below); +# if the API does not know it, every call fails with its `failed` message and +# the reason is in this service's log. +DEFAULT_MODEL = "claude-sonnet-5-5" +MODEL = os.environ.get("CLAUDE_MODEL", "").strip() or DEFAULT_MODEL + +# Models that take no `output_config.effort` and do not think unless asked to. +# Everything newer thinks by default, and that changes two things in the +# request - see _model_options. +_NO_EFFORT_PREFIXES = ("claude-haiku-4-5",) + +# Thinking is billed against `max_tokens` like the reply is, and the callers' +# ceilings are sized for the reply alone (a few hundred tokens of JSON). On a +# model that thinks, this is added on top so that a posting worth a moment's +# thought cannot use the whole allowance and leave no room for the answer. +THINKING_HEADROOM = 4000 + +# Every call here is extraction or classification: read something, return a +# small JSON object. "low" is the level meant for that - the model skips +# thinking on most simple requests - and it is set explicitly because the +# default differs between models. +EFFORT = "low" + # Seconds per attempt. The SDK retries twice on top (429/5xx/connection), so # the worst case is roughly three of these plus backoff; the Go callers' own # timeout is set above that so they see this side's error, not their own. @@ -69,6 +97,19 @@ def strip_markdown_fence(raw: str) -> str: return raw.strip() +def _model_options(model: str, max_tokens: int) -> dict: + """The parts of the request that depend on which model is configured. + + `max_tokens` is the caller's ceiling on the reply. A model that thinks + gets THINKING_HEADROOM on top and an explicit effort level; Haiku 4.5 + gets neither, because it rejects `output_config.effort` and does not think + unless a budget is requested, which nothing here does. + """ + if model.startswith(_NO_EFFORT_PREFIXES): + return {"max_tokens": max_tokens} + return {"max_tokens": max_tokens + THINKING_HEADROOM, "output_config": {"effort": EFFORT}} + + def ask_json( model_cls: type[T], *, @@ -90,7 +131,8 @@ def ask_json( Args: model_cls: the pydantic model the reply must validate as; its field names are the keys the caller's prompt asks for. - max_tokens: ceiling on the reply. + max_tokens: ceiling on the reply; see _model_options for what is + actually sent. messages: the `messages` list, passed to the API as is. system: the system prompt, left out of the request when None. failed: ReadError text when the API call itself failed. @@ -105,7 +147,7 @@ def ask_json( NotConfigured: no API key. ReadError: with one of the three messages above. """ - request = {"model": MODEL, "max_tokens": max_tokens, "messages": messages} + request = {"model": MODEL, "messages": messages, **_model_options(MODEL, max_tokens)} if system is not None: request["system"] = system @@ -121,8 +163,19 @@ def ask_json( log.warning("Claude API unreachable: %s", e) raise ReadError(failed) from e + # A refusal is an ordinary 200 whose content is not the answer. Say so in + # the log rather than letting it surface as an "empty" or "unparseable" + # reply, which would point at the prompt instead of at the classifier. + if getattr(message, "stop_reason", None) == "refusal": + log.warning("Claude declined the request: %s", getattr(message, "stop_details", None)) + raise ReadError(failed) + + # By type, not position: on a model that thinks, the first block can be a + # (possibly empty) thinking block. text = next((block.text for block in message.content if block.type == "text"), None) if text is None: + if getattr(message, "stop_reason", None) == "max_tokens": + log.warning("Claude ran out of tokens before answering (max_tokens=%s)", request["max_tokens"]) raise ReadError(empty) try: diff --git a/python/tests/test_claude.py b/python/tests/test_claude.py index 9ab740d..854445e 100644 --- a/python/tests/test_claude.py +++ b/python/tests/test_claude.py @@ -1,6 +1,6 @@ -"""Tests for `ask_json`, the one Claude call the three callers share. +"""Tests for `ask_json`, the one Claude call the four callers share. -test_rowing, test_jobs and test_email_classify each cover their own prompt, +test_rowing, test_jobs, test_job_score and test_email_classify each cover their own prompt, model and messages through this function; what is pinned here is the function's own contract - what it sends, which failure produces which of the caller's three messages, and where it gets its client from. @@ -53,7 +53,59 @@ def test_sends_the_request_and_validates_the_reply(): assert result == Count(n=3) # No system prompt was given, so the key is absent rather than None: the # SDK would send a null the API rejects. - assert call == {"model": claude.MODEL, "max_tokens": 64, "messages": MESSAGES} + assert call == {"model": claude.MODEL, "messages": MESSAGES, **claude._model_options(claude.MODEL, 64)} + + +def test_a_thinking_model_gets_headroom_and_low_effort(monkeypatch): + """Thinking is billed against max_tokens, so the caller's reply ceiling alone would starve the answer.""" + monkeypatch.setattr(claude, "MODEL", "claude-sonnet-5-5") + _, (call,) = ask(text_reply("{}")) + + assert call["model"] == "claude-sonnet-5-5" + assert call["max_tokens"] == 64 + claude.THINKING_HEADROOM + assert call["output_config"] == {"effort": "low"} + # Nothing these models reject: no thinking override, sampling or forced tool. + assert not {"thinking", "temperature", "top_p", "top_k", "tool_choice"} & call.keys() + + +def test_haiku_gets_the_plain_request(monkeypatch): + """Haiku 4.5 rejects output_config.effort and does not think unless asked to.""" + monkeypatch.setattr(claude, "MODEL", "claude-haiku-4-5") + _, (call,) = ask(text_reply("{}")) + + assert call == {"model": "claude-haiku-4-5", "max_tokens": 64, "messages": MESSAGES} + + +def test_the_default_model_is_one_the_admin_panel_offers(): + """CLAUDE_MODEL's options in the env registry are what the Environment tab lets an admin pick.""" + import json + from pathlib import Path + + registry = json.loads((Path(__file__).parents[2] / "backend/services/env_registry.json").read_text()) + (entry,) = [v for v in registry if v["name"] == "CLAUDE_MODEL"] + assert claude.DEFAULT_MODEL in entry["options"] + assert "python" in entry["services"] + + +def test_the_answer_is_found_after_a_thinking_block(): + reply = SimpleNamespace( + stop_reason="end_turn", + content=[SimpleNamespace(type="thinking", thinking=""), SimpleNamespace(type="text", text='{"n": 7}')], + ) + result, _ = ask(reply) + assert result == Count(n=7) + + +def test_a_refusal_is_a_failed_call_not_an_empty_reply(): + reply = SimpleNamespace(stop_reason="refusal", stop_details=SimpleNamespace(category="general_harms"), content=[]) + with pytest.raises(claude.ReadError, match="call failed"): + ask(reply) + + +def test_running_out_of_tokens_while_thinking_is_an_empty_reply(): + reply = SimpleNamespace(stop_reason="max_tokens", content=[SimpleNamespace(type="thinking", thinking="")]) + with pytest.raises(claude.ReadError, match="nothing came back"): + ask(reply) def test_passes_a_system_prompt_through(): diff --git a/python/tests/test_email_classify.py b/python/tests/test_email_classify.py index 75d9235..94e25bb 100644 --- a/python/tests/test_email_classify.py +++ b/python/tests/test_email_classify.py @@ -16,7 +16,7 @@ import httpx2 as httpx import pytest from fastapi.testclient import TestClient -from app import email_classify, main +from app import claude, email_classify, main ROUTE = "/internal/email/classify" MESSAGE = ( @@ -90,7 +90,9 @@ def test_classify_sends_the_email_unchanged_as_the_user_turn(fake_claude): assert analysis.model_dump() == ANALYSIS (call,) = fake_claude.calls assert call["model"] == email_classify.MODEL - assert call["max_tokens"] == 512 + # 512 is the reply's ceiling; what is sent adds room for thinking on a + # model that thinks (claude._model_options). + assert call["max_tokens"] == claude._model_options(claude.MODEL, 512)["max_tokens"] # The instructions travel in the system prompt and the email in the user # turn, exactly as Go formatted it. assert call["system"] == email_classify.SYSTEM