
    b\j                      % S SK Jr  S SKrS SKrS SKrS SKJrJrJ	r	J
r
JrJrJrJrJrJrJr  S SKJrJr  S SKJrJr  S SKrSSKJr  SSKJr  SS	KJr  SS
KJ r J!r!  SSK"J#r#J$r$J%r%  SSK&J'r'  SSK(J)r)J*r*J+r+  SSK,J-r-  SSK.J/r/  SSK0J1r1  SSK2J3r3  SSK4J5r5  SSK6J7r7  SS/r8\Rr                  " S5      r:S\;S'   Sr<Sr=S\;S'     " S S5      r>\" SSS 9r?S!\;S"'   \" S#S$S 9r@S%\;S&'    " S' S\*5      rA " S( S)\5      rB " S* S+\5      rC " S, S-\5      rD " S. S/\5      rE " S0 S15      rFSTS2 jrGSUS3 jrH " S4 S55      rISVS6 jrJSWS7 jrK " S8 S95      rLSXS: jrMSYS; jrNSZS< jrOS[S= jrPS\S> jrQS\S? jrRS]S@ jrSS^SA jrTS_SB jrUS`SC jrVSaSD jrWSbSE jrXScSF jrYSdSG jrZSeSH jr[SeSI jr\SfSJ jr]SgSK jr^ShSL jr_        SiSM jr`SjSN jra      SkSO jrb " SP SQ\R                  5      rd " SR SS\R                  5      rfg)l    )annotationsN)AnyDictListCallableIterableIteratorOptional	GeneratorAsyncIteratorAsyncGeneratorcast)Token
ContextVar)Literaloverride   )is_dict)	BaseModel)
APIRequest)APIResponseAsyncAPIResponse)StreamAsyncStreamServerSentEvent)AnthropicError)CallNext
MiddlewareAsyncCallNext)merge_headers)Message   )helper_header)BetaMessage)AnthropicBetaParam)BetaFallbackParamBetaFallbackStateBetaRefusalFallbackMiddlewarezanthropic.lib.middlewarezlogging.Loggerlogz/v1/messages)zfallback-credit-2026-06-01tuple[AnthropicBetaParam, ...]DEFAULT_BETASc                  D    \ rS rSr% SrS\S'    S
S jrSS jrSS jrSr	g	)r'   4   ug  Tracks which fallback a sequence of requests is pinned to.

Create one and enter it (`with state:` — the same context manager works for
both clients) around every request that should share the pin — the turns of
one conversation, or any wider scope the stickiness should apply to;
`BetaRefusalFallbackMiddleware` mutates it in place when a model refuses.
z
int | Noneindexc                    S U l         g Nr.   selfs    Y/var/www/website/venv/lib/python3.13/site-packages/anthropic/lib/middleware/_fallbacks.py__init__BetaFallbackState.__init__D   s	    
    c                    [         R                  U 5      n[        R                  / [        R                  5       QUP75        U $ r0   )_fallback_stateset_fallback_state_tokensget)r3   tokens     r4   	__enter__BetaFallbackState.__enter__G   s:    ##D)""#I%;%?%?%A#I5#IJr7   c                    [         R                  5       n[         R                  US S 5        [        R	                  US   5        g )N)r;   r<   r:   r9   reset)r3   exc_infotokenss      r4   __exit__BetaFallbackState.__exit__L   s6    '++-""6#2;/fRj)r7   r1   NreturnNone)rH   r'   )rC   objectrH   rI   )
__name__
__module____qualname____firstlineno____doc____annotations__r5   r>   rE   __static_attributes__ r7   r4   r'   r'   4   s#     
*r7   anthropic_beta_fallback_state)defaultz$ContextVar[BetaFallbackState | None]r9   $anthropic_beta_fallback_state_tokensrR   z7ContextVar[tuple[Token[BetaFallbackState | None], ...]]r;   c                     \ rS rSrSrSS.     SS jjr\SS j5       r\SS j5       rSS jr	SS	 jr
SS
 jr              SS jr              SS jr              SS jr              SS jrSrg)r(   ^   u  Middleware that retries refused beta `/v1/messages` requests down a
fallback chain, reproducing the server-side `fallbacks` wire shape
client-side.

Only `client.beta.messages` requests are handled — refusals minted by the
first-party `client.messages` surface carry no `fallback_credit_token`, so
those requests pass through untouched.

Non-streaming: when a response comes back with `stop_reason: "refusal"`, the
request is retried with each entry of `fallbacks` merged over the original
params — passing along the refusal's `fallback_credit_token` when it minted
one — until a model accepts or the chain is exhausted. A `fallback` seam
block per model boundary is prepended to the served message's content —
the same block shape the streaming splice emits. The served hop's `usage`
is left verbatim (streaming rewrites it to per-hop `usage.iterations`).

Streaming: when the stream ends in `stop_reason: "refusal"`, a second
request is issued to the fallback model. It carries the refusal's
`fallback_credit_token`, plus the refused model's partial output as a
trailing assistant prefill when the refusal grants one
(`fallback_has_prefill_claim`). The fallback's events are then spliced onto
the still-open stream, so the client sees one continuous message in the
server-side `fallbacks` wire shape: a `fallback` content block at each
model boundary, monotonic block indices, and per-hop `usage.iterations` on
the final `message_delta`. A refusal before any output streamed retries
even without a credit token, and the serving hop's `message_start` opens
the wire carrying the primary's message id.

The fallback-credit beta the credit tokens require is sent by default on
every request the middleware handles; the `betas` option controls this.

In both modes a fallback that itself refuses with a fresh credit token
continues down the chain. A streaming fallback whose appended prefill the
server rejects (HTTP 400 body mismatch) is retried once without it; a
fallback whose request fails outright is skipped — its token was never
redeemed, so it carries to the next entry. When every remaining entry fails
over HTTP, the suppressed refusal is replayed to the client with
`recommended_model` stamped from the final failure (the failed model for
capacity errors, `null` otherwise). A refusal surfaced to the client rather
than retried is reported through the `anthropic.lib.middleware` logger.

To keep later requests on the model that accepted, run them inside a shared
`BetaFallbackState` context; requests sharing that state start directly at
the pinned fallback. Reuse one state across whatever scope the pin should
apply to — typically a conversation. The state is the only pin: `fallback`
seam blocks replayed in the request history are stripped from the outgoing
request (an assistant turn left empty by the strip is dropped whole), never
read back as a pin.

```py
client = Anthropic(middleware=[BetaRefusalFallbackMiddleware([{"model": "claude-opus-4-8"}])])

state = BetaFallbackState()
with state:
    message = client.beta.messages.create(**params)
```
N)betasc               d    [        U5      U l        Uc  [        O
[        U5      U l        SU l        g)u  
Args:
    fallbacks: The fallback chain, tried in order. An empty chain disables
        the middleware.

    betas: Betas added to the `anthropic-beta` header of every `/v1/messages`
        request this middleware handles — the original request included, since
        refusals only carry a `fallback_credit_token` when the beta is enabled.
        Defaults to `("fallback-credit-2026-06-01",)`; pass `()` to send none.
NF)tuple
_fallbacksr+   _betas_warned_missing_state)r3   	fallbacksrX   s      r4   r5   &BetaRefusalFallbackMiddleware.__init__   s)       	*',}m%,%*"r7   c           	        U R                  U5      nUc  U" U5      $ [        R                  5       nU R                  U5      nU R	                  U5      n[        XR                  5      n[        U5      nUS:X  a  UO0 UEU R                  U   EnUR                  US9nU" U5      n	U	R                  R                  (       d  U	$ UR                  (       a4  US-   n
U
[        U R                  5      :  a  U	$ U R                  UUU	UU
US9$ UnU	n[        UR                  S5      =(       d    S5      n/ nU[        U R                  5      S-
  :  Ga5  UR                  R                  (       Ga  UR!                  5       n[#        U[$        [&        45      (       a  UR(                  S:w  a  OUS-  nU" U5        [+        U5      n[-        U5      nU" UR                  [/        X0R                  U   U5      S95      nUR                  R                  (       a9  [        U R                  U   S   5      nUR1                  [3        UUU5      5        UnU[        U R                  5      S-
  :  a  UR                  R                  (       a  GM  U(       aa  UR                  R                  (       aF  UR!                  5       n[#        U[$        [&        45      (       a  UR(                  S:w  a  [5        X5      $ U$ NrA   body   requestrc   response	call_next	first_hoppinmodel refusal)_applicable_bodyr9   r<   _start_index	_make_pin_with_middleware_headersr\   _strip_seam_blocksr[   copyhttp_response
is_successstreamlen_splice_fallback_streamstrparse
isinstancer!   r$   stop_reason_credit_token_refusal_category_merged_bodyappend_seam_block_prepend_seam_blocksr3   rf   rh   rc   statestart_indexrj   initial_bodyinitial_requestrg   ri   r.   res
from_modelseamsmessager=   categoryto_modelserveds                       r4   handle$BetaRefusalFallbackMiddleware.handle   s   $$W-<W%%##%''.nnU# +7KK@
 "$'*b0t6^6^Q\A]6^!,,L,9_-%%00O>>#aI C00//'!!## 0   ))'28b9
&(c$//*Q..33D3D3O3O3OiikGg'=>>'BUBUYbBbQJEJ!'*E(1HGLLl4QVAWY^._L`aC  ++tu5g>?[XxHI%
 c$//*Q..33D3D3O3O3O S&&11YY[F&7K"899f>P>PT]>] ,C77
r7   c           	     L  #    U R                  U5      nUc  U" U5      I S h  vN $ [        R                  5       nU R                  U5      nU R	                  U5      n[        XR                  5      n[        U5      nUS:X  a  UO0 UEU R                  U   EnUR                  US9nU" U5      I S h  vN n	U	R                  R                  (       d  U	$ UR                  (       a4  US-   n
U
[        U R                  5      :  a  U	$ U R                  UUU	UU
US9$ UnU	n[        UR                  S5      =(       d    S5      n/ nU[        U R                  5      S-
  :  GaE  UR                  R                  (       Ga)  UR!                  5       I S h  vN n[#        U[$        [&        45      (       a  UR(                  S:w  a  OUS-  nU" U5        [+        U5      n[-        U5      nU" UR                  [/        X0R                  U   U5      S95      I S h  vN nUR                  R                  (       a9  [        U R                  U   S   5      nUR1                  [3        UUU5      5        UnU[        U R                  5      S-
  :  a  UR                  R                  (       a  GM)  U(       ai  UR                  R                  (       aN  UR!                  5       I S h  vN n[#        U[$        [&        45      (       a  UR(                  S:w  a  [5        X5      $ U$  GN GNg GN GN NH7fra   )rn   r9   r<   ro   rp   rq   r\   rr   r[   rs   rt   ru   rv   rw   _splice_fallback_stream_asyncry   rz   r{   r!   r$   r|   r}   r~   r   r   r   _prepend_seam_blocks_asyncr   s                       r4   handle_async*BetaRefusalFallbackMiddleware.handle_async   s    $$W-<"7+++##%''.nnU# +7KK@
 "$'*b0t6^6^Q\A]6^!,,L,9"?33%%00O>>#aI C0055'!!## 6   ))'28b9
&(c$//*Q..33D3D3O3O3OIIK'Gg'=>>'BUBUYbBbQJEJ!'*E(1H!',,LW\G]_d4e,"fggC  ++tu5g>?[XxHI%
 c$//*Q..33D3D3O3O3O S&&1199;&F&7K"899f>P>PT]>] 2#==
} ," 40 ( h 'sa    L$LBL$2L3CL$LBL$LBL$$5L$L"=L$L$L$L$"L$c                v   [        UR                  5      n[        R                  " UR                  5      nU R
                  (       aT  UR                  R                  5       S:w  d6  UR                  [        :w  d"  UR                  R                  S5      S:w  d  Uc  gUR                  S5      b  [        S5      eU$ )zMThe request's JSON body when this middleware applies to it, `None` otherwise.postbetatrueNr^   az  Sending the `fallbacks:` request param is not supported when using the `BetaRefusalFallbackMiddleware`. You should either remove the middleware and send `fallbacks:` with the `server-side-fallback-2026-06-01` beta header to let the API handle refusal fallbacks, or omit the `fallbacks:` param if you'd like `BetaRefusalFallbackMiddleware` to handle fallbacks on the client side.)_as_dictjsonhttpxURLurlr[   methodlowerpath_MESSAGES_PATHparamsr<   r   )r3   rf   rc   r   s       r4   rn   .BetaRefusalFallbackMiddleware._applicable_body5  s    %ii$  ~~##%/xx>)zz~~f%/|88K , 0  r7   c                    Ub  UR                   c  gUR                   nSUs=::  a  [        U R                  5      :  d'  O  [        SU S[        U R                  5       S35      eU$ )zThe chain entry this request starts at (-1 = the original params).

Only an explicit `BetaFallbackState` pin moves the start; without one
the request starts at the original params.
rA   zBetaFallbackState.index z! is out of bounds for a chain of z? fallback(s); was the state shared with a different middleware?)r.   rw   r[   r   )r3   r   r   s      r4   ro   *BetaRefusalFallbackMiddleware._start_indexO  sk     =EKK/kk[73t#77 *;-7Xt'((gi  r7   c                   ^ ^ SU U4S jjnU$ )zUPin requests sharing the state to the entry being tried (or warn that there is none).c                x   > Tb  U Tl         g TR                  (       d  STl        [        R                  S5        g g )NTzanthropic-sdk: BetaRefusalFallbackMiddleware fell back without an active BetaFallbackState; follow-up requests will retry models that already refused. Run them inside a shared `with BetaFallbackState():` block to pin them to the accepted model.)r.   r]   r)   warning)r.   r3   r   s    r4   rj   4BetaRefusalFallbackMiddleware._make_pin.<locals>.pinb  s7     #//-1*& 0r7   )r.   intrH   rI   rR   )r3   r   rj   s   `` r4   rp   'BetaRefusalFallbackMiddleware._make_pin_  s    
	 
	 
r7   c          
         U R                  UUUUUUS9n[        [        UR                  [	        U5      5      UR
                  UR                  SUR                  UR                  UR                  S9$ )a(  Wrap the refusable stream in a response whose body passes events through
until a retryable refusal, then splices the fallback chain's events on.

Closing the returned response (or the `Stream` parsed from it) tears down
whichever stream is being read and abandons any in-flight fallback request.
re   Trawcast_toclientrv   
stream_clsoptionsretries_taken)
_spliced_framesr   _spliced_http_responsert   _FrameByteStream_cast_to_client_stream_cls_optionsr   r3   rf   rc   rg   rh   ri   rj   framess           r4   rx   5BetaRefusalFallbackMiddleware._splice_fallback_streamp  s      %% & 
 &x'='=?OPV?WX%%##++%%"00
 	
r7   c          
         U R                  UUUUUUS9n[        [        UR                  [	        U5      5      UR
                  UR                  SUR                  UR                  UR                  S9$ )Nre   Tr   )
_spliced_frames_asyncr   r   rt   _AsyncFrameByteStreamr   r   r   r   r   r   s           r4   r   ;BetaRefusalFallbackMiddleware._splice_fallback_stream_async  s     ++ , 
  &x'='=?TU[?\]%%##++%%"00
 	
r7   c          
   #  N  #    U R                   nUR                  n UR                  n	[        SSS SS / S9n
[        X5       S h  vN nUR                  c   Ub  UR                  5         g g U	R                  5         S n[        R                  X+5      n[        U[        U5      5       GH  nX}   n[        US   5      nUS-   [        U5      :  nU" U5        UR                  5       nS nS n[        S5       GH  nUR                  UR                  UU5      S9n U" U5      nUR                  R$                  (       a  UR                  n  O['        UR                  5      nUR                  R                  5         US:X  aF  UR(                  S:X  a6  U(       a/  [        R+                  S[-        U5      5        UR.                  nS nM  [        R!                  SUUR(                  [-        U5      5        [#        UUR(                  S
9n  O   Ub<  U(       a  GMn  UR1                  U5       H  nUv   M	       Ub  UR                  5         g g Uc   eUR                  nUR3                  U5        [        UR4                  U[7        UR8                  US9UR:                  UR<                  UR?                  5       S9n
[        UU
5       S h  vN nUR@                  (       a  URC                  5         UR                  c    Ub  UR                  5         g g UR                  5         S nURE                  XU5        GM     Ub  UR                  5         g g  GN! [         a.  n[        R!                  S	UU5        [#        US S
9n S nA  GMy  S nAff = f N! Ub  UR                  5         f f = f7fNr   TF)
index_basehas_nextsplice	wire_open
primary_idseam_framesrk   rd   r"   rb   zOanthropic-sdk: BetaRefusalFallbackMiddleware: fallback request to %s failed: %s)rk   statusi  zanthropic-sdk: BetaRefusalFallbackMiddleware: fallback request with the partial output appended was rejected (HTTP 400: %s); retrying without itzXanthropic-sdk: BetaRefusalFallbackMiddleware: fallback request to %s failed: HTTP %s: %s)
iterationsrk   )#r[   rt   
_HopReader
_drive_hoprefusedclose_ChainStatebeginrangerw   ry   continuationrs   hop_body	Exceptionr)   error_HopFailureru   
_read_jsonstatus_coder   _json_dumpsbaseterminal_failure_frames
queue_seam
next_index_SpliceInfor   r   r   pending_seam_framesopenedmark_openedabsorb_refusal)r3   rf   rc   rg   rh   ri   rj   r^   currentstream_areaderoutcomechainhopentryrk   r   r   res_bfailureattempthop_requesterrerr_bodyframehop_responses                             r4   r   -BetaRefusalFallbackMiddleware._spliced_frames  s     OO	)1)?)?k	 --HF ",H!==G&x " #w NNG  %%d4EYI7!E'N+7S^3C  %11315.2$QxG"),,ENN5,4W,"XK	 )+ 6 **55"'"5"5)%*=*=>H''--/!|(9(9S(@\g'1
 (-zz $ IIr))#H-	 *e>O>OPGC  (F &  "'!>!>w!G# "H6 " #1 ((($22  '#$//%&%2B2B%P#oo$// % 9 9 ; &0f%EE>>%%'??* " # ""$
 $$W\Bg 8j " #} >8 % 		m!
 #.E$"Gj F " #s   N%(N MN N%,B-N M"DN 3N%A=N N
3N 9N%)N 7N%N 
N!N:N NN N""N%c          
    h  #    U R                   nUR                  n UR                  n	[        SSS SS / S9n
[        X5        S h  vN nU7v   M   N
 U
R	                  5       nUR
                  c   Ub  UR                  5       I S h  vN    g g U	R                  5       I S h  vN    S n[        R                  X,5      n[        U[        U5      5       GH  nX~   n[        US   5      nUS-   [        U5      :  nU" U5        UR                  5       nS nS n[        S5       GHe  nUR                  UR                  UU5      S9n U" U5      I S h  vN  nO:! [         a-  n[         R#                  S	UU5        [%        US S
9n S nA  GOS nAff = fUR                  R&                  (       a  UR                  n  O[)        UR                  5      I S h  vN  nUR                  R                  5       I S h  vN    US:X  aG  UR*                  S:X  a7  U(       a0  [         R-                  S[/        U5      5        UR0                  nS nGM'  [         R#                  SUUR*                  [/        U5      5        [%        UUR*                  S
9n  O   UbF  U(       a  GM  UR3                  U5       H  nU7v   M
       Ub  UR                  5       I S h  vN    g g Uc   eUR                  nUR5                  U5        [        UR6                  U[9        UR:                  US9UR<                  UR>                  URA                  5       S9n
[        UU
5        S h  vN  nU7v   M  
 U
R	                  5       nURB                  (       a  URE                  5         UR
                  c    Ub  UR                  5       I S h  vN    g g UR                  5       I S h  vN    S nURG                  UUU5        GM     Ub  UR                  5       I S h  vN    g g ! Ub  UR                  5       I S h  vN    f f = f7fr   )$r[   rt   r   _drive_hop_asyncfinishr   acloser   r   r   rw   ry   r   rs   r   r   r)   r   r   ru   _read_json_asyncr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r3   rf   rc   rg   rh   ri   rj   r^   r   r   r   r   r   r   r   r   rk   r   r   r   r   r   r   r   r   r   s                             r4   r   3BetaRefusalFallbackMiddleware._spliced_frames_asyncE  s     OO	)1)?)?b	'--HF  0A eAmmoG&b "nn&&& #a //###G%%d4EYI7!E'N+7S^3C$1136:.2$QxG"),,ENN5,4W,"XK	&/&< < <$ 		m!
 #.E$"G **55"'"5"5%5e6I6I%JJJH--44666!|(9(9S(@\g'1
 (-zz $ IIr))#H-	 *e>O>OPGC  (F & !&!>!>w!G# "H2 "nn&&& #/ ((($22  '#$//%&%2B2B%P#oo$// % 9 9 ; $4L&#I    %K $J --/>>%%'??* "nn&&& # #))+++$$We\BS 8V "nn&&& #w"nn&&& #s#  P2%P AAA	P AP 2P2B	P2P #B&$B"P EEEP 
F#!FP FAP G"P 7G:8C P 8P2KP2A:P M!MM!AP !P27N:8P2?P OP 2P2P	P2P/'P*(P//P2)r\   r[   r]   )r^   zIterable[BetaFallbackParam]rX   z#Iterable[AnthropicBetaParam] | NonerH   rI   )rf   r   rh   r   rH   APIResponse[Any])rf   r   rh   r   rH   AsyncAPIResponse[Any])rf   r   rH   dict[str, Any] | None)r   BetaFallbackState | NonerH   r   )r   r   rH   Callable[[int], None])rf   r   rc   dict[str, Any]rg   r   rh   r   ri   r   rj   r   rH   r   )rf   r   rc   r   rg   r   rh   r   ri   r   rj   r   rH   r   )rf   r   rc   r   rg   r   rh   r   ri   r   rj   r   rH   Generator[bytes, None, None])rf   r   rc   r   rg   r   rh   r   ri   r   rj   r   rH   AsyncGenerator[bytes, None])rK   rL   rM   rN   rO   r5   r   r   r   rn   ro   rp   rx   r   r   r   rQ   rR   r7   r4   r(   r(   ^   s   8| 6:	+.+ 3	+
 
+( A AF A AF4 " 
  
 	 

 # 
  
  
 # 
 
 
D
 
 	

 (
 !
 
 #
 

py  y  	y 
 #y  y  y  #y  
&y vp' p' 	p'
 (p' !p' p' #p' 
%p'r7   c                  L    \ rS rSr% S\S'    S\S'    S\S'   S\S'   S\S	'   S
rg)_Refusali  Optional[str]r=   r   boolhas_prefill_claimDict[str, Any]usageeventrR   N)rK   rL   rM   rN   rP   rQ   rR   r7   r4   r  r    s+    SS(r7   r  c                  .    \ rS rSr% SrS\S'   S\S'   Srg)	r   i  z6Splice context for fallback hops; `None` for stream A.List[Dict[str, Any]]r   ry   rk   rR   NrK   rL   rM   rN   rO   rP   rQ   rR   r7   r4   r   r     s    @$$Jr7   r   c                  .    \ rS rSr% SrS\S'   S\S'   Srg)	r   i  zWA fallback hop whose request failed; stamps `recommended_model` when it
ends the chain.ry   rk   zOptional[int]r   rR   Nr  rR   r7   r4   r   r     s     JRr7   r   c                  l    \ rS rSr% SrS\S'    S\S'    S\S'    S	\S
'    S\S'    S\S'    S\S'   Srg)_HopOutcomei  z*The outcome of consuming one hop's stream.zOptional[_Refusal]r   r  rk   zOptional[Dict[str, Any]]start_eventr  blocksr   r   r  r   last_fallback_torR   Nr  rR   r7   r4   r  r    sD    4E:))0  \O^LT##3r7   r  c                      \ rS rSr% SrS\S'                  SS jr\SS j5       rSS jr	SS jr
SS	 jrSS
 jrSrg)r   i  u~  Consumes one hop's SSE events, producing the frames to forward to the
client while accumulating its content blocks.

Events are held until the hop produces output (a content block or a
terminal event), so a refusal that arrives before any output — a pre-stream
decline — leaves no trace on the wire and chains silently. On open, stream
A's held `message_start` is flushed in its original wire bytes; a spliced
hop's is suppressed when the wire is already open, or emitted with its `id`
rewritten to the primary's when this hop's start opens the wire. Queued
seam frames for every hop reached so far are flushed right after.

A spliced hop has its block indices shifted by `index_base` and its
terminal message_delta's usage rewritten to the `usage.iterations` chain
shape.

A refusal that can be chained — an entry remains, and either a
`fallback_credit_token` was minted or nothing has streamed yet — ends the
hop early: open blocks are closed, the terminal message_delta +
message_stop are suppressed, and the refusal is set on the outcome so the
caller can issue the next hop. Any other refusal is logged and passes
through to the client.
z_HopOutcome | Noner   c                   [        U5      U l        X l        X0l        X@l        XPl        X`l        S U l        S U l        S U l	        S U l
        / U l        SU l        S U l        S U l        g )NF)_BlockTracker_tracker	_has_next_splice
_wire_open_primary_id_seam_frames_model_start_usage_start_event_held_start_held_opened_last_fallback_tor   )r3   r   r   r   r   r   r   s          r4   r5   _HopReader.__init__  sg     &j1!#%'"&373737,.
-1r7   c                    U R                   $ r0   )r"  r2   s    r4   r   _HopReader.opened'      ||r7   c           
        [        [        UR                  5      5      nUb  UR                  S5      OSnU R                  nUS:X  a|  Uby  [        UR                  S5      5      nUbN  UR                  S5      n[        U[        5      (       a  UOSU l        [        UR                  S5      5      U l        X l	        Xl
        / $ US:X  a  Ub  U R                  5       n[        UR                  S5      5      nUb`  UR                  S5      S	:X  aK  [        UR                  S
5      5      n	U	b  U	R                  S5      OSn
[        U
[        5      (       a  Xl        U R                  R                  U5        Ub  / UQ[        SU5      P$ / UQ[!        U5      P$ US:X  aP  UbM  U R                  5       nU R                  R#                  U5        Ub  / UQ[        SU5      P$ / UQ[!        U5      P$ US:X  aP  UbM  U R                  5       nU R                  R%                  U5        Ub  / UQ[        SU5      P$ / UQ[!        U5      P$ US:X  Ga  UGb  [        UR                  S5      5      =(       d    0 nUR                  S5      S:X  Ga	  [        UR                  S5      5      nUb  UR                  S5      S:X  a  UOSnUb  UR                  S5      OSn[        U[        5      (       a	  U(       a  UOSnU R&                  (       + =(       a    U R                  R)                  5       (       + nU R*                  (       Ga"  Uc  U(       Ga  [-        [        UR                  S5      5      U R                  5      n[/        U R                  R1                  5       5      nSU l
        U R2                  R5                  5         [7        [9        UUb  UR                  S5      OSUSL=(       a    UR                  S5      SL UUS9U R                  U R                  U R                  R)                  5       U R                  R:                  U R&                  U R                  S9U l        U$ U(       d  [>        RA                  S5        O[>        RA                  S5        U R                  5       nUb  UR                  S5      S:X  a/  [        UR                  S5      5      nUb  URC                  SS5        [        UR                  S5      5      =(       d    0 n/ URD                  Q[G        UURH                  5      PUS'   UUS'   / UQ[        SU5      P$ / UQ[!        U5      P$ U R&                  (       d  U R2                  RK                  U5        / $ [!        U5      /$ )z:Process one event, returning the frames to forward for it.Ntypemessage_startr   rk   r	  content_block_startcontent_blockfallbacktocontent_block_deltacontent_block_stopmessage_deltadeltar|   rm   stop_detailsfallback_credit_tokenr   fallback_has_prefill_claimT)r=   r   r  r	  r
  r   rk   r  r  r   r   r  zvanthropic-sdk: BetaRefusalFallbackMiddleware: refusal stop_details has no fallback_credit_token; surfacing the refusalzkanthropic-sdk: BetaRefusalFallbackMiddleware: refusal but no fallback entries remain; surfacing the refusalrecommended_modelr   )&r   
_safe_jsondatar<   r  r{   ry   r  r  r  r   _openr#  r  start_emit_passthrough_sser2  stopr"  content_blocksr  	_backfilllistclose_open_blocksr!  clearr  r  r   r   r)   r   
setdefaultr   _serving_iteration_entryrk   r   )r3   sser
  
event_typer   r   rk   r   r,  r.  r   r2  r3  detailsr=   
pre_streamr	  s                    r4   feed_HopReader.feed+  s   CHH-.*/*;UYYv&
(U->uyy34G"G,'1%'='=e4$,W[[-A$B! %"I00U5FZZ\F$UYY%?@M(]->->v-F*-Tm//56.0n266'?$h,,-5*MM& % ?&>% 5u=> 6v5/45
 00U5FZZ\FMM& % ?&>% 5u=> 6v5/45
 //E4EZZ\FMMu% % >&=% 4e<= 6v5/45
 ?*u/@UYYw/06BEyy'94'		.(AB*6*B|GWGWX^G_clGl,rv@G@S$;<Y]!+E3!7!7Et!%-Tdmm6R6R6T2T
 >>>u'8J%huyy/A&BDDUDUVE!$--"A"A"CDF (,D$JJ$$&#. ("'@G@SW[[%<Y].5T.A.wgkkRnFoswFw"'"'! #kk$($5$5#}};;=#'==#;#;#||)-)?)?$DL "MIIG
 II@ ZZ\F!99]+y8 $,EIIn,E#FL#/$//0CTJ !7!34:'&&',UFLLA'l# "'g??!>??3V3-c233||JJc"I !%&&r7   c                   U R                   (       a  / $ SU l         / nU R                  c2  U R                  b$  UR                  [	        U R                  5      5        OU R
                  (       d  U R                  bt  [        R                  " U R                  5      n[        UR                  S5      5      nUb  U R                  b  U R                  US'   UR                  [        SU5      5        UR                  U R                  5        UR                  S U R                   5       5        SU l        U R                  R!                  5         U$ )zOpen the wire for this hop: its message_start (raw for stream A;
suppressed or id-rewritten for a spliced hop), the queued seam frames,
then anything else held.TNr   idr*  c              3  8   #    U  H  n[        U5      v   M     g 7fr0   )r=  ).0helds     r4   	<genexpr>#_HopReader._open.<locals>.<genexpr>  s     D&t,,   )r"  r  r   r   r=  r  r  _copydeepcopyr   r<   r  r<  extendr  r!  rC  )r3   r   r  r   s       r4   r:  _HopReader._open  s     <<I <<+.t/?/?@AT%6%6%B..):):;K{y9:G"t'7'7'C $ 0 0MM%=>d''(DDD

r7   c                b    U R                   c  U R                  (       a  / $ U R                  5       $ )zCFrames still owed when the stream ends without a chainable refusal.)r   r"  r:  r2   s    r4   finish_frames_HopReader.finish_frames  s#    <<#t||Izz|r7   c           
         U R                   b  U R                   $ [        SU R                  U R                  U R                  R                  5       U R                  R                  U R                  U R                  S9$ )zCThe outcome once the hop's stream is fully consumed (or cut early).Nr6  )	r   r  r  r  r  r?  r   r"  r#  r2   s    r4   r   _HopReader.finish  sc    <<#<<++))==//1}}//<<!33
 	
r7   )r  r!  r   r#  r  r"  r  r  r  r  r  r  r  r   N)r   r   r   r  r   z_SpliceInfo | Noner   r  r   
str | Noner   list[bytes]rH   rI   )rH   r  )rF  r   rH   r^  rH   r^  )rH   r  )rK   rL   rM   rN   rO   rP   r5   propertyr   rJ  r:  rY  r   rQ   rR   r7   r4   r   r     s    .  U  	
 #   ! 
2  x't.
r7   r   c              #     #    [         R                  " U 5       H.  nUR                  U5       H  nUv   M	     UR                  c  M.    O   UR	                  5        H  nUv   M	     UR                  5       $ 7f)zKFeed one hop's SSE events through `reader`, yielding the frames to forward.)r   
raw_eventsrJ  r   rY  r   rg   r   rF  r   s       r4   r   r     se       *[[%EK &>>%	 +
 %%' (==?s   AA6/A6c                  #    [         R                  " U 5        Sh  vN nUR                  U5       H  nU7v   M
     UR                  c  M5    UR	                  5        H  nU7v   M
     g NN
 N!7f)u   Feed one hop's SSE events through `reader`, yielding the frames to forward.

The outcome is read from `reader.finish()` afterwards — async generators
cannot return a value.
N)r   rb  rJ  r   rY  rc  s       r4   r   r     sa      !++H5 c[[%EK &>>%%%' (5s+   A0A.A,A.)A0A0,A..A0c                      \ rS rSr% SrS\S'    S\S'    S\S'    S	\S
'    S\S'   S\S'   S\S'   S	\S'   S\S'   S\S'   S\S'    S!S jr\S"S j5       rS#S jr	S$S jr
S%S jrS&S jrS'S jrS(S jrS)S jrSrg )*r   i  z9Bookkeeping shared across the hops of one spliced stream.r   r   r  r   r]  r   ry   primary_modelr=   	List[Any]r   partialr   r  last_refusalzDict[str, Any] | Nonelast_start_eventr  r   c                    Xl         / U l        g r0   )_body_pending_seams)r3   rc   s     r4   r5   _ChainState.__init__  s    
+-r7   c                   UR                   c   eU " U5      n[        UR                  S5      =(       d    S5      Ul        UR                  Ul        UR
                  Ul        [        UR                  =(       d    0 R                  S5      5      nUb  UR                  S5      OSn[        U[        5      (       a  UOSUl
        UR                   R                  Ul        / Ul        UR                   R                  (       a  [        UR                  5      O/ Ul        UR"                  =(       d    UR                  Ul        UR                   Ul        UR                  Ul        [+        UR                   UR                  5      Ul        U$ )z3The chain state after stream A's chainable refusal.Nrk   rl   r   rM  )r   ry   r<   rf  r   r   r   r   r  r{   r   r=   r   r  _to_prefill_blocksr  rh  r  r   ri  rj  _declined_iteration_entriesr   )clsrc   r   r   start_messagestart_ids         r4   r   _ChainState.begin  s)    ***D	!$((7"3"9r:"--!.. '"5"5";!@!@!KL.;.G=$$T*T'1(C'@'@8doo++
>Eoo>_>_*7>>:eg #33Ju7J7J$__!(!4!46wH[H[\r7   c                   U R                   nU =R                   S-  sl         U R                  R                  [        SSU[	        U R
                  XR                  R                  5      S.5      [        SSUS.5      /5        Xl        g)zQueue the reached hop's `fallback` seam block at the next monotonic index.

Queued seams are flushed by the hop reader once output reaches the wire,
so a chain of pre-stream declines lines its seams up after the serving
hop's message_start.
rd   r+  )r)  r.   r,  r0  r)  r.   N)r   rm  rV  r<  r   r   ri  r   )r3   r   
seam_indexs      r4   r   _ChainState.queue_seam#  s     __
1"") 5!+)4T__hPaPaPjPj)k *5IT^,_`
	
 #r7   c                ,    [        U R                  5      $ r0   )rA  rm  r2   s    r4   r   _ChainState.pending_seam_frames;  s    D''((r7   c                F    SU l         U R                  R                  5         g )NT)r   rm  rC  r2   s    r4   r   _ChainState.mark_opened>  s    !!#r7   c                6    / U R                   QU R                  Q$ r0   )r   rh  r2   s    r4   r   _ChainState.continuationB  s    **T\\**r7   c                4   0 U R                   EUER                  5        VVs0 s H  u  p4US:w  d  M  X4_M     nnnU R                  b  U R                  US'   U(       a4  UR                  S5      n/ [	        U[
        5      (       a  UO/ QSUS.PUS'   U$ s  snnf )uR  The hop's request body: the refused request's, with the entry's
overrides merged over it and extended by the continuation.

The server-side `fallbacks` param is stripped — it is mutually exclusive
with a credit-token retry. When the refusal granted no prefill claim the
appended turn is omitted entirely and the same-body form is sent.
r^   r4  messages	assistant)rolecontent)rl  itemsr=   r<   r{   rA  )r3   r   r   keyvaluerc   r  s          r4   r   _ChainState.hop_bodyE  s     >U

=Te=T=Z=Z=\s=\zs`cgr`r

=\s::!,0JJD()xx
+H (488(b $> D   ts
   BBc                   UR                   c   eUR                   R                  U l        X0l        UR                   R                  (       a  [	        UR
                  5      O/ U l        U R                  R                  [        UR                   U5      5        UR                   U l
        UR                  b  UR                  U l        UR                  U l        g)z7Fold a refused hop's outcome in, readying the next hop.N)r   r=   r   r  rp  r  rh  r   rV  rq  ri  r  rj  r   )r3   r   rk   r   s       r4   r   _ChainState.absorb_refusalX  s    ***__**
 	=D__=^=^)'..9df:7??ERS#OO*$+$7$7D!!,,r7   c                r   / nU R                   (       d  U R                  bt  [        R                  " U R                  5      n[	        UR                  S5      5      nUb  U R                  b  U R                  US'   UR                  [        SU5      5        UR                  U R                  5        [        R                  " U R                  R                  5      n[	        UR                  S5      5      nUb>  [	        UR                  S5      5      nUb!  UR                  S;   a  UR                  OSUS'   [	        UR                  S	5      5      =(       d    0 n[        R                  " U R                  5      US
'   XS	'   UR                  [        SU5      5        UR                  [        SSS05      5        U$ )u+  Degrade to the suppressed refusal when every remaining entry failed
over HTTP: replay its message_delta verbatim — `recommended_model`
stamped from the final failure (the failed model for capacity errors,
`null` otherwise) and `usage.iterations` carrying the recorded chain —
then message_stop.
Nr   rM  r*  r2  r3  )i  i  r7  r	  r   r1  message_stopr)  )r   rj  rT  rU  r   r<   r   r   r<  rV  rm  ri  r
  r   rk   r   )	r3   r   r   r  r   r
  r2  rH  r	  s	            r4   r   #_ChainState.terminal_failure_framesd  sS    !~~$"7"7"C..)>)>?K{y9:G"t'B $MM%=>d))*t006677+,uyy89G"@GR\@\w}}bf+,7+,2#nnT__=lgeOU34eNV^,DEFr7   )
rl  rm  r   r   ri  rj  r   rh  r=   r   N)rc   r   rH   rI   )rc   r   r   r  rH   r   )r   ry   rH   rI   r_  rG   )rH   	list[Any])r   r&   r   r  rH   r   )r   r  rk   ry   r   r  rH   rI   )r   r   rH   r^  )rK   rL   rM   rN   rO   rP   r5   classmethodr   r   r   r   r   r   r   r   rQ   rR   r7   r4   r   r     s    CO;O=2 ; 
OO++$$I.  ,#0)$+&
-r7   r   c                   U R                   R                  S5      n[        U[        5      (       a|  U(       au  S [	        SU5       5       nU Vs/ s H  oDc  M  0 UESS0EPM     nnU(       a?  [        U5      S:X  a.  [        US   R                  S5      [        5      (       d  XS   S'   U$ [        SXR                   5      /$ s  snf )	u3  The `usage.iterations` entries a declined hop contributes to the chain.

The hop's refusal self-reports its iterations: adopt them, retyped to
`message` (every one of them declined — a server-stitched envelope labels
its last hop `fallback_message`). A single-entry self-report describes the
hop itself and gains its model — `model_label`, the caller-spelled primary
or the chain entry's id — when the wire didn't name one; a multi-entry
self-report (a server-tool loop) is kept verbatim. Without a self-report,
one entry is built from the refusal's usage.
r   c              3  8   #    U  H  n[        U5      v   M     g 7fr0   )r   )rO  r   s     r4   rQ  ._declined_iteration_entries.<locals>.<genexpr>  s     Q5PE5PrS  rg  r)  r   rd   r   rk   )r	  r<   r{   rA  r   rw   ry   _to_iteration_usage)rm   model_labelreporteddict_entriesr   entriess         r4   rq  rq    s     }}  .H(D!!hQT+x5PQS_(uS_%)EE)E69)ES_(u7|q GAJNN74KS)Q)Q&1
7#N	;FGG )vs   CCc                    U R                  S5      n[        U[        5      (       aC  U(       a<  [        [	        SU5      S   5      nUb!  0 UESUR                  S5      =(       d    US.E$ [        SX5      $ )zThe serving hop's `fallback_message` completer entry: its own
self-reported iteration relabeled, or one built from its delta usage.r   rg  rA   fallback_messagerk   )r)  rk   )r<   r{   rA  r   r   r  )delta_usagerk   r  lasts       r4   rE  rE    sm     |,H(D!!h[(3B78\d\$6'ARA[V[\\15FFr7   c                  f    \ rS rSr% SrS\S'    SSS jjrSS jrSS jrSS jr	SS	 jr
SS
 jrSrg)r  i  a  Block bookkeeping for one stream of the splice: accumulates each content
block from its deltas (for the continuation prefill), shifts wire indices
by `index_base` so they stay monotonic across hops, and tracks which blocks
are still open so a refusal that cuts mid-block can close them.
r   r   c                8    Xl         Xl        / U l        / U l        g r0   )_index_baser   _blocksr:  )r3   r   s     r4   r5   _BlockTracker.__init__  s    %$9; "
r7   c                P    U R                    VVs/ s H  u  pUPM	     snn$ s  snnf )z/The accumulated content blocks, in start order.)r  )r3   _blocks      r4   r?  _BlockTracker.content_blocks  s     &*ll3l(!l333s   "c                p   UR                  S5      n[        U[        5      (       d  g[        UR                  S5      5      nU R                  R                  X#b  [        U5      O0 45        X R                  -   nXAS'   U R                  R                  U5        [        U R                  US-   5      U l
        g)z7Track a content_block_start, shifting `event["index"]`.r.   Nr,  rd   )r<   r{   r   r   r  r   dictr  r:  maxr   )r3   r
  r.   r,  shifteds        r4   r;  _BlockTracker.start  s    		'"%%% ?!;<U;TD$7Z\]^*** g

'"doow{;r7   c                    UR                  S5      n[        U[        5      (       d  g[        UR                  S5      5      nUb  [	        U R
                  X#5        X R                  -   US'   g)zQApply a content_block_delta to its accumulating block, shifting `event["index"]`.r.   Nr2  )r<   r{   r   r   _apply_deltar  r  )r3   r
  r.   r2  s       r4   r2  _BlockTracker.delta  sY    		'"%%%7+,u4!1!11gr7   c                   UR                  S5      n[        U[        5      (       d  gX R                  -   nX1S'   X0R                  ;   a  U R                  R                  U5        [        U R                  US-   5      U l        g)z6Track a content_block_stop, shifting `event["index"]`.r.   Nrd   )r<   r{   r   r  r:  remover  r   )r3   r
  r.   r  s       r4   r>  _BlockTracker.stop  sg    		'"%%%*** gjj JJg&doow{;r7   c              #     #    U R                    H  n[        SSUS.5      v   M     U R                   R                  5         g7f)z4content_block_stop events for any blocks still open.r0  rw  N)r:  r<  rC  )r3   r.   s     r4   rB  _BlockTracker.close_open_blocks  s8     ZZE,7KV[.\]]  

s   A A)r  r  r:  r   N)r   )r   r   rH   rI   )rH   list[dict[str, Any]])r
  r   rH   rI   rH   zIterator[bytes])rK   rL   rM   rN   rO   rP   r5   r?  r;  r2  r>  rB  rQ   rR   r7   r4   r  r    s/     O8#4
<2	<r7   r  c                2  ^ [        U4S jU  5       S5      nUc  gUR                  S5      nUS:X  aK  [        UR                  S5      =(       d    S5      [        UR                  S5      =(       d    S5      -   US'   gUS:X  aK  [        UR                  S5      =(       d    S5      [        UR                  S	5      =(       d    S5      -   US'   gUS
:X  aW  UR                  S5      n[        U[        5      (       d  / nXSS'   [        SU5      R                  UR                  S5      5        gUS:X  aK  [        UR                  S5      =(       d    S5      [        UR                  S5      =(       d    S5      -   US'   gUS:X  a  UR                  S5      US'   gg)zAApply a content_block_delta to the accumulating block at `index`.c              3  <   >#    U  H  u  pUT:X  d  M  Uv   M     g 7fr0   rR   )rO  block_indexr  r.   s      r4   rQ  _apply_delta.<locals>.<genexpr>  s     Q&.KK5<P%%&s   	Nr)  
text_deltatextrl   input_json_delta_partial_jsonpartial_jsoncitations_delta	citationsrg  citationthinking_deltathinkingsignature_delta	signature)nextr<   ry   r{   rA  r   r   )r  r.   r2  r  
delta_typer  s    `    r4   r  r    sX   Q&QSWXE}6"J\!EIIf-34s599V;L;RPR7SSf	)	)!$UYY%?%E2!FUYYWeMfMljlIm!mo	(	(IIk*	)T**I!*+[)$++EIIj,AB	'	'		* 5 ;<s599ZCXC^\^?__j	(	("YY{3k 
)r7   c                *   / nU  H  nUR                  S5      S:X  a  M  UR                  S5      n[        U[        5      (       d  UR                  U5        MS  UR	                  5        VVs0 s H  u  pEUS:w  d  M  XE_M     nnn[        U5      nUb  UOUR                  S5      US'   UR                  U5        M     U(       aI  US   R                  S5      S;   a1  UR                  5         U(       a  US   R                  S5      S;   a  M1  U$ s  snnf )u  Convert a hop's accumulated response blocks to the appended assistant turn.

A `fallback_has_prefill_claim` refusal guarantees the partial output is
resendable, so the blocks go out near-verbatim. Three rewrites apply:
`fallback` seam blocks (wire markers, not content) are dropped, tool inputs
are reassembled from their accumulated `input_json_delta` JSON
(content_block_start carries `input: {}`), and trailing thinking blocks are
stripped — the server rejects an assistant turn whose final block is
`thinking`, so a refusal that cut the stream mid-thought would otherwise
400 the continuation. A partial that was nothing but thinking strips to
empty, and the hop falls back to the same-body form.
r)  r-  r  inputrA   )r  redacted_thinking)r<   r{   ry   r   r  r8  pop)response_blocksoutr  r  r  r  parseds          r4   rp  rp    s     C 99V
*yy1,,,JJu.3kkmVm
so?UmVL)#)#5599W;Mg

5 ! #b'++f%)JJ	 #b'++f%)JJJ Ws   +D;Dc                   U R                  S5      n[        U[        5      (       d  U $ Sn/ n[        SU5       H  n[	        U5      nUb  UR                  S5      OSnUb  [        U[        5      (       d  UR                  U5        MO  [        SU5      nU Vs/ s H,  n[        U5      (       a  UR                  S5      S:X  a  M*  UPM.     n	n[        U	5      [        U5      :X  a  UR                  U5        M  SnU	(       d  UR                  S	5      S
:X  a  M  UR                  0 UESU	0E5        M     U(       d  U $ 0 U ESU0E$ s  snf )u  A copy of `body` with `{type: "fallback"}` seam blocks filtered out of the
replayed message history; `body` itself when there are none.

An assistant turn left with no content by the strip — a seam-only turn — is
dropped whole; the server rejects empty-content turns.r  Frg  Nr  r)  r-  Tr  r  )r<   r{   rA  r   r   r   r   rw   )
rc   r  strippedstripped_messagesr   message_dictr  content_listr  kepts
             r4   rr   rr     s;    xx
#Hh%%H#%X.(1=1I,""9-tz'4'@'@$$W-K1#/l<%599U[K\`jKj<lt9L))$$W-((0K?  !BL!B)T!BC / 2d2J 122 ms   )EEc           
       ^ [         R                  " U R                  R                  5        VVs0 s H  u  p#[	        U[
        5      (       d  M  X#_M      snn5      R                  SS5      nUR                  S5       Vs1 s H  oUR                  5       iM     snm[        R                  U4S jU 5       5      nU R                  R                  5        VVs0 s H  u  p#UR                  5       S:w  d  M  X#_M     nnnU(       d  U(       a!  SR                  [        SU/UQ5      5      US'   U R                  [        U[!        S5      5      S9$ s  snnf s  snf s  snnf )	zA copy of `request` with `betas` appended to its `anthropic-beta` header
(skipping values already present) and the middleware's helper-telemetry tag
appended to `x-stainless-helper`. Single `request.copy()` for both.
zanthropic-betarl   ,c              3  \   >#    U  H!  n[        U5      T;  d  M  [        U5      v   M#     g 7fr0   )ry   )rO  r   existings     r4   rQ  +_with_middleware_headers.<locals>.<genexpr>C  s$     WEDSYh=Vic$iiEs   ,,z, Nzfallback-refusal-middleware)headers)r   Headersr  r  r{   ry   r<   splitstripr  fromkeysr   joinfilterrs   r    r#   )	rf   rX   kvr   r  	additionsr  r  s	           @r4   rq   rq   :  s    mmgoo.C.C.E\.EdaTUWZI[TQT.E\]aabrtvwG+2==+=>+=%+=>HWEWWI ' 5 5 7Y 71779HX;Xtqt 7GY)$(IIfTG;Pi;P.Q$R !<<g}Eb7c d<ee ]>Ys   E
E
?EE5Ec                t    [        U [        5      (       a#  U R                  b  U R                  R                  $ g)zEThe refusal's minted credit token; only the beta surface carries one.N)r{   r$   r3  r4  r   s    r4   r}   r}   J  s/    ';''G,@,@,L##999r7   c                t    [        U [        5      (       a#  U R                  b  U R                  R                  $ g)zOThe policy category that caused the refusal; only the beta surface carries one.N)r{   r$   r3  r   r  s    r4   r~   r~   Q  s/    ';''G,@,@,L##,,,r7   c                    SSU 0SU0SUS.S.$ )zBThe synthetic `fallback` content block marking one model boundary.r-  rk   rm   )r)  r   )r)  fromr.  triggerrR   )r   r   r   s      r4   r   r   X  s)     *%!%8<	 r7   c           
        [        [        U R                  R                  S5      5      5      nUb$  [	        UR                  S5      [        5      (       d  g[        0 UES/ UQ[        SUS   5      Q0E5      R                  S5      nU R                  R                  5       nS H  nXT;   d  M
  XE	 M     [        R                  " U R                  UUU R                  S9$ )zA copy of the served hop's response with `seams` prepended to its
`content`, or `None` when the body isn't the expected message shape.

The caller has already parsed the response, so its body is buffered.
utf-8Nr  rg  zcontent-encodingzcontent-length)r   r  r  rf   )r   r8  r  decoder{   r<   rA  r   r   encoder  rs   r   Responser   rf   )originalr   r   rc   r  headers         r4   _seamed_http_responser  b  s     z("2"2"9"9'"BCDGjY)?FF_'_9.^.^['R[J\8].^_`gghopD##%G8 9 >>((  	 r7   c           
         [        U R                  U5      nUc  U $ [        UU R                  U R                  SU R
                  U R                  U R                  S9$ NFr   )r  rt   r   r   r   r   r   r   rg   r   r   s      r4   r   r   x  s^    
 6 6
>C
{!!''!!,, r7   c           
         [        U R                  U5      nUc  U $ [        UU R                  U R                  SU R
                  U R                  U R                  S9$ r  )r  rt   r   r   r   r   r   r   r  s      r4   r   r     s^    
 6 6
>C
{!!''!!,, r7   c                (    0 U EUEnU(       a  X#S'   U$ )zThe non-streaming retry body: the fallback entry merged whole over the
original params, plus the refusal's credit token when it minted one.r4  rR   )rc   r-  credit_tokenmergeds       r4   r   r     s$     211F*6&'Mr7   c                P     [         R                  " U 5      $ ! [         a     g f = fr0   )r   loadsr   )r  s    r4   r8  r8    s(    zz$ s    
%%c                ,    [         R                  " U SS9$ )N)r  :)
separators)r   dumpsr  s    r4   r   r     s    ::e
33r7   c                >    [        U 5      (       a  [        SU 5      $ S $ )Nr  )r   r   r  s    r4   r   r     s    ,3ENN4 %(DDr7   c                l     [         R                  " U R                  5       5      $ ! [         a     g f = fr0   )r   r  readr   rg   s    r4   r   r     s.    zz(--/** s   #& 
33c                   #     [         R                  " U R                  5       I S h  vN 5      $  N! [         a     g f = f7fr0   )r   r  areadr   r  s    r4   r   r     s7     zz 00110 s,   A#2 02 A2 
?A?Ac                F    [        U [        U5      S9R                  S5      $ )Nr
  r9  r  )_serialize_sser   r  )r
  payloads     r4   r<  r<    s    K,@AHHQQr7   c                    U R                   (       a-  SR                  U R                   5      S-   R                  S5      $ [        U R                  U R
                  S9R                  S5      $ )zForward a decoded event in its original wire bytes, preserving SSE fields
beyond `event:`/`data:` (`id:`, `retry:`, comment lines). Falls back to
re-serializing for events with no raw lines.

z

r  r  )r   r  r  r  r
  r9  )rF  s    r4   r=  r=    sN    
 ww		#''"V+33G<<		9@@IIr7   c                j    SnU b	  USU  S3-  nUR                  S5       H  nUSU S3-  nM     US-   $ )zSerialize an event back to its SSE wire form (`event: ...\ndata: ...\n\n`).

Multi-line `data` is emitted as one `data:` line per line, matching the
spec. The inverse of the decoder behind `Stream.raw_events`.
rl   zevent: r
  zdata: )r  )r
  r9  r  lines       r4   r  r    sR     Cr""

4 vR   !:r7   c           	     
   U=(       d    0 nU UUR                  S5      =(       d    SUR                  S5      =(       d    SUR                  S5      =(       d    SUR                  S5      =(       d    SUR                  S5      S.$ )Ninput_tokensr   output_tokenscache_read_input_tokenscache_creation_input_tokenscache_creation)r)  rk   r  r  r  r  r  )r<   )r)  rk   r	  us       r4   r  r    sp     	An-2/41#$55)B#C#Hq'(uu-J'K'Pq%% 01 r7   c                    U=(       d    0 n0 UEU =(       d    0 EnUR                  5        H$  u  p4Ub  M
  UR                  U5      c  M  X   X#'   M&     U$ )z0Fill `None` fields on `primary` from `fallback`.)r  r<   )primaryr-  r  r  r  s        r4   r@  r@    sS    ~2H9X9'-R9Ciik
=X\\#.:}CH " Jr7   c                    U R                   R                  5       nS H  nX2;   d  M
  X#	 M     [        R                  " U R                  UUU R
                  S9$ )zA synthetic response standing in for `original`, with `stream` as its body.

The spliced frames are emitted post-decode, so the original's
content-encoding/length headers no longer describe the body.
r  )r   r  rv   rf   )r  rs   r   r  r   rf   )r  rv   r  r  s       r4   r   r     sX     ##%G8 9 >>((  	 r7   c                  F    \ rS rSrSS jr\SS j5       r\S	S j5       rSrg)
r   i  c                    Xl         g r0   _framesr3   r   s     r4   r5   _FrameByteStream.__init__      r7   c                    U R                   $ r0   r  r2   s    r4   __iter___FrameByteStream.__iter__	  r'  r7   c                8    U R                   R                  5         g r0   )r  r   r2   s    r4   r   _FrameByteStream.close  s    r7   r  N)r   r  rH   rI   r  rG   )	rK   rL   rM   rN   r5   r   r  r   rQ   rR   r7   r4   r   r     s/        r7   r   c                  F    \ rS rSrSS jr\SS j5       r\S	S j5       rSrg)
r   i  c                    Xl         g r0   r  r  s     r4   r5   _AsyncFrameByteStream.__init__  r  r7   c                    U R                   $ r0   r  r2   s    r4   	__aiter___AsyncFrameByteStream.__aiter__  r'  r7   c                T   #    U R                   R                  5       I S h  vN   g  N7fr0   )r  r   r2   s    r4   r   _AsyncFrameByteStream.aclose  s     ll!!###s   (&(r  N)r   r  rH   rI   )rH   AsyncIterator[bytes]rG   )	rK   rL   rM   rN   r5   r   r'  r   rQ   rR   r7   r4   r   r     s/       $ $r7   r   )rg   httpx.Responser   r   rH   z#Generator[bytes, None, _HopOutcome])rg   r,  r   r   rH   r+  )rm   r  r  ry   rH   r  )r  r   rk   ry   rH   r   )r  z list[tuple[int, dict[str, Any]]]r.   r   r2  r   rH   rI   )r  r  rH   r  )rc   r   rH   r   )rf   r   rX   r*   rH   r   )r   zMessage | BetaMessagerH   r]  )r   ry   r   ry   r   r]  rH   r   )r  r,  r   r  rH   zhttpx.Response | None)rg   r   r   r  rH   r   )rg   r   r   r  rH   r   )rc   r   r-  r&   r  r]  rH   r   )r  ry   rH   r   )r  r   rH   ry   )r  rJ   rH   r   )rg   r,  rH   r   )r
  ry   r  r   rH   bytes)rF  r   rH   r-  )r
  r]  r9  ry   rH   ry   )r)  z&Literal['message', 'fallback_message']rk   ry   r	  r   rH   r   )r  r   r-  r   rH   r   )r  r,  rv   z,httpx.SyncByteStream | httpx.AsyncByteStreamrH   r,  )g
__future__r   rs   rT  r   loggingtypingr   r   r   r   r   r	   r
   r   r   r   r   contextvarsr   r   typing_extensionsr   r   r   _utilsr   _modelsr   _requestr   	_responser   r   
_streamingr   r   r   _exceptionsr   _middlewarer   r   r   _base_clientr    types.messager!   _stainless_helpersr#   types.beta.beta_messager$   types.anthropic_beta_paramr%   types.beta.beta_fallback_paramr&   __all__	getLoggerr)   rP   r   r+   r'   r9   r;   r(   r  r   r   r  r   r   r   r   rq  rE  r  r  rp  rr   rq   r}   r~   r   r  r   r   r   r8  r   r   r   r   r<  r=  r  r  r@  r   SyncByteStreamr   AsyncByteStreamr   rR   r7   r4   <module>rD     s    "       * /     " 6 > > ) > > ) $ . 2 < ? # ''(BC^ C0O- O >* *< 9CCblp8q5 q S]*BS O 
W	'J W	'z(y () S) S3) 34[
 [
|	S SlH,G; ;B4,B3>f ,4ERJ
09<EZ&R(
u++ 

$E11 
$r7   