diff --git a/src/backread_exp/estimate.py b/src/backread_exp/estimate.py index a38e626..fbf54fb 100644 --- a/src/backread_exp/estimate.py +++ b/src/backread_exp/estimate.py @@ -136,29 +136,37 @@ def count( return counted.input_tokens +def has_credentials(client: anthropic.Anthropic) -> bool: + """Whether the SDK found credentials for `client`, checked without sending anything. + + The SDK finds credentials itself, from the environment or an `ant auth login` profile. When + it finds none, building the client still works and the first request raises a bare + `TypeError` ("Could not resolve authentication method"), so callers check this first. It + mirrors the SDK's own check: an auth header from a key or token, or a credentials provider. + """ + return bool(client.auth_headers) or client.credentials is not None + + def best_counter( model: str, *, client: Callable[[], anthropic.Anthropic] = anthropic.Anthropic, say: Callable[[str], None] = print, ) -> TokenCounter: - """`ApiCounter` if the API answers for `model` with the credentials found, else `CharCounter`. - - The SDK finds credentials itself, from the environment or an `ant auth login` profile. When - it finds none it raises a `TypeError` ("Could not resolve authentication method") on the - first request rather than an `AnthropicError`, so that one is caught too. - """ + """`ApiCounter` if the API answers for `model` with the credentials found, else + `CharCounter`.""" try: - counter = ApiCounter(client().with_options(max_retries=8)) + made = client() + if not has_credentials(made): + say( + "Token counting unavailable (no API credentials found); estimating from characters." + ) + return CharCounter() + counter = ApiCounter(made.with_options(max_retries=8)) counter.count(model, [{"role": "user", "content": "hi"}], [], PROBE_SCHEMA, "low") except anthropic.AnthropicError as error: say(f"Token counting unavailable ({type(error).__name__}); estimating from characters.") return CharCounter() - except TypeError as error: - if "authentication" not in str(error): - raise - say("Token counting unavailable (no API credentials found); estimating from characters.") - return CharCounter() return counter diff --git a/src/backread_exp/grid.py b/src/backread_exp/grid.py index a9b23ef..9ba37d6 100644 --- a/src/backread_exp/grid.py +++ b/src/backread_exp/grid.py @@ -4,13 +4,15 @@ --model claude-haiku-5-5 --max-usd 2 uv run python -m backread_exp estimate # the core grid, as `make estimate` prints -`run` prints its estimate before the first request and refuses to start without `--max-usd`, -which caps the run's spend over every attempt in its run directory: ledger spend under the same -run id from before the directory was created, by a run since moved aside, isn't counted. A paid -run also refuses to start while any memory it needs is missing. `--model fake` runs offline -against `AnsweringFake`, priced as Haiku so its dollars can be read against an estimate, with -placeholder text for any memory not produced yet; it makes no paid call, writes no ledger, and -keeps its runs under the ignored `data/cache/fake-runs/` unless `--runs-dir` says otherwise. +A paid `run`, and `estimate --counter api`, refuse to start when the SDK finds no Anthropic API +credentials. `run` prints its estimate before the first request and refuses to start without +`--max-usd`, which caps the run's spend over every attempt in its run directory: ledger spend +under the same run id from before the directory was created, by a run since moved aside, isn't +counted. A paid run also refuses to start while any memory it needs is missing. `--model fake` +runs offline against `AnsweringFake`, priced as Haiku so its dollars can be read against an +estimate, with placeholder text for any memory not produced yet; it makes no paid call, writes no +ledger, and keeps its runs under the ignored `data/cache/fake-runs/` unless `--runs-dir` says +otherwise. Each start saves the whole run's estimate as `estimate.json`. A start of at most `gates.PILOT_CASES` cases also saves it as `pilot-estimate.json`, which the pilot's cost gate @@ -47,6 +49,7 @@ best_counter, estimate_run, format_estimate, + has_credentials, ) from backread_exp.gates import PILOT_CASES, harness_hash, save_pilot_estimate from backread_exp.memories import estimate_memories @@ -198,11 +201,26 @@ def spec_for( return RunSpec(model, effort, question_set or default_set, tuple(arms), cases) +NO_CREDENTIALS = ( + "no Anthropic API credentials found; set an API key in the environment or run `ant auth login`" +) + + +def require_credentials() -> None: + """Refuse a paid command before it does any work if the SDK finds no credentials, rather + than let the first request die with the SDK's bare `TypeError`.""" + with anthropic.Anthropic() as client: + if not has_credentials(client): + raise RunError(NO_CREDENTIALS) + + def run_command(args: argparse.Namespace, *, say: Say = print) -> None: spec = spec_for(args.model, args.arms, args.cases, args.effort, args.question_set) + fake = spec.model == FAKE + if not fake: + require_credentials() harness = harness_hash() check_size(spec.cases, args.gates, harness) # before loading anything - fake = spec.model == FAKE run_id: str = args.run_id or f"{spec.question_set}-{spec.model}" run_dir: Path = (args.runs_dir or (FAKE_RUNS_DIR if fake else RUNS_DIR)) / run_id items = grid(select(read_manifest(), spec.question_set, spec.cases), spec.arms) @@ -322,6 +340,8 @@ def estimate_command(args: argparse.Namespace, *, say: Say = print) -> None: ] if given: raise RunError(f"{', '.join(given)} need --model; the core grid fixes them") + if args.counter == "api": + require_credentials() cases = practice_cases() manifest = read_manifest() memories = MemoryFiles() diff --git a/tests/test_estimate.py b/tests/test_estimate.py index 6f7ab4a..1937271 100644 --- a/tests/test_estimate.py +++ b/tests/test_estimate.py @@ -6,6 +6,7 @@ import anthropic import pytest +from anthropic.lib.credentials import AccessToken from anthropic.types import MessageParam, ToolParam from grid_fixtures import CASES, QUESTIONS_PER_CYCLE, Memories, NoMemories, case, entries @@ -18,6 +19,7 @@ best_counter, estimate_run, format_estimate, + has_credentials, ) from backread_exp.model import Effort from backread_exp.run import grid @@ -174,7 +176,8 @@ def no_client() -> anthropic.Anthropic: @pytest.mark.usefixtures("no_credentials") def test_best_counter_falls_back_to_characters_when_the_sdk_finds_no_credentials() -> None: - """The real SDK raises a `TypeError`, not an `AnthropicError`, when it finds no credentials.""" + """The real SDK builds a client with no credentials; the check catches that before a request, + which would raise a bare `TypeError`.""" said: list[str] = [] assert isinstance(best_counter(MODEL, say=said.append), CharCounter) assert said == [ @@ -182,9 +185,12 @@ def test_best_counter_falls_back_to_characters_when_the_sdk_finds_no_credentials ] -def test_best_counter_does_not_hide_other_type_errors() -> None: - def broken() -> anthropic.Anthropic: - raise TypeError("unexpected keyword argument") +@pytest.mark.usefixtures("no_credentials") +def test_has_credentials_sees_what_the_sdk_found() -> None: + assert not has_credentials(anthropic.Anthropic()) + assert has_credentials(anthropic.Anthropic(auth_token="a token")) + + def provider(*, force_refresh: bool = False) -> AccessToken: + return AccessToken("a token") - with pytest.raises(TypeError, match="unexpected keyword"): - best_counter(MODEL, client=broken, say=print) + assert has_credentials(anthropic.Anthropic(credentials=provider)) diff --git a/tests/test_run.py b/tests/test_run.py index 132c7aa..3694c68 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -371,6 +371,12 @@ def no_loading() -> None: assert not (tmp_path / "main-fake").exists() +@pytest.fixture +def credentials_found(monkeypatch: pytest.MonkeyPatch) -> None: + """Let a paid run past its credentials check; its model and counter are faked anyway.""" + monkeypatch.setattr(cli, "require_credentials", lambda: None) + + def synthetic_data(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(cli, "practice_cases", lambda: CASES) monkeypatch.setattr(cli, "read_manifest", entries) @@ -473,6 +479,7 @@ def complete(self, *args: Any, **kwargs: Any) -> Reply: return self._inner.complete(*args, **kwargs) +@pytest.mark.usefixtures("credentials_found") def test_an_error_in_a_paid_run_stops_every_further_paid_call( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -524,6 +531,7 @@ def __init__(self) -> None: super().__init__("claude-haiku-5-5") +@pytest.mark.usefixtures("credentials_found") def test_a_paid_run_caps_only_spend_since_its_directory_was_created( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: @@ -640,6 +648,7 @@ def test_run_locks_are_ignored() -> None: assert ignored.returncode == 0 +@pytest.mark.usefixtures("credentials_found") def test_a_paid_run_refuses_to_start_without_its_memories( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: @@ -699,6 +708,50 @@ def test_estimate_without_credentials_falls_back_to_characters( assert any(line.split()[:1] == ["total"] and "$" in line for line in said) +NO_CREDENTIALS_LINE = ( + "error: no Anthropic API credentials found; " + "set an API key in the environment or run `ant auth login`" +) + + +@pytest.mark.usefixtures("no_credentials") +def test_a_paid_run_without_credentials_stops_before_doing_anything( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + def no_work(*args: object, **kwargs: object) -> None: + raise AssertionError("did work before checking for credentials") + + for name in ("harness_hash", "check_size", "practice_cases", "read_manifest", "best_counter"): + monkeypatch.setattr(cli, name, no_work) + args = ["run", "--arms", "floor", "--model", "claude-haiku-5-5", "--cases", "1"] + args += ["--max-usd", "1", "--runs-dir", str(tmp_path)] + assert main(args) == 1 + assert lines(capsys) == [f"run: {NO_CREDENTIALS_LINE}"] + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.usefixtures("no_credentials") +def test_a_fake_run_needs_no_credentials( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + synthetic_data(monkeypatch) + assert main(run_args(tmp_path, "--cases", "1", "--max-usd", "1")) == 0 + assert lines(capsys)[-1].startswith("Done: ") + + +@pytest.mark.usefixtures("no_credentials") +def test_estimate_with_the_api_counter_and_no_credentials_stops_before_doing_anything( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + def no_work(*args: object, **kwargs: object) -> None: + raise AssertionError("did work before checking for credentials") + + for name in ("practice_cases", "read_manifest", "MemoryFiles"): + monkeypatch.setattr(cli, name, no_work) + assert main(["estimate", "--counter", "api", "--model", "claude-haiku-5-5"]) == 1 + assert lines(capsys) == [f"estimate: {NO_CREDENTIALS_LINE}"] + + def core_grid( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], *extra: str ) -> dict[str, dict[str, int]]: