Debian Codegraph @

src/anthropic/lib/middleware/_fallbacks.py

raw
1 from __future__ import annotations
2
3 import copy as _copy
4 import json
5 import logging
6 from typing import (
7 Any,
8 Dict,
9 List,
10 Callable,
11 Iterable,
12 Iterator,
13 Optional,
14 Generator,
15 AsyncIterator,
16 AsyncGenerator,
17 cast,
18 )
19 from contextvars import Token, ContextVar
20 from typing_extensions import Literal, override
21
22 import httpx2
23
24 from ..._utils import is_dict
25 from ..._models import BaseModel
26 from ..._request import APIRequest
27 from ..._response import APIResponse, AsyncAPIResponse
28 from ..._streaming import Stream, AsyncStream, ServerSentEvent
29 from ..._exceptions import AnthropicError
30 from ..._middleware import CallNext, Middleware, AsyncCallNext
31 from ..._base_client import build_headers, merge_headers
32 from ...types.message import Message
33 from .._stainless_helpers import helper_header
34 from ...types.beta.beta_message import BetaMessage
35 from ...types.anthropic_beta_param import AnthropicBetaParam
36 from ...types.beta.beta_fallback_param import BetaFallbackParam
37 from ...types.beta.beta_fallback_credit_token_param import BetaFallbackCreditTokenParam
38
39 __all__ = [
40 "BetaFallbackState",
41 "BetaRefusalFallbackMiddleware",
42 ]
43
44 # the documented logger name is the public package, not this private submodule
45 log: logging.Logger = logging.getLogger("anthropic.lib.middleware")
46
47 _MESSAGES_PATH = "/v1/messages"
48
49 DEFAULT_BETAS: tuple[AnthropicBetaParam, ...] = ("fallback-credit-2026-07-01",)
50 """Betas sent by default; override with the `betas` option."""
51
52
53 def _credit_token_param(token: str) -> BetaFallbackCreditTokenParam:
54 """The retry's `fallback_credit_token`, in the object form.
55
56 `best_effort` keeps the retry serving even when redemption fails — a bare
57 string would 400 the hop on any token-layer failure.
58 """
59 return {"token": token, "mode": "best_effort"}
60
61
62 class BetaFallbackState:
63 """Tracks which fallback a sequence of requests is pinned to.
64
65 Create one and enter it (`with state:` — the same context manager works for
66 both clients) around every request that should share the pin — the turns of
67 one conversation, or any wider scope the stickiness should apply to;
68 `BetaRefusalFallbackMiddleware` mutates it in place when a model refuses.
69 """
70
71 index: int | None
72 """Index into the fallback chain the requests are pinned to.
73
74 `None` (or -1) targets the original request params; the middleware sets it
75 to the index of the fallback that accepted the request.
76 """
77
78 def __init__(self) -> None:
79 self.index = None
80
81 def __enter__(self) -> BetaFallbackState:
82 token = _fallback_state.set(self)
83 _fallback_state_tokens.set((*_fallback_state_tokens.get(), token))
84 return self
85
86 def __exit__(self, *exc_info: object) -> None:
87 tokens = _fallback_state_tokens.get()
88 _fallback_state_tokens.set(tokens[:-1])
89 _fallback_state.reset(tokens[-1])
90
91
92 _fallback_state: ContextVar[BetaFallbackState | None] = ContextVar("anthropic_beta_fallback_state", default=None)
93
94 # The reset tokens for every `with state:` block the current context is inside,
95 # innermost last. Kept in a ContextVar — NOT on the state instance — so that one
96 # state shared across threads/tasks (the documented usage) has each context
97 # entering and exiting with its own tokens; a `Token` can only be reset in the
98 # context that created it.
99 _fallback_state_tokens: ContextVar[tuple[Token[BetaFallbackState | None], ...]] = ContextVar(
100 "anthropic_beta_fallback_state_tokens", default=()
101 )
102
103
104 class BetaRefusalFallbackMiddleware(Middleware):
105 """Middleware that retries refused beta `/v1/messages` requests down a
106 fallback chain, reproducing the server-side `fallbacks` wire shape
107 client-side.
108
109 Only `client.beta.messages` requests are handled — refusals minted by the
110 first-party `client.messages` surface carry no `fallback_credit_token`, so
111 those requests pass through untouched.
112
113 Each `fallbacks` entry is a patch against the ORIGINAL request params: a
114 field set to a value overrides it, a field explicitly `None` unsets it, an
115 absent field keeps the original value; `output_config` patches its
116 subfields the same way one level deep. Hops never compound — every hop
117 patches the original params, never the previous hop's patched request.
118 A `between_tools` thinking config is sent to a hop as `disabled` unless
119 the entry sets `thinking` itself.
120
121 Non-streaming: when a response comes back with `stop_reason: "refusal"`, the
122 request is retried with each entry of `fallbacks` applied as a patch to the
123 original params — passing along the refusal's `fallback_credit_token` (in
124 the object form, with `mode: "best_effort"`) when it minted one — until a
125 model accepts or the chain is exhausted. A `fallback` seam
126 block per model boundary is prepended to the served message's content —
127 the same block shape the streaming splice emits. The served hop's `usage`
128 is left verbatim (streaming rewrites it to per-hop `usage.iterations`).
129
130 Streaming: when the stream ends in `stop_reason: "refusal"`, a second
131 request is issued to the fallback model. It carries the refusal's
132 `fallback_credit_token`, plus the refused model's partial output as a
133 trailing assistant prefill when the refusal grants one
134 (`fallback_has_prefill_claim`). The fallback's events are then spliced onto
135 the still-open stream, so the client sees one continuous message in the
136 server-side `fallbacks` wire shape: a `fallback` content block at each
137 model boundary, monotonic block indices, and per-hop `usage.iterations` on
138 the final `message_delta`. A refusal before any output streamed retries
139 even without a credit token, and the serving hop's `message_start` opens
140 the wire carrying the primary's message id.
141
142 The fallback-credit beta the credit tokens require is sent by default on
143 every request the middleware handles; the `betas` option controls this.
144
145 In both modes a fallback that itself refuses with a fresh credit token
146 continues down the chain. A streaming fallback whose appended prefill the
147 server rejects (HTTP 400 body mismatch) is retried once without it; a
148 fallback whose request fails outright is skipped — its token was never
149 redeemed, so it carries to the next entry. When every remaining entry fails
150 over HTTP, the suppressed refusal is replayed to the client with
151 `recommended_model` stamped from the final failure (the failed model for
152 capacity errors, `null` otherwise). A refusal surfaced to the client rather
153 than retried is reported through the `anthropic.lib.middleware` logger.
154
155 To keep later requests on the model that accepted, run them inside a shared
156 `BetaFallbackState` context; requests sharing that state start directly at
157 the pinned fallback. Reuse one state across whatever scope the pin should
158 apply to — typically a conversation. The state is the only pin: `fallback`
159 seam blocks replayed in the request history are stripped from the outgoing
160 request (an assistant turn left empty by the strip is dropped whole), never
161 read back as a pin.
162
163 ```py
164 client = Anthropic(middleware=[BetaRefusalFallbackMiddleware([{"model": "claude-opus-4-8"}])])
165
166 state = BetaFallbackState()
167 with state:
168 message = client.beta.messages.create(**params)
169 ```
170 """
171
172 def __init__(
173 self,
174 fallbacks: Iterable[BetaFallbackParam],
175 *,
176 betas: Iterable[AnthropicBetaParam] | None = None,
177 ) -> None:
178 """
179 Args:
180 fallbacks: The fallback chain, tried in order. An empty chain disables
181 the middleware.
182
183 betas: Betas added to the `anthropic-beta` header of every `/v1/messages`
184 request this middleware handles — the original request included, since
185 refusals only carry a `fallback_credit_token` when the beta is enabled.
186 Defaults to `("fallback-credit-2026-07-01",)`; pass `()` to send none.
187 """
188 self._fallbacks = tuple(fallbacks)
189 self._betas = DEFAULT_BETAS if betas is None else tuple(betas)
190 self._warned_missing_state = False
191
192 @override
193 def handle(self, request: APIRequest, call_next: CallNext) -> APIResponse[Any]:
194 body = self._applicable_body(request)
195 if body is None:
196 return call_next(request)
197
198 state = _fallback_state.get()
199 start_index = self._start_index(state)
200 pin = self._make_pin(state)
201
202 # Send the configured betas on this and every hop request derived from it,
203 # and tag this and every hop with the middleware's helper telemetry.
204 request = _with_middleware_headers(request, self._betas)
205
206 # The seam blocks this middleware splices into streams are client-side
207 # markers — the server rejects them as unknown tags — so a history that
208 # replays them is rewritten without them.
209 body = _strip_seam_blocks(body)
210 initial_body = body if start_index == -1 else _apply_hop(body, self._fallbacks[start_index])
211 initial_request = request.copy(body=initial_body)
212
213 response = call_next(initial_request)
214 if not response.http_response.is_success:
215 return response
216
217 if request.stream:
218 first_hop = start_index + 1
219 # Splicing needs at least one entry left to hop to; otherwise the
220 # stream passes through untouched.
221 if first_hop >= len(self._fallbacks):
222 return response
223 return self._splice_fallback_stream(
224 request=initial_request,
225 body=body,
226 initial_model=str(initial_body.get("model") or ""),
227 response=response,
228 call_next=call_next,
229 first_hop=first_hop,
230 pin=pin,
231 )
232
233 index = start_index
234 res = response
235 from_model = str(initial_body.get("model") or "")
236 seams: list[dict[str, Any]] = []
237 while index < len(self._fallbacks) - 1 and res.http_response.is_success:
238 message = res.parse()
239 if not isinstance(message, (Message, BetaMessage)) or message.stop_reason != "refusal":
240 break
241
242 index += 1
243 pin(index)
244 token = _credit_token(message)
245 category = _refusal_category(message)
246 res = call_next(request.copy(body=_merged_body(body, self._fallbacks[index], token)))
247 if res.http_response.is_success:
248 to_model = str(self._fallbacks[index]["model"])
249 seams.append(_seam_block(from_model, to_model, category))
250 from_model = to_model
251
252 if seams and res.http_response.is_success:
253 served = res.parse()
254 if isinstance(served, (Message, BetaMessage)) and served.stop_reason != "refusal":
255 # Prepend one `fallback` seam block per model boundary to the
256 # serving hop's content — the same block shape the streaming
257 # splice emits.
258 return _prepend_seam_blocks(res, seams)
259 return res
260
261 @override
262 async def handle_async(self, request: APIRequest, call_next: AsyncCallNext) -> AsyncAPIResponse[Any]:
263 body = self._applicable_body(request)
264 if body is None:
265 return await call_next(request)
266
267 state = _fallback_state.get()
268 start_index = self._start_index(state)
269 pin = self._make_pin(state)
270
271 # Send the configured betas on this and every hop request derived from it,
272 # and tag this and every hop with the middleware's helper telemetry.
273 request = _with_middleware_headers(request, self._betas)
274
275 # The seam blocks this middleware splices into streams are client-side
276 # markers — the server rejects them as unknown tags — so a history that
277 # replays them is rewritten without them.
278 body = _strip_seam_blocks(body)
279 initial_body = body if start_index == -1 else _apply_hop(body, self._fallbacks[start_index])
280 initial_request = request.copy(body=initial_body)
281
282 response = await call_next(initial_request)
283 if not response.http_response.is_success:
284 return response
285
286 if request.stream:
287 first_hop = start_index + 1
288 # Splicing needs at least one entry left to hop to; otherwise the
289 # stream passes through untouched.
290 if first_hop >= len(self._fallbacks):
291 return response
292 return self._splice_fallback_stream_async(
293 request=initial_request,
294 body=body,
295 initial_model=str(initial_body.get("model") or ""),
296 response=response,
297 call_next=call_next,
298 first_hop=first_hop,
299 pin=pin,
300 )
301
302 index = start_index
303 res = response
304 from_model = str(initial_body.get("model") or "")
305 seams: list[dict[str, Any]] = []
306 while index < len(self._fallbacks) - 1 and res.http_response.is_success:
307 message = await res.parse()
308 if not isinstance(message, (Message, BetaMessage)) or message.stop_reason != "refusal":
309 break
310
311 index += 1
312 pin(index)
313 token = _credit_token(message)
314 category = _refusal_category(message)
315 res = await call_next(request.copy(body=_merged_body(body, self._fallbacks[index], token)))
316 if res.http_response.is_success:
317 to_model = str(self._fallbacks[index]["model"])
318 seams.append(_seam_block(from_model, to_model, category))
319 from_model = to_model
320
321 if seams and res.http_response.is_success:
322 served = await res.parse()
323 if isinstance(served, (Message, BetaMessage)) and served.stop_reason != "refusal":
324 # Prepend one `fallback` seam block per model boundary to the
325 # serving hop's content — the same block shape the streaming
326 # splice emits.
327 return _prepend_seam_blocks_async(res, seams)
328 return res
329
330 def _applicable_body(self, request: APIRequest) -> dict[str, Any] | None:
331 """The request's JSON body when this middleware applies to it, `None` otherwise."""
332 body = _as_dict(request.json)
333 url = httpx2.URL(request.url)
334 if (
335 # an empty chain disables this middleware
336 not self._fallbacks
337 # this middleware only applies to the beta messages API
338 # (`client.beta.messages`, marked by the `beta=true` query param) —
339 # only the beta surface mints fallback credit tokens
340 or request.method.lower() != "post"
341 or url.path != _MESSAGES_PATH
342 or url.params.get("beta") != "true"
343 or body is None
344 ):
345 return None
346 if body.get("fallbacks") is not None:
347 raise AnthropicError(
348 "Sending the `fallbacks:` request param is not supported when using the "
349 "`BetaRefusalFallbackMiddleware`. You should either remove the middleware and send `fallbacks:` with the "
350 "`server-side-fallback-2026-07-01` beta header to let the API handle refusal fallbacks, or omit the "
351 "`fallbacks:` param if you'd like `BetaRefusalFallbackMiddleware` to handle "
352 "fallbacks on the client side."
353 )
354 return body
355
356 def _start_index(self, state: BetaFallbackState | None) -> int:
357 """The chain entry this request starts at (-1 = the original params).
358
359 Only an explicit `BetaFallbackState` pin moves the start; without one
360 the request starts at the original params.
361 """
362 if state is None or state.index is None:
363 return -1
364 start_index = state.index
365 if not -1 <= start_index < len(self._fallbacks):
366 raise AnthropicError(
367 f"BetaFallbackState.index {start_index} is out of bounds for a chain of "
368 f"{len(self._fallbacks)} fallback(s); was the state shared with a different middleware?"
369 )
370 return start_index
371
372 def _make_pin(self, state: BetaFallbackState | None) -> Callable[[int], None]:
373 """Pin requests sharing the state to the entry being tried (or warn that there is none)."""
374
375 def pin(index: int) -> None:
376 if state is not None:
377 state.index = index
378 elif not self._warned_missing_state:
379 self._warned_missing_state = True
380 log.warning(
381 "anthropic-sdk: BetaRefusalFallbackMiddleware fell back without an active "
382 "BetaFallbackState; follow-up requests will retry models that already refused. "
383 "Run them inside a shared `with BetaFallbackState():` block to pin them to the "
384 "accepted model."
385 )
386
387 return pin
388
389 def _splice_fallback_stream(
390 self,
391 *,
392 request: APIRequest,
393 body: dict[str, Any],
394 initial_model: str,
395 response: APIResponse[Any],
396 call_next: CallNext,
397 first_hop: int,
398 pin: Callable[[int], None],
399 ) -> APIResponse[Any]:
400 """Wrap the refusable stream in a response whose body passes events through
401 until a retryable refusal, then splices the fallback chain's events on.
402
403 `body` is the original request params — every hop patches it, never the
404 previous hop's patched body; `initial_model` is the model the initial
405 request actually queried (the pinned entry's when a state pin applied).
406
407 Closing the returned response (or the `Stream` parsed from it) tears down
408 whichever stream is being read and abandons any in-flight fallback request.
409 """
410 frames = self._spliced_frames(
411 request=request,
412 body=body,
413 initial_model=initial_model,
414 response=response,
415 call_next=call_next,
416 first_hop=first_hop,
417 pin=pin,
418 )
419 return APIResponse(
420 raw=_spliced_http_response(response.http_response, _FrameByteStream(frames)),
421 cast_to=response._cast_to,
422 client=response._client,
423 stream=True,
424 stream_cls=response._stream_cls,
425 options=response._options,
426 retries_taken=response.retries_taken,
427 )
428
429 def _splice_fallback_stream_async(
430 self,
431 *,
432 request: APIRequest,
433 body: dict[str, Any],
434 initial_model: str,
435 response: AsyncAPIResponse[Any],
436 call_next: AsyncCallNext,
437 first_hop: int,
438 pin: Callable[[int], None],
439 ) -> AsyncAPIResponse[Any]:
440 frames = self._spliced_frames_async(
441 request=request,
442 body=body,
443 initial_model=initial_model,
444 response=response,
445 call_next=call_next,
446 first_hop=first_hop,
447 pin=pin,
448 )
449 return AsyncAPIResponse(
450 raw=_spliced_http_response(response.http_response, _AsyncFrameByteStream(frames)),
451 cast_to=response._cast_to,
452 client=response._client,
453 stream=True,
454 stream_cls=response._stream_cls,
455 options=response._options,
456 retries_taken=response.retries_taken,
457 )
458
459 # --- streaming fallback (credit-token continuation) -------------------------
460 #
461 # The retry uses the appended-assistant form documented on
462 # `fallback_credit_token`: the refused request's body, extended by one
463 # trailing assistant turn carrying the refused model's partial output. The
464 # token authorizes that turn as a prefill continuation and applies the
465 # fallback credit. The refusal's `fallback_has_prefill_claim` says whether
466 # the partial output may be resent: when true the accumulated blocks are
467 # appended (trailing thinking blocks stripped — an assistant turn cannot
468 # end in one); when false the refused hop's output is dropped and the
469 # token is redeemed against the same body.
470 #
471 # Wire-shape rules (pinned by the fable-fallback conformance suites):
472 #
473 # * A refusal that arrives MID-STREAM keeps the primary's `message_start`
474 # on the wire; the seam block's `to.model` carries the serving model.
475 # A refusal BEFORE any output (pre-stream) holds the wire instead: the
476 # serving hop's `message_start` opens it, with its `id` rewritten to the
477 # primary's, followed by one queued seam per hop that was reached.
478 # * The seam's `from.model` echoes the model string the caller sent (alias
479 # or canonical) while the declining hop is the requested model; fallback
480 # hops use their entry's model id.
481 # * A hop's seam is emitted only once its response arrives OK — a hop whose
482 # request fails over HTTP was never reached and leaves no seam and no
483 # iterations entry; its token and continuation carry to the next entry.
484 # * Refusal text streamed before the refusal stays in the message and is
485 # resent as-is — the appended turn must match the partial output verbatim.
486
487 def _spliced_frames(
488 self,
489 *,
490 request: APIRequest,
491 body: dict[str, Any],
492 initial_model: str,
493 response: APIResponse[Any],
494 call_next: CallNext,
495 first_hop: int,
496 pin: Callable[[int], None],
497 ) -> Generator[bytes, None, None]:
498 fallbacks = self._fallbacks
499 # the response whose body is currently being consumed; closed on teardown
500 current: httpx2.Response | None = response.http_response
501
502 try:
503 # --- stream A: pass through until a chainable refusal ---
504 stream_a = response.http_response
505 reader = _HopReader(
506 index_base=0,
507 # the caller guarantees first_hop < len(fallbacks)
508 has_next=True,
509 splice=None,
510 wire_open=False,
511 primary_id=None,
512 seam_frames=[],
513 )
514 outcome = yield from _drive_hop(stream_a, reader)
515 if outcome.refused is None:
516 return # non-refusal or not-retryable: pure pass-through.
517 stream_a.close()
518 current = None
519
520 # --- fallback chain: try each entry in order ---
521 chain = _ChainState.begin(body, initial_model, outcome)
522
523 for hop in range(first_hop, len(fallbacks)):
524 entry = fallbacks[hop]
525 model = str(entry["model"])
526 has_next = hop + 1 < len(fallbacks)
527 pin(hop)
528
529 # --- build the request: appended-assistant continuation ---
530 # First attempt carries the newest partial appended (when its
531 # refusal granted a prefill claim); a 400 on that form is taken
532 # as the server rejecting the prefill, so the hop is retried
533 # once without it — the same-body form the token always
534 # supports.
535 continuation = chain.continuation()
536 res_b: APIResponse[Any] | None = None
537 failure: _HopFailure | None = None
538 for attempt in range(2):
539 hop_request = request.copy(body=chain.hop_body(entry, continuation))
540 try:
541 res_b = call_next(hop_request)
542 except Exception as err:
543 log.error(
544 "anthropic-sdk: BetaRefusalFallbackMiddleware: fallback request to %s failed: %s",
545 model,
546 err,
547 )
548 failure = _HopFailure(model=model, status=None)
549 break
550 if res_b.http_response.is_success:
551 current = res_b.http_response
552 break
553 err_body = _read_json(res_b.http_response)
554 res_b.http_response.close()
555 if attempt == 0 and res_b.status_code == 400 and continuation:
556 log.warning(
557 "anthropic-sdk: BetaRefusalFallbackMiddleware: fallback request with the "
558 "partial output appended was rejected (HTTP 400: %s); retrying without it",
559 _json_dumps(err_body),
560 )
561 continuation = chain.base
562 res_b = None
563 continue
564 log.error(
565 "anthropic-sdk: BetaRefusalFallbackMiddleware: fallback request to %s failed: HTTP %s: %s",
566 model,
567 res_b.status_code,
568 _json_dumps(err_body),
569 )
570 failure = _HopFailure(model=model, status=res_b.status_code)
571 break
572
573 if failure is not None:
574 # The token was never redeemed — retry it against the next entry.
575 if has_next:
576 continue
577 # Every remaining entry failed: degrade to the suppressed
578 # refusal, stamped with the final failure's recommendation.
579 for frame in chain.terminal_failure_frames(failure):
580 yield frame
581 return
582
583 # --- splice: queued seam, monotonic indices, usage.iterations ---
584 assert res_b is not None
585 hop_response = res_b.http_response
586 chain.queue_seam(model)
587 reader = _HopReader(
588 index_base=chain.next_index,
589 has_next=has_next,
590 splice=_SpliceInfo(iterations=chain.iterations, model=model),
591 wire_open=chain.wire_open,
592 primary_id=chain.primary_id,
593 seam_frames=chain.pending_seam_frames(),
594 )
595 outcome = yield from _drive_hop(hop_response, reader)
596 if outcome.opened:
597 chain.mark_opened()
598 if outcome.refused is None:
599 return
600 hop_response.close()
601 current = None
602
603 # This hop refused too: its emitted partial (if any) stays in
604 # the client's message, becomes the next partial segment, and
605 # the chain continues.
606 chain.absorb_refusal(outcome, model, continuation)
607 finally:
608 if current is not None:
609 current.close()
610
611 async def _spliced_frames_async(
612 self,
613 *,
614 request: APIRequest,
615 body: dict[str, Any],
616 initial_model: str,
617 response: AsyncAPIResponse[Any],
618 call_next: AsyncCallNext,
619 first_hop: int,
620 pin: Callable[[int], None],
621 ) -> AsyncGenerator[bytes, None]:
622 fallbacks = self._fallbacks
623 # the response whose body is currently being consumed; closed on teardown
624 current: httpx2.Response | None = response.http_response
625
626 try:
627 # --- stream A: pass through until a chainable refusal ---
628 stream_a = response.http_response
629 reader = _HopReader(
630 index_base=0,
631 # the caller guarantees first_hop < len(fallbacks)
632 has_next=True,
633 splice=None,
634 wire_open=False,
635 primary_id=None,
636 seam_frames=[],
637 )
638 async for frame in _drive_hop_async(stream_a, reader):
639 yield frame
640 outcome = reader.finish()
641 if outcome.refused is None:
642 return # non-refusal or not-retryable: pure pass-through.
643 await stream_a.aclose()
644 current = None
645
646 chain = _ChainState.begin(body, initial_model, outcome)
647
648 for hop in range(first_hop, len(fallbacks)):
649 entry = fallbacks[hop]
650 model = str(entry["model"])
651 has_next = hop + 1 < len(fallbacks)
652 pin(hop)
653
654 continuation = chain.continuation()
655 res_b: AsyncAPIResponse[Any] | None = None
656 failure: _HopFailure | None = None
657 for attempt in range(2):
658 hop_request = request.copy(body=chain.hop_body(entry, continuation))
659 try:
660 res_b = await call_next(hop_request)
661 except Exception as err:
662 log.error(
663 "anthropic-sdk: BetaRefusalFallbackMiddleware: fallback request to %s failed: %s",
664 model,
665 err,
666 )
667 failure = _HopFailure(model=model, status=None)
668 break
669 if res_b.http_response.is_success:
670 current = res_b.http_response
671 break
672 err_body = await _read_json_async(res_b.http_response)
673 await res_b.http_response.aclose()
674 if attempt == 0 and res_b.status_code == 400 and continuation:
675 log.warning(
676 "anthropic-sdk: BetaRefusalFallbackMiddleware: fallback request with the "
677 "partial output appended was rejected (HTTP 400: %s); retrying without it",
678 _json_dumps(err_body),
679 )
680 continuation = chain.base
681 res_b = None
682 continue
683 log.error(
684 "anthropic-sdk: BetaRefusalFallbackMiddleware: fallback request to %s failed: HTTP %s: %s",
685 model,
686 res_b.status_code,
687 _json_dumps(err_body),
688 )
689 failure = _HopFailure(model=model, status=res_b.status_code)
690 break
691
692 if failure is not None:
693 # The token was never redeemed — retry it against the next entry.
694 if has_next:
695 continue
696 for frame in chain.terminal_failure_frames(failure):
697 yield frame
698 return
699
700 assert res_b is not None
701 hop_response = res_b.http_response
702 chain.queue_seam(model)
703 reader = _HopReader(
704 index_base=chain.next_index,
705 has_next=has_next,
706 splice=_SpliceInfo(iterations=chain.iterations, model=model),
707 wire_open=chain.wire_open,
708 primary_id=chain.primary_id,
709 seam_frames=chain.pending_seam_frames(),
710 )
711 async for frame in _drive_hop_async(hop_response, reader):
712 yield frame
713 outcome = reader.finish()
714 if outcome.opened:
715 chain.mark_opened()
716 if outcome.refused is None:
717 return
718 await hop_response.aclose()
719 current = None
720
721 chain.absorb_refusal(outcome, model, continuation)
722 finally:
723 if current is not None:
724 await current.aclose()
725
726
727 class _Refusal(BaseModel):
728 token: Optional[str]
729 """The minted credit token; `None` for a token-less start-of-stream refusal."""
730
731 category: Optional[str]
732 """The policy category that triggered the refusal; `None` when not surfaced."""
733
734 has_prefill_claim: bool
735 usage: Dict[str, Any]
736 event: Dict[str, Any]
737 """The suppressed refusal `message_delta` event, verbatim — replayed if every
738 remaining entry fails over HTTP."""
739
740 suppressed_start_message: Optional[Dict[str, Any]] = None
741 """The `message` object from a spliced fallback hop's suppressed `message_start`
742 event. Retained so its `input_transformations` field can be forwarded onto the
743 replayed refusal `message_delta` event."""
744
745
746 class _SpliceInfo(BaseModel):
747 """Splice context for fallback hops; `None` for stream A."""
748
749 iterations: List[Dict[str, Any]]
750 model: str
751
752
753 class _HopFailure(BaseModel):
754 """A fallback hop whose request failed; stamps `recommended_model` when it
755 ends the chain."""
756
757 model: str
758 status: Optional[int]
759 """The HTTP status, or `None` when the request raised instead of resolving."""
760
761
762 class _HopOutcome(BaseModel):
763 """The outcome of consuming one hop's stream."""
764
765 refused: Optional[_Refusal]
766 """Set when the hop refused and an entry remained to chain to."""
767
768 model: Optional[str]
769 """The hop's serving model, from its message_start."""
770
771 start_event: Optional[Dict[str, Any]]
772 """The hop's message_start event, parsed."""
773
774 blocks: List[Dict[str, Any]]
775 """The hop's accumulated content blocks, in start order — the next partial segment."""
776
777 next_index: int
778 """One past the highest (shifted) block index emitted — where the next boundary goes."""
779
780 opened: bool
781 """Whether this hop emitted output (its frames opened or continued the wire)."""
782
783 last_fallback_to: Optional[str]
784 """`to.model` of the last `fallback` seam block seen in this hop's stream —
785 a server-stitched envelope's last decliner."""
786
787
788 class _HopReader:
789 """Consumes one hop's SSE events, producing the frames to forward to the
790 client while accumulating its content blocks.
791
792 Events are held until the hop produces output (a content block or a
793 terminal event), so a refusal that arrives before any output — a pre-stream
794 decline — leaves no trace on the wire and chains silently. On open, stream
795 A's held `message_start` is flushed in its original wire bytes; a spliced
796 hop's is suppressed when the wire is already open, or emitted with its `id`
797 rewritten to the primary's when this hop's start opens the wire. Queued
798 seam frames for every hop reached so far are flushed right after.
799
800 A spliced hop has its block indices shifted by `index_base` and its
801 terminal message_delta's usage rewritten to the `usage.iterations` chain
802 shape. When its `message_start` was not re-emitted, its
803 `input_transformations` are copied onto that message_delta.
804
805 A refusal that can be chained — an entry remains, and either a
806 `fallback_credit_token` was minted or nothing has streamed yet — ends the
807 hop early: open blocks are closed, the terminal message_delta +
808 message_stop are suppressed, and the refusal is set on the outcome so the
809 caller can issue the next hop. Any other refusal is logged and passes
810 through to the client.
811 """
812
813 outcome: _HopOutcome | None
814 """Set when a chainable refusal ended the hop early; the driver stops feeding."""
815
816 def __init__(
817 self,
818 *,
819 index_base: int,
820 has_next: bool,
821 splice: _SpliceInfo | None,
822 wire_open: bool,
823 primary_id: str | None,
824 seam_frames: list[bytes],
825 ) -> None:
826 self._tracker = _BlockTracker(index_base)
827 self._has_next = has_next
828 self._splice = splice
829 self._wire_open = wire_open
830 self._primary_id = primary_id
831 self._seam_frames = seam_frames
832 self._model: str | None = None
833 self._start_usage: dict[str, Any] | None = None
834 self._start_event: dict[str, Any] | None = None
835 self._held_start: ServerSentEvent | None = None
836 self._held: list[ServerSentEvent] = []
837 self._opened = False
838 self._last_fallback_to: str | None = None
839 self.outcome = None
840
841 @property
842 def opened(self) -> bool:
843 return self._opened
844
845 def feed(self, sse: ServerSentEvent) -> list[bytes]:
846 """Process one event, returning the frames to forward for it."""
847 event = _as_dict(_safe_json(sse.data))
848 event_type = event.get("type") if event is not None else None
849 splice = self._splice
850
851 if event_type == "message_start" and event is not None:
852 message = _as_dict(event.get("message"))
853 if message is not None:
854 model = message.get("model")
855 self._model = model if isinstance(model, str) else None
856 self._start_usage = _as_dict(message.get("usage"))
857 self._start_event = event
858 self._held_start = sse
859 return []
860 elif event_type == "content_block_start" and event is not None:
861 frames = self._open()
862 content_block = _as_dict(event.get("content_block"))
863 if content_block is not None and content_block.get("type") == "fallback":
864 to = _as_dict(content_block.get("to"))
865 to_model = to.get("model") if to is not None else None
866 if isinstance(to_model, str):
867 self._last_fallback_to = to_model
868 self._tracker.start(event)
869 return (
870 [*frames, _emit("content_block_start", event)]
871 if splice is not None
872 else [*frames, _passthrough_sse(sse)]
873 )
874 elif event_type == "content_block_delta" and event is not None:
875 frames = self._open()
876 self._tracker.delta(event)
877 return (
878 [*frames, _emit("content_block_delta", event)]
879 if splice is not None
880 else [*frames, _passthrough_sse(sse)]
881 )
882 elif event_type == "content_block_stop" and event is not None:
883 frames = self._open()
884 self._tracker.stop(event)
885 return (
886 [*frames, _emit("content_block_stop", event)]
887 if splice is not None
888 else [*frames, _passthrough_sse(sse)]
889 )
890 elif event_type == "message_delta" and event is not None:
891 delta = _as_dict(event.get("delta")) or {}
892 if delta.get("stop_reason") == "refusal":
893 stop_details = _as_dict(delta.get("stop_details"))
894 details = stop_details if stop_details is not None and stop_details.get("type") == "refusal" else None
895 token = details.get("fallback_credit_token") if details is not None else None
896 token = token if isinstance(token, str) and token else None
897 pre_stream = not self._opened and not self._tracker.content_blocks()
898 # A mid-stream refusal chains only when it minted a credit token;
899 # a pre-stream refusal chains even without one — nothing has
900 # streamed, so the retry is free and invisible.
901 if self._has_next and (token is not None or pre_stream):
902 usage = _backfill(_as_dict(event.get("usage")), self._start_usage)
903 frames = list(self._tracker.close_open_blocks())
904 # suppress this hop's message_delta + message_stop (and, for a
905 # pre-stream decline, everything held before them)
906 self._held_start = None
907 self._held.clear()
908 self.outcome = _HopOutcome(
909 refused=_Refusal(
910 token=token,
911 category=details.get("category") if details is not None else None,
912 has_prefill_claim=details is not None and details.get("fallback_has_prefill_claim") is True,
913 usage=usage,
914 event=event,
915 suppressed_start_message=self._suppressed_start_message(),
916 ),
917 model=self._model,
918 start_event=self._start_event,
919 blocks=self._tracker.content_blocks(),
920 next_index=self._tracker.next_index,
921 opened=self._opened,
922 last_fallback_to=self._last_fallback_to,
923 )
924 return frames
925 if not token:
926 log.error(
927 "anthropic-sdk: BetaRefusalFallbackMiddleware: refusal stop_details has no "
928 "fallback_credit_token; surfacing the refusal"
929 )
930 else:
931 log.error(
932 "anthropic-sdk: BetaRefusalFallbackMiddleware: refusal but no fallback "
933 "entries remain; surfacing the refusal"
934 )
935 frames = self._open()
936 if splice is not None:
937 if delta.get("stop_reason") == "refusal":
938 # the terminal refusal's stop_details always carries a model
939 # recommendation slot in the stitched shape
940 stop_details = _as_dict(delta.get("stop_details"))
941 if stop_details is not None:
942 stop_details.setdefault("recommended_model", None)
943 # Terminal hop. Replace iterations, don't append: this hop's own
944 # message_delta self-reports its iterations without a `model` (a
945 # fresh non-fallback request doesn't know it served a chain).
946 # Server-side `fallbacks` relabels the whole chain instead —
947 # refused hops as `message`, the serving hop as
948 # `fallback_message` — so the recorded chain replaces the
949 # self-report, with this hop's own entry relabeled as the
950 # `fallback_message` completer.
951 usage = _as_dict(event.get("usage")) or {}
952 usage["iterations"] = [
953 *splice.iterations,
954 _serving_iteration_entry(usage, splice.model),
955 ]
956 event["usage"] = usage
957 _forward_input_transformations(event, self._suppressed_start_message())
958 return [*frames, _emit("message_delta", event)]
959 return [*frames, _passthrough_sse(sse)]
960
961 if not self._opened:
962 # ping, error, unrecognised — held until the wire-open decision
963 self._held.append(sse)
964 return []
965 # message_stop, ping, error, unrecognised — and for stream A every
966 # event — pass through in their original wire bytes.
967 return [_passthrough_sse(sse)]
968
969 def _suppressed_start_message(self) -> dict[str, Any] | None:
970 """`message` from this fallback's `message_start` when it was not
971 re-emitted because the caller already received a `message_start`.
972 `None` for stream A, whose start is always emitted."""
973 if self._splice is None or not self._wire_open or self._start_event is None:
974 return None
975 return _as_dict(self._start_event.get("message"))
976
977 def _open(self) -> list[bytes]:
978 """Open the wire for this hop: its message_start (raw for stream A;
979 suppressed or id-rewritten for a spliced hop), the queued seam frames,
980 then anything else held."""
981 if self._opened:
982 return []
983 self._opened = True
984 frames: list[bytes] = []
985 if self._splice is None:
986 if self._held_start is not None:
987 frames.append(_passthrough_sse(self._held_start))
988 elif not self._wire_open and self._start_event is not None:
989 start_event = _copy.deepcopy(self._start_event)
990 message = _as_dict(start_event.get("message"))
991 if message is not None and self._primary_id is not None:
992 message["id"] = self._primary_id
993 frames.append(_emit("message_start", start_event))
994 frames.extend(self._seam_frames)
995 frames.extend(_passthrough_sse(held) for held in self._held)
996 self._held_start = None
997 self._held.clear()
998 return frames
999
1000 def finish_frames(self) -> list[bytes]:
1001 """Frames still owed when the stream ends without a chainable refusal."""
1002 if self.outcome is not None or self._opened:
1003 return []
1004 return self._open()
1005
1006 def finish(self) -> _HopOutcome:
1007 """The outcome once the hop's stream is fully consumed (or cut early)."""
1008 if self.outcome is not None:
1009 return self.outcome
1010 return _HopOutcome(
1011 refused=None,
1012 model=self._model,
1013 start_event=self._start_event,
1014 blocks=self._tracker.content_blocks(),
1015 next_index=self._tracker.next_index,
1016 opened=self._opened,
1017 last_fallback_to=self._last_fallback_to,
1018 )
1019
1020
1021 def _drive_hop(response: httpx2.Response, reader: _HopReader) -> Generator[bytes, None, _HopOutcome]:
1022 """Feed one hop's SSE events through `reader`, yielding the frames to forward."""
1023 for sse in Stream.raw_events(response):
1024 for frame in reader.feed(sse):
1025 yield frame
1026 if reader.outcome is not None:
1027 break
1028 for frame in reader.finish_frames():
1029 yield frame
1030 return reader.finish()
1031
1032
1033 async def _drive_hop_async(response: httpx2.Response, reader: _HopReader) -> AsyncIterator[bytes]:
1034 """Feed one hop's SSE events through `reader`, yielding the frames to forward.
1035
1036 The outcome is read from `reader.finish()` afterwards — async generators
1037 cannot return a value.
1038 """
1039 async for sse in AsyncStream.raw_events(response):
1040 for frame in reader.feed(sse):
1041 yield frame
1042 if reader.outcome is not None:
1043 break
1044 for frame in reader.finish_frames():
1045 yield frame
1046
1047
1048 class _ChainState:
1049 """Bookkeeping shared across the hops of one spliced stream."""
1050
1051 next_index: int
1052 """Monotonic block index across all spliced streams."""
1053
1054 wire_open: bool
1055 """Whether a message_start has reached the client yet."""
1056
1057 primary_id: str | None
1058 """The primary's message id — stamped onto the message_start that opens the
1059 wire when the primary declined pre-stream."""
1060
1061 primary_model: str
1062 """The model string the initial request queried (alias or canonical; the
1063 pinned entry's when a state pin applied) — echoed by the first seam's
1064 `from.model` and the first iterations entry."""
1065
1066 token: str | None
1067 base: List[Any]
1068 partial: List[Any]
1069 from_model: str
1070 last_refusal: _Refusal
1071 last_start_event: Dict[str, Any] | None
1072 iterations: List[Dict[str, Any]]
1073 """One `message` entry per hop that was reached and declined, in order — the
1074 primary first. Failed hops are skipped (no usage came back); the serving hop
1075 is appended as `fallback_message` when its message_delta arrives."""
1076
1077 def __init__(self, body: dict[str, Any]) -> None:
1078 self._body = body
1079 self._pending_seams: list[bytes] = []
1080
1081 @classmethod
1082 def begin(cls, body: dict[str, Any], initial_model: str, outcome: _HopOutcome) -> _ChainState:
1083 """The chain state after stream A's chainable refusal.
1084
1085 `body` is the original request params (pre-pin) — the base every hop
1086 patches; `initial_model` is the model the initial request queried.
1087 """
1088 assert outcome.refused is not None
1089 chain = cls(body)
1090 chain.primary_model = initial_model
1091 chain.next_index = outcome.next_index
1092 chain.wire_open = outcome.opened
1093 start_message = _as_dict((outcome.start_event or {}).get("message"))
1094 start_id = start_message.get("id") if start_message is not None else None
1095 chain.primary_id = start_id if isinstance(start_id, str) else None
1096 chain.token = outcome.refused.token
1097 chain.base = []
1098 chain.partial = _to_prefill_blocks(outcome.blocks) if outcome.refused.has_prefill_claim else []
1099 # A server-stitched envelope's last decliner is the model the first
1100 # client-side seam hands off from; a plain stream hands off from the
1101 # caller-spelled primary.
1102 chain.from_model = outcome.last_fallback_to or chain.primary_model
1103 chain.last_refusal = outcome.refused
1104 chain.last_start_event = outcome.start_event
1105 chain.iterations = _declined_iteration_entries(outcome.refused, chain.primary_model)
1106 return chain
1107
1108 def queue_seam(self, to_model: str) -> None:
1109 """Queue the reached hop's `fallback` seam block at the next monotonic index.
1110
1111 Queued seams are flushed by the hop reader once output reaches the wire,
1112 so a chain of pre-stream declines lines its seams up after the serving
1113 hop's message_start.
1114 """
1115 seam_index = self.next_index
1116 self.next_index += 1
1117 self._pending_seams.extend(
1118 [
1119 _emit(
1120 "content_block_start",
1121 {
1122 "type": "content_block_start",
1123 "index": seam_index,
1124 "content_block": _seam_block(self.from_model, to_model, self.last_refusal.category),
1125 },
1126 ),
1127 _emit("content_block_stop", {"type": "content_block_stop", "index": seam_index}),
1128 ]
1129 )
1130 self.from_model = to_model
1131
1132 def pending_seam_frames(self) -> list[bytes]:
1133 return list(self._pending_seams)
1134
1135 def mark_opened(self) -> None:
1136 self.wire_open = True
1137 self._pending_seams.clear()
1138
1139 def continuation(self) -> list[Any]:
1140 return [*self.base, *self.partial]
1141
1142 def hop_body(self, entry: BetaFallbackParam, continuation: list[Any]) -> dict[str, Any]:
1143 """The hop's request body: the entry applied as a patch against the
1144 ORIGINAL request params (never a previous hop's patched body), extended
1145 by the continuation.
1146
1147 The server-side `fallbacks` param is stripped — it is mutually exclusive
1148 with a credit-token retry. When the refusal granted no prefill claim the
1149 appended turn is omitted entirely and the same-body form is sent.
1150 """
1151 body: dict[str, Any] = {
1152 key: value for key, value in _apply_hop(self._body, entry).items() if key != "fallbacks"
1153 }
1154 if self.token is not None:
1155 body["fallback_credit_token"] = _credit_token_param(self.token)
1156 if continuation:
1157 messages = body.get("messages")
1158 body["messages"] = [
1159 *(messages if isinstance(messages, list) else []),
1160 {"role": "assistant", "content": continuation},
1161 ]
1162 return body
1163
1164 def absorb_refusal(self, outcome: _HopOutcome, model: str, continuation: list[Any]) -> None:
1165 """Fold a refused hop's outcome in, readying the next hop."""
1166 assert outcome.refused is not None
1167 self.token = outcome.refused.token
1168 self.base = continuation
1169 self.partial = _to_prefill_blocks(outcome.blocks) if outcome.refused.has_prefill_claim else []
1170 self.iterations.extend(_declined_iteration_entries(outcome.refused, model))
1171 self.last_refusal = outcome.refused
1172 if outcome.start_event is not None:
1173 self.last_start_event = outcome.start_event
1174 self.next_index = outcome.next_index
1175
1176 def terminal_failure_frames(self, failure: _HopFailure) -> list[bytes]:
1177 """Degrade to the suppressed refusal when every remaining entry failed
1178 over HTTP: replay its message_delta verbatim — `recommended_model`
1179 stamped from the final failure (the failed model for capacity errors,
1180 `null` otherwise), `usage.iterations` carrying the recorded chain, and
1181 `input_transformations` copied from a `message_start` that was not
1182 re-emitted — then message_stop.
1183 """
1184 frames: list[bytes] = []
1185 if not self.wire_open and self.last_start_event is not None:
1186 start_event = _copy.deepcopy(self.last_start_event)
1187 message = _as_dict(start_event.get("message"))
1188 if message is not None and self.primary_id is not None:
1189 message["id"] = self.primary_id
1190 frames.append(_emit("message_start", start_event))
1191 frames.extend(self._pending_seams)
1192
1193 event = _copy.deepcopy(self.last_refusal.event)
1194 delta = _as_dict(event.get("delta"))
1195 if delta is not None:
1196 details = _as_dict(delta.get("stop_details"))
1197 if details is not None:
1198 details["recommended_model"] = failure.model if failure.status in (429, 529) else None
1199 usage = _as_dict(event.get("usage")) or {}
1200 usage["iterations"] = _copy.deepcopy(self.iterations)
1201 event["usage"] = usage
1202 _forward_input_transformations(event, self.last_refusal.suppressed_start_message)
1203 frames.append(_emit("message_delta", event))
1204 frames.append(_emit("message_stop", {"type": "message_stop"}))
1205 return frames
1206
1207
1208 def _forward_input_transformations(event: dict[str, Any], suppressed_start_message: dict[str, Any] | None) -> None:
1209 """Copy `input_transformations` from a fallback's `message_start` that was
1210 not re-emitted onto the emitted `message_delta`, matching what a server-side
1211 mid-stream fallback sends. A list already on the delta is kept."""
1212 if suppressed_start_message is None or "input_transformations" in event:
1213 return
1214 if "input_transformations" in suppressed_start_message:
1215 event["input_transformations"] = _copy.deepcopy(suppressed_start_message["input_transformations"])
1216
1217
1218 def _declined_iteration_entries(refusal: _Refusal, model_label: str) -> list[dict[str, Any]]:
1219 """The `usage.iterations` entries a declined hop contributes to the chain.
1220
1221 The hop's refusal self-reports its iterations: adopt them, retyped to
1222 `message` (every one of them declined — a server-stitched envelope labels
1223 its last hop `fallback_message`). A single-entry self-report describes the
1224 hop itself and gains its model — `model_label`, the caller-spelled primary
1225 or the chain entry's id — when the wire didn't name one; a multi-entry
1226 self-report (a server-tool loop) is kept verbatim. Without a self-report,
1227 one entry is built from the refusal's usage.
1228 """
1229 reported = refusal.usage.get("iterations")
1230 if isinstance(reported, list) and reported:
1231 dict_entries = (_as_dict(entry) for entry in cast("List[Any]", reported))
1232 entries: list[dict[str, Any]] = [{**entry, "type": "message"} for entry in dict_entries if entry is not None]
1233 if entries:
1234 if len(entries) == 1 and not isinstance(entries[0].get("model"), str):
1235 entries[0]["model"] = model_label
1236 return entries
1237 return [_to_iteration_usage("message", model_label, refusal.usage)]
1238
1239
1240 def _serving_iteration_entry(delta_usage: dict[str, Any], model: str) -> dict[str, Any]:
1241 """The serving hop's `fallback_message` completer entry: its own
1242 self-reported iteration relabeled, or one built from its delta usage."""
1243 reported = delta_usage.get("iterations")
1244 if isinstance(reported, list) and reported:
1245 last = _as_dict(cast("List[Any]", reported)[-1])
1246 if last is not None:
1247 return {**last, "type": "fallback_message", "model": last.get("model") or model}
1248 return _to_iteration_usage("fallback_message", model, delta_usage)
1249
1250
1251 class _BlockTracker:
1252 """Block bookkeeping for one stream of the splice: accumulates each content
1253 block from its deltas (for the continuation prefill), shifts wire indices
1254 by `index_base` so they stay monotonic across hops, and tracks which blocks
1255 are still open so a refusal that cuts mid-block can close them.
1256 """
1257
1258 next_index: int
1259 """One past the highest shifted block index seen."""
1260
1261 def __init__(self, index_base: int = 0) -> None:
1262 self._index_base = index_base
1263 self.next_index = index_base
1264 # the stream's accumulated blocks keyed by their original wire index
1265 self._blocks: list[tuple[int, dict[str, Any]]] = []
1266 # shifted indices of blocks started but not yet stopped
1267 self._open: list[int] = []
1268
1269 def content_blocks(self) -> list[dict[str, Any]]:
1270 """The accumulated content blocks, in start order."""
1271 return [block for _, block in self._blocks]
1272
1273 def start(self, event: dict[str, Any]) -> None:
1274 """Track a content_block_start, shifting `event["index"]`."""
1275 index = event.get("index")
1276 if not isinstance(index, int):
1277 return
1278 content_block = _as_dict(event.get("content_block"))
1279 self._blocks.append((index, dict(content_block) if content_block is not None else {}))
1280 shifted = index + self._index_base
1281 event["index"] = shifted
1282 self._open.append(shifted)
1283 self.next_index = max(self.next_index, shifted + 1)
1284
1285 def delta(self, event: dict[str, Any]) -> None:
1286 """Apply a content_block_delta to its accumulating block, shifting `event["index"]`."""
1287 index = event.get("index")
1288 if not isinstance(index, int):
1289 return
1290 delta = _as_dict(event.get("delta"))
1291 if delta is not None:
1292 _apply_delta(self._blocks, index, delta)
1293 event["index"] = index + self._index_base
1294
1295 def stop(self, event: dict[str, Any]) -> None:
1296 """Track a content_block_stop, shifting `event["index"]`."""
1297 index = event.get("index")
1298 if not isinstance(index, int):
1299 return
1300 shifted = index + self._index_base
1301 event["index"] = shifted
1302 if shifted in self._open:
1303 self._open.remove(shifted)
1304 self.next_index = max(self.next_index, shifted + 1)
1305
1306 def close_open_blocks(self) -> Iterator[bytes]:
1307 """content_block_stop events for any blocks still open."""
1308 for index in self._open:
1309 yield _emit("content_block_stop", {"type": "content_block_stop", "index": index})
1310 self._open.clear()
1311
1312
1313 def _apply_delta(blocks: list[tuple[int, dict[str, Any]]], index: int, delta: dict[str, Any]) -> None:
1314 """Apply a content_block_delta to the accumulating block at `index`."""
1315 block = next((block for block_index, block in blocks if block_index == index), None)
1316 if block is None:
1317 return
1318 delta_type = delta.get("type")
1319 if delta_type == "text_delta":
1320 block["text"] = str(block.get("text") or "") + str(delta.get("text") or "")
1321 elif delta_type == "input_json_delta":
1322 block["_partial_json"] = str(block.get("_partial_json") or "") + str(delta.get("partial_json") or "")
1323 elif delta_type == "citations_delta":
1324 citations = block.get("citations")
1325 if not isinstance(citations, list):
1326 citations = []
1327 block["citations"] = citations
1328 cast("List[Any]", citations).append(delta.get("citation"))
1329 elif delta_type == "thinking_delta":
1330 block["thinking"] = str(block.get("thinking") or "") + str(delta.get("thinking") or "")
1331 elif delta_type == "signature_delta":
1332 block["signature"] = delta.get("signature")
1333
1334
1335 def _to_prefill_blocks(response_blocks: list[dict[str, Any]]) -> list[Any]:
1336 """Convert a hop's accumulated response blocks to the appended assistant turn.
1337
1338 A `fallback_has_prefill_claim` refusal guarantees the partial output is
1339 resendable, so the blocks go out near-verbatim. Three rewrites apply:
1340 `fallback` seam blocks (wire markers, not content) are dropped, tool inputs
1341 are reassembled from their accumulated `input_json_delta` JSON
1342 (content_block_start carries `input: {}`), and trailing thinking blocks are
1343 stripped — the server rejects an assistant turn whose final block is
1344 `thinking`, so a refusal that cut the stream mid-thought would otherwise
1345 400 the continuation. A partial that was nothing but thinking strips to
1346 empty, and the hop falls back to the same-body form.
1347 """
1348 out: list[Any] = []
1349 for block in response_blocks:
1350 if block.get("type") == "fallback":
1351 continue
1352 partial_json = block.get("_partial_json")
1353 if not isinstance(partial_json, str):
1354 out.append(block)
1355 continue
1356 block = {key: value for key, value in block.items() if key != "_partial_json"}
1357 parsed = _safe_json(partial_json)
1358 block["input"] = parsed if parsed is not None else block.get("input")
1359 out.append(block)
1360 while out and out[-1].get("type") in ("thinking", "redacted_thinking"):
1361 out.pop()
1362 return out
1363
1364
1365 def _strip_seam_blocks(body: dict[str, Any]) -> dict[str, Any]:
1366 """A copy of `body` with `{type: "fallback"}` seam blocks filtered out of the
1367 replayed message history; `body` itself when there are none.
1368
1369 An assistant turn left with no content by the strip — a seam-only turn — is
1370 dropped whole; the server rejects empty-content turns."""
1371 messages = body.get("messages")
1372 if not isinstance(messages, list):
1373 return body
1374 stripped = False
1375 stripped_messages: list[Any] = []
1376 for message in cast("List[Any]", messages):
1377 message_dict = _as_dict(message)
1378 content = message_dict.get("content") if message_dict is not None else None
1379 if message_dict is None or not isinstance(content, list):
1380 stripped_messages.append(message)
1381 continue
1382 content_list = cast("List[Any]", content)
1383 kept = [block for block in content_list if not (is_dict(block) and block.get("type") == "fallback")]
1384 if len(kept) == len(content_list):
1385 stripped_messages.append(message)
1386 continue
1387 stripped = True
1388 if not kept and message_dict.get("role") == "assistant":
1389 continue
1390 stripped_messages.append({**message_dict, "content": kept})
1391 if not stripped:
1392 return body
1393 return {**body, "messages": stripped_messages}
1394
1395
1396 def _with_middleware_headers(request: APIRequest, betas: tuple[AnthropicBetaParam, ...]) -> APIRequest:
1397 """A copy of `request` with `betas` appended to its `anthropic-beta` header
1398 (skipping values already present) and the middleware's helper-telemetry tag
1399 appended to `x-stainless-helper`. Single `request.copy()` for both.
1400 """
1401 current = build_headers(request.headers)[0].get("anthropic-beta", "")
1402 existing = {value.strip() for value in current.split(",")}
1403 additions = dict.fromkeys(str(beta) for beta in betas if str(beta) not in existing)
1404 beta_header = {"anthropic-beta": ",".join(filter(None, [current, *additions]))} if current or additions else {}
1405 return request.copy(
1406 headers=merge_headers(request.headers, beta_header, helper_header("fallback-refusal-middleware"))
1407 )
1408
1409
1410 def _credit_token(message: Message | BetaMessage) -> str | None:
1411 """The refusal's minted credit token; only the beta surface carries one."""
1412 if isinstance(message, BetaMessage) and message.stop_details is not None:
1413 return message.stop_details.fallback_credit_token
1414 return None
1415
1416
1417 def _refusal_category(message: Message | BetaMessage) -> str | None:
1418 """The policy category that caused the refusal; only the beta surface carries one."""
1419 if isinstance(message, BetaMessage) and message.stop_details is not None:
1420 return message.stop_details.category
1421 return None
1422
1423
1424 def _seam_block(from_model: str, to_model: str, category: str | None) -> dict[str, Any]:
1425 """The synthetic `fallback` content block marking one model boundary."""
1426 return {
1427 "type": "fallback",
1428 "from": {"model": from_model},
1429 "to": {"model": to_model},
1430 "trigger": {"type": "refusal", "category": category},
1431 }
1432
1433
1434 def _seamed_http_response(original: httpx2.Response, seams: list[dict[str, Any]]) -> httpx2.Response | None:
1435 """A copy of the served hop's response with `seams` prepended to its
1436 `content`, or `None` when the body isn't the expected message shape.
1437
1438 The caller has already parsed the response, so its body is buffered.
1439 """
1440 message = _as_dict(_safe_json(original.content.decode("utf-8")))
1441 if message is None or not isinstance(message.get("content"), list):
1442 return None
1443 body = _json_dumps({**message, "content": [*seams, *cast("List[Any]", message["content"])]}).encode("utf-8")
1444 headers = original.headers.copy()
1445 for header in ("content-encoding", "content-length"):
1446 if header in headers:
1447 del headers[header]
1448 return httpx2.Response(
1449 status_code=original.status_code,
1450 headers=headers,
1451 content=body,
1452 request=original.request,
1453 )
1454
1455
1456 def _prepend_seam_blocks(response: APIResponse[Any], seams: list[dict[str, Any]]) -> APIResponse[Any]:
1457 raw = _seamed_http_response(response.http_response, seams)
1458 if raw is None:
1459 return response
1460 return APIResponse(
1461 raw=raw,
1462 cast_to=response._cast_to,
1463 client=response._client,
1464 stream=False,
1465 stream_cls=response._stream_cls,
1466 options=response._options,
1467 retries_taken=response.retries_taken,
1468 )
1469
1470
1471 def _prepend_seam_blocks_async(response: AsyncAPIResponse[Any], seams: list[dict[str, Any]]) -> AsyncAPIResponse[Any]:
1472 raw = _seamed_http_response(response.http_response, seams)
1473 if raw is None:
1474 return response
1475 return AsyncAPIResponse(
1476 raw=raw,
1477 cast_to=response._cast_to,
1478 client=response._client,
1479 stream=False,
1480 stream_cls=response._stream_cls,
1481 options=response._options,
1482 retries_taken=response.retries_taken,
1483 )
1484
1485
1486 def _apply_hop(body: dict[str, Any], entry: BetaFallbackParam) -> dict[str, Any]:
1487 """`entry` applied as a patch against `body`: a field set to a value
1488 overrides it, a field explicitly `None` unsets it (absent from the retried
1489 request — not sent as `null`), an absent field keeps the original value.
1490
1491 `output_config` patches one level deep: its subfields follow the same
1492 set / `None`-unsets / absent-keeps rule against the original request's
1493 `output_config`; the whole object is dropped when nothing is left.
1494
1495 A carried `between_tools` thinking config becomes `disabled` unless the
1496 entry sets `thinking`: the fallback model may not accept `between_tools`.
1497
1498 Always a fresh dict; `body` is never mutated."""
1499 patched = _patch(body, cast("Dict[str, Any]", entry))
1500 thinking = _as_dict(body.get("thinking"))
1501 if "thinking" not in entry and thinking is not None and thinking.get("type") == "between_tools":
1502 patched["thinking"] = {"type": "disabled"}
1503 output_config = _as_dict(entry.get("output_config"))
1504 if output_config is not None:
1505 merged = _patch(_as_dict(body.get("output_config")) or {}, output_config)
1506 if merged:
1507 patched["output_config"] = merged
1508 else:
1509 patched.pop("output_config", None)
1510 return patched
1511
1512
1513 def _patch(base: dict[str, Any], overrides: dict[str, Any]) -> dict[str, Any]:
1514 """`overrides` applied flat against `base`: a key set to a value overrides
1515 it, a key explicitly `None` unsets it, an absent key keeps the base value.
1516 Always a fresh dict."""
1517 patched = dict(base)
1518 for key, value in overrides.items():
1519 if value is None:
1520 patched.pop(key, None)
1521 else:
1522 patched[key] = value
1523 return patched
1524
1525
1526 def _merged_body(body: dict[str, Any], fallback: BetaFallbackParam, credit_token: str | None) -> dict[str, Any]:
1527 """The non-streaming retry body: the fallback entry applied as a patch
1528 against the original params, plus the refusal's credit token when it minted one."""
1529 merged = _apply_hop(body, fallback)
1530 if credit_token:
1531 merged["fallback_credit_token"] = _credit_token_param(credit_token)
1532 return merged
1533
1534
1535 def _safe_json(text: str) -> Any:
1536 try:
1537 return json.loads(text)
1538 except Exception:
1539 return None
1540
1541
1542 def _json_dumps(value: Any) -> str:
1543 return json.dumps(value, separators=(",", ":"))
1544
1545
1546 def _as_dict(value: object) -> dict[str, Any] | None:
1547 return cast("Dict[str, Any]", value) if is_dict(value) else None
1548
1549
1550 def _read_json(response: httpx2.Response) -> Any:
1551 try:
1552 return json.loads(response.read())
1553 except Exception:
1554 return None
1555
1556
1557 async def _read_json_async(response: httpx2.Response) -> Any:
1558 try:
1559 return json.loads(await response.aread())
1560 except Exception:
1561 return None
1562
1563
1564 def _emit(event: str, payload: dict[str, Any]) -> bytes:
1565 return _serialize_sse(event=event, data=_json_dumps(payload)).encode("utf-8")
1566
1567
1568 def _passthrough_sse(sse: ServerSentEvent) -> bytes:
1569 """Forward a decoded event in its original wire bytes, preserving SSE fields
1570 beyond `event:`/`data:` (`id:`, `retry:`, comment lines). Falls back to
1571 re-serializing for events with no raw lines.
1572 """
1573 if sse.raw:
1574 return ("\n".join(sse.raw) + "\n\n").encode("utf-8")
1575 return _serialize_sse(event=sse.event, data=sse.data).encode("utf-8")
1576
1577
1578 def _serialize_sse(*, event: str | None, data: str) -> str:
1579 """Serialize an event back to its SSE wire form (`event: ...\\ndata: ...\\n\\n`).
1580
1581 Multi-line `data` is emitted as one `data:` line per line, matching the
1582 spec. The inverse of the decoder behind `Stream.raw_events`.
1583 """
1584 out = ""
1585 if event is not None:
1586 out += f"event: {event}\n"
1587 for line in data.split("\n"):
1588 out += f"data: {line}\n"
1589 return out + "\n"
1590
1591
1592 def _to_iteration_usage(
1593 type: Literal["message", "fallback_message"], model: str, usage: dict[str, Any] | None
1594 ) -> dict[str, Any]:
1595 u = usage or {}
1596 return {
1597 "type": type,
1598 "model": model,
1599 "input_tokens": u.get("input_tokens") or 0,
1600 "output_tokens": u.get("output_tokens") or 0,
1601 "cache_read_input_tokens": u.get("cache_read_input_tokens") or 0,
1602 "cache_creation_input_tokens": u.get("cache_creation_input_tokens") or 0,
1603 "cache_creation": u.get("cache_creation"),
1604 }
1605
1606
1607 def _backfill(primary: dict[str, Any] | None, fallback: dict[str, Any] | None) -> dict[str, Any]:
1608 """Fill `None` fields on `primary` from `fallback`."""
1609 fallback = fallback or {}
1610 out: dict[str, Any] = {**fallback, **(primary or {})}
1611 for key, value in out.items():
1612 if value is None and fallback.get(key) is not None:
1613 out[key] = fallback[key]
1614 return out
1615
1616
1617 def _spliced_http_response(
1618 original: httpx2.Response, stream: httpx2.SyncByteStream | httpx2.AsyncByteStream
1619 ) -> httpx2.Response:
1620 """A synthetic response standing in for `original`, with `stream` as its body.
1621
1622 The spliced frames are emitted post-decode, so the original's
1623 content-encoding/length headers no longer describe the body.
1624 """
1625 headers = original.headers.copy()
1626 for header in ("content-encoding", "content-length"):
1627 if header in headers:
1628 del headers[header]
1629 return httpx2.Response(
1630 status_code=original.status_code,
1631 headers=headers,
1632 stream=stream,
1633 request=original.request,
1634 )
1635
1636
1637 class _FrameByteStream(httpx2.SyncByteStream):
1638 def __init__(self, frames: Generator[bytes, None, None]) -> None:
1639 self._frames = frames
1640
1641 @override
1642 def __iter__(self) -> Iterator[bytes]:
1643 return self._frames
1644
1645 @override
1646 def close(self) -> None:
1647 self._frames.close()
1648
1649
1650 class _AsyncFrameByteStream(httpx2.AsyncByteStream):
1651 def __init__(self, frames: AsyncGenerator[bytes, None]) -> None:
1652 self._frames = frames
1653
1654 @override
1655 def __aiter__(self) -> AsyncIterator[bytes]:
1656 return self._frames
1657
1658 @override
1659 async def aclose(self) -> None:
1660 await self._frames.aclose()