Skip to content

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.

Studio: Anthropic fast_mode toggle and streaming refusal handling (#5715)

Daniel Han7d1b68079ed8
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 25e1725337c..d8a36610b81 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -173,10 +173,28 @@ _ANTHROPIC_COMPACTION_TYPE = "compact_20260112"
_ANTHROPIC_COMPACTION_MIN = 50_000
+# Anthropic fast-mode beta (Opus 4.6 / 4.7 only, per
+# https://platform.claude.com/docs/en/build-with-claude/fast-mode).
+# Mutually exclusive with the Priority service tier.
+_ANTHROPIC_FAST_MODE_BETA = "fast-mode-2026-02-01"
+_ANTHROPIC_FAST_MODE_PREFIXES = (
+ "claude-opus-4-7",
+ "claude-opus-4-6",
+)
+
+
def _anthropic_supports_compaction(model: str) -> bool:
return model.startswith(_ANTHROPIC_COMPACTION_PREFIXES)
+def _anthropic_supports_fast_mode(model: str) -> bool:
+ # Require a family boundary ("" or "-") after the prefix so IDs like
+ # "claude-opus-4-70" / "claude-opus-4-7b" do not match.
+ return any(
+ model == p or model.startswith(f"{p}-") for p in _ANTHROPIC_FAST_MODE_PREFIXES
+ )
+
+
class _MistralThinkingSpec(NamedTuple):
models: tuple[str, ...]
style: Literal["prompt_mode", "reasoning_effort", "disabled"]
@@ -348,6 +366,7 @@ class ExternalProviderClient:
anthropic_code_exec_container_id: Optional[str] = None,
prompt_cache_ttl: Optional[str] = None,
compaction_threshold: Optional[int] = None,
+ fast_mode: Optional[bool] = None,
stream: bool = True,
) -> AsyncGenerator[str, None]:
"""
@@ -360,6 +379,9 @@ class ExternalProviderClient:
supplies a value the provider accepts — the frontend's
provider-capability map already filters these per provider, so we
treat them as opt-in here.
+
+ ``fast_mode`` only applies to Anthropic Opus 4.6 / 4.7 (silently
+ dropped elsewhere); adds the beta header and ``speed: "fast"``.
"""
if not self._is_openai_compatible():
async for line in self._stream_anthropic(
@@ -376,6 +398,7 @@ class ExternalProviderClient:
anthropic_code_exec_container_id,
prompt_cache_ttl,
compaction_threshold,
+ fast_mode = fast_mode,
):
yield line
return
@@ -1186,6 +1209,8 @@ class ExternalProviderClient:
anthropic_code_exec_container_id: Optional[str] = None,
prompt_cache_ttl: Optional[str] = None,
compaction_threshold: Optional[int] = None,
+ *,
+ fast_mode: Optional[bool] = None,
) -> AsyncGenerator[str, None]:
"""
Call the Anthropic Messages API and translate its SSE to OpenAI format.
@@ -1611,6 +1636,13 @@ class ExternalProviderClient:
]
}
+ # fast_mode is Opus 4.6/4.7 only; silently drop elsewhere.
+ # Incompatible with the Priority service_tier (frontend gate
+ # prevents both at once; backend lets Anthropic 400 if combined).
+ fast_mode_active = bool(fast_mode) and _anthropic_supports_fast_mode(model)
+ if fast_mode_active:
+ body["speed"] = "fast"
+
url = f"{self.base_url}/messages"
completion_id = f"chatcmpl-anthropic-{model.replace('/', '-')}"
@@ -1669,6 +1701,8 @@ class ExternalProviderClient:
beta_parts.append(_ANTHROPIC_CODE_EXECUTION_BETA)
if compaction_active and _ANTHROPIC_COMPACTION_BETA not in beta_parts:
beta_parts.append(_ANTHROPIC_COMPACTION_BETA)
+ if fast_mode_active and _ANTHROPIC_FAST_MODE_BETA not in beta_parts:
+ beta_parts.append(_ANTHROPIC_FAST_MODE_BETA)
if beta_parts:
request_headers["anthropic-beta"] = ",".join(beta_parts)
@@ -2410,6 +2444,29 @@ class ExternalProviderClient:
# finish_reason="stop" chunk that would
# truncate the rendered message in the UI.
mapped = _finish_reason_map.get(stop_reason, "stop")
+ # Streaming refusal: emit a visible notice
+ # plus an out-of-band _toolEvent so the
+ # frontend can prune the refused turn.
+ # The mapped finish_reason is
+ # "content_filter" per OpenAI spec.
+ # https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
+ if stop_reason == "refusal":
+ logger.warning(
+ "Anthropic refusal stop_reason (model=%s)",
+ model,
+ )
+ # Drop signal rides _toolEvent (not
+ # text) so assistant content cannot
+ # spoof a context reset.
+ yield _content_chunk(
+ "\n\n_The response was stopped by "
+ "Anthropic's safety classifier. Edit "
+ "or remove the previous turn and try "
+ "again._"
+ )
+ yield _emit_tool_event(
+ {"type": "anthropic_refusal"}
+ )
if mapped is not None:
chunk = {
"id": completion_id,
@@ -3939,6 +3996,12 @@ def _build_usage_chunk(
"cache_creation_input_tokens": cache_creation,
"cache_read_input_tokens": cache_read,
}
+ # Propagate fast-mode `usage.speed` so the cost ledger can apply
+ # the 6x multiplier without re-derivation (Anthropic falls back
+ # to "standard" when fast-mode is unsupported or rate-limited).
+ speed = last_usage.get("speed")
+ if speed in ("fast", "standard"):
+ usage_block["speed"] = speed
else:
prompt_tokens = last_usage.get("input_tokens") or 0
cached = 0
diff --git a/studio/backend/core/inference/pricing.py b/studio/backend/core/inference/pricing.py
index 74c57fa5943..4241f67296c 100644
--- a/studio/backend/core/inference/pricing.py
+++ b/studio/backend/core/inference/pricing.py
@@ -105,6 +105,9 @@ OPENAI_PRICING: dict[str, dict[str, float]] = {
ANTHROPIC_CACHE_5M_WRITE_MULT = 1.25
ANTHROPIC_CACHE_1H_WRITE_MULT = 2.0
ANTHROPIC_CACHE_READ_MULT = 0.1
+# Anthropic fast-mode (Opus 4.6 / 4.7 only): 6x standard on input + output.
+# https://platform.claude.com/docs/en/build-with-claude/fast-mode#pricing
+ANTHROPIC_FAST_MODE_MULT = 6.0
# OpenAI: cache reads are 0.1x base input, cache writes are not billed
# separately (the first prefix-write request just pays normal input).
@@ -235,6 +238,15 @@ def calculate_cost(
base = prices["input_per_mtok"]
out_per = prices["output_per_mtok"]
+ # Anthropic fast-mode: 6x on input + output. Cache multipliers stack
+ # on top of fast-mode, so applying once to (base, out_per) propagates
+ # into the cache_*_usd buckets computed below.
+ if provider == "anthropic" and usage.get("speed") == "fast":
+ base *= ANTHROPIC_FAST_MODE_MULT
+ out_per *= ANTHROPIC_FAST_MODE_MULT
+ if out["model_priced"]:
+ out["model_priced"] = f"{out['model_priced']} (fast)"
+
out["input_usd"] = (input_tokens / 1_000_000.0) * base
out["output_usd"] = (output_tokens / 1_000_000.0) * out_per
@@ -315,6 +327,7 @@ def pricing_snapshot() -> dict[str, Any]:
"cache_5m_write_mult": ANTHROPIC_CACHE_5M_WRITE_MULT,
"cache_1h_write_mult": ANTHROPIC_CACHE_1H_WRITE_MULT,
"cache_read_mult": ANTHROPIC_CACHE_READ_MULT,
+ "fast_mode_mult": ANTHROPIC_FAST_MODE_MULT,
"web_search_usd_per_1k": ANTHROPIC_WEB_SEARCH_USD_PER_1K,
"code_execution_usd_per_hour": ANTHROPIC_CODE_EXEC_USD_PER_HOUR,
},
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index b5626951c4e..68bc7a70173 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -786,6 +786,16 @@ class ChatCompletionRequest(BaseModel):
"to auto-create."
),
)
+ fast_mode: Optional[bool] = Field(
+ None,
+ description = (
+ "[x-unsloth] Anthropic fast-mode toggle. On Claude Opus 4.6 / "
+ "4.7 adds the `fast-mode-2026-02-01` beta header and sends "
+ "`speed: 'fast'` for higher OTPS at premium pricing. Silently "
+ "ignored on every other model + provider. See "
+ "https://platform.claude.com/docs/en/build-with-claude/fast-mode"
+ ),
+ )
@model_validator(mode = "after")
def _resolve_missing_tool_call_ids(self) -> "ChatCompletionRequest":
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index bf92055929e..143947efc83 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1876,6 +1876,7 @@ async def _proxy_to_external_provider(
anthropic_code_exec_container_id = payload.anthropic_code_exec_container_id,
prompt_cache_ttl = payload.prompt_cache_ttl,
compaction_threshold = payload.compaction_threshold,
+ fast_mode = payload.fast_mode,
stream = payload.stream,
)
try:
diff --git a/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py b/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
new file mode 100644
index 00000000000..e7e5ec64d43
--- /dev/null
+++ b/studio/backend/tests/test_anthropic_fast_mode_and_refusal.py
@@ -0,0 +1,164 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for Anthropic fast-mode wiring and streaming refusal handling.
+
+fast_mode=True on Opus 4.6/4.7 attaches the ``fast-mode-2026-02-01``
+beta header and sets ``speed: "fast"``; unsupported models drop both.
+Streaming ``stop_reason: "refusal"`` surfaces a user notice before the
+``content_filter`` finish chunk.
+https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
+"""
+
+import asyncio
+import json
+
+import httpx
+
+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 _empty_message_sse() -> bytes:
+ return (
+ b'event: message_start\ndata: {"type":"message_start","message":'
+ b'{"id":"m1","content":[],"model":"claude-opus-4-7","role":"assistant",'
+ b'"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":1}}}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta",'
+ b'"delta":{"stop_reason":"end_turn"}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+ )
+
+
+def _refusal_sse() -> bytes:
+ return (
+ b'event: message_start\ndata: {"type":"message_start","message":'
+ b'{"id":"m1","content":[],"model":"claude-opus-4-7","role":"assistant",'
+ b'"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":1}}}\n\n'
+ b'event: content_block_start\ndata: {"type":"content_block_start",'
+ b'"index":0,"content_block":{"type":"text","text":""}}\n\n'
+ b'event: content_block_delta\ndata: {"type":"content_block_delta",'
+ b'"index":0,"delta":{"type":"text_delta","text":"Hello."}}\n\n'
+ b'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta",'
+ b'"delta":{"stop_reason":"refusal"}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+ )
+
+
+def _capture(monkeypatch, sse: bytes = b"", **kwargs) -> tuple[dict, list[str]]:
+ """Install a MockTransport, drive one streamed call, return body+lines."""
+ 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 = sse or _empty_message_sse(),
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),
+ )
+
+ out_lines: list[str] = []
+
+ async def run():
+ client = _make_client()
+ try:
+ async for line in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = kwargs.get("model", "claude-opus-4-7"),
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 32,
+ fast_mode = kwargs.get("fast_mode"),
+ ):
+ out_lines.append(line)
+ finally:
+ await client.close()
+
+ _drive(run())
+ return captured, out_lines
+
+
+def test_fast_mode_attaches_beta_header_and_speed_on_opus_4_7(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-7")
+ assert cap["body"].get("speed") == "fast", cap["body"]
+ beta = cap["headers"].get("anthropic-beta", "")
+ assert "fast-mode-2026-02-01" in beta, beta
+
+
+def test_fast_mode_attaches_beta_header_and_speed_on_opus_4_6(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-6")
+ assert cap["body"].get("speed") == "fast", cap["body"]
+ assert "fast-mode-2026-02-01" in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_dropped_on_sonnet(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-sonnet-4-6")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_dropped_on_haiku(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-haiku-4-5")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_dropped_on_older_opus(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-5")
+ assert "speed" not in cap["body"], cap["body"]
+
+
+def test_fast_mode_false_does_not_attach_header_or_field(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = False)
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_none_does_not_attach_header_or_field(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = None)
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_refusal_emits_user_facing_notice_and_content_filter_finish(monkeypatch):
+ _, lines = _capture(monkeypatch, sse = _refusal_sse())
+ body = "\n".join(lines)
+ # User-visible refusal notice.
+ assert "stopped by Anthropic's safety classifier" in body, body
+ # OpenAI-spec finish_reason mapping.
+ assert '"finish_reason": "content_filter"' in body, body
+ # Original deltas preserved before the refusal supplement.
+ assert "Hello." in body, body
+
+
+def test_refusal_emits_tool_event_for_chat_adapter_drop(monkeypatch):
+ """Refused turns emit an out-of-band `_toolEvent` that the chat-adapter
+ latches into assistant `metadata.custom.anthropicRefusal`, driving
+ the next-request prune. Tool event (not text) prevents spoofing.
+ """
+ _, lines = _capture(monkeypatch, sse = _refusal_sse())
+ body = "\n".join(lines)
+ assert '"_toolEvent": {"type": "anthropic_refusal"}' in body, body
+ # Visible refusal text must not embed a sentinel that could spoof
+ # a context reset if echoed by another assistant message.
+ assert "studio:anthropic-refusal" not in body, body
diff --git a/studio/backend/tests/test_anthropic_fast_mode_edge.py b/studio/backend/tests/test_anthropic_fast_mode_edge.py
new file mode 100644
index 00000000000..0052cb94ad1
--- /dev/null
+++ b/studio/backend/tests/test_anthropic_fast_mode_edge.py
@@ -0,0 +1,442 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Edge-case coverage for the Anthropic fast-mode + refusal wiring.
+
+Complements ``test_anthropic_fast_mode_and_refusal.py`` (happy path)
+with dated snapshots, strict opt-in (future Opus families do not
+auto-enable), multi-beta header merging, refusal stream ordering, and
+the non-destruction guarantee for unset/None fast_mode.
+"""
+
+import asyncio
+import json
+import re
+
+import httpx
+
+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 _empty_message_sse(model: str = "claude-opus-4-7") -> bytes:
+ return (
+ b'event: message_start\ndata: {"type":"message_start","message":'
+ b'{"id":"m1","content":[],"model":"' + model.encode() + b'",'
+ b'"role":"assistant","stop_reason":null,"usage":'
+ b'{"input_tokens":1,"output_tokens":1}}}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta",'
+ b'"delta":{"stop_reason":"end_turn"}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+ )
+
+
+def _refusal_sse(model: str = "claude-opus-4-7") -> bytes:
+ return (
+ b'event: message_start\ndata: {"type":"message_start","message":'
+ b'{"id":"m1","content":[],"model":"' + model.encode() + b'",'
+ b'"role":"assistant","stop_reason":null,"usage":'
+ b'{"input_tokens":1,"output_tokens":1}}}\n\n'
+ b'event: content_block_start\ndata: {"type":"content_block_start",'
+ b'"index":0,"content_block":{"type":"text","text":""}}\n\n'
+ b'event: content_block_delta\ndata: {"type":"content_block_delta",'
+ b'"index":0,"delta":{"type":"text_delta","text":"Hello."}}\n\n'
+ b'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta",'
+ b'"delta":{"stop_reason":"refusal"}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+ )
+
+
+def _capture(monkeypatch, sse: bytes = b"", **kwargs) -> tuple[dict, list[str]]:
+ """Install a MockTransport, drive one streamed call, return body+lines."""
+ 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 = sse or _empty_message_sse(kwargs.get("model", "claude-opus-4-7")),
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),
+ )
+
+ out_lines: list[str] = []
+
+ async def run():
+ client = _make_client()
+ try:
+ extra = {}
+ for key in (
+ "enabled_tools",
+ "compaction_threshold",
+ "fast_mode",
+ ):
+ if key in kwargs:
+ extra[key] = kwargs[key]
+ async for line in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = kwargs.get("model", "claude-opus-4-7"),
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 32,
+ **extra,
+ ):
+ out_lines.append(line)
+ finally:
+ await client.close()
+
+ _drive(run())
+ return captured, out_lines
+
+
+# ──────────────────────────── dated snapshot prefix ────────────────────────────
+def test_fast_mode_attaches_on_dated_opus_4_7_snapshot(monkeypatch):
+ """Dated snapshot ``claude-opus-4-7-2026-02-01`` must match the prefix."""
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-7-2026-02-01")
+ assert cap["body"].get("speed") == "fast", cap["body"]
+ assert "fast-mode-2026-02-01" in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_attaches_on_dated_opus_4_6_snapshot(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-6-2026-02-01")
+ assert cap["body"].get("speed") == "fast", cap["body"]
+ assert "fast-mode-2026-02-01" in cap["headers"].get("anthropic-beta", "")
+
+
+# ──────────────────────────── strict opt-in semantics ────────────────────────────
+def test_fast_mode_does_not_auto_enable_on_future_opus_4_8(monkeypatch):
+ """Future ``claude-opus-4-8`` must not auto-enable; opt-in per family."""
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-8")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_does_not_auto_enable_on_future_opus_5(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-5")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_does_not_auto_enable_on_sonnet_dated_snapshot(monkeypatch):
+ """Sonnet snapshots share the compaction prefix but not fast_mode."""
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-sonnet-4-6-2026-02-01")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+# ──────────────────────────── beta header merge ────────────────────────────
+def _beta_parts(headers: dict) -> list[str]:
+ raw = headers.get("anthropic-beta", "")
+ return [p.strip() for p in raw.split(",") if p.strip()]
+
+
+def test_fast_mode_merges_with_code_execution_beta(monkeypatch):
+ """fast_mode + code_execution -> two comma-separated betas, no overwrite."""
+ cap, _ = _capture(
+ monkeypatch,
+ fast_mode = True,
+ model = "claude-opus-4-7",
+ enabled_tools = ["code_execution"],
+ )
+ parts = _beta_parts(cap["headers"])
+ assert "fast-mode-2026-02-01" in parts, cap["headers"]
+ assert any(p.startswith("code-execution-") for p in parts), cap["headers"]
+ # No duplicates.
+ assert len(parts) == len(set(parts)), parts
+
+
+def test_fast_mode_merges_with_compaction_beta(monkeypatch):
+ """fast_mode + compaction_threshold >= 50K -> both betas present."""
+ cap, _ = _capture(
+ monkeypatch,
+ fast_mode = True,
+ model = "claude-opus-4-7",
+ compaction_threshold = 100_000,
+ )
+ parts = _beta_parts(cap["headers"])
+ assert "fast-mode-2026-02-01" in parts, cap["headers"]
+ assert "compact-2026-01-12" in parts, cap["headers"]
+
+
+def test_fast_mode_merges_with_code_execution_and_compaction(monkeypatch):
+ """Three betas coexist in one comma-separated header, no duplicates."""
+ cap, _ = _capture(
+ monkeypatch,
+ fast_mode = True,
+ model = "claude-opus-4-7",
+ enabled_tools = ["code_execution"],
+ compaction_threshold = 100_000,
+ )
+ parts = _beta_parts(cap["headers"])
+ assert "fast-mode-2026-02-01" in parts
+ assert "compact-2026-01-12" in parts
+ assert any(p.startswith("code-execution-") for p in parts), parts
+ assert len(parts) >= 3
+ assert len(parts) == len(set(parts)), parts
+
+
+def test_fast_mode_beta_value_is_pinned(monkeypatch):
+ """Pin the exact beta tag ``fast-mode-2026-02-01`` from the docs."""
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-7")
+ parts = _beta_parts(cap["headers"])
+ assert "fast-mode-2026-02-01" in parts, parts
+ # Reject obvious typos.
+ assert not any(p.startswith("fastmode-") for p in parts), parts
+ assert not any("fast_mode" in p for p in parts), parts
+
+
+# ──────────────────────────── non-destruction guarantee ────────────────────────────
+def test_fast_mode_unset_is_byte_identical_to_omitted(monkeypatch):
+ """``fast_mode=None`` must produce the same body/headers as omission."""
+ cap_none, _ = _capture(monkeypatch, fast_mode = None, model = "claude-opus-4-7")
+
+ # Re-run without passing fast_mode at all.
+ 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 = _empty_message_sse(),
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),
+ )
+
+ async def run():
+ client = _make_client()
+ try:
+ async for _ in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "claude-opus-4-7",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 32,
+ ):
+ pass
+ finally:
+ await client.close()
+
+ _drive(run())
+
+ assert cap_none["body"] == captured["body"], (cap_none["body"], captured["body"])
+ # Headers can vary by httpx-injected fields (host, connection); compare
+ # the load-bearing ones.
+ for key in ("anthropic-version", "x-api-key", "content-type"):
+ assert cap_none["headers"].get(key) == captured["headers"].get(key), key
+ assert "anthropic-beta" not in cap_none["headers"]
+ assert "anthropic-beta" not in captured["headers"]
+ assert "speed" not in cap_none["body"]
+ assert "speed" not in captured["body"]
+
+
+def test_fast_mode_false_on_opus_4_7_byte_identical_to_unset(monkeypatch):
+ """``fast_mode=False`` produces the same outbound shape as unset."""
+ cap_false, _ = _capture(monkeypatch, fast_mode = False, model = "claude-opus-4-7")
+ assert "speed" not in cap_false["body"], cap_false["body"]
+ assert "fast-mode-2026-02-01" not in cap_false["headers"].get("anthropic-beta", "")
+
+
+# ──────────────────────────── refusal stream ordering ────────────────────────────
+def test_refusal_notice_appears_before_content_filter_chunk(monkeypatch):
+ """The notice content delta must precede the finish_reason chunk."""
+ _, lines = _capture(monkeypatch, sse = _refusal_sse(), model = "claude-opus-4-7")
+ notice_idx = next(i for i, l in enumerate(lines) if "stopped by Anthropic" in l)
+ filter_idx = next(
+ i for i, l in enumerate(lines) if '"finish_reason": "content_filter"' in l
+ )
+ assert notice_idx < filter_idx, (notice_idx, filter_idx, lines)
+
+
+def test_refusal_tool_event_emitted_exactly_once(monkeypatch):
+ """A single refusal emits the chat-adapter drop signal exactly once."""
+ _, lines = _capture(monkeypatch, sse = _refusal_sse())
+ body = "\n".join(lines)
+ count = body.count('"_toolEvent": {"type": "anthropic_refusal"}')
+ assert count == 1, (count, body)
+
+
+def test_refusal_text_carries_no_html_sentinel(monkeypatch):
+ """Visible refusal text must not embed a ``studio:anthropic-refusal``
+ sentinel; the drop signal rides _toolEvent only."""
+ _, lines = _capture(monkeypatch, sse = _refusal_sse())
+ body = "\n".join(lines)
+ assert "studio:anthropic-refusal" not in body, body
+
+
+def test_refusal_handling_works_on_sonnet_model(monkeypatch):
+ """Refusal handling is provider-side; Sonnet refusals must also surface."""
+ _, lines = _capture(
+ monkeypatch, sse = _refusal_sse("claude-sonnet-4-6"), model = "claude-sonnet-4-6"
+ )
+ body = "\n".join(lines)
+ assert "stopped by Anthropic's safety classifier" in body, body
+ assert '"_toolEvent": {"type": "anthropic_refusal"}' in body, body
+ assert '"finish_reason": "content_filter"' in body, body
+
+
+def test_refusal_preserves_partial_assistant_text(monkeypatch):
+ """Partial deltas already streamed must precede the refusal notice."""
+ _, lines = _capture(monkeypatch, sse = _refusal_sse(), model = "claude-opus-4-7")
+ body = "\n".join(lines)
+ hello_idx = body.index("Hello.")
+ notice_idx = body.index("stopped by Anthropic")
+ assert hello_idx < notice_idx, (hello_idx, notice_idx)
+
+
+def test_refusal_chunk_is_proper_openai_delta_shape(monkeypatch):
+ """The notice rides ``choices[0].delta.content`` (not a finish chunk);
+ OpenAI-spec clients treat it as ordinary streamed text."""
+ _, lines = _capture(monkeypatch, sse = _refusal_sse(), model = "claude-opus-4-7")
+ # Find the chunk that carries the refusal text.
+ notice_chunk = None
+ for line in lines:
+ if line.startswith("data: ") and "stopped by Anthropic" in line:
+ notice_chunk = json.loads(line[len("data: ") :])
+ break
+ assert notice_chunk is not None, lines
+ choice = notice_chunk["choices"][0]
+ assert "delta" in choice and "content" in choice["delta"], notice_chunk
+ # Must NOT carry a finish_reason itself -- that comes on the next
+ # chunk.
+ assert choice.get("finish_reason") in (None,), notice_chunk
+ # Refusal text is plain-spoken; no embedded sentinel.
+ assert "studio:anthropic-refusal" not in choice["delta"]["content"]
+
+
+def test_refusal_tool_event_chunk_shape(monkeypatch):
+ """Drop signal rides a Studio `_toolEvent` envelope (delta={},
+ finish_reason=null); the frontend latches on
+ `_toolEvent.type == "anthropic_refusal"`."""
+ _, lines = _capture(monkeypatch, sse = _refusal_sse(), model = "claude-opus-4-7")
+ refusal_chunk = None
+ for line in lines:
+ if line.startswith("data: ") and "anthropic_refusal" in line:
+ refusal_chunk = json.loads(line[len("data: ") :])
+ break
+ assert refusal_chunk is not None, lines
+ assert refusal_chunk["_toolEvent"] == {"type": "anthropic_refusal"}, refusal_chunk
+ choice = refusal_chunk["choices"][0]
+ assert choice["delta"] == {}, refusal_chunk
+ assert choice["finish_reason"] is None, refusal_chunk
+
+
+# ──────────────────────────── future-proofing ────────────────────────────
+def test_fast_mode_prefix_tuple_matches_capability_doc(monkeypatch):
+ """Tuple must exactly match the two families in the upstream docs:
+ https://platform.claude.com/docs/en/build-with-claude/fast-mode."""
+ from core.inference.external_provider import _ANTHROPIC_FAST_MODE_PREFIXES
+
+ assert set(_ANTHROPIC_FAST_MODE_PREFIXES) == {
+ "claude-opus-4-7",
+ "claude-opus-4-6",
+ }, _ANTHROPIC_FAST_MODE_PREFIXES
+
+
+def test_fast_mode_speed_field_value_is_literal_fast(monkeypatch):
+ """Pin the wire value to the literal string ``"fast"``."""
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-7")
+ assert cap["body"]["speed"] == "fast", cap["body"]
+
+
+def test_fast_mode_dropped_on_opus_4_5_dated_snapshot(monkeypatch):
+ """Previous-family snapshots like ``claude-opus-4-5-2025-...`` must not match."""
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-5-2025-08-01")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_rejects_prefix_collision_4_70(monkeypatch):
+ """IDs like ``claude-opus-4-70`` / ``-4-7b`` must not match the prefix."""
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-70")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_rejects_prefix_collision_4_7b(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-7b")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+def test_fast_mode_rejects_prefix_collision_4_6_extra(monkeypatch):
+ cap, _ = _capture(monkeypatch, fast_mode = True, model = "claude-opus-4-60")
+ assert "speed" not in cap["body"], cap["body"]
+ assert "fast-mode-2026-02-01" not in cap["headers"].get("anthropic-beta", "")
+
+
+# ──────────────────────────── usage.speed propagation ────────────────────────────
+def _fast_speed_sse(model: str = "claude-opus-4-7", speed: str = "fast") -> bytes:
+ return (
+ b'event: message_start\ndata: {"type":"message_start","message":'
+ b'{"id":"m1","content":[],"model":"' + model.encode() + b'",'
+ b'"role":"assistant","stop_reason":null,"usage":'
+ b'{"input_tokens":4,"output_tokens":1}}}\n\n'
+ b'event: content_block_start\ndata: {"type":"content_block_start",'
+ b'"index":0,"content_block":{"type":"text","text":""}}\n\n'
+ b'event: content_block_delta\ndata: {"type":"content_block_delta",'
+ b'"index":0,"delta":{"type":"text_delta","text":"hi"}}\n\n'
+ b'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta",'
+ b'"delta":{"stop_reason":"end_turn"},'
+ b'"usage":{"output_tokens":5,"speed":"' + speed.encode() + b'"}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+ )
+
+
+def test_usage_speed_propagates_to_final_usage_chunk_fast(monkeypatch):
+ """``usage.speed == "fast"`` from upstream must reach the Studio usage chunk."""
+ _, lines = _capture(monkeypatch, sse = _fast_speed_sse(speed = "fast"))
+ usage_lines = [l for l in lines if l.startswith("data: ") and '"usage"' in l]
+ assert usage_lines, lines
+ parsed = [json.loads(l[len("data: ") :]) for l in usage_lines]
+ speeds = [p["usage"].get("speed") for p in parsed if "usage" in p]
+ assert "fast" in speeds, parsed
+
+
+def test_usage_speed_propagates_to_final_usage_chunk_standard(monkeypatch):
+ _, lines = _capture(monkeypatch, sse = _fast_speed_sse(speed = "standard"))
+ parsed = [
+ json.loads(l[len("data: ") :])
+ for l in lines
+ if l.startswith("data: ") and '"usage"' in l
+ ]
+ speeds = [p["usage"].get("speed") for p in parsed if "usage" in p]
+ assert "standard" in speeds, parsed
+
+
+def test_usage_speed_absent_when_anthropic_does_not_report(monkeypatch):
+ """Studio must not invent ``usage.speed`` when upstream omits it."""
+ _, lines = _capture(monkeypatch)
+ parsed = [
+ json.loads(l[len("data: ") :])
+ for l in lines
+ if l.startswith("data: ") and '"usage"' in l
+ ]
+ for p in parsed:
+ usage = p.get("usage") or {}
+ assert "speed" not in usage, p
diff --git a/studio/backend/tests/test_anthropic_web_fetch.py b/studio/backend/tests/test_anthropic_web_fetch.py
index cdb5f6254cd..7277757fcf2 100644
--- a/studio/backend/tests/test_anthropic_web_fetch.py
+++ b/studio/backend/tests/test_anthropic_web_fetch.py
@@ -365,7 +365,9 @@ def test_web_fetch_error_renders_error_code(monkeypatch):
def _finish_reasons(lines: list[str]) -> list:
- """Return the finish_reason fields from every chat.completion.chunk."""
+ """Return non-null finish_reason fields from each chat.completion.chunk.
+ Mid-stream content deltas carry ``finish_reason: None`` and are skipped
+ (the refusal path emits a notice delta before the content_filter chunk)."""
out: list = []
for line in lines:
if not line.startswith("data:"):
@@ -380,8 +382,9 @@ def _finish_reasons(lines: list[str]) -> list:
if parsed.get("object") != "chat.completion.chunk":
continue
for choice in parsed.get("choices") or []:
- if "finish_reason" in choice:
- out.append(choice["finish_reason"])
+ reason = choice.get("finish_reason")
+ if reason is not None:
+ out.append(reason)
return out
diff --git a/studio/backend/tests/test_pricing.py b/studio/backend/tests/test_pricing.py
index cc8c16993c2..f534f1f58a3 100644
--- a/studio/backend/tests/test_pricing.py
+++ b/studio/backend/tests/test_pricing.py
@@ -14,6 +14,7 @@ from core.inference.pricing import (
ANTHROPIC_CACHE_5M_WRITE_MULT,
ANTHROPIC_CACHE_1H_WRITE_MULT,
ANTHROPIC_CACHE_READ_MULT,
+ ANTHROPIC_FAST_MODE_MULT,
ANTHROPIC_PRICING,
OPENAI_CACHE_READ_MULT,
OPENAI_CONTAINER_USD_PER_HOUR,
@@ -57,6 +58,64 @@ def test_anthropic_opus_4_7_input_and_output_math():
assert _isclose(out["total_usd"], 30.0)
+# ── Anthropic fast-mode 6x multiplier (Opus 4.6 / 4.7 only) ─────────
+
+
+def test_anthropic_fast_mode_charges_6x_standard_opus():
+ """6x on input + output when ``usage.speed == "fast"``.
+ https://platform.claude.com/docs/en/build-with-claude/fast-mode"""
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "input_tokens": 1_000_000,
+ "output_tokens": 1_000_000,
+ "speed": "fast",
+ },
+ )
+ assert _isclose(out["input_usd"], 5.0 * ANTHROPIC_FAST_MODE_MULT)
+ assert _isclose(out["output_usd"], 25.0 * ANTHROPIC_FAST_MODE_MULT)
+ assert _isclose(out["total_usd"], 30.0 * ANTHROPIC_FAST_MODE_MULT)
+ assert "(fast)" in out["model_priced"], out["model_priced"]
+
+
+def test_anthropic_fast_mode_does_not_affect_standard_speed():
+ """``speed: "standard"`` (or missing) keeps the base rates."""
+ out_standard = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "input_tokens": 1_000_000,
+ "output_tokens": 1_000_000,
+ "speed": "standard",
+ },
+ )
+ out_missing = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {"input_tokens": 1_000_000, "output_tokens": 1_000_000},
+ )
+ assert _isclose(out_standard["total_usd"], out_missing["total_usd"])
+ assert _isclose(out_standard["total_usd"], 30.0)
+
+
+def test_anthropic_fast_mode_stacks_with_cache_read_multiplier():
+ """Cache multipliers apply on top of fast-mode (per docs)."""
+ base = ANTHROPIC_PRICING["claude-opus-4-7"]["input_per_mtok"]
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cache_read_input_tokens": 1_000_000,
+ "speed": "fast",
+ },
+ )
+ expected = base * ANTHROPIC_FAST_MODE_MULT * ANTHROPIC_CACHE_READ_MULT
+ assert _isclose(out["cache_read_usd"], expected)
+
+
# ── Anthropic cache write 5m + read multipliers ──────────────────────
@@ -412,6 +471,7 @@ def test_snapshot_contains_provider_buckets_and_multipliers():
assert a["cache_5m_write_mult"] == ANTHROPIC_CACHE_5M_WRITE_MULT
assert a["cache_1h_write_mult"] == ANTHROPIC_CACHE_1H_WRITE_MULT
assert a["cache_read_mult"] == ANTHROPIC_CACHE_READ_MULT
+ assert a["fast_mode_mult"] == ANTHROPIC_FAST_MODE_MULT
assert "web_search_usd_per_1k" in a
assert "code_execution_usd_per_hour" in a
assert "models" in o and "gpt-5.5" in o["models"]
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 9842e380e08..800395bddc8 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -28,6 +28,7 @@ import {
providerSupportsBuiltinImageGeneration,
providerSupportsBuiltinWebFetch,
providerSupportsBuiltinWebSearch,
+ providerSupportsFastMode,
} from "../provider-capabilities";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import { useExternalProvidersStore } from "../stores/external-providers-store";
@@ -347,6 +348,18 @@ function collectImageParts(
return parts;
}
+// Refusal flag stamped on assistant metadata when the backend emits the
+// `anthropic_refusal` _toolEvent. We drop the refused pair from the next
+// request body (Anthropic guidance: leaving refusals in context keeps
+// refusing). Metadata (not text) prevents content from spoofing a reset.
+function isAnthropicRefusalMessage(message: RunMessage): boolean {
+ if (message.role !== "assistant") return false;
+ const metadata = (message as { metadata?: unknown }).metadata as
+ | { custom?: Record<string, unknown> }
+ | undefined;
+ return metadata?.custom?.anthropicRefusal === true;
+}
+
function toOpenAIMessage(message: RunMessage): {
role: "system" | "user" | "assistant";
content: OpenAIMessageContent;
@@ -367,6 +380,11 @@ function toOpenAIMessage(message: RunMessage): {
/data:audio\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/g,
"[audio]",
);
+ if (isAnthropicRefusalMessage(message)) {
+ // Prune refused assistant turn from outbound history; the
+ // rendered transcript still shows the user-visible notice.
+ return null;
+ }
}
const imageParts = collectImageParts(message);
@@ -925,7 +943,24 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
),
);
- const outboundMessages = messages
+ // Two-pass build: a refused assistant turn also drops the user
+ // prompt that triggered it (leaving it in context re-triggers
+ // the classifier). Refusal flag rides assistant
+ // metadata.custom.anthropicRefusal, set out-of-band from the
+ // backend _toolEvent.
+ const survivingMessages: RunMessage[] = [];
+ for (const message of messages) {
+ if (isAnthropicRefusalMessage(message)) {
+ const last = survivingMessages.at(-1);
+ if (last && last.role === "user") {
+ survivingMessages.pop();
+ }
+ continue;
+ }
+ survivingMessages.push(message);
+ }
+
+ const outboundMessages = survivingMessages
.map(toOpenAIMessage)
.filter((message): message is NonNullable<typeof message> =>
Boolean(message),
@@ -995,8 +1030,10 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
});
}
}
- const imageBase64 = findLatestUserImageBase64(messages);
- const audioBase64 = findLatestUserAudioBase64(messages);
+ // Scan post-prune history so a refused user turn's image/audio
+ // doesn't gate or mis-attribute the next non-refused turn.
+ const imageBase64 = findLatestUserImageBase64(survivingMessages);
+ const audioBase64 = findLatestUserAudioBase64(survivingMessages);
// Block when ANY image is in the outbound payload (current or
// prior turns) and the loaded model can't process images. Keeps
@@ -1032,7 +1069,7 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
if (audioBase64) {
const audioName = runtime.pendingAudioName;
if (audioName) {
- const lastUserMsg = [...messages]
+ const lastUserMsg = [...survivingMessages]
.reverse()
.find((m) => m.role === "user");
if (lastUserMsg) sentAudioNames.set(lastUserMsg.id, audioName);
@@ -1143,6 +1180,10 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
// Tool call content parts — accumulated and yielded cumulatively.
// result is set directly on the tool-call part when tool_end arrives.
const toolCallParts: ToolCallMessagePart[] = [];
+ // Latched on the `anthropic_refusal` tool event; stamped onto the
+ // final assistant metadata as `custom.anthropicRefusal` to drive
+ // the history-prune above.
+ let anthropicRefusalSeen = false;
let serverMetadata: {
usage?: ServerUsage;
timings?: ServerTimings;
@@ -1485,6 +1526,16 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
isPromptCacheTtl(externalProvider.promptCacheTtl)
? { prompt_cache_ttl: externalProvider.promptCacheTtl }
: {}),
+ // Anthropic fast mode (Opus 4.6 / 4.7 only); backend
+ // silently drops on unsupported models as a second
+ // line of defence.
+ ...(params.fastMode &&
+ providerSupportsFastMode(
+ externalProvider.providerType,
+ externalSelection.modelId,
+ )
+ ? { fast_mode: true }
+ : {}),
...(externalReasoningCaps.supportsReasoning
? externalReasoningCaps.reasoningStyle === "reasoning_effort"
? externalReasoningEnabled
@@ -1603,6 +1654,12 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
}
continue;
}
+ if (toolEvent.type === "anthropic_refusal") {
+ // Latch the backend refusal signal so the final
+ // message metadata can drive the prune.
+ anthropicRefusalSeen = true;
+ continue;
+ }
if (toolEvent.type === "tool_start") {
const id =
(toolEvent.tool_call_id as string) ||
@@ -1936,6 +1993,8 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
timing: finalTiming,
custom: {
reasoningDuration,
+ // Persisted refusal flag driving the two-pass prune.
+ anthropicRefusal: anthropicRefusalSeen || undefined,
serverTimings: meta?.timings ?? undefined,
contextUsage: meta?.usage
? {
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 9cd4db2705f..ac1ef8a24ca 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -87,6 +87,7 @@ import {
type ProviderCapabilities,
getExternalMinOutputTokens,
providerSupportsBuiltinCodeExecution,
+ providerSupportsFastMode,
} from "./provider-capabilities";
import { useChatRuntimeStore } from "./stores/chat-runtime-store";
import type { InferenceParams } from "./types/runtime";
@@ -552,6 +553,12 @@ export function ChatSettingsPanel({
activeExternalProvider.baseUrl,
) &&
activeExternalProvider.providerType === "openai";
+ const showFastModeControl =
+ activeExternalProvider != null &&
+ providerSupportsFastMode(
+ activeExternalProvider.providerType,
+ externalSelection?.modelId,
+ );
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const openAiApiKeyForSection = activeExternalProvider
? getExternalProviderApiKey(activeExternalProvider.id) || null
@@ -1152,6 +1159,28 @@ export function ChatSettingsPanel({
</Select>
</div>
) : null}
+ {showFastModeControl ? (
+ <div className="flex items-center justify-between gap-3 pt-3">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="min-w-0 text-[13px] font-medium leading-[1.25] tracking-nav text-nav-fg">
+ Fast mode
+ </span>
+ <InfoHint>
+ Beta. Up to 2.5x higher output tokens per second on
+ Claude Opus 4.6 and 4.7 at 6x standard Opus pricing.
+ Switching between fast and standard invalidates the
+ prompt cache and is incompatible with the Priority
+ service tier.
+ </InfoHint>
+ </div>
+ <Switch
+ className="panel-switch shrink-0"
+ checked={Boolean(params.fastMode)}
+ onCheckedChange={set("fastMode")}
+ aria-label="Fast mode"
+ />
+ </div>
+ ) : null}
</CollapsibleSection>
) : null}
diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.ts
index da1d6e3431f..562a60a18f1 100644
--- a/studio/frontend/src/features/chat/provider-capabilities.ts
+++ b/studio/frontend/src/features/chat/provider-capabilities.ts
@@ -135,6 +135,30 @@ export function providerSupportsBuiltinWebFetch(
return providerType === "anthropic";
}
+/**
+ * Whether the active provider + model supports Anthropic fast-mode
+ * (`speed: "fast"` + `fast-mode-2026-02-01` header). Opus 4.6 / 4.7
+ * only per https://platform.claude.com/docs/en/build-with-claude/fast-mode.
+ * Backend silently drops on unsupported models as a second defence.
+ */
+const ANTHROPIC_FAST_MODE_MODEL_PREFIXES = [
+ "claude-opus-4-7",
+ "claude-opus-4-6",
+] as const;
+
+export function providerSupportsFastMode(
+ providerType: string | null | undefined,
+ modelId: string | null | undefined,
+): boolean {
+ if (providerType !== "anthropic") return false;
+ if (!modelId) return false;
+ // Family boundary ("" or "-") required so IDs like "claude-opus-4-70"
+ // / "claude-opus-4-7b" do not match.
+ return ANTHROPIC_FAST_MODE_MODEL_PREFIXES.some(
+ (prefix) => modelId === prefix || modelId.startsWith(`${prefix}-`),
+ );
+}
+
/**
* Whether the selected external provider/model exposes a server-side
* code-execution tool. Two providers ship one today:
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 6b60ed51eae..73266b9234e 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -379,6 +379,7 @@ const PERSISTED_INFERENCE_PARAM_KEYS = [
"maxTokens",
"systemPrompt",
"trustRemoteCode",
+ "fastMode",
] as const satisfies readonly PersistedInferenceParamKey[];
const SCALAR_SETTING_KEYS = [
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 1e6bcf8b876..f18407413dc 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -262,6 +262,12 @@ export interface OpenAIChatCompletionsRequest {
* the Anthropic provider with `code_execution` in `enabled_tools`.
*/
anthropic_code_exec_container_id?: string | null;
+ /**
+ * Anthropic fast-mode toggle. Opus 4.6 / 4.7 only; backend drops
+ * silently on every other model + provider. See
+ * https://platform.claude.com/docs/en/build-with-claude/fast-mode
+ */
+ fast_mode?: boolean | null;
}
export interface OpenAIChatDelta {
diff --git a/studio/frontend/src/features/chat/types/runtime.ts b/studio/frontend/src/features/chat/types/runtime.ts
index 2967584653c..4c44ee1e9ca 100644
--- a/studio/frontend/src/features/chat/types/runtime.ts
+++ b/studio/frontend/src/features/chat/types/runtime.ts
@@ -14,6 +14,12 @@ export interface InferenceParams {
checkpoint: string;
/** Allow loading models with custom code (e.g. NVIDIA Nemotron). Only enable for repos you trust. */
trustRemoteCode?: boolean;
+ /**
+ * Anthropic fast-mode toggle. Opus 4.6 / 4.7 only; higher OTPS at
+ * 6x standard Opus pricing. Default false.
+ * https://platform.claude.com/docs/en/build-with-claude/fast-mode
+ */
+ fastMode?: boolean;
}
export const DEFAULT_INFERENCE_PARAMS: InferenceParams = {
@@ -28,6 +34,7 @@ export const DEFAULT_INFERENCE_PARAMS: InferenceParams = {
systemPrompt: "",
checkpoint: "",
trustRemoteCode: false,
+ fastMode: false,
};
export interface ChatModelSummary {
diff --git a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
index e07e1ddb1d3..4e93a20bffe 100644
--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
@@ -140,6 +140,11 @@ function sanitizeInferenceParams(
if (typeof value.trustRemoteCode === "boolean") {
params.trustRemoteCode = value.trustRemoteCode;
}
+ // Mirror trustRemoteCode handling so the toggle survives reload
+ // and the /api/chat/settings round-trip.
+ if (typeof value.fastMode === "boolean") {
+ params.fastMode = value.fastMode;
+ }
return hasKeys(params) ? params : undefined;
}