Skip to content

Phase 2: Anthropic-only key and model policy, community config migration - #368

Merged
neuromechanist merged 13 commits into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-362-phase2-key-model-policy
Sep 17, 2026
Merged

neuromechanist merged 13 commits into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-362-phase2-key-model-policy

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Flips request routing onto the Claude Platform on AWS. Platform-funded and community-funded traffic now runs Claude Haiku 4.5 by default with a 2048-token thinking budget, or Claude Sonnet 5 on request. Bring-your-own-key stays additive: an Anthropic key is accepted as a first-class credential, and an OpenRouter key still unlocks any model OpenRouter serves.

Closes #362
Part of epic #360

Provider and model resolution

_select_api_key becomes _resolve_provider, returning the provider, key, and key source together. BYOK wins; otherwise an authorized origin falls back to a community key, then the platform key; otherwise 403, now naming both BYOK headers. Community configs gain anthropic_api_key_env_var, and the existing openrouter_api_key_env_var keeps working so a community can still fund itself through OpenRouter.

_select_model is provider-aware. On Anthropic it normalizes through normalize_model and turns an unoffered id into a 400 that lists what is available; on OpenRouter it keeps the previous behavior.

One correction to the original plan, worth calling out because it would have been a quiet behavior change: making every default a bare first-party id left the OpenRouter path with nothing routable, and the first fix substituted OpenRouter's own default. That would have answered an OpenRouter-funded request with a different model family than the community configured, decided only by which key paid, and the four communities that set openrouter_api_key_env_var would have silently dropped to a non-Claude model. Instead, first-party ids now map to the same model's OpenRouter slug (claude-haiku-4-5 to anthropic/claude-haiku-4.5). An unmappable configured default still falls back, but logs an error rather than substituting silently.

Content shape, the part that breaks silently

With thinking on, and whenever tools are bound, langchain-anthropic stops coercing content to a string: messages and chunks carry thinking and text blocks. Before this PR, _extract_agent_result would have put a stringified Python list into the answer field and the streaming handler would have raised TypeError on the first chunk. A single helper in src/agents/content.py now serves all three call sites.

Text streams as the existing content event. Thinking emits a separate thinking event carrying no reasoning text, only the signal that the model is working, so the widget can show a quiet indicator without reasoning ever reaching a client. Rendering lands in Phase 3; the current widget ignores unknown events.

src/api/routers/chat.py is deleted. It had the same bug but was dead code: nothing imported it, main.py never registered it, no test covered it, all three verified before removal.

Cache-aware cost

estimate_cost now prices a cache write at 1.25x and a cache read at 0.1x of the input rate, fed by cache_read and cache_creation from usage metadata. Without this the dashboard overstates spend, and the overstatement grows the better caching works.

Test plan

  • uv run pytest tests/ -m "not llm and not integration and not network and not slow" - 1988 passed, 13 skipped. The one remaining failure, test_version_shows_version, is a pre-existing Rich ANSI assertion that fails identically on the base commit and passes in CI, where there is no TTY.
  • uv run ruff check . && uv run ruff format --check . - clean.
  • End to end against the live endpoint, which is the check no unit test can make. Non-streaming returned a plain string answer with no block-list artifacts. Streaming returned 16 thinking events carrying no payload, then text content, then done, with no reasoning and no non-string chunks reaching the client.

Known follow-ups, tracked not forgotten

Five tests in tests/test_integration/test_llm.py are stale: they reference start_standalone_server and a nested osa hed ask command structure that no longer exists. They fail identically on the base commit and are out of scope here.

Adds ByokCredential/resolve_byok (src/api/security.py) so a caller can bring
an Anthropic or OpenRouter key, preferring Anthropic when both headers are
sent. Replaces _select_api_key with _resolve_provider/ProviderChoice in the
community router: BYOK wins, then a community-funded key (Anthropic env var
checked before OpenRouter's), then the platform key, preferring the Claude
Platform on AWS over OpenRouter. _select_model becomes provider-aware: the
Anthropic path normalizes any requested/default model against the two
offered Claude models and returns 400 (naming them) for anything else;
the OpenRouter path keeps its existing BYOK-gated custom-model behavior,
with a fallback to OpenRouter's own default when a resolved default_model
is a bare first-party id (no longer a valid OpenRouter slug post-migration).
create_community_assistant now builds the model via create_anthropic_llm or
create_openrouter_llm depending on the resolved provider; the ask/chat
endpoints and their streaming helpers accept the new X-Anthropic-API-Key
header alongside X-OpenRouter-Key.

Also lands the content-shape fix this phase depends on: langchain-anthropic
returns a list of typed content blocks (not a plain string) whenever
thinking is enabled or tools are bound. src/agents/content.py adds
extract_text/classify_content_blocks; _extract_agent_result and both
streaming on_chat_model_stream handlers use them instead of str(content) /
`+=`, which previously stringified the block list into answers or raised
TypeError. Thinking blocks now emit a content-free `thinking` SSE event
(a liveness signal only) instead of leaking reasoning or crashing the
stream. The streaming token-usage extraction also now carries the
cache_read/cache_creation breakdown through for cache-aware cost (next
commit).

Deletes src/api/routers/chat.py: verified unimported, unregistered in
main.py, and uncovered by any test, so it carried the same content-shape
bug as genuinely dead code.

Tested manually end to end against the real Claude Platform on AWS via
/hed/ask (non-streaming and streaming): clean answers, no stringified
block-list artifacts, and `thinking` events carrying no reasoning text.
Every src/assistants/*/config.yaml now sets default_model to the
first-party claude-haiku-4-5 id and drops default_model_provider (an
OpenRouter-only routing hint no longer applicable); metabci moves off
deepseek/deepseek-v3.2. src/api/config.py's default_model/test_model follow
the same default, with default_model_provider/test_model_provider now
documented as OpenRouter-BYOK-only.

CommunityConfig gains anthropic_api_key_env_var (ANTHROPIC_API_KEY_* only,
same validation style as openrouter_api_key_env_var) so a community can
fund its own Anthropic usage; the OpenRouter field keeps working for
communities that still fund themselves that way.
_MODEL_ID_PATTERN now accepts a bare first-party id (no provider prefix)
alongside the existing provider/model-name form.
validate_expensive_model_without_byok's BYOK bypass now also checks
anthropic_api_key_env_var, and its guidance mentions the Anthropic offering
as a cost-capped alternative to OpenRouter BYOK.
extract_token_usage now returns a TokenUsage namedtuple that also carries
cache_read_tokens/cache_creation_tokens, summed from each AIMessage's
usage_metadata["input_token_details"] (langchain-anthropic's input_tokens
already includes both, so this only breaks out the existing total, it
does not change it). estimate_cost gains matching cache_read_tokens/
cache_creation_tokens parameters (default 0, so existing callers are
unaffected): ordinary input prices at 1x, a cache write at 1.25x, and a
cache read at 0.1x, mirroring Anthropic's own cache economics. The
community router's callers (src/api/routers/community.py, updated in the
prior commit) already carry the cache breakdown through from both the
non-streaming and streaming paths.
OSAClient sends X-Anthropic-API-Key (preferred) or X-OpenRouter-Key,
matching the server's own resolve_byok preference. Adds
get_effective_anthropic_key() (ANTHROPIC_API_KEY env > credentials.yaml,
which already had the field) alongside the existing OpenRouter-only
get_effective_config(), left unchanged so its behavior and tests keep
working. The ask/chat commands resolve both keys and pass whichever are
set; _check_api_key now accepts either.
test_authorization.py is reworked around _resolve_provider/ProviderChoice
and the provider-aware _select_model: each BYOK header alone, both
together (Anthropic wins), community key (Anthropic env var checked
before OpenRouter's), platform key (Anthropic preferred over OpenRouter),
unauthorized origin, and nothing configured; an unoffered model on a
platform key returns 400 naming the offered models, the same model with
OpenRouter BYOK is allowed, a legacy anthropic/claude-haiku-4.5 default
still resolves, and a bare default_model on the OpenRouter path falls
back to OpenRouter's own default instead of forwarding an invalid slug.
test_community_router.py and test_cost_protection.py needed no changes
(neither depends on OpenRouter-specific shapes). test_community.py adds
coverage for anthropic_api_key_env_var and the relaxed model-id pattern.

Adds tests/test_agents/test_content.py for extract_text/
classify_content_blocks: a list of thinking and text blocks yields only
the text, a thinking block classifies as a content-free signal, and a
plain string still works untouched.

test_db.py and test_cost.py cover the cache-aware token/cost plumbing:
extract_token_usage's cache_read/cache_creation breakdown, and
estimate_cost pricing identical token counts cheaper when mostly a cache
read than when all fresh (and more expensive when writing a cache entry).

test_client.py/test_config.py cover the CLI's Anthropic-preferred BYOK
header and get_effective_anthropic_key.

Adds tests/test_integration/test_anthropic_router.py (llm + integration,
skipped when Settings().anthropic_api_key is falsy): a real /hed/ask
request, non-streaming and streamed, against the live Claude Platform on
AWS, asserting a real answer with no stringified block-list artifacts and
that `thinking` SSE events never carry reasoning text.
A bare first-party default such as claude-haiku-4-5 is not a valid
OpenRouter slug, so an OpenRouter-funded request with no explicit model
had nothing routable to use. Falling back to the factory default meant
such a request silently answered with a different model family than the
community configured, decided only by which key paid for it. The four
communities that fund themselves through openrouter_api_key_env_var
would have had their implicit default become a non-Claude model.

OpenRouter serves the same Claude models under creator/model slugs, so
map across instead: claude-haiku-4-5 resolves to
anthropic/claude-haiku-4.5, and a caller may also name an offered model
by its first-party id. A default that is neither an offered model nor an
OpenRouter slug still falls back, but now logs an error rather than
substituting silently. A test asserts the mapping stays in step with
OFFERED_MODELS so adding a model cannot skip it.
langchain-anthropic zeroes input_token_details["cache_creation"] whenever
Anthropic's per-TTL breakdown is present (the normal shape once a
cache_control marker is sent, which CachingChatAnthropic always does) and
moves the real count under ephemeral_5m_input_tokens/ephemeral_1h_input_tokens.
Both extractors read the generic key only, so cache writes read as 0 and
were priced at 1x instead of 1.25x. Add a shared
resolve_cache_creation_tokens() helper in src/metrics/db.py that mirrors
langchain's own precedence (TTL-specific sum first, generic key as
fallback) and use it from both extract_token_usage (src/metrics/db.py) and
_extract_token_usage (src/api/routers/community.py).

Also raise _extract_token_usage's catch-all from DEBUG to WARNING: this
repo's default level is INFO, so a genuine extraction bug was silently
showing up as a free request on the dashboard instead of a visible log
line. Still swallows and returns zeros so a stream is never broken by a
metrics problem.
to_openrouter_model() only recognizes the two canonical first-party ids,
so the bare legacy aliases in MODEL_ALIASES (claude-haiku-4.5,
claude-sonnet-4.5) returned None and fell through to the OpenRouter
emergency default -- the exact model-family substitution the previous
commit set out to eliminate. _select_model now canonicalizes through
normalize_model() before mapping to an OpenRouter slug (via a small
_to_openrouter_model_via_canonical() helper), falling back to the raw
value only when normalize_model() raises.

Also:
- Add anthropic/claude-sonnet-5 to MODEL_PRICING (src/metrics/cost.py) at
  the same rate as the first-party claude-sonnet-5 entry: a community
  whose default resolves to that OpenRouter slug was otherwise blocked
  with a 403 as "not in the approved pricing list".
- Name the community in _select_model's unmappable-default log line
  (message and extra={"community_id": ...}), matching _resolve_provider's
  existing pattern, so a misconfigured default is actionable from logs.
- Note in a comment that the cache multipliers are Anthropic-derived, so
  applying them to an OpenRouter-reported cache read is an approximation.
- _platform_choice logs a warning when it falls through to the OpenRouter
  platform key, naming the fact that ANTHROPIC_API_KEY is unset and
  requests are therefore not running on the Claude Platform on AWS. A
  dedicated platform_provider setting was considered and rejected: it
  would reintroduce the configuration ambiguity this epic is removing, so
  inferring from key presence plus a loud warning is enough for now.
- classify_content_blocks logs a warning (deduped per call) for any
  content block type it does not recognize, instead of silently dropping
  it. A future block type that carries answer text would otherwise
  truncate answers with no error -- the same invisible-failure class the
  caching layer already guards against.
- anthropic_api_key_env_var and openrouter_api_key_env_var log a warning
  when coercing a present-but-blank value to None, so a broken template
  substitution is as visible as a wrong env var name already is.
- Add a `model: str` field to AskResponse and ChatResponse, and include
  the resolved model in the streaming `done` event, so callers can see
  which model actually answered instead of only server logs.
BYOKHeaders, get_byok_headers, GetBYOK, and get_llm_api_key have zero
callers in src/ now that chat.py is gone (verified with a repo-wide
grep). They implement the weaker pre-Phase-2 key resolution with no
origin check or community scoping (see resolve_byok/_resolve_provider in
src/api/routers/community.py for the current logic), so leaving them
around invites a future route to copy the weaker pattern. Remove them
and their tests.
Needed for the new BYOK/CLI regression tests (items 16-17): the CLI
client and the FastAPI BYOK path both build their own httpx.Client
internally with no transport injection point, so the existing
httpx.MockTransport pattern (used elsewhere in this repo) cannot reach
them. respx patches httpx at the transport level app-wide instead.
…BYOK

- Real-shape cache regression (item 12, the important one): build
  usage_metadata through the real langchain_anthropic._create_usage_metadata
  against a real anthropic.types.usage.Usage/CacheCreation, for both
  extract_token_usage and _extract_token_usage. The hand-built
  {"cache_read": N, "cache_creation": M} shape the existing tests use is
  not what the real API produces once caching is active, which is why the
  mispricing bug went unnoticed.
- Provider dispatch: create_community_assistant with a ByokCredential for
  each provider, asserting the constructed model type (CachingChatAnthropic
  vs CachingLLMWrapper).
- Drift tests alongside test_every_offered_model_has_an_openrouter_slug:
  every OFFERED_MODELS key and every OPENROUTER_MODEL_IDS value must be in
  MODEL_PRICING.
- Alias mapping: every MODEL_ALIASES entry resolves to a valid OpenRouter
  slug through the canonicalize-then-map path, plus _select_model cases
  for a legacy alias on the OpenRouter path (both as a community default
  and as a requested model).
- HTTP-level BYOK (tests/test_api/test_byok_http.py): TestClient requests
  carrying X-Anthropic-API-Key to /ask and /chat from an unauthorized
  origin, asserting no 403, with a control test proving the same origin
  without BYOK really is rejected. respx mocks the Anthropic Messages API
  boundary so the full router/authorization/agent-loop path runs for real
  without leaving the process.
- CLI: a user with only ANTHROPIC_API_KEY configured does not take the
  "No API key" path, and the outgoing request carries X-Anthropic-API-Key
  (respx-mocked HTTP boundary).
- Pin CACHE_WRITE_MULTIPLIER == 1.25 and CACHE_READ_MULTIPLIER == 0.1 as
  external business facts.
- classify_content_blocks: unrecognized-type warning (once per call, and
  never for tool_use), plus a {"type": "text"} block with no "text" key.
- Rename test_authorization.py's TestIntegration (misleading name for
  unit-level, non-HTTP tests) and soften test_anthropic_router.py's module
  docstring, which claimed to prove reasoning never leaks: it greps for
  dict-repr artifacts, so it cannot catch a classification swap that
  streams reasoning as ordinary text; the unit tests in
  tests/test_agents/test_content.py cover that classification.
- Note on test_slugs_are_openrouter_shaped that it checks shape only; a
  wrong-but-well-formed slug would only surface as a live 400 from
  OpenRouter, since nothing here makes a real OpenRouter call.
src/core/services/llm.py carried a third model-construction path with its
own direct OpenAI, direct Anthropic, and OpenRouter factories. Nothing in
production called it: create_community_assistant uses only
get_config_with_tracing, for LangFuse. Its model tables had already drifted
out of step with the offered models, so CI failed once the platform default
became claude-haiku-4-5, an id those tables do not know.

Teaching a dead path the new ids would have kept a contradictory third
route alive, so remove the construction surface instead and keep the
tracing helper that production actually uses. Model construction stays in
anthropic_llm for platform traffic and litellm_llm for bring-your-own-key
OpenRouter traffic.

The tests for the removed surface go with it; the LangFuse and singleton
tests are unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant