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