
    gB                       U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZm	Z	m
Z
mZmZmZmZmZmZmZ d dlmZmZmZmZmZ d dlZd dlZd dlZddlmZ ddlmZmZm Z m!Z! ddl"m#Z#m$Z$m%Z% dd	l&m'Z' dd
l(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1 erddl"m2Z2 ddl3m4Z4  ed      Z5 ed      Z6 ed      Z7 edd      Z8 ejr                  e:      Z;de<d<    G d dee6         Z= G d de>      Z?ddZ@d dZA G d d      ZBy)!    )annotationsN)
TYPE_CHECKINGAnyUnionGenericTypeVarCallableIteratorAsyncIteratorcastoverload)	Awaitable	ParamSpecoverride
deprecated
get_origin   )NoneType)is_givenextract_type_argis_annotated_typeis_type_alias_type)	BaseModelis_basemodeladd_request_id)RAW_RESPONSE_HEADER)StreamAsyncStreamis_stream_class_typeextract_stream_chunk_type)APIResponseValidationError)JSONLDecoderAsyncJSONLDecoder)FinalRequestOptions)
BaseClientPR_T_T_coT)	covariantzlogging.Loggerlogc                     e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   ded<   	 dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZed(d       Zed)d       Z	ed*d       Z	ddd+dZ	ed,d       Z
ed-d       Zed.d       Zed/d       Zed0d       Zed1d        Zed0d!       Zed0d"       Zed2d#       Zed3d$       Zddd+d%Zed0d&       Zy)4LegacyAPIResponsea  This is a legacy class as it will be replaced by `APIResponse`
    and `AsyncAPIResponse` in the `_response.py` file in the next major
    release.

    For the sync client this will mostly be the same with the exception
    of `content` & `text` will be methods instead of properties. In the
    async client, all methods will be async.

    A migration script will be provided & the migration in general should
    be smooth.
    type[R]_cast_toBaseClient[Any, Any]_clientzdict[type[Any], Any]_parsed_by_typebool_stream1type[Stream[Any]] | type[AsyncStream[Any]] | None_stream_clsr$   _optionshttpx.Responsehttp_responseintretries_takenr   )r;   c               t    || _         || _        i | _        || _        || _        || _        || _        || _        y N)r/   r1   r2   r4   r6   r7   r9   r;   )selfrawcast_toclientstream
stream_clsoptionsr;   s           O/var/www/openai/venv/lib/python3.12/site-packages/anthropic/_legacy_response.py__init__zLegacyAPIResponse.__init__H   s@      !% *    c                L    | j                   j                  j                  d      S )Nz
request-id)r9   headersgetr>   s    rE   
request_idzLegacyAPIResponse.request_id\   s    !!))--l;;rG   c                    y r=    )r>   tos     rE   parsezLegacyAPIResponse.parse`   s    ,/rG   c                     y r=   rN   rK   s    rE   rP   zLegacyAPIResponse.parsec   s    rG   NrO   c                  ||n| j                   }| j                  j                  |      }||S | j                  |      }t	        | j
                  j                        r| j
                  j                  |      }t        |t              rt        || j                         || j                  |<   t        t        |      S )a  Returns the rich python representation of this response's data.

        NOTE: For the async client: this will become a coroutine in the next major version.

        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`
        rR   )r/   r2   rJ   _parser   r7   post_parser
isinstancer   r   rL   r   r'   )r>   rO   	cache_keycachedparseds        rE   rP   zLegacyAPIResponse.parsef   s    @ .Bdmm	%%)))4M#DMM--.]]..v6Ffi(64??3*0Y'AvrG   c                .    | j                   j                  S r=   )r9   rI   rK   s    rE   rI   zLegacyAPIResponse.headers       !!)))rG   c                .    | j                   j                  S r=   )r9   requestrK   s    rE   http_requestzLegacyAPIResponse.http_request   r[   rG   c                .    | j                   j                  S r=   )r9   status_coderK   s    rE   r`   zLegacyAPIResponse.status_code   s    !!---rG   c                .    | j                   j                  S r=   )r9   urlrK   s    rE   rb   zLegacyAPIResponse.url   s    !!%%%rG   c                .    | j                   j                  S r=   )r^   methodrK   s    rE   rd   zLegacyAPIResponse.method   s      '''rG   c                .    | j                   j                  S )zReturn the binary response content.

        NOTE: this will be removed in favour of `.read()` in the
        next major version.
        )r9   contentrK   s    rE   rf   zLegacyAPIResponse.content   s     !!)))rG   c                .    | j                   j                  S )zyReturn the decoded response content.

        NOTE: this will be turned into a method in the next major version.
        )r9   textrK   s    rE   rh   zLegacyAPIResponse.text   s     !!&&&rG   c                .    | j                   j                  S r=   )r9   http_versionrK   s    rE   rj   zLegacyAPIResponse.http_version   s    !!...rG   c                .    | j                   j                  S r=   )r9   	is_closedrK   s    rE   rl   zLegacyAPIResponse.is_closed   s    !!+++rG   c                .    | j                   j                  S )zCThe time taken for the complete request/response cycle to complete.)r9   elapsedrK   s    rE   rn   zLegacyAPIResponse.elapsed   s     !!)))rG   c                  ||n| j                   }t        |      r|j                  }|rt        |      rt	        |d      }t        |      xs |}t        j                  |      rt        |t              rQt        t         t        d|      | j                  j                  d      t	        |d      | j                              S t        |t              rQt        t         t        d|      | j                  j                  d      t	        |d      | j                              S | j                   r6|rjt#        |      st%        dt&         dt(               t        t*         |t-        |d	
      | j                  t        t.        | j0                                    S | j2                  rWt        t        | j3                  t-        | j2                        | j                  t        t.        | j0                                    S t        d| j0                  j4                        }|
t7               t        t         ||| j                  t        t.        | j0                                    S |t8        u rt        t        d       S | j                  }|t:        k(  rt        t        |j<                        S |t>        k(  r#t        t        t?        |j<                              S |t@        k(  r#t        t        tA        |j<                              S |tB        k(  r+t        t        |j<                  jE                         dk(        S t        |      xs |}t        j                  |      r&t        |tF              rt        t         ||            S |tH        k(  rtK        d      t        j                  |      rHt        |tL        jN                        r.|tL        jN                  k7  rtQ        d      t        t        |      S t        j                  |      r5t        |tR              s%t        |tT        jR                        rt%        d      |tV        urr|tX        urj|tZ        urb|t\        urZt        |tR              sJtK        d| dtR         dtZ         dtX         dt\         dt8         dt:         dtL        jN                   d      |j^                  ja                  dd      jc                  d      ^}}|dk7  rxte        |      r/	 |jg                         }| j0                  ji                  |||      S | j0                  jr                  rtu        |d| d|j<                        |j<                  S |jg                         }| j0                  ji                  |||      S # tj        $ r*}	tl        jo                  dtq        |	      |	       Y d }	~	d }	~	ww xY w)Nr   ztype[JSONLDecoder[Any]]i   
chunk_size)raw_iterator	line_typer9   ztype[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)r@   responserA   r5   truez+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`zUnsupported type, expected z to be a subclass of z, .zcontent-type*;zapplication/json)datar@   ru   z5Could not read JSON from response data due to %s - %szMExpected Content-Type response header to be `application/json` but received `z
` instead.)ru   messagebody);r/   r   	__value__r   r   r   inspectisclass
issubclassr"   r   r'   r9   
iter_bytesr#   aiter_bytesr4   r   	TypeErrorr   r   r(   r    r   r1   r6   _default_stream_clsMissingStreamClassErrorr   strrh   r:   floatr3   lowerHttpxBinaryResponseContentr-   RuntimeErrorhttpxResponse
ValueErrorr   pydanticobjectlistdictr   rI   rJ   splitr   json_process_response_data	Exceptionr+   debugtype_strict_response_validationr!   )
r>   rO   r@   originrC   ru   content_type_rz   excs
             rE   rT   zLegacyAPIResponse._parse   sH   "DMM g&''G (1&w2GG$/??6"&<1<D2G<%)%7%7%B%Bd%B%S"27A">&*&8&8  &"34AD7A%)%7%7%C%Ct%C%T"27A">&*&8&8  <<+B/#&UV\U]]abman$opp 9 -D! "&!3!3#C6
 
 $$ 9$:J:J K!%!3!3#C6 %   QSWS_S_SsSstJ!-//#!//T\\2  h4= %%c>8==))c>3x}}-..e5/00d?8==..0F:;;G$/??6"z&:T'U78,--&&LMM??6"z&%..'I %..( #]__8$$??6":fi+HZX^`h`r`rMswxx 6!dNdNeOvy1-gY6KI;VXY]X^^`ae`ffhinhooqrzq{{}  B  ~C  CG  HM  HV  HV  GW  WX  Y  $++//DJJ3Oq--G$	#==?D  <<>>! '!) ?   ||770%klxky  zD  E!  == }}||22 3 
 	
/ ! gIIUW[\_W`beffgs   :V 	W WWc                j    d| j                    d| j                  j                   d| j                   dS )Nz<APIResponse [ z] type=>)r`   r9   reason_phraser/   rK   s    rE   __repr__zLegacyAPIResponse.__repr__e  s;     0 0143E3E3S3S2TT[\`\i\i[jjkllrG   )r?   r8   r@   r.   rA   r0   rB   r3   rC   r5   rD   r$   r;   r:   returnNoner   z
str | None)rO   ztype[_T]r   r(   )r   r'   )rO   ztype[_T] | Noner   zR | _T)r   zhttpx.Headers)r   zhttpx.Request)r   r:   )r   z	httpx.URLr   r   r   bytes)r   r3   )r   zdatetime.timedelta)__name__
__module____qualname____doc____annotations__rF   propertyrL   r   rP   rI   r^   r`   rb   rd   rf   rh   rj   rl   rn   rT   r   r   rN   rG   rE   r-   r-   /   s   
 !!))MBB!!!!M + + 	+
 %+ + F+ %+ + 
+( < < / / -1 -^ * * * * . . & & ( ( * * ' ' / / , , * * /3 \
| m mrG   r-   c                        e Zd Zd fdZ xZS )r   c                $    t         |   d       y )Nz}The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `anthropic._streaming` for reference)superrF   )r>   	__class__s    rE   rF   z MissingStreamClassError.__init__k  s     L	
rG   r   r   )r   r   r   rF   __classcell__)r   s   @rE   r   r   j  s    
 
rG   r   c                D     t        j                         d fd       }|S )Higher order function that takes one of our bound API methods and wraps it
    to support returning the raw `APIResponse` object directly.
    c                     i t        t        |j                  d            xs i }d|t        <   ||d<   t        t        t
            | i |      S Nextra_headersrv   r   r   rJ   r   r-   r'   argskwargsr   funcs      rE   wrappedz(to_raw_response_wrapper.<locals>.wrappedv  sU    (ZDfjj6Q,R,XVX(Z-3)*"/%a($*?*?@@rG   r   zP.argsr   zP.kwargsr   zLegacyAPIResponse[R]	functoolswrapsr   r   s   ` rE   to_raw_response_wrapperr   q  s)    
 __TA A NrG   c                D     t        j                         d fd       }|S )r   c                    K   i t        t        |j                  d            xs i }d|t        <   ||d<   t        t        t
            | i | d {         S 7 wr   r   r   s      rE   r   z.async_to_raw_response_wrapper.<locals>.wrapped  s_     (ZDfjj6Q,R,XVX(Z-3)*"/%a(d0Ef0E*EFF*Es   AAA
	Ar   r   r   s   ` rE   async_to_raw_response_wrapperr     s)    
 __TG G NrG   c                  H   e Zd ZU ded<   ddZedd       Zedd       Zedd       Zedd       Z	ddZ
dd	Zd d!dZd d"dZd#dZd d!dZ	 	 	 	 d$dZ ed      d
d	 	 	 	 	 d%d       Zd&dZddZd d'dZd d(dZd)dZd d'dZ ed      d
d	 	 	 	 	 d%d       Zd&dZy
)*r   r8   ru   c                    || _         y r=   )ru   )r>   ru   s     rE   rF   z#HttpxBinaryResponseContent.__init__  s	     rG   c                .    | j                   j                  S r=   )ru   rf   rK   s    rE   rf   z"HttpxBinaryResponseContent.content  s    }}$$$rG   c                .    | j                   j                  S r=   )ru   rh   rK   s    rE   rh   zHttpxBinaryResponseContent.text  s    }}!!!rG   c                .    | j                   j                  S r=   )ru   encodingrK   s    rE   r   z#HttpxBinaryResponseContent.encoding  s    }}%%%rG   c                .    | j                   j                  S r=   )ru   charset_encodingrK   s    rE   r   z+HttpxBinaryResponseContent.charset_encoding  s    }}---rG   c                :     | j                   j                  di |S )NrN   )ru   r   )r>   r   s     rE   r   zHttpxBinaryResponseContent.json  s    !t}}!!+F++rG   c                6    | j                   j                         S r=   )ru   readrK   s    rE   r   zHttpxBinaryResponseContent.read  s    }}!!##rG   Nc                8    | j                   j                  |      S r=   )ru   r   r>   rq   s     rE   r   z%HttpxBinaryResponseContent.iter_bytes  s    }}''
33rG   c                8    | j                   j                  |      S r=   )ru   	iter_textr   s     rE   r   z$HttpxBinaryResponseContent.iter_text  s    }}&&z22rG   c                6    | j                   j                         S r=   )ru   
iter_linesrK   s    rE   r   z%HttpxBinaryResponseContent.iter_lines  s    }}''))rG   c                8    | j                   j                  |      S r=   )ru   iter_rawr   s     rE   r   z#HttpxBinaryResponseContent.iter_raw  s    }}%%j11rG   c                    t        |d      5 }| j                  j                         D ]  }|j                  |        	 ddd       y# 1 sw Y   yxY w)av  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. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')`
        wbmodeNopenru   r   write)r>   filefrz   s       rE   write_to_filez(HttpxBinaryResponseContent.write_to_file  s>     $T"a002 3 #""s   1A		AzDue to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used insteadrp   c                   t        |d      5 }| j                  j                  |      D ]  }|j                  |        	 d d d        y # 1 sw Y   y xY wNr   r   r   )r>   r   rq   r   rz   s        rE   stream_to_filez)HttpxBinaryResponseContent.stream_to_file  s@     $T"a00< = #""s   2A

Ac                6    | j                   j                         S r=   )ru   closerK   s    rE   r   z HttpxBinaryResponseContent.close  s    }}""$$rG   c                R   K   | j                   j                          d {   S 7 wr=   )ru   areadrK   s    rE   r   z HttpxBinaryResponseContent.aread  s     ]]((****   '%'c                @   K   | j                   j                  |      S wr=   )ru   r   r   s     rE   r   z&HttpxBinaryResponseContent.aiter_bytes  s     }}((44   c                @   K   | j                   j                  |      S wr=   )ru   
aiter_textr   s     rE   r   z%HttpxBinaryResponseContent.aiter_text  s     }}''
33r   c                >   K   | j                   j                         S wr=   )ru   aiter_linesrK   s    rE   r   z&HttpxBinaryResponseContent.aiter_lines  s     }}((**s   c                @   K   | j                   j                  |      S wr=   )ru   	aiter_rawr   s     rE   r   z$HttpxBinaryResponseContent.aiter_raw  s     }}&&z22r   c               V  K   t        j                  |      }|j                  d       d {   4 d {   }| j                  j	                  |      2 3 d {   }|j                  |       d {    #7 K7 D7 "7 6 d d d       d {  7   y # 1 d {  7  sw Y   y xY wwr   )anyioPathr   ru   r   r   )r>   r   rq   pathr   rz   s         rE   astream_to_filez*HttpxBinaryResponseContent.astream_to_file  s      zz$----"mm77
C $dggdm## .-$# D .----s   +B)A9B)A;B)BBA=BB3A?4B9B);B)=B?BBB)BB)B&BB&"B)c                R   K   | j                   j                          d {   S 7 wr=   )ru   acloserK   s    rE   r   z!HttpxBinaryResponseContent.aclose  s     ]]))++++r   )ru   r8   r   r   r   r   r   )r   r   r   r   r=   )rq   
int | Noner   zIterator[bytes])rq   r   r   Iterator[str])r   r   )r   str | os.PathLike[str]r   r   )r   r   rq   r   r   r   r   )rq   r   r   zAsyncIterator[bytes])rq   r   r   AsyncIterator[str])r   r   )r   r   r   r   rF   r   rf   rh   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rN   rG   rE   r   r     s5   ! % % " " & & . .,$43*2$ 
   	M "&	$ 	
 
%+54+3  	M "&		$$	$ 		$
 
	$	$,rG   r   )r   zCallable[P, R]r   z!Callable[P, LegacyAPIResponse[R]])r   zCallable[P, Awaitable[R]]r   z,Callable[P, Awaitable[LegacyAPIResponse[R]]])C
__future__r   osr~   loggingdatetimer   typingr   r   r   r   r   r	   r
   r   r   r   typing_extensionsr   r   r   r   r   r   r   r   _typesr   _utilsr   r   r   r   _modelsr   r   r   
_constantsr   
_streamingr   r   r   r    _exceptionsr!   _decoders.jsonlr"   r#   r$   _base_clientr%   r&   r'   r(   r)   	getLoggerr   r+   r   r-   r   r   r   r   r   rN   rG   rE   <module>r     s    " 	       U T     U U < < + \ \ 3 <,( cNCLT]4('g''1^ 1xm
 xmv	
i 
""f, f,rG   