L iNwtUddlmZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z m Z mZmZmZmZmZmZddlmZmZmZmZddlZddlZddlZddlmZddlmZm Z m!Z!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'dd l(m)Z)m*Z*dd l+m,Z,m-Z-m.Z.m/Z/dd l0m1Z1m2Z2dd l3m4Z4m5Z5e r ddl$m6Z6ddl7m8Z8edZ9edZ:edZ;eddZ<eddZ=ej|e?Z@deAd<Gdde e:ZBGddeBe:ZCGddeBe:ZDGd d!eCeEZFGd"d#eDeEZGGd$d%eCeEZHGd&d'eDeEZIGd(d)eJZKGd*d+e1ZLGd,d-e e<ZMGd.d/e e=ZNd9d0ZO d:d1ZP d;d2ZQ dd5ZT d?d6ZU d@d7ZVdAd8ZWy)B) annotationsN) TracebackType) TYPE_CHECKINGAnyUnionGenericTypeVarCallableIterator AsyncIteratorcastoverload) Awaitable ParamSpecoverride get_origin)NoneType)is_givenextract_type_argis_annotated_typeis_type_alias_typeextract_type_var_from_base) BaseModel is_basemodeladd_request_id)RAW_RESPONSE_HEADEROVERRIDE_CAST_TO_HEADER)Stream AsyncStreamis_stream_class_typeextract_stream_chunk_type)AnthropicErrorAPIResponseValidationError) JSONLDecoderAsyncJSONLDecoder)FinalRequestOptions) BaseClientPR_T _APIResponseTzAPIResponse[Any])bound_AsyncAPIResponseTzAsyncAPIResponse[Any]zlogging.Loggerlogc<eZdZUded<ded<ded<ded<d ed <d ed <d ed<ded< dd d dZed!dZed"dZed#dZed$dZ ed%dZ ed%dZ ed&dZ ed'dZ ed%dZddd(dZy))BaseAPIResponsetype[R]_cast_toBaseClient[Any, Any]_clientzdict[type[Any], Any]_parsed_by_typebool_is_sse_stream1type[Stream[Any]] | type[AsyncStream[Any]] | None _stream_clsr'_optionshttpx.Response http_responseint retries_takenr)r?ct||_||_i|_||_||_||_||_||_yN)r3r5r6r8r:r;r=r?)selfrawcast_toclientstream stream_clsoptionsr?s Y/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/anthropic/_response.py__init__zBaseAPIResponse.__init__>sA   !$%  *c.|jjSrA)r=headersrBs rIrMzBaseAPIResponse.headersRs!!)))rKc.|jjS)zHReturns the httpx Request instance associated with the current response.)r=requestrNs rI http_requestzBaseAPIResponse.http_requestV!!)))rKc.|jjSrA)r= status_coderNs rIrTzBaseAPIResponse.status_code[s!!---rKc.|jjS)z/Returns the URL for which the request was made.)r=urlrNs rIrVzBaseAPIResponse.url_s!!%%%rKc.|jjSrA)rQmethodrNs rIrXzBaseAPIResponse.methodds  '''rKc.|jjSrA)r= http_versionrNs rIrZzBaseAPIResponse.http_versionhs!!...rKc.|jjS)zCThe time taken for the complete request/response cycle to complete.)r=elapsedrNs rIr\zBaseAPIResponse.elapsedlrRrKc.|jjS)aWhether or not the response body has been closed. If this is False then there is response data that has not been read yet. You must either fully consume the response body or call `.close()` before discarding the response to prevent resource leaks. )r= is_closedrNs rIr^zBaseAPIResponse.is_closedqs!!+++rKc d|jjd|jd|jjd|j d S)N) __class____name__rTr= reason_phraser3rNs rI__repr__zBaseAPIResponse.__repr__{sP''(4+;+;*P>P>^>^=__fgkgtgtfuuv w rKNtoc ||n |j}t|r |j}|rt|r t |d}t |xs|}t j|rttt|trQtttd||jjdt |d|jSttt|trQtttd||jj!dt |d|jS|j"r6|rjt%|st'dt(dt*tt,|t/|d |jtt|j0 S|j2rWtt|j3t/|j2|jtt|j0 Std |j0j4}| t7tt|||jtt|j0 S|t8urttdS|j}|t:k(rtt|j<S|t>k(rtt|j@S|tBk(r#tttC|j<S|tDk(r#tttE|j<S|tFk(r+tt|j<jId k(St j|r%|jJdk(rtt||S|tLk(r tOdt j|rHt|tPjRr.|tPjRk7r tUdtt|St j|r5t|tVs%t|tXjVr t'd|tZurr|t\urj|t^urb|t`urZt|tVsJtOd|dtVdt^dt\dt`dt8dt:dtPjRd|jbjeddjgd^}}|jidsxtk|r/ |jm}|j0jo|||S|j0jxrt{|d|d|j<|j<S|jm}|j0jo|||S#tp$r*} trjudtw| | Yd} ~ d} ~ wwxYw)Nrztype[JSONLDecoder[Any]]@ chunk_size) raw_iterator line_typer=ztype[AsyncJSONLDecoder[Any]]z/Expected custom parse type to be a subclass of z or zUExpected custom stream type to be passed with a type argument, e.g. Stream[ChunkType])failure_message)rDresponserEr9trueHttpxBinaryResponseContentz+Unexpected state - cast_to is `APIResponse`z:Subclasses of httpx.Response cannot be passed to `cast_to`zYPydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`zUnsupported type, expected z to be a subclass of z, .z content-type*;json)datarDrpz5Could not read JSON from response data due to %s - %szMExpected Content-Type response header to be `application/json` but received `z ` instead.)rpmessagebody)>r3r __value__rrrinspectisclass issubclassr rr%r*r= iter_bytesr& aiter_bytesr8r! TypeErrorrr r+r"r5r:_default_stream_clsMissingStreamClassErrorrstrtextbytescontentr>floatr7lowerrd APIResponse RuntimeErrorhttpxResponse ValueErrorrpydanticobjectlistdictrrMgetsplitendswithrrv_process_response_data Exceptionr/debugtype_strict_response_validationr$) rBrhrDoriginrGrp content_type_rwexcs rI_parsezBaseAPIResponse._parsesy"DMM g &''G (1&w2GG$/ ??6 "$sF+\:&*&8&8$sF+->?AD7A%)%7%7%C%Cr%C%R"27A">&*&8&8   +B/#&UV\U]]abman$opp 9-D!"&!3!3#C6   $$ 9$:J:J K!%!3!3#C6%QSWS_S_SsSstJ!-//#!//T\\2  h 4= %% c>8==) ) e 8++, , c>3x}}-. . e 5/0 0 d?8==..0F:; ; ??7 #(8(8>! '!)? ||770%klxkyzDE!== }}||223  /!gIIUW[\_W`beffgs5W X W==X)rCr<rDr2rEr4rFr7rGr9rHr'r?r>returnNone)rz httpx.Headers)rz httpx.Request)rr>)rz httpx.URLrr)rzdatetime.timedelta)rr7rhztype[_T] | NonerzR | _T)rd __module__ __qualname____annotations__rJpropertyrMrQrTrVrXrZr\r^rrfrrKrIr1r11sO !!))BB!!!!M++ + % +  +F+%++ +(****..&&((//**,,  /3f rKr1ceZdZeddZeddZeddZddddZddZddZdd Z dd Z ddd Z ddd Z dd Z y)rcL|jjjdSNz request-idr=rMrrNs rI request_idzAPIResponse.request_id+!!))--l;;rKcyrArrBrhs rIparsezAPIResponse.parse/s,/rKcyrArrNs rIrzAPIResponse.parse2srKNrgc||n |j}|jj|}||S|js|j |j |}t |jjr|jj|}t|trt||j||j|<tt|S)aReturns the rich python representation of this response's data. For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. You can customise the type that the response is parsed into through the `to` argument, e.g. ```py from anthropic import BaseModel class MyModel(BaseModel): foo: str obj = response.parse(to=MyModel) print(obj.foo) ``` We support parsing: - `BaseModel` - `dict` - `list` - `Union` - `str` - `int` - `float` - `httpx.Response` rgr3r6rr8readrrr; post_parser isinstancerrrr r*rBrh cache_keycachedparseds rIrzAPIResponse.parse5s<.Bdmm %%)))4  M"" IIK# DMM-- .]]..v6F fi ( 64?? 3*0Y'AvrKc |jjS#tj$r}t |d}~wwxYwz,Read and return the binary response content.N)r=rrStreamConsumedStreamAlreadyConsumedrBrs rIrzAPIResponse.reades? 3%%**, ,## 3()s 2  3s? :?cN|j|jjS)3Read and decode the response content into a string.rr=rrNs rIrzAPIResponse.textos !!&&&rKcV|j|jjS)*Read and decode the JSON response content.rr=rvrNs rIrvzAPIResponse.jsonts  !!&&((rKc8|jjyzClose the response and release the connection. Automatically called if the response body is read to completion. N)r=closerNs rIrzAPIResponse.closeys   "rKc#TK|jj|D]}|ywz A byte-iterator over the decoded response content. This automatically handles gzip, deflate and brotli encoded responses. N)r=r~rBrlchunks rIr~zAPIResponse.iter_bytess- ''22:> EK &(c#TK|jj|D]}|ywzA str-iterator over the decoded response content that handles both gzip, deflate, etc but also detects the content's string encoding. N)r= iter_textrs rIrzAPIResponse.iter_texts- ''11*= EK rc#RK|jjD]}|ywz;Like `iter_text()` but will only yield chunks for each lineN)r= iter_linesrBrs rIrzAPIResponse.iter_liness)''224 EK s%'rz str | Nonerhztype[_T]rr+rr*rrrrrrrrrA)rl int | NonerzIterator[bytes])rlrr Iterator[str])rrrdrrrrrrrrrvrr~rrrrKrIrr*s^ <<// -1.`3' ) #rKrceZdZeddZeddZeddZddddZddZddZdd Z dd Z ddd Z ddd Z dd Z y)AsyncAPIResponsecL|jjjdSrrrNs rIrzAsyncAPIResponse.request_idrrKc KywrArrs rIrzAsyncAPIResponse.parses 25c KywrArrNs rIrzAsyncAPIResponse.parses #rNrgcK||n |j}|jj|}||S|js|j d{|j |}t |jjr|jj|}t|trt||j||j|<tt|S7w)a^Returns the rich python representation of this response's data. For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. You can customise the type that the response is parsed into through the `to` argument, e.g. ```py from anthropic import BaseModel class MyModel(BaseModel): foo: str obj = response.parse(to=MyModel) print(obj.foo) ``` We support parsing: - `BaseModel` - `dict` - `list` - `Union` - `str` - `httpx.Response` Nrgrrs rIrzAsyncAPIResponse.parses8.Bdmm %%)))4  M""))+  # DMM-- .]]..v6F fi ( 64?? 3*0Y'Av sAC)C'BC)cK |jjd{S7#tj$r}t |d}~wwxYwwr)r=areadrrrrs rIrzAsyncAPIResponse.readsH 3++1133 33## 3()s 2  3s0A(&(A(A  AA  AcjK|jd{|jjS7w)rNrrNs rIrzAsyncAPIResponse.texts,iik!!&&& s 313crK|jd{|jjS7w)rNrrNs rIrvzAsyncAPIResponse.jsons/iik!!&&(( s 757cTK|jjd{y7wr)r=acloserNs rIrzAsyncAPIResponse.closes   '')))s (&(cfK|jj|23d{}|7 6ywr)r=rrs rIr~zAsyncAPIResponse.iter_bytess6  --99*E  %K E1/-/1/1cfK|jj|23d{}|7 6ywr)r= aiter_textrs rIrzAsyncAPIResponse.iter_texts6  --88D  %K DrcdK|jj23d{}|7 6ywr)r= aiter_linesrs rIrzAsyncAPIResponse.iter_liness2--99;  %K ;s0.,.0.0rrrrrrrrrA)rlrrzAsyncIterator[bytes])rlrrAsyncIterator[str])rrrrrKrIrrs^ <<55 ##37,\3' ) *rKrc eZdZdZ ddZy)BinaryAPIResponse3Subclass of APIResponse providing helpers for dealing with binary data. Note: If you want to stream the response data instead of eagerly reading it all at once then you should use `.with_streaming_response` when making the API request, e.g. `.with_streaming_response.get_binary_response()` ct|d5}|jD]}|j| dddy#1swYyxYwa^Write the output to the given file. Accepts a filename or any path-like object, e.g. pathlib.Path Note: if you want to stream the data to the file instead of writing all at once then you should use `.with_streaming_response` when making the API request, e.g. `.with_streaming_response.get_binary_response()` wbmodeNopenr~write)rBfilefrws rI write_to_filezBinaryAPIResponse.write_to_file sF$T " a)      s '?ANrstr | os.PathLike[str]rrrdrr__doc__rrrKrIrrs$ rKrc eZdZdZ ddZy)AsyncBinaryAPIResponserc@Ktj|}|jdd{4d{}|j23d{}|j |d{#7@797"7 6dddd{7y#1d{7swYyxYwwranyioPathrr~r)rBrpathrrws rIrz$AsyncBinaryAPIResponse.write_to_file#szz$-- $ $"oo/ $ $dggdm##. $ $#0 $ $ $ $ $s+BA.BA0BB  A6A2A6B (A4)B .B0B2A64B 6B 7 BBB BB BBNrrrrKrIrrs$$$ $rKrc$eZdZdd ddZy)StreamedBinaryAPIResponseNrkct|d5}|j|D]}|j| dddy#1swYyxYwzuStreams the output to the given file. Accepts a filename or any path-like object, e.g. pathlib.Path rrNr)rBrrlrrws rIstream_to_filez(StreamedBinaryAPIResponse.stream_to_file6sH$T " a 3      s (AA rrrlrrrrdrrrrrKrIr r 5s( "& $    rKr c$eZdZdd ddZy)AsyncStreamedBinaryAPIResponseNrkcBKtj|}|jdd{4d{}|j|23d{}|j |d{#7A7:7"7 6dddd{7y#1d{7swYyxYwwrr)rBrrlr rrws rIrz-AsyncStreamedBinaryAPIResponse.stream_to_fileFszz$-- $ $"ooj9 $ $dggdm##. $ $#: $ $ $ $ $s+BA/BA1BB  A7A3A7B )A5*B /B1B3A75B 7B 8 BBB BB BBrrrrKrIrrEs( "& $$ $ $  $rKrc eZdZdfd ZxZS)rc$t|dy)Nz}The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `anthropic._streaming` for referencesuperrJ)rBrcs rIrJz MissingStreamClassError.__init__Ws  L rKr)rdrrrJ __classcell__rcs@rIrrVs   rKrc$eZdZdZdfd ZxZS)raG Attempted to read or stream content, but the content has already been streamed. This can happen if you use a method like `.iter_lines()` and then attempt to read th entire response body afterwards, e.g. ```py response = await client.post(...) async for line in response.iter_lines(): ... # do something with `line` content = await response.read() # ^ error ``` If you want this behaviour you'll need to either manually accumulate the response content or call `await response.read()` before iterating over the stream. c(d}t||y)Na&Attempted to read or stream some content, but the content has already been streamed. This could be due to attempting to stream the response content more than once. You can fix this by manually accumulating the response content while streaming or by calling `.read()` before starting to stream.r)rBrxrcs rIrJzStreamAlreadyConsumed.__init__rs A  !rKr)rdrrrrJrrs@rIrr]s( " "rKrc8eZdZdZddZddZ ddZy) ResponseContextManagerContext manager for ensuring that a request is not made until it is entered and that the response will always be closed when the context manager exits c ||_d|_yrA _request_func!_ResponseContextManager__response)rB request_funcs rIrJzResponseContextManager.__init__s)04rKcD|j|_|jSrAr!rNs rI __enter__z ResponseContextManager.__enter__s,,.rKcR|j|jjyyrA)r#rrBexc_typerexc_tbs rI__exit__zResponseContextManager.__exit__s# ?? & OO ! ! # 'rKN)r$zCallable[[], _APIResponseT]rr)rr,r)ztype[BaseException] | NonerzBaseException | Noner*zTracebackType | Nonerr)rdrrrrJr&r+rrKrIrrs< 5$,$"$% $  $rKrc8eZdZdZddZddZ ddZy) AsyncResponseContextManagerrc ||_d|_yrA _api_request&_AsyncResponseContextManager__response)rB api_requests rIrJz$AsyncResponseContextManager.__init__s'59rKcXK|jd{|_|jS7wrAr0rNs rI __aenter__z&AsyncResponseContextManager.__aenter__s% $ 1 112s *(*cnK|j#|jjd{yy7wrA)r2rr(s rI __aexit__z%AsyncResponseContextManager.__aexit__s0 ?? &//'') ) ) ' )s *535N)r3Awaitable[_AsyncAPIResponseT]rr)rr.r,)rdrrrrJr5r7rrKrIr.r.s< :*,*"*% *  *rKr.cDtjdfd }|S)Higher order function that takes one of our bound API methods and wraps it to support streaming and returning the raw `APIResponse` object directly. citt|jdxsi}d|t<||d<t j g|i|}t ttgttf|SN extra_headersrF) r rrr functoolspartialrr rr*argskwargsr= make_requestfuncs rIwrappedz-to_streamed_response_wrapper..wrappedsr(ZDfjj6Q,R,XVX(Z -5 )*"/ ((??? %d8B A4F+G&VWWrK)rAP.argsrBP.kwargsrz&ResponseContextManager[APIResponse[R]]r>wrapsrDrEs` rIto_streamed_response_wrapperrKs) __TXX NrKcDtjdfd }|S)r:citt|jdxsi}d|t<||d<|i|}t tt t t|Sr<)r rrrr.rrr*r@s rIrEz3async_to_streamed_response_wrapper..wrappedse(ZDfjj6Q,R,XVX(Z -5 )*"/T,V, *4 :J1:M0NP\+]^^rK)rArFrBrGrz0AsyncResponseContextManager[AsyncAPIResponse[R]]rHrJs` rI"async_to_streamed_response_wrapperrNs)__T__ NrKcHtjdfd }|S)'Higher order function that takes one of our bound API methods and an `APIResponse` class and wraps the method to support streaming and returning the given response class directly. Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` citt|jdxsi}d|t<|t<||d<t j g|i|}tttgtf|Sr<) r rrrrr>r?rr r,rArBr=rCrD response_clss rIrEz4to_custom_streamed_response_wrapper..wrappedsy(ZDfjj6Q,R,XVX(Z -5 )*1= -."/ ((??? %d8B 4E+F &UVVrK)rArFrBrGrz%ResponseContextManager[_APIResponseT]rHrDrSrEs`` rI#to_custom_streamed_response_wrapperrUs)__T W W NrKcHtjdfd }|S)rPcitt|jdxsi}d|t<|t<||d<|i|}t tt t|Sr<)r rrrrr.rr.rRs rIrEz:async_to_custom_streamed_response_wrapper..wrappedsj(ZDfjj6Q,R,XVX(Z -5 )*1= -."/T,V, *4 :L0M|+\]]rK)rArFrBrGrz/AsyncResponseContextManager[_AsyncAPIResponseT]rHrTs`` rI)async_to_custom_streamed_response_wrapperrXs)__T ^ ^ NrKcDtjdfd }|S)Higher order function that takes one of our bound API methods and wraps it to support returning the raw `APIResponse` object directly. citt|jdxsi}d|t<||d<ttt |i|SNr=rC)r rrrrr*rArBr=rDs rIrEz(to_raw_response_wrapper..wrappedsS(ZDfjj6Q,R,XVX(Z -2 )*"/KND$$9&$9::rK)rArFrBrGrzAPIResponse[R]rHrJs` rIto_raw_response_wrapperr^ s' __T;; NrKcDtjdfd }|S)rZcKitt|jdxsi}d|t<||d<ttt |i|d{S7wr\)r rrrrr*r]s rIrEz.async_to_raw_response_wrapper..wrappeds_(ZDfjj6Q,R,XVX(Z -2 )*"/$Q'tT/DV/D)DEE)DsAAA  A)rArFrBrGrzAsyncAPIResponse[R]rHrJs` rIasync_to_raw_response_wrapperras) __TFF NrKcHtjdfd }|S)Higher order function that takes one of our bound API methods and an `APIResponse` class and wraps the method to support returning the given response class directly. Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` citt|jdxsi}d|t<|t<||d<tt |i|Sr\)r rrrrr,rArBr=rDrSs rIrEz/to_custom_raw_response_wrapper..wrapped5sZ(ZDfjj6Q,R,XVX(Z -2 )*1= -."/M4#8#899rK)rArFrBrGrr,rHrTs`` rIto_custom_raw_response_wrapperrf+s'__T:: NrKcHtjdfd }|S)rccitt|jdxsi}d|t<|t<||d<tt t |i|Sr\)r rrrrrr.res rIrEz5async_to_custom_raw_response_wrapper..wrappedLs`(ZDfjj6Q,R,XVX(Z -2 )*1= -."/I0143H3HIIrK)rArFrBrGrr8rHrTs`` rI$async_to_custom_raw_response_wrapperriBs)__TJJ NrKc Pt|tdtttfdS)aGiven a type like `APIResponse[T]`, returns the generic type variable `T`. This also handles the case where a concrete subclass is given, e.g. ```py class MyResponse(APIResponse[bytes]): ... extract_response_type(MyResponse) -> bytes ``` ztuple[type, ...]r) generic_basesindex)rr r1rr)typs rIextract_response_typernYs* & -N^/_` rK)rDCallable[P, R]rz3Callable[P, ResponseContextManager[APIResponse[R]]])rDCallable[P, Awaitable[R]]rz=Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]])rDCallable[P, object]rStype[_APIResponseT]rz2Callable[P, ResponseContextManager[_APIResponseT]])rDCallable[P, Awaitable[object]]rStype[_AsyncAPIResponseT]rztypesrtypingrrrrr r r r r rtyping_extensionsrrrrrrr_typesr_utilsrrrrr_modelsrrr _constantsrr _streamingrr r!r" _exceptionsr#r$_decoders.jsonlr%r&r' _base_clientr(r)r*r+r,r. getLoggerrdr/rr1rrrrrr rrrrrr.rKrNrUrXr^rarfrirnrrKrIrs"    IH qq<<D\\C<,(cN CL T]/AB 19PQ'g''1^1v gajv rj/!$jZhq)hV E*2$-e4$4  E 2  $%5e%<$" i "N"D$W]3$0*'*<"=*0& #B* %82 (*B2"" % . (*0.rK