B
    fO0                 @  s$  d dl m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
mZmZmZ d dlmZmZmZmZmZmZ d dlZddlmZmZ erddlmZmZ e
d	ZG d
d de	e ZG dd de	e ZG dd dZG dd dZ eG dd deZ!dddddZ"ddddddddZ#dS )    )annotationsN)TracebackType)TYPE_CHECKINGAnyGenericTypeVarIteratorAsyncIteratorcast)SelfProtocol	TypeGuardoverride
get_originruntime_checkable   )is_dictextract_type_var_from_base)	AnthropicAsyncAnthropic_Tc               @  s   e Zd ZU dZded< ded< ddddd	d
dZddddZddddZddddZddddZ	ddddZ
ddddddd Zddd!d"Zd#S )$StreamzJProvides the core interface to iterate over a synchronous stream response.zhttpx.ResponseresponseSSEBytesDecoder_decoderztype[_T]r   None)cast_tor   clientreturnc            C  s*   || _ || _|| _| | _|  | _d S )N)r   _cast_to_client_make_sse_decoderr   
__stream__	_iterator)selfr   r   r    r%   W/home/ankuromar296_gmail_com/.local/lib/python3.7/site-packages/anthropic/_streaming.py__init__   s
    
zStream.__init__r   )r   c             C  s
   | j  S )N)r#   __next__)r$   r%   r%   r&   r(   )   s    zStream.__next__zIterator[_T]c             c  s   x| j D ]
}|V  qW d S )N)r#   )r$   itemr%   r%   r&   __iter__,   s    zStream.__iter__zIterator[ServerSentEvent]c             c  s   | j | j E d H  d S )N)r   
iter_bytesr   )r$   r%   r%   r&   _iter_events0   s    zStream._iter_eventsc       
   	   c  sB  t t| j}| j}| jj}|  }x|D  ]}|jdkrN|| ||dV  |jdks|jdks|jdks|jdks|jdks|jdkr| }t	|rd	|kr|j|d	< ||||dV  |jd
krq*|jdkr*|j
}y| }| }W n* tk
r   |j
pd|j }Y nX | jj||| jdq*W x|D ]}	q4W d S )N
completion)datar   r   message_startmessage_deltamessage_stopcontent_block_startcontent_block_deltacontent_block_stoptypepingerrorzError code: )bodyr   )r
   r   r   r   r    _process_response_datar,   eventjsonr   r.   	Exceptionstatus_code_make_status_error)
r$   r   r   process_dataiteratorsser.   r8   err_msg_sser%   r%   r&   r"   3   s@    











zStream.__stream__r   c             C  s   | S )Nr%   )r$   r%   r%   r&   	__enter__a   s    zStream.__enter__ztype[BaseException] | NonezBaseException | NonezTracebackType | None)exc_typeexcexc_tbr   c             C  s   |    d S )N)close)r$   rE   rF   rG   r%   r%   r&   __exit__d   s    zStream.__exit__c             C  s   | j   dS )z
        Close the response and release the connection.

        Automatically called if the response body is read to completion.
        N)r   rH   )r$   r%   r%   r&   rH   l   s    zStream.closeN)__name__
__module____qualname____doc____annotations__r'   r(   r*   r,   r"   rD   rI   rH   r%   r%   r%   r&   r      s   
.r   c               @  s   e Zd ZU dZded< ded< ddddd	d
dZddddZddddZddddZddddZ	ddddZ
ddddddd Zddd!d"Zd#S )$AsyncStreamzLProvides the core interface to iterate over an asynchronous stream response.zhttpx.Responser   zSSEDecoder | SSEBytesDecoderr   ztype[_T]r   r   )r   r   r   r   c            C  s*   || _ || _|| _| | _|  | _d S )N)r   r   r    r!   r   r"   r#   )r$   r   r   r   r%   r%   r&   r'   |   s
    
zAsyncStream.__init__r   )r   c               s   | j  I d H S )N)r#   	__anext__)r$   r%   r%   r&   rP      s    zAsyncStream.__anext__zAsyncIterator[_T]c          	   C s8   x2| j 2 y3 d H }W n
 tk
s(X |V  q   Y  W d S )N)r#   StopAsyncIteration)r$   r)   r%   r%   r&   	__aiter__   s     zAsyncStream.__aiter__zAsyncIterator[ServerSentEvent]c          	   C sD   x>| j | j 2 y3 d H }W n
 tk
s4X |V  q   Y  W d S )N)r   aiter_bytesr   rQ   )r$   rA   r%   r%   r&   r,      s    ,zAsyncStream._iter_eventsc       
   	   C s  t t| j}| j}| jj}|  }x&|2 y3 d H }W n tk
s@X |jdkrb||	 ||dV  |jdks|jdks|jdks|jdks|jdks|jdkr|	 }t
|rd	|kr|j|d	< ||||dV  |jd
krq*|jdkr*|j}y|	 }| }W n* tk
r(   |jp"d|j }Y nX | jj||| jdq*   Y  W x.|2 y3 d H }	W n tk
spX qR   Y  W d S )Nr-   )r.   r   r   r/   r0   r1   r2   r3   r4   r5   r6   r7   zError code: )r8   r   )r
   r   r   r   r    r9   r,   rQ   r:   r;   r   r.   r<   r=   r>   )
r$   r   r   r?   r@   rA   r.   r8   rB   rC   r%   r%   r&   r"      s@    "










 zAsyncStream.__stream__r   c               s   | S )Nr%   )r$   r%   r%   r&   
__aenter__   s    zAsyncStream.__aenter__ztype[BaseException] | NonezBaseException | NonezTracebackType | None)rE   rF   rG   r   c               s   |   I d H  d S )N)rH   )r$   rE   rF   rG   r%   r%   r&   	__aexit__   s    zAsyncStream.__aexit__c               s   | j  I dH  dS )z
        Close the response and release the connection.

        Automatically called if the response body is read to completion.
        N)r   aclose)r$   r%   r%   r&   rH      s    zAsyncStream.closeN)rJ   rK   rL   rM   rN   r'   rP   rR   r,   r"   rT   rU   rH   r%   r%   r%   r&   rO   u   s   
.rO   c               @  s   e Zd Z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Zedd	ddZedd	ddZdd	ddZ	e
dd	ddZdS )ServerSentEventN)r:   r.   idretryz
str | Nonez
int | Noner   )r:   r.   rX   rY   r   c            C  s,   |d krd}|| _ || _|pd | _|| _d S )N )_id_data_event_retry)r$   r:   r.   rX   rY   r%   r%   r&   r'      s    
zServerSentEvent.__init__)r   c             C  s   | j S )N)r]   )r$   r%   r%   r&   r:      s    zServerSentEvent.eventc             C  s   | j S )N)r[   )r$   r%   r%   r&   rX      s    zServerSentEvent.idc             C  s   | j S )N)r^   )r$   r%   r%   r&   rY      s    zServerSentEvent.retrystrc             C  s   | j S )N)r\   )r$   r%   r%   r&   r.      s    zServerSentEvent.datar   c             C  s   t | jS )N)r;   loadsr.   )r$   r%   r%   r&   r;      s    zServerSentEvent.jsonc          	   C  s&   d| j  d| j d| j d| j d	S )NzServerSentEvent(event=z, data=z, id=z, retry=))r:   r.   rX   rY   )r$   r%   r%   r&   __repr__   s    zServerSentEvent.__repr__)rJ   rK   rL   r'   propertyr:   rX   rY   r.   r;   r   rb   r%   r%   r%   r&   rW      s   
rW   c               @  s   e Zd ZU ded< ded< ded< ded< dd	d
dZdddddZdddddZdddddZdddddZdddddZ	dS )
SSEDecoderz	list[str]r\   z
str | Noner]   z
int | Noner^   _last_event_idr   )r   c             C  s   d | _ g | _d | _d | _d S )N)r]   r\   re   r^   )r$   r%   r%   r&   r'     s    zSSEDecoder.__init__zIterator[bytes]zIterator[ServerSentEvent])r@   r   c             c  sH   xB|  |D ]4}x.| D ]"}|d}| |}|r|V  qW qW dS )z^Given an iterator that yields raw binary data, iterate over it & yield every event encounteredzutf-8N)_iter_chunks
splitlinesdecode)r$   r@   chunkraw_linelinerA   r%   r%   r&   r+     s    

zSSEDecoder.iter_bytesc             c  sR   d}x>|D ]6}x0|j ddD ] }||7 }|dr|V  d}qW q
W |rN|V  dS )z^Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks    T)keepends)s   s   

s   

N)rg   endswith)r$   r@   r.   ri   rk   r%   r%   r&   rf     s    

zSSEDecoder._iter_chunkszAsyncIterator[bytes]zAsyncIterator[ServerSentEvent]c          	   C sf   x`|  |2 y3 dH }W n
 tk
sVX x.| D ]"}|d}| |}|r.|V  q.W q   Y  W dS )z^Given an iterator that yields raw binary data, iterate over it & yield every event encounteredNzutf-8)_aiter_chunksrQ   rg   rh   )r$   r@   ri   rj   rk   rA   r%   r%   r&   rS   !  s    $

zSSEDecoder.aiter_bytesc          	   C sp   d}x\|2 y3 dH }W n
 t k
sVX x0|jddD ] }||7 }|dr0|V  d}q0W q
   Y  W |rl|V  dS )z^Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunksrl   NT)rm   )s   s   

s   

)rQ   rg   rn   )r$   r@   r.   ri   rk   r%   r%   r&   ro   +  s    
zSSEDecoder._aiter_chunksr_   zServerSentEvent | None)rk   r   c          	   C  s  |sX| j s$| js$| js$| jd kr$d S t| j d| j| j| jd}d | _ g | _d | _|S |drfd S |d\}}}|dr|dd  }|dkr|| _ nb|dkr| j| nL|dkrd	|krq|| _n2|d
kryt	|| _W q t
tfk
r   Y qX n d S )N
)r:   r.   rX   rY   : r   r:   r.   rX    rY   )r]   r\   re   r^   rW   join
startswith	partitionappendint	TypeError
ValueError)r$   rk   rA   	fieldname_valuer%   r%   r&   rh   7  s>    



zSSEDecoder.decodeN)
rJ   rK   rL   rN   r'   r+   rf   rS   ro   rh   r%   r%   r%   r&   rd      s   


rd   c               @  s,   e Zd ZdddddZddddd	Zd
S )r   zIterator[bytes]zIterator[ServerSentEvent])r@   r   c             C  s   dS )z^Given an iterator that yields raw binary data, iterate over it & yield every event encounteredNr%   )r$   r@   r%   r%   r&   r+   j  s    zSSEBytesDecoder.iter_byteszAsyncIterator[bytes]zAsyncIterator[ServerSentEvent]c             C  s   dS )zdGiven an async iterator that yields raw binary data, iterate over it & yield every event encounteredNr%   )r$   r@   r%   r%   r&   rS   n  s    zSSEBytesDecoder.aiter_bytesN)rJ   rK   rL   r+   rS   r%   r%   r%   r&   r   h  s   r   r5   z;TypeGuard[type[Stream[object]] | type[AsyncStream[object]]])typr   c             C  s$   t | p
| }t|o"t|ttfS )zaTypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`)r   inspectisclass
issubclassr   rO   )r~   originr%   r%   r&   is_stream_class_types  s    r   )failure_messagez
str | None)
stream_clsr   r   c            C  s*   ddl m}m} t| dtd||f|dS )a  Given a type like `Stream[T]`, returns the generic type variable `T`.

    This also handles the case where a concrete subclass is given, e.g.
    ```py
    class MyStream(Stream[bytes]):
        ...

    extract_stream_chunk_type(MyStream) -> bytes
    ```
    r   )r   rO   r   ztuple[type, ...])indexZgeneric_basesr   )Z_base_clientr   rO   r   r
   )r   r   r   rO   r%   r%   r&   extract_stream_chunk_typey  s    r   )$
__future__r   r;   r   typesr   typingr   r   r   r   r   r	   r
   typing_extensionsr   r   r   r   r   r   Zhttpx_utilsr   r   r    r   r   r   r   rO   rW   rd   r   r   r   r%   r%   r%   r&   <module>   s$   $ `a)i
	