U
    ·ÜŸjn?  ã                   @  s   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. e�r ddl"m/Z/ ddl0m1Z1 edƒZ2edƒZ3edƒZ4e 5e6¡Z7de8d< G dd„ dee3 ƒZ9G dd„ de:ƒZ;dddœdd„Z<dddœdd„Z=G d d!„ d!ƒZ>dS )"é    )Ú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)ÚFinalRequestOptions)Ú
BaseClientÚPÚRÚ_Tzlogging.LoggerÚlogc                
   @  sž  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ddd
ddddœdd„Zeddœdd„ƒZedddœdd „ƒZ	ed!dœd"d „ƒZ	d#d$œd%d&dœd'd „Z	ed(dœd)d*„ƒZ
ed+dœd,d-„ƒZeddœd.d/„ƒZed0dœd1d2„ƒZed3dœd4d5„ƒZed6dœd7d8„ƒZed3dœd9d:„ƒZed3dœd;d<„ƒZeddœd=d>„ƒZed?dœd@dA„ƒZd#d$œd%d&dœdBdC„Zed3dœdDdE„ƒZd#S )FÚ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.
    ztype[R]Ú_cast_tozBaseClient[Any, Any]Ú_clientzdict[type[Any], Any]Ú_parsed_by_typeÚboolÚ_streamú1type[Stream[Any]] | type[AsyncStream[Any]] | NoneÚ_stream_clsr!   Ú_optionsúhttpx.ResponseÚhttp_responseÚintÚretries_takenr   )r3   ÚNone)ÚrawÚcast_toÚclientÚstreamÚ
stream_clsÚoptionsr3   Úreturnc                C  s4   || _ || _i | _|| _|| _|| _|| _|| _d S ©N)r(   r)   r*   r,   r.   r/   r1   r3   )Úselfr5   r6   r7   r8   r9   r:   r3   © r>   ú;/tmp/pip-unpacked-wheel-2qj3ofc_/openai/_legacy_response.pyÚ__init__F   s    zLegacyAPIResponse.__init__ú
str | None©r;   c                 C  s   | j j d¡S )Nzx-request-id)r1   ÚheadersÚget©r=   r>   r>   r?   Ú
request_idZ   s    zLegacyAPIResponse.request_idztype[_T]r%   )Útor;   c                C  s   d S r<   r>   )r=   rG   r>   r>   r?   Úparse^   s    zLegacyAPIResponse.parser$   c                 C  s   d S r<   r>   rE   r>   r>   r?   rH   a   s    N©rG   ztype[_T] | NonezR | _Tc                C  sx   |dk	r|n| j }| j |¡}|dk	r*|S | j|d�}t| jjƒrN| j |¡}t|tƒrdt	|| 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 openai 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`
        NrI   )r(   r*   rD   Ú_parser   r/   Zpost_parserÚ
isinstancer   r   rF   r   r$   )r=   rG   Ú	cache_keyÚcachedÚparsedr>   r>   r?   rH   d   s     

zhttpx.Headersc                 C  s   | j jS r<   )r1   rC   rE   r>   r>   r?   rC   “   s    zLegacyAPIResponse.headerszhttpx.Requestc                 C  s   | j jS r<   )r1   ÚrequestrE   r>   r>   r?   Úhttp_request—   s    zLegacyAPIResponse.http_requestc                 C  s   | j jS r<   )r1   Ústatus_coderE   r>   r>   r?   rQ   ›   s    zLegacyAPIResponse.status_codez	httpx.URLc                 C  s   | j jS r<   )r1   ÚurlrE   r>   r>   r?   rR   Ÿ   s    zLegacyAPIResponse.urlÚstrc                 C  s   | j jS r<   )rP   ÚmethodrE   r>   r>   r?   rT   £   s    zLegacyAPIResponse.methodÚbytesc                 C  s   | j jS )zŠReturn the binary response content.

        NOTE: this will be removed in favour of `.read()` in the
        next major version.
        )r1   ÚcontentrE   r>   r>   r?   rV   §   s    zLegacyAPIResponse.contentc                 C  s   | j jS )zyReturn the decoded response content.

        NOTE: this will be turned into a method in the next major version.
        )r1   ÚtextrE   r>   r>   r?   rW   °   s    zLegacyAPIResponse.textc                 C  s   | j jS r<   )r1   Úhttp_versionrE   r>   r>   r?   rX   ¸   s    zLegacyAPIResponse.http_versionc                 C  s   | j jS r<   )r1   Ú	is_closedrE   r>   r>   r?   rY   ¼   s    zLegacyAPIResponse.is_closedzdatetime.timedeltac                 C  s   | j jS )zCThe time taken for the complete request/response cycle to complete.)r1   ÚelapsedrE   r>   r>   r?   rZ   À   s    zLegacyAPIResponse.elapsedc          
      C  sH  |d k	r|n| j }t|ƒr |j}|r6t|ƒr6t|dƒ}t|ƒp@|}| jrô|rŽt|ƒshtdt	› dt
› �ƒ‚tt|t|dd�| jtt| jƒd�ƒS | jrºtt| jt| jƒ| jtt| jƒd�ƒS td| jjƒ}|d krÖtƒ ‚tt||| jtt| jƒd�ƒS |tk�rttd ƒS | j}|tk�r$tt|jƒS |tk�r>ttt|jƒƒS |tk�rXttt|jƒƒS |tk�rvtt|j ¡ dkƒS t |¡�rœt|tƒ�rœtt||ƒƒS |t k�r®t!d	ƒ‚t |¡�ræt|t"j#ƒ�ræ|t"j#k�rÜt$d
ƒ‚tt|ƒS t |¡�rt|t%ƒ�st|t&j%ƒ�rtdƒ‚|t'k	�r„|t(k	�r„|t)k	�r„|t*k	�r„t|t%ƒ�s„t!d|› dt%› dt)› dt(› dt*› dt› dt› dt"j#› d�ƒ‚|j+ ,dd¡ -d¡^}}|dk�r.t.|ƒ�rz| /¡ }W n6 t0k
�rò }	 zt1 2dt3|	ƒ|	¡ W 5 d }	~	X Y nX | jj4|||d�S | jj5�r(t6|d|› d�|jd�‚|jS | /¡ }| jj4|||d�S )Nr   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])Zfailure_message)r6   Úresponser7   r-   Útruez+Unexpected state - cast_to is `APIResponse`z:Subclasses of httpx.Response cannot be passed to `cast_to`zVPydantic models must subclass our base model type, e.g. `from openai import BaseModel`zUnsupported type, expected z to be a subclass of z, Ú.zcontent-typeÚ*ú;zapplication/jsonz5Could not read JSON from response data due to %s - %s)Údatar6   r[   zMExpected Content-Type response header to be `application/json` but received `z
` instead.)r[   ÚmessageÚbody)7r(   r   Ú	__value__r   r   r   r,   r   Ú	TypeErrorr   r   r   r%   r   r1   r   r)   r.   r$   Z_default_stream_clsÚMissingStreamClassErrorr   rS   rW   r2   Úfloatr+   ÚlowerÚinspectÚisclassÚ
issubclassÚHttpxBinaryResponseContentr'   ÚRuntimeErrorÚhttpxÚResponseÚ
ValueErrorr   ÚpydanticÚobjectÚlistÚdictr   rC   rD   Úsplitr   ÚjsonÚ	Exceptionr&   ÚdebugÚtypeZ_process_response_dataZ_strict_response_validationr    )
r=   rG   r6   Úoriginr9   r[   Úcontent_typeÚ_r`   Úexcr>   r>   r?   rJ   Å   sÞ    
þ
úþ
ýþ	
ýþ	






ÿ
þ
ÿÿü
ûÿþýüû6ÿ

$ý

ý	ýzLegacyAPIResponse._parsec                 C  s    d| j › d| jj› d| j› d�S )Nz<APIResponse [ú z] type=ú>)rQ   r1   Zreason_phraser(   rE   r>   r>   r?   Ú__repr__T  s    zLegacyAPIResponse.__repr__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r@   ÚpropertyrF   r   rH   rC   rP   rQ   rR   rT   rV   rW   rX   rY   rZ   rJ   r   r   r>   r>   r>   r?   r'   -   sT   
÷ / r'   c                      s"   e Zd Zddœ‡ fdd„Z‡  ZS )re   r4   rB   c                   s   t ƒ  d¡ d S )NzzThe `stream` argument was set to `True` but the `stream_cls` argument was not given. See `openai._streaming` for reference)Úsuperr@   rE   ©Ú	__class__r>   r?   r@   Z  s    ÿz MissingStreamClassError.__init__)r€   r�   r‚   r@   Ú__classcell__r>   r>   r‡   r?   re   Y  s   re   zCallable[P, R]z!Callable[P, LegacyAPIResponse[R]])Úfuncr;   c                   s$   t  ˆ ¡ddddœ‡ fdd„ƒ}|S )ú�Higher order function that takes one of our bound API methods and wraps it
    to support returning the raw `APIResponse` object directly.
    úP.argsúP.kwargsúLegacyAPIResponse[R]©ÚargsÚkwargsr;   c                    s:   t t| d¡ƒpi –}d|t< ||d< t tt ˆ | |ŽƒS ©NÚextra_headersr\   ©r   r   rD   r   r'   r$   ©r�   r‘   r“   ©rŠ   r>   r?   Úwrappede  s    z(to_raw_response_wrapper.<locals>.wrapped©Ú	functoolsÚwraps©rŠ   r—   r>   r–   r?   Úto_raw_response_wrapper`  s    rœ   zCallable[P, Awaitable[R]]z,Callable[P, Awaitable[LegacyAPIResponse[R]]]c                   s$   t  ˆ ¡ddddœ‡ fdd„ƒ}|S )r‹   rŒ   r�   rŽ   r�   c                  Ÿ  s@   t t| d¡ƒpi –}d|t< ||d< t tt ˆ | |ŽI d H ƒS r’   r”   r•   r–   r>   r?   r—   v  s    z.async_to_raw_response_wrapper.<locals>.wrappedr˜   r›   r>   r–   r?   Úasync_to_raw_response_wrapperq  s    r�   c                   @  sŽ  e Zd ZU ded< dddœdd„Zeddœd	d
„ƒZeddœdd„ƒZeddœdd„ƒZeddœdd„ƒZ	dddœdd„Z
ddœdd„ZdAdddœdd„ZdBdddœd d!„Zddœd"d#„ZdCdddœd$d%„Zd&dd'œd(d)„Zed*ƒdd+œd&ddd,œd-d.„ƒZddœd/d0„Zddœd1d2„ZdDdd3dœd4d5„ZdEdd6dœd7d8„Zd6dœd9d:„ZdFdd3dœd;d<„Zed*ƒdd+œd&ddd,œd=d>„ƒZddœd?d@„ZdS )Grk   r0   r[   r4   )r[   r;   c                 C  s
   || _ d S r<   )r[   )r=   r[   r>   r>   r?   r@   …  s    z#HttpxBinaryResponseContent.__init__rU   rB   c                 C  s   | j jS r<   )r[   rV   rE   r>   r>   r?   rV   ˆ  s    z"HttpxBinaryResponseContent.contentrS   c                 C  s   | j jS r<   )r[   rW   rE   r>   r>   r?   rW   Œ  s    zHttpxBinaryResponseContent.textrA   c                 C  s   | j jS r<   )r[   ÚencodingrE   r>   r>   r?   rž   �  s    z#HttpxBinaryResponseContent.encodingc                 C  s   | j jS r<   )r[   Úcharset_encodingrE   r>   r>   r?   rŸ   ”  s    z+HttpxBinaryResponseContent.charset_encodingr   )r‘   r;   c                 K  s   | j jf |ŽS r<   )r[   ru   )r=   r‘   r>   r>   r?   ru   ˜  s    zHttpxBinaryResponseContent.jsonc                 C  s
   | j  ¡ S r<   )r[   ÚreadrE   r>   r>   r?   r    ›  s    zHttpxBinaryResponseContent.readNz
int | NonezIterator[bytes])Ú
chunk_sizer;   c                 C  s   | j  |¡S r<   )r[   Ú
iter_bytes©r=   r¡   r>   r>   r?   r¢   ž  s    z%HttpxBinaryResponseContent.iter_byteszIterator[str]c                 C  s   | j  |¡S r<   )r[   Ú	iter_textr£   r>   r>   r?   r¤   ¡  s    z$HttpxBinaryResponseContent.iter_textc                 C  s
   | j  ¡ S r<   )r[   Ú
iter_linesrE   r>   r>   r?   r¥   ¤  s    z%HttpxBinaryResponseContent.iter_linesc                 C  s   | j  |¡S r<   )r[   Úiter_rawr£   r>   r>   r?   r¦   §  s    z#HttpxBinaryResponseContent.iter_rawzstr | os.PathLike[str])Úfiler;   c              	   C  s6   t |dd�� }| j ¡ D ]}| |¡ qW 5 Q R X dS )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©Úopenr[   r¢   Úwrite)r=   r§   Úfr`   r>   r>   r?   Úwrite_to_fileª  s    z(HttpxBinaryResponseContent.write_to_filez‚Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead)r¡   )r§   r¡   r;   c             	   C  s8   t |dd��"}| j |¡D ]}| |¡ qW 5 Q R X d S ©Nr¨   r©   r«   )r=   r§   r¡   r®   r`   r>   r>   r?   Ústream_to_fileº  s    	z)HttpxBinaryResponseContent.stream_to_filec                 C  s
   | j  ¡ S r<   )r[   ÚcloserE   r>   r>   r?   r²   Ç  s    z HttpxBinaryResponseContent.closec                 Ã  s   | j  ¡ I d H S r<   )r[   ÚareadrE   r>   r>   r?   r³   Ê  s    z HttpxBinaryResponseContent.areadzAsyncIterator[bytes]c                 Ã  s   | j  |¡S r<   )r[   Úaiter_bytesr£   r>   r>   r?   r´   Í  s    z&HttpxBinaryResponseContent.aiter_byteszAsyncIterator[str]c                 Ã  s   | j  |¡S r<   )r[   Ú
aiter_textr£   r>   r>   r?   rµ   Ð  s    z%HttpxBinaryResponseContent.aiter_textc                 Ã  s
   | j  ¡ S r<   )r[   Úaiter_linesrE   r>   r>   r?   r¶   Ó  s    z&HttpxBinaryResponseContent.aiter_linesc                 Ã  s   | j  |¡S r<   )r[   Ú	aiter_rawr£   r>   r>   r?   r·   Ö  s    z$HttpxBinaryResponseContent.aiter_rawc             
   Ã  sf   t  |¡}|jdd�I d H 4 I d H š2}| j |¡2 z3 d H W }| |¡I d H  q26 W 5 Q I d H R X d S r°   )ÚanyioÚPathr¬   r[   r´   r­   )r=   r§   r¡   Úpathr®   r`   r>   r>   r?   Úastream_to_fileÙ  s    	
z*HttpxBinaryResponseContent.astream_to_filec                 Ã  s   | j  ¡ I d H S r<   )r[   ÚacloserE   r>   r>   r?   r¼   ç  s    z!HttpxBinaryResponseContent.aclose)N)N)N)N)N)N)r€   r�   r‚   r„   r@   r…   rV   rW   rž   rŸ   ru   r    r¢   r¤   r¥   r¦   r¯   r   r±   r²   r³   r´   rµ   r¶   r·   r»   r¼   r>   r>   r>   r?   rk   ‚  sD   
ÿü
ÿürk   )?Ú
__future__r   Úosrh   ÚloggingÚdatetimer™   Útypingr   r   r   r   r   r   r	   r
   r   r   Útyping_extensionsr   r   r   r   r   r¸   rm   rp   Ú_typesr   Ú_utilsr   r   r   r   Z_modelsr   r   r   Ú
_constantsr   Z
_streamingr   r   r   r   Ú_exceptionsr    r!   Z_base_clientr"   r#   r$   r%   Ú	getLoggerr€   r&   r„   r'   rd   re   rœ   r�   rk   r>   r>   r>   r?   Ú<module>   s>    0  .