Default to Sonnet 5.5 and make the Claude model an admin setting
Every Claude call used a hard-coded claude-haiku-4-5. The model is now CLAUDE_MODEL, read by the Python service, defaulting to claude-sonnet-5-5 and offered on the admin panel's Environment tab as a choice of Haiku 4.5, Sonnet 5.5 and Opus 5.5. The request is shaped per model. Sonnet and Opus think by default and bill that against max_tokens, so they get low effort and 4,000 tokens of headroom over each caller's reply ceiling; Haiku 4.5 rejects the effort setting and keeps the plain request. A refusal is logged and reported as the route's failed message instead of surfacing as an empty reply. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+10
-2
@@ -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
|
||||
|
||||
+58
-5
@@ -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:
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user