Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agent-core): cache the Claude prompt prefix for an hour (#2484)
Call White259726f1bc0d
diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex d5e80f948..99b8dfc32 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -8,6 +8,8 @@ httpx directly so Model Hub remains the only gateway boundary.from __future__ import annotationsimport json+import logging+import refrom collections.abc import AsyncIterator, Mappingfrom typing import Any@@ -32,6 +34,7 @@ from core.agent_core.ai._common import ()from core.agent_core.ai.provider import (Done,+ ModelEndpoint,ModelRequest,ProviderAdapter,ProviderError,@@ -48,8 +51,17 @@ from core.agent_core.messages import (UserMessage,)+logger = logging.getLogger(__name__)+ANTHROPIC_VERSION = "2023-06-01"_MAX_CACHE_BREAKPOINTS = 4+# A Claude route caches its static prefix, the tools and then the system prompt, for an hour (``_prefix_ttl``); the+# conversation's breakpoints keep the default five minutes. Anthropic evaluates breakpoints as tools, system, messages+# and requires every longer lifetime to come before every shorter one, which this placement satisfies.+_PREFIX_TTL = "1h"+# Routes whose endpoint rejected the field. They keep the default lifetime for the rest of the process.+_TTL_REJECTED_ROUTES: set[tuple[str, str, str]] = set()+_TTL_REJECTION = re.compile(r"cache_control|\bttl\b", re.IGNORECASE)_LEGACY_THINKING_BUDGETS = {"minimal": 1024,"low": 2048,@@ -191,13 +203,17 @@ class AnthropicAdapter(ProviderAdapter):async def _stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[Any]:origin = endpoint_origin(request.endpoint)- assembler = StreamAssembler(- origin=origin,- protocol=self.protocol,- verified_origin=not self._gateway,- endpoint_url=request.endpoint.base_url,- sensitive_values=request_credential_values(request.endpoint),- )++ def new_assembler() -> StreamAssembler:+ return StreamAssembler(+ origin=origin,+ protocol=self.protocol,+ verified_origin=not self._gateway,+ endpoint_url=request.endpoint.base_url,+ sensitive_values=request_credential_values(request.endpoint),+ )++ assembler = new_assembler()if cancel.cancelled:terminal = assembler.terminal(assembler.aborted(cancel.reason))if terminal is not None:@@ -226,8 +242,8 @@ class AnthropicAdapter(ProviderAdapter):stop_reason: str | None = Nonemessage_started = Falsemessage_stopped = False+ prefix_ttl = _prefix_ttl(request)try:- payload = build_messages_payload(request, transformed_messages, loaded_images=loaded_images)headers = auth_headers(request.endpoint, provider="anthropic", gateway=self._gateway)headers.update({"anthropic-version": ANTHROPIC_VERSION, "content-type": "application/json"})url = join_endpoint_url(request.endpoint.base_url, "/messages")@@ -723,24 +739,39 @@ class AnthropicAdapter(ProviderAdapter):terminal = assembler.terminal(assembler.incomplete())if terminal is not None:yield terminal- driver = drive_sse_stream(- self._client,- method="POST",- url=url,- json_body=payload,- headers=headers,- cancel=cancel,- assembler=assembler,- endpoint=request.endpoint,- resolver=self._served_hop_resolver,- gateway=self._gateway,- translate=translate,- )- try:- async for event in driver:- yield event- finally:- await driver.aclose()+ while True:+ payload = build_messages_payload(+ request, transformed_messages, loaded_images=loaded_images, prefix_ttl=prefix_ttl+ )+ driver = drive_sse_stream(+ self._client,+ method="POST",+ url=url,+ json_body=payload,+ headers=headers,+ cancel=cancel,+ assembler=assembler,+ endpoint=request.endpoint,+ resolver=self._served_hop_resolver,+ gateway=self._gateway,+ translate=translate,+ )+ rejected = False+ try:+ async for event in driver:+ if prefix_ttl is not None and _rejects_ttl(event):+ rejected = True+ break+ yield event+ finally:+ await driver.aclose()+ if not rejected:+ return+ # The endpoint refused the request before answering, so the consumer saw nothing: send it once more+ # with the default lifetime, which this route keeps from now on.+ _remember_ttl_rejection(request.endpoint)+ prefix_ttl = None+ assembler = new_assembler()except Exception as exc:terminal = assembler.terminal(assembler.exception(exc))if terminal is not None:@@ -752,8 +783,12 @@ def build_messages_payload(messages: tuple[Any, ...],*,loaded_images: Mapping[str, tuple[str, str]] | None = None,+ prefix_ttl: str | None = None,) -> dict[str, Any]:- """Build the Anthropic Messages request body."""+ """Build the Anthropic Messages request body.++ ``prefix_ttl`` is the lifetime of the tool and system breakpoints; message breakpoints keep the default.+ """payload_messages: list[dict[str, Any]] = []for message in messages:@@ -766,7 +801,7 @@ def build_messages_payload(system: Any = request.systemif request.cache == "default" and request.system:- system = [{"type": "text", "text": request.system, "cache_control": {"type": "ephemeral"}}]+ system = [{"type": "text", "text": request.system, "cache_control": _cache_control(prefix_ttl)}]if request.cache == "default":_mark_message_breakpoints(payload_messages)payload: dict[str, Any] = {@@ -783,7 +818,7 @@ def build_messages_payload("description": tool.description,"input_schema": dict(tool.input_schema),**(- {"cache_control": {"type": "ephemeral"}}+ {"cache_control": _cache_control(prefix_ttl)}if request.cache == "default" and index == len(request.tools) - 1else {}),@@ -886,11 +921,68 @@ def _mark_message_breakpoints(messages: list[dict[str, Any]]) -> None:for index in candidates[-2:]:content = messages[index]["content"]if isinstance(content, str):- messages[index]["content"] = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}]+ messages[index]["content"] = [{"type": "text", "text": content, "cache_control": _cache_control()}]elif content:last = content[-1]if isinstance(last, dict) and last.get("type") in {"text", "image", "tool_result"}:- last["cache_control"] = {"type": "ephemeral"}+ last["cache_control"] = _cache_control()+++def _cache_control(ttl: str | None = None) -> dict[str, str]:+ """One breakpoint; without ``ttl`` it keeps Anthropic's default five-minute lifetime."""++ return {"type": "ephemeral", "ttl": ttl} if ttl else {"type": "ephemeral"}+++def _prefix_ttl(request: ModelRequest) -> str | None:+ """The static prefix's lifetime: an hour where the field is known to work, else the default (``None``).++ Known means a Claude model on the Anthropic vendor, read from the hop: the vendor id exactly, and a model id that+ starts with ``claude-``. Another vendor's Anthropic-compatible endpoint keeps the default even for a Claude id.+ """++ endpoint = request.endpoint+ if (+ request.cache != "default"+ or not (request.tools or request.system)+ or endpoint.provider != "anthropic"+ or not endpoint.model_id.startswith("claude-")+ or _ttl_route(endpoint) in _TTL_REJECTED_ROUTES+ ):+ return None+ return _PREFIX_TTL+++def _ttl_route(endpoint: ModelEndpoint) -> tuple[str, str, str]:+ return (endpoint.base_url, endpoint.provider, endpoint.model_id)+++def _rejects_ttl(event: Any) -> bool:+ """A request the endpoint refused with an error naming the field.++ Only an HTTP error status sets ``status``, so such an error is the response's first and only event.+ """++ return (+ isinstance(event, ProviderError)+ and event.kind == "invalid_request"+ and event.status is not None+ and 400 <= event.status < 500+ and _TTL_REJECTION.search(event.message) is not None+ )+++def _remember_ttl_rejection(endpoint: ModelEndpoint) -> None:+ route = _ttl_route(endpoint)+ if route in _TTL_REJECTED_ROUTES:+ return+ _TTL_REJECTED_ROUTES.add(route)+ logger.warning(+ "The endpoint for %s model %s rejected the 1-hour prompt-cache TTL; "+ "this route uses the default 5-minute TTL until the process restarts",+ endpoint.provider,+ endpoint.model_id,+ )def _error_event_shape_error(chunk: Mapping[str, Any]) -> str | None:diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 2e58a62d7..715bdcfb6 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -304,7 +304,7 @@ Pi's separate `cacheWrite1h` (`:840-847`) has no canonical counterpart.| `cache_creation_input_tokens` | `cache_write_tokens`; non-null aggregate wins over every TTL value, including when aggregate is zero || `cache_creation` | Nullable TTL breakdown container. If aggregate is missing/null, sum its non-null counters as the reported snapshot; missing/null/empty/all-null breakdown preserves current aggregate. Do not add a TTL snapshot to previous usage. || `cache_creation.ephemeral_5m_input_tokens` | Part of fallback `cache_write_tokens` sum only; absent/null contributes nothing. Explicit zero is a reported value. No separate TTL field. |-| `cache_creation.ephemeral_1h_input_tokens` | Same fallback policy as 5m; never added on top of an aggregate. No separate 1h billing field. |+| `cache_creation.ephemeral_1h_input_tokens` | Same fallback policy as 5m; never added on top of an aggregate. No separate 1h billing field; Model Hub's usage ledger meters the one-hour part (`cache_write_1h_input_tokens`, `model-hub-contracts/api.md`). || `output_tokens_details` | Nullable decomposition container; not itself a count || `output_tokens_details.thinking_tokens` | `reasoning_tokens`; non-null merge at both message start and delta. This observability subset does not increase `output_tokens`. || `server_tool_use` | Ignored: server-side request-count metadata, not tokens or canonical tool calls |@@ -501,15 +501,16 @@ credential-free stubs and did not alter the Pi source or Avibe dependencies.| Canonical field | Request mapping || --- | --- |-| `system` | `system`, as a text string or one text block with `cache_control` when `cache="default"`. |+| `system` | `system`, as a text string, or as one text block carrying the prefix breakpoint (Cache, below) when `cache="default"`. || User text/image | `messages[].role="user"`; text blocks become `text`; images become `image` with a base64 `source`. || Assistant text | `messages[].role="assistant"` with `text` blocks. || Thinking | Same-origin signed thinking becomes `thinking` with `thinking` and `signature`; same-origin redacted thinking becomes `redacted_thinking` with `data`; unsigned thinking becomes text. || Tool call | `tool_use` with `id`, `name`, and parsed `input`. || Tool result | A user message containing `tool_result` with `tool_use_id`, `content`, and `is_error`. |-| Tools | `tools[]` with `name`, `description`, and `input_schema`; the final tool receives a cache breakpoint for `cache="default"`. |+| Tools | `tools[]` with `name`, `description`, and `input_schema`; the final tool carries the prefix breakpoint (Cache, below) for `cache="default"`. || Reasoning effort | `none/off/disabled` → `thinking.type="disabled"`; other values → adaptive thinking and `output_config.effort` (`minimal` maps to `low`, `xhigh` to `max`). |-| Cache | At most four breakpoints: system, final tool, and the two latest eligible user-message tails. |+| Cache | For `cache="default"`, at most four breakpoints, in Anthropic's evaluation order: the final tool, the system block, and the two latest eligible user-message tails. On a Claude route (the hop's `provider` is exactly `anthropic` and its model id starts with `claude-`), the tool and system breakpoints are `{"type":"ephemeral","ttl":"1h"}`. Message tails are always `{"type":"ephemeral"}`, the five-minute default, so no longer lifetime follows a shorter one. Every other route, including another vendor's Anthropic-compatible endpoint even for a `claude-` id, sends `{"type":"ephemeral"}` everywhere. `cache="none"` sends no breakpoint. |+| Cache TTL rejection | A 4xx `invalid_request` whose message names `ttl` or `cache_control`, answering a request that carried `ttl`, is resent once without it before any event reaches the loop. The route (`base_url`, `provider`, model id) then sends no `ttl` for the rest of the process; the downgrade is logged once per route. |Anthropic stream events:diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdindex 312bf3318..f1d55dffb 100644--- a/docs/plans/agent-core-contracts/provider.md+++ b/docs/plans/agent-core-contracts/provider.md@@ -44,7 +44,8 @@ class ModelRequest:tools: Sequence[ToolSpec] # C-7; may differ on every callmax_tokens: intreasoning_effort: str | None # one of the hop's declared efforts, or None- cache: Literal["default", "none"] # "none" for the compaction summarizer+ cache: Literal["default", "none"] # "default": the protocol's cache breakpoints and their lifetimes+ # (conversion-tables.md); "none" for the compaction summarizersupports_images: bool # resolved by the loop; unknown capability counts as False```diff --git a/tests/agent_core/ai/test_anthropic_prompt_cache.py b/tests/agent_core/ai/test_anthropic_prompt_cache.pynew file mode 100644index 000000000..33f7051ef--- /dev/null+++ b/tests/agent_core/ai/test_anthropic_prompt_cache.py@@ -0,0 +1,266 @@+"""Anthropic prompt-cache breakpoints, read on the wire at the adapter's HTTP boundary.++A Claude route caches its static prefix (tools, then system) for an hour and the conversation for the default five+minutes; every other route keeps the default everywhere. An endpoint that rejects the field never fails a turn+(C-2 ``conversion-tables.md``, Anthropic "Cache" row). Usage parsing of the TTL breakdown is pinned by+``test_provider_adapters.py`` (``test_anthropic_usage_*``).+"""++from __future__ import annotations++import json+import logging+import uuid+from typing import Any++import httpx+import pytest++from core.agent_core.ai.anthropic import AnthropicAdapter+from core.agent_core.ai.provider import Done, ModelEndpoint, ModelRequest, ProviderError+from core.agent_core.cancel import CancelToken+from core.agent_core.messages import AssistantMessage, Origin, TextBlock, ToolCallBlock, ToolResultMessage, UserMessage+from core.agent_core.tools.base import ToolSpec+from core.handlers.model_hub.provenance import produce_turn_outcome, render_turn_outcome_copy++HOUR = {"type": "ephemeral", "ttl": "1h"}+DEFAULT = {"type": "ephemeral"}+LIFETIME_S = {"1h": 3600, None: 300}+SYSTEM = "You are a coding agent."+CLAUDE = "claude-opus-5-5"+TOOLS = (+ ToolSpec("read", "Read a file.", {"type": "object"}),+ ToolSpec("bash", "Run a command.", {"type": "object"}),+)+CONVERSATION = (+ UserMessage((TextBlock("list the files"),)),+ AssistantMessage(+ (ToolCallBlock("toolu_1", "bash", {"command": "ls"}),),+ origin=Origin("anthropic", "anthropic", CLAUDE),+ stop_reason="tool_use",+ ),+ ToolResultMessage("toolu_1", "bash", (TextBlock("a.txt"),)),+)+SUCCESS = (+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":1}}}\n\n'+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}\n\n'+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}\n\n'+ 'data: {"type":"content_block_stop","index":0}\n\n'+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}\n\n'+ 'data: {"type":"message_stop"}\n\n'+)+TTL_REJECTED = "system.0.cache_control.ttl: Extra inputs are not permitted"+# The two shapes the rejection reaches the adapter in: the endpoint's own Anthropic envelope, and Model Hub's gateway+# (Vibey's only route), which surfaces the upstream message inside its own copy.+ANTHROPIC_REJECTION = {"type": "error", "error": {"type": "invalid_request_error", "message": TTL_REJECTED}}+GATEWAY_REJECTION = {+ "error": {+ "type": "upstream_request_invalid",+ "code": "upstream_request_invalid",+ "message": render_turn_outcome_copy(+ produce_turn_outcome("turn.request_nonfallback", upstream_detail=TTL_REJECTED), "en"+ ),+ }+}+++def _request(+ provider: str = "anthropic",+ model_id: str = CLAUDE,+ *,+ cache: str = "default",+ system: str = SYSTEM,+ tools: tuple[ToolSpec, ...] = TOOLS,+ messages: tuple[Any, ...] = CONVERSATION,+ base_url: str | None = None,+) -> ModelRequest:+ # A fresh endpoint per request unless one is given: a route's TTL memory lasts the process.+ return ModelRequest(+ endpoint=ModelEndpoint(+ "anthropic", base_url or f"https://{uuid.uuid4().hex}.test/v1", model_id, "token", provider=provider+ ),+ system=system,+ messages=messages,+ tools=tools,+ max_tokens=128,+ cache=cache, # type: ignore[arg-type]+ )+++def _breakpoints(body: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]:+ """Every breakpoint in Anthropic's evaluation order: tools, then system, then messages."""++ blocks = [(f"tools.{i}", tool) for i, tool in enumerate(body.get("tools", ()))]+ if isinstance(body["system"], list):+ blocks += [(f"system.{i}", block) for i, block in enumerate(body["system"])]+ for m, message in enumerate(body["messages"]):+ if isinstance(message["content"], list):+ blocks += [(f"messages.{m}.content.{c}", block) for c, block in enumerate(message["content"])]+ return [(where, block["cache_control"]) for where, block in blocks if "cache_control" in block]+++def _carries_ttl(body: dict[str, Any]) -> bool:+ return any("ttl" in cache_control for _, cache_control in _breakpoints(body))+++def _without_ttl(value: Any) -> Any:+ if isinstance(value, list):+ return [_without_ttl(item) for item in value]+ if not isinstance(value, dict):+ return value+ return {+ key: {k: v for k, v in item.items() if k != "ttl"} if key == "cache_control" else _without_ttl(item)+ for key, item in value.items()+ }+++async def _run(client: httpx.AsyncClient, request: ModelRequest) -> list[Any]:+ return [event async for event in AnthropicAdapter(client).stream(request, CancelToken())]+++async def _wire(request: ModelRequest) -> tuple[bytes, dict[str, Any]]:+ sent: list[bytes] = []++ def handler(wire: httpx.Request) -> httpx.Response:+ sent.append(wire.content)+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=SUCCESS)++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ events = await _run(client, request)+ assert isinstance(events[-1], Done)+ assert len(sent) == 1+ return sent[0], json.loads(sent[0])+++ ("provider", "model_id", "cache", "prefix"),+ [+ ("anthropic", CLAUDE, "default", HOUR),+ ("anthropic", "claude-haiku-4-5-20251001", "default", HOUR),+ # Another vendor's Anthropic-compatible endpoint, even when it names a Claude model: support is unknown.+ ("custom", CLAUDE, "default", DEFAULT),+ ("custom", "kimi-k2-turbo-preview", "default", DEFAULT),+ # A non-Claude model behind the Anthropic vendor, and an id that only contains the family name.+ ("anthropic", "gpt-5", "default", DEFAULT),+ ("anthropic", "relay-claude-opus-5-5", "default", DEFAULT),+ ("anthropic", CLAUDE, "none", None),+ ],+)+async def test_only_a_claude_route_caches_its_static_prefix_for_an_hour(+ provider: str, model_id: str, cache: str, prefix: dict[str, str] | None,+) -> None:+ raw, body = await _wire(_request(provider, model_id, cache=cache))++ if prefix is None:+ assert body["system"] == SYSTEM+ assert _breakpoints(body) == []+ else:+ assert _breakpoints(body) == [+ ("tools.1", prefix),+ ("system.0", prefix),+ ("messages.0.content.0", DEFAULT),+ ("messages.2.content.0", DEFAULT),+ ]+ if prefix is not HOUR:+ # Today's request, unchanged: no route but a Claude one ever sees the field.+ assert b'"ttl"' not in raw+++ ("system", "tools", "messages"),+ [+ (SYSTEM, TOOLS, CONVERSATION),+ (SYSTEM, (), CONVERSATION),+ ("", TOOLS, CONVERSATION),+ (SYSTEM, TOOLS, (UserMessage((TextBlock("hello"),)),)),+ ("", (), CONVERSATION),+ ],+ ids=["tools-system-messages", "no-tools", "no-system", "one-message", "messages-only"],+)+async def test_a_longer_cache_lifetime_never_follows_a_shorter_one(+ system: str, tools: tuple[ToolSpec, ...], messages: tuple[Any, ...],+) -> None:+ # Anthropic rejects a 1h breakpoint evaluated after a 5m one; tools, system, messages is its evaluation order.+ _raw, body = await _wire(_request(system=system, tools=tools, messages=messages))++ lifetimes = [LIFETIME_S[cache_control.get("ttl")] for _, cache_control in _breakpoints(body)]+ assert lifetimes == sorted(lifetimes, reverse=True)+ assert len(lifetimes) <= 4+ assert all(+ where.startswith(("tools.", "system.")) == (cache_control == HOUR)+ for where, cache_control in _breakpoints(body)+ )++[email protected]("rejection", [ANTHROPIC_REJECTION, GATEWAY_REJECTION], ids=["endpoint", "model-hub"])[email protected]("retry_accepted", [True, False], ids=["ttl-rejected", "cache-control-rejected"])+async def test_a_rejected_ttl_is_retried_once_without_it_and_remembered_for_the_route(+ rejection: dict[str, Any], retry_accepted: bool, caplog: pytest.LogCaptureFixture,+) -> None:+ sent: list[dict[str, Any]] = []++ def handler(wire: httpx.Request) -> httpx.Response:+ body = json.loads(wire.content)+ sent.append(body)+ if _carries_ttl(body) or not retry_accepted:+ return httpx.Response(400, json=rejection)+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=SUCCESS)++ caplog.set_level(logging.WARNING, logger="core.agent_core.ai.anthropic")+ request = _request()+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ runs = [+ await _run(client, request),+ # A later run builds its own adapter; the route keeps the default for the process.+ await _run(client, request),+ # The memory is the route's: another model on the same endpoint still asks for the hour.+ await _run(client, _request(model_id="claude-sonnet-5", base_url=request.endpoint.base_url)),+ ]++ rejected, retried, remembered, other_rejected, other_retried = sent+ assert _breakpoints(rejected)[:2] == [("tools.1", HOUR), ("system.0", HOUR)]+ # Exactly one retry: the same request with the default lifetime.+ assert retried == _without_ttl(rejected)+ assert not _carries_ttl(retried)+ assert not _carries_ttl(remembered)+ assert _carries_ttl(other_rejected)+ assert other_retried == _without_ttl(other_rejected)+ for events in runs:+ # One terminal per run: a rejected attempt never reaches the consumer.+ terminals = [event for event in events if isinstance(event, (Done, ProviderError))]+ assert [type(event) for event in terminals] == [Done if retry_accepted else ProviderError]+ assert retry_accepted or terminals[0].status == 400+ # Logged once per route, not once per request.+ assert len([record for record in caplog.records if record.name == "core.agent_core.ai.anthropic"]) == 2+++ ("provider", "message"),+ [+ # A Claude route's request rejected for something else.+ ("anthropic", "messages.2: tool_result block(s) provided when previous message has no tool_use"),+ # A rejection naming the field on a route that never sent it.+ ("custom", TTL_REJECTED),+ ],+ ids=["unrelated-rejection", "no-ttl-sent"],+)+async def test_a_rejection_the_ttl_did_not_cause_is_surfaced_without_a_retry(provider: str, message: str) -> None:+ sent: list[dict[str, Any]] = []++ def handler(wire: httpx.Request) -> httpx.Response:+ sent.append(json.loads(wire.content))+ if len(sent) == 1:+ error = {"type": "invalid_request_error", "message": message}+ return httpx.Response(400, json={"type": "error", "error": error})+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=SUCCESS)++ request = _request(provider)+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ events = await _run(client, request)+ assert len(sent) == 1+ await _run(client, request)++ assert isinstance(events[-1], ProviderError)+ assert events[-1].kind == "invalid_request"+ # The route was not downgraded: its next request asks for the hour again.+ assert _carries_ttl(sent[1]) == (provider == "anthropic")