Repository navigation
Phase 1: Anthropic LLM service for the Claude Platform on AWS - #365
Conversation
Add src/core/services/anthropic_llm.py: server-mode (AWS Claude Platform) and BYOK (first-party API) credential handling, per-model thinking policy for claude-haiku-4-5 and claude-sonnet-5, and a CachingChatAnthropic subclass that applies prompt-cache breakpoints via ChatAnthropic's _get_request_payload funnel so caching survives tool binding and streaming. Does not change request routing or default_model; wiring this into agents/routers is phase 2.
Add anthropic_base_url, anthropic_workspace_id, anthropic_thinking_budget_tokens, anthropic_max_output_tokens, and anthropic_cache_ttl to Settings for the Claude Platform on AWS. default_model / default_model_provider are unchanged (phase 2 flips routing). Add first-party pricing entries claude-haiku-4-5 and claude-sonnet-5 to MODEL_PRICING; existing OpenRouter-format entries are kept for BYOK requests.
Unit tests (tests/test_core/test_anthropic_llm.py): normalize_model, default_thinking, _validate_thinking, create_anthropic_llm credential and thinking/temperature/caching selection, and CachingChatAnthropic payload shape (system cache_control, trailing breakpoint, marker count within Anthropic's limit of 4, caching preserved through bind_tools, and a plain ChatAnthropic control case with no cache_control). No mocks: all assertions run against real constructed objects and real _get_request_payload output. Integration tests (tests/test_integration/test_anthropic_platform.py): real calls against the Claude Platform on AWS for Haiku default thinking (including a tool-call round trip) and Sonnet adaptive thinking. Skips on missing credentials via Settings rather than os.getenv, since ANTHROPIC_API_KEY here is only available through Settings' .env loading and is never exported to the process environment.
- Stop mutating caller-owned system message blocks when placing the
system prompt cache breakpoint; langchain_anthropic reuses the
caller's own dict objects for list-content system messages, so the
previous in-place assignment leaked one instance's cache TTL into a
later request built from the same SystemMessage.
- Make explicit thinking=None actually disable thinking on
adaptive-default models (claude-sonnet-5) by sending
{"type": "disabled"} instead of omitting the key, since an omitted
key defaults to adaptive thinking on that generation. Budget-style
models keep the existing omit-the-key behavior.
- Raise RuntimeError at construction time when ANTHROPIC_BASE_URL is
set without ANTHROPIC_WORKSPACE_ID, instead of failing later with an
opaque 4xx from the AWS endpoint, which requires the
anthropic-workspace-id header.
- Add module logging: warn when the parent's cache_control kwarg
silently fails to land on any message block (a permanent, invisible
caching no-op otherwise), and warn if a system cache breakpoint
cannot be placed because the last system block is not a dict.
- Validate cache_ttl on CachingChatAnthropic itself via a pydantic
field validator, so the invariant holds even when the class is
constructed directly instead of through create_anthropic_llm.
- Include the offending thinking "type" value in the non-adaptive
validation error message, matching the adaptive branch.
- Document the prompt-cache breakpoint budget (at most 2 markers added
per call, out of Anthropic's 4-marker limit) on CachingChatAnthropic
for Phase 2's benefit.
Not run against a live endpoint yet; verified via
tests/test_core/test_anthropic_llm.py in a follow-up commit.
- Module docstring: restate the env var requirements precisely now that a base URL without a workspace id is rejected at construction time; only ANTHROPIC_API_KEY is strictly required. - Temperature-forwarding comment: attribute the rules correctly. claude-sonnet-5 rejects any non-default temperature/top_p/top_k unconditionally, independent of thinking state; claude-haiku-4-5 accepts temperature except while extended thinking is on. - anthropic_workspace_id field description: it identifies a Claude Platform on AWS workspace (format wrkspc_...); AWS Marketplace is only the billing channel, not the resource itself. - Integration test docstring: narrow the claim about the old LiteLLM wrapper. Its public invoke()/bind_tools() path would have worked; the actual breakage was _generate()/_agenerate() delegating to self.llm._generate(), which a RunnableBinding does not expose.
…fig fixes
- Replace a tautological base_url assertion with a comparison against a
real no-argument ChatAnthropic instance.
- Add a source-introspection guard that fails loudly if a
langchain-anthropic upgrade stops calling _get_request_payload from
_generate/_stream/_agenerate/_astream, since every caching test here
calls that method directly and would stay green regardless.
- Cover the list-form system content branch: breakpoint lands on the
last block only, an already-marked list is not double-marked, and
the caller's SystemMessage is left unmutated (locks in the fix-1
mutation bug).
- Add a distinct-value test proving anthropic_thinking_budget_tokens
is read from settings rather than the module's own default constant
(both happen to be 2048, which the previous tests never exercised).
- Lock DEFAULT_THINKING_BUDGET_TOKENS and Settings' field default
together with an explicit equality assertion.
- Exercise the thinking-budget-vs-max_tokens conflict through the
public create_anthropic_llm() entry point.
- Cover explicit thinking=None on claude-sonnet-5 (must send
{"type": "disabled"}) and rename the misleading with_thinking_off
local variable now that "off" for sonnet-5 is an explicit value, not
an omitted key.
- Cover base_url-without-workspace_id raising RuntimeError, and
workspace_id-without-base_url still constructing.
- Assert the non-default cache TTL on the trailing message block, not
only the system block.
- Add direct-construction tests for CachingChatAnthropic's cache_ttl
field validator (valid and invalid TTLs).
All 56 tests pass; ruff check and format clean.
Add a test that two sequential calls sharing a large, unique system prefix (repeated text comfortably above Haiku's ~4096-token minimum cacheable prefix) produce a non-zero cache_read on the second call's usage_metadata. No unit test can prove caching actually works on the wire, only that a cache_control marker is present in the outgoing payload. Verified manually that the test fails (cache_read == 0) when enable_caching=False, and that the first call's cache_read is 0 with a fresh unique run marker, so the pass is not vacuous.
The integration-tests job only checked and exported OPENROUTER_API_KEY, so tests/test_integration/test_anthropic_platform.py could never run in CI; it silently skipped every time (Settings finds no ANTHROPIC_API_KEY). Add a parallel check step for the three Anthropic env vars with its own has_anthropic_key output and warning, and a step that runs just the Anthropic integration test module when that check passes. Existing OpenRouter steps are unchanged. Secrets (ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL, ANTHROPIC_WORKSPACE_ID) still need to be added to the repository by the owner; until then this job continues to warn and skip, same as it does today for OpenRouter.
CI and the deployment image both install with uv pip install --system, which ignores uv.lock and resolved langchain-anthropic 1.7.2 while the lockfile pinned 1.3.1. The caching override was therefore written and verified against a version that never reaches production. On 1.7.2 the library forwards a top-level cache_control kwarg straight to the direct Anthropic API, which attaches the breakpoint to the last cacheable block itself, and only expands the kwarg into block-level markers for transports that cannot take the parameter. Caching still works, verified against the live endpoint, but the payload shape differs. Raise the floor to 1.7.2 so the lockfile matches what is deployed, accept either breakpoint shape in the no-op warning and in the tests, and count a top-level parameter as one marker against the Anthropic limit of four.
|
Note on the lockfile churn in the last commit, since it is larger than the one-line pyproject change suggests. CI and What moved: The behavioral difference that caused the original CI failure: on 1.7.2 langchain-anthropic forwards a top-level Separately, |
6d163f8
into
feature/issue-360-epic-anthropic-platform
Summary
Adds the provider layer for the Claude Platform on AWS, an Anthropic-operated Messages API billed through AWS Marketplace (not Amazon Bedrock), which is where HEDit already runs and where OSA now has its own key.
Nothing in the request path changes yet.
default_modelanddefault_model_providerare deliberately untouched, so the API keeps serving through OpenRouter after this merges; Phase 2 switches routing over.src/core/services/anthropic_llm.pyprovides:claude-haiku-4-5(default) andclaude-sonnet-5, plus aliases that normalize the legacy OpenRouter-style ids sitting in saved widget settings, CLI configs, and every communityconfig.yaml.adaptiveordisabled, Haiku 4.5 has no adaptive mode and needs an explicitbudget_tokens(default 2048). Temperature is dropped wherever the model would reject it.ANTHROPIC_API_KEYwithANTHROPIC_BASE_URLand theanthropic-workspace-idheader; a caller-supplied key is not authorized on that workspace, so BYOK pinsapi.anthropic.comexplicitly. Pinning matters: without itChatAnthropicinherits the process-wide base URL and sends a first-party key to the AWS endpoint, which rejects it.CachingChatAnthropic, aChatAnthropicsubclass overriding the single private funnel_get_request_payload. ABaseChatModelwrapper, the shape the LiteLLM path uses, has to reimplement seven methods and its_generatebreaks oncebind_toolsreturns aRunnableBinding. The subclass keeps tool binding, streaming,astream_events, and usage metadata native, and it is the reason a tool-calling round trip with thinking on now works.Settings gain
anthropic_base_url,anthropic_workspace_id,anthropic_thinking_budget_tokens,anthropic_max_output_tokens, andanthropic_cache_ttl. Pricing gains the two first-party ids; every OpenRouter-format key stays, since BYOK requests still need them.Closes #361
Part of epic #360
Test plan
uv run pytest tests/test_core/test_anthropic_llm.py- 40 unit tests over model normalization, the per-model thinking rules, both credential modes, and the payload shape. The payload assertions are deliberate: the caching override depends on one private method of langchain-anthropic, and a test that asserts a plainChatAnthropicpayload carries nocache_controlis what turns a silent no-op after an upgrade into a failure.uv run pytest -m llm tests/test_integration/test_anthropic_platform.py- 3 tests making real calls against the platform endpoint: Haiku with the default thinking budget, a Haiku tool-call round trip with thinking on, and Sonnet 5 with adaptive thinking.uv run pytest tests/test_core tests/test_metrics tests/test_api- 767 passed, 7 skipped, no regressions.uv run ruff check . && uv run ruff format --check .- clean.The integration run is the real gate, and it passed: it proves the key, base URL, and workspace header are correct before Phase 2 routes traffic onto them.