Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: support Anthropic 1h cache TTL via prompt_cache_ttl (#5685)
Daniel Hanb8dde0a8355b
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 638312b9db4..44e8720fedc 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -292,6 +292,7 @@ class ExternalProviderClient:enable_prompt_caching: Optional[bool] = None,openai_code_exec_container_id: Optional[str] = None,anthropic_code_exec_container_id: Optional[str] = None,+ prompt_cache_ttl: Optional[str] = None,stream: bool = True,) -> AsyncGenerator[str, None]:"""@@ -318,6 +319,7 @@ class ExternalProviderClient:enabled_tools,enable_prompt_caching,anthropic_code_exec_container_id,+ prompt_cache_ttl,):yield linereturn@@ -1125,6 +1127,7 @@ class ExternalProviderClient:enabled_tools: Optional[list[str]] = None,enable_prompt_caching: Optional[bool] = None,anthropic_code_exec_container_id: Optional[str] = None,+ prompt_cache_ttl: Optional[str] = None,) -> AsyncGenerator[str, None]:"""Call the Anthropic Messages API and translate its SSE to OpenAI format.@@ -1218,6 +1221,27 @@ class ExternalProviderClient:# same as True here (callers that don't set the flag still get# caching). Pass False explicitly to opt out.prompt_caching_enabled = enable_prompt_caching is not False+ # Anthropic accepts an optional `ttl` on each cache_control marker+ # (default is the 5m ephemeral pool; set "1h" to land in the 1h+ # pool instead). Per the prompt-caching docs, 1h cache writes are+ # billed at 2x base input vs 1.25x for 5m, but reads are 0.1x for+ # both. The 1h pool is the right pick when conversations span+ # multiple short bursts more than 5 minutes apart -- the read+ # discount makes up for the 1.6x write premium after a single+ # additional hit. Anything other than the known TTL strings is+ # dropped to avoid sending a malformed marker.+ #+ # The `extended-cache-ttl-2025-04-11` beta header that originally+ # gated 1h TTL has been promoted to GA: as of 2026-05 the live+ # API accepts `ttl: "1h"` without any beta opt-in. Verified+ # against api.anthropic.com on claude-opus-4-7 (status 200 ++ # `ephemeral_1h_input_tokens` populated). The test below pins+ # the contract by asserting the header is NOT on the wire so a+ # future regression that reintroduces the gate would surface+ # before users see a 400.+ cache_marker: dict[str, Any] = {"type": "ephemeral"}+ if prompt_cache_ttl in ("5m", "1h"):+ cache_marker["ttl"] = prompt_cache_ttlif system:if prompt_caching_enabled:@@ -1229,7 +1253,7 @@ class ExternalProviderClient:{"type": "text","text": system,- "cache_control": {"type": "ephemeral"},+ "cache_control": dict(cache_marker),}]else:@@ -1252,7 +1276,7 @@ class ExternalProviderClient:{"type": "text","text": content,- "cache_control": {"type": "ephemeral"},+ "cache_control": dict(cache_marker),}]elif isinstance(content, list) and content:@@ -1263,7 +1287,7 @@ class ExternalProviderClient:head = list(content[:-1])tail = content[-1]if isinstance(tail, dict):- head.append({**tail, "cache_control": {"type": "ephemeral"}})+ head.append({**tail, "cache_control": dict(cache_marker)})else:head.append(tail)last_msg["content"] = headdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex f8bf219846f..b33aa259353 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -662,6 +662,19 @@ class ChatCompletionRequest(BaseModel):"vllm, local, etc.). Treated as enabled when omitted."),)+ prompt_cache_ttl: Optional[str] = Field(+ None,+ description = (+ "[x-unsloth] Anthropic cache_control TTL. Defaults to the 5-minute "+ "ephemeral pool when omitted. Pass `1h` to write into the 1-hour "+ "pool instead -- 1h writes are billed at 2x base input vs 1.25x "+ "for 5m, but reads stay at 0.1x for both, so 1h pays off the "+ "moment a single extra read lands more than 5 minutes after the "+ "write. Only `5m` and `1h` are forwarded; any other value is "+ "silently ignored downstream so a stale frontend can't make the "+ "API 422 on the request. No-op on every non-Anthropic provider."+ ),+ )openai_code_exec_container_id: Optional[str] = Field(None,description = (diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 47b0bdef742..8baf0b4198b 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1802,6 +1802,7 @@ async def _proxy_to_external_provider(enable_prompt_caching = payload.enable_prompt_caching,openai_code_exec_container_id = payload.openai_code_exec_container_id,anthropic_code_exec_container_id = payload.anthropic_code_exec_container_id,+ prompt_cache_ttl = payload.prompt_cache_ttl,stream = payload.stream,)try:diff --git a/studio/backend/tests/test_anthropic_cache_ttl.py b/studio/backend/tests/test_anthropic_cache_ttl.pynew file mode 100644index 00000000000..e5d806e3c27--- /dev/null+++ b/studio/backend/tests/test_anthropic_cache_ttl.py@@ -0,0 +1,201 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Unit tests for the prompt_cache_ttl threading on the Anthropic path.++Anthropic accepts an optional ``ttl`` on each ``cache_control`` marker:+the default is the 5-minute ephemeral pool; ``ttl:"1h"`` writes into+the 1-hour pool instead. The 1h pool is the right pick when+conversations span multiple short bursts more than 5 minutes apart --+1h writes are billed at 2x base input vs 1.25x for 5m, but reads stay+at 0.1x for both, so one extra read pays off the premium.++These tests pin the outbound body shape: when prompt_cache_ttl="1h"+both cache_control markers carry ``ttl:"1h"``; default omits the field+entirely so the 5m pool is used; garbage values are silently dropped.+"""++import asyncio+import json++import httpx+import pytest++from core.inference import external_provider as ep_mod+from core.inference.external_provider import ExternalProviderClient+++def _drive(coro):+ return asyncio.new_event_loop().run_until_complete(coro)+++def _make_client() -> ExternalProviderClient:+ return ExternalProviderClient(+ provider_type = "anthropic",+ base_url = "https://api.anthropic.com/v1",+ api_key = "sk-ant-test",+ )+++def _capture(monkeypatch, ttl = None) -> dict:+ captured: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["body"] = json.loads(request.content.decode("utf-8"))+ captured["headers"] = dict(request.headers)+ return httpx.Response(+ 200,+ content = (b"event: message_stop\n" b'data: {"type": "message_stop"}\n\n'),+ headers = {"content-type": "text/event-stream"},+ )++ monkeypatch.setattr(+ ep_mod,+ "_http_client",+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),+ )++ async def run():+ client = _make_client()+ async for _ in client.stream_chat_completion(+ messages = [+ {"role": "system", "content": "Be brief."},+ {"role": "user", "content": "hi"},+ ],+ model = "claude-opus-4-7",+ temperature = 0.7,+ top_p = 0.95,+ max_tokens = 32,+ enable_prompt_caching = True,+ prompt_cache_ttl = ttl,+ ):+ pass+ await client.close()++ _drive(run())+ return captured+++def _cache_controls(body: dict) -> list[dict]:+ """Pull every cache_control marker from the system block + tail message."""+ out = []+ sys_blocks = body.get("system") or []+ if isinstance(sys_blocks, list):+ for b in sys_blocks:+ if isinstance(b, dict) and "cache_control" in b:+ out.append(b["cache_control"])+ msgs = body.get("messages") or []+ if msgs:+ tail = msgs[-1].get("content")+ if isinstance(tail, list):+ for b in tail:+ if isinstance(b, dict) and "cache_control" in b:+ out.append(b["cache_control"])+ return out+++# ── default (omitted) writes into the 5m pool ──────────────────────+++def test_omitted_ttl_uses_default_5m_pool(monkeypatch):+ captured = _capture(monkeypatch, ttl = None)+ ccs = _cache_controls(captured["body"])+ assert len(ccs) == 2, ccs+ for cc in ccs:+ assert cc == {"type": "ephemeral"}, cc+++# ── explicit 5m round-trips as-is ─────────────────────────────────+++def test_explicit_5m_ttl_round_trips(monkeypatch):+ captured = _capture(monkeypatch, ttl = "5m")+ ccs = _cache_controls(captured["body"])+ assert len(ccs) == 2, ccs+ for cc in ccs:+ assert cc == {"type": "ephemeral", "ttl": "5m"}, cc+++# ── 1h writes the new pool field on every marker ───────────────────+++def test_1h_ttl_writes_into_1h_pool(monkeypatch):+ captured = _capture(monkeypatch, ttl = "1h")+ ccs = _cache_controls(captured["body"])+ assert len(ccs) == 2, ccs+ for cc in ccs:+ assert cc == {"type": "ephemeral", "ttl": "1h"}, cc+++def test_1h_ttl_does_not_send_extended_cache_ttl_beta_header(monkeypatch):+ # The `extended-cache-ttl-2025-04-11` beta header that originally+ # gated 1h cache TTL has been promoted to GA: verified live against+ # api.anthropic.com on 2026-05-22 -- a request with+ # `cache_control:{type:"ephemeral", ttl:"1h"}` and NO beta header+ # returns 200 and populates `ephemeral_1h_input_tokens`. Pin the+ # contract so we don't reintroduce the gate by accident; a future+ # regression that re-adds the header would surface here.+ captured = _capture(monkeypatch, ttl = "1h")+ beta = captured["headers"].get("anthropic-beta", "")+ assert "extended-cache-ttl-2025-04-11" not in beta, beta+++def test_5m_ttl_does_not_send_extended_cache_ttl_beta_header(monkeypatch):+ captured = _capture(monkeypatch, ttl = "5m")+ beta = captured["headers"].get("anthropic-beta", "")+ assert "extended-cache-ttl-2025-04-11" not in beta, beta+++# ── unknown values are dropped, not forwarded ──────────────────────++[email protected]("bogus", ["6m", "2h", "", "forever", "1d", "0", "1"])+def test_unknown_ttl_silently_dropped(monkeypatch, bogus):+ captured = _capture(monkeypatch, ttl = bogus)+ ccs = _cache_controls(captured["body"])+ assert len(ccs) == 2, ccs+ for cc in ccs:+ # Bogus TTLs must NOT round-trip; marker stays at the default+ # (no `ttl` key, which means the 5m pool upstream).+ assert cc == {"type": "ephemeral"}, cc+++# ── opt-out still skips cache_control entirely ─────────────────────+++def test_opt_out_skips_cache_control(monkeypatch):+ captured: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["body"] = json.loads(request.content.decode("utf-8"))+ return httpx.Response(+ 200,+ content = b'event: message_stop\ndata: {"type": "message_stop"}\n\n',+ headers = {"content-type": "text/event-stream"},+ )++ monkeypatch.setattr(+ ep_mod,+ "_http_client",+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),+ )++ async def run():+ client = _make_client()+ async for _ in client.stream_chat_completion(+ messages = [+ {"role": "system", "content": "Be brief."},+ {"role": "user", "content": "hi"},+ ],+ model = "claude-opus-4-7",+ temperature = 0.7,+ top_p = 0.95,+ max_tokens = 32,+ enable_prompt_caching = False,+ prompt_cache_ttl = "1h", # ignored when caching is off+ ):+ pass+ await client.close()++ _drive(run())+ assert _cache_controls(captured["body"]) == []