a
    ”˜ëj‹*  ã                   @   s@  d Z ddlmZ ddlmZmZmZmZmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZmZmZmZmZ ddlmZ edƒZeƒ Zefee eeef eeeed	f  d
œdd„ZG dd„ dƒZee ee eee  e
e eed	f dœdd„ZG dd„ dee ƒZeZ G dd„ de
ƒZ!e"ee eee  dœdd„Z#d	S )z�Asynchronous iterator utilities.

Adapted from
https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
MIT License.
é    ©Údeque)ÚAsyncGeneratorÚAsyncIterableÚAsyncIteratorÚ	AwaitableÚIterator)ÚAbstractAsyncContextManager)ÚTracebackType)ÚAnyÚCallableÚGenericÚOptionalÚTypeVarÚUnionÚcastÚoverload)ÚoverrideÚTN)ÚiteratorÚdefaultÚreturnc              
      s‚   zt dtˆƒjƒ‰ W n8 tyL } z ˆ›d�}t|ƒ|‚W Y d}~n
d}~0 0 ˆtu r^ˆ ˆƒS tttf dœ‡ ‡‡fdd„}|ƒ S )a·  Pure-Python implementation of anext() for testing purposes.

    Closely matches the builtin anext() C implementation.
    Can be used to compare the built-in implementation of the inner
    coroutines machinery to C-implementation of __anext__() and send()
    or throw() on the returned generator.

    Args:
        iterator: The async iterator to advance.
        default: The value to return if the iterator is exhausted.
            If not provided, a StopAsyncIteration exception is raised.

    Returns:
        The next value from the iterator, or the default value
            if the iterator is exhausted.

    Raises:
        TypeError: If the iterator is not an async iterator.
    z*Callable[[AsyncIterator[T]], Awaitable[T]]z is not an async iteratorN©r   c                   “   s,   zˆ ˆƒI d H W S  t y&   ˆ Y S 0 d S ©N)ÚStopAsyncIteration© ©Ú	__anext__r   r   r   úY/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/utils/aiter.pyÚ
anext_implG   s    zpy_anext.<locals>.anext_impl)	r   Útyper   ÚAttributeErrorÚ	TypeErrorÚ_no_defaultr   r   r   )r   r   ÚeÚmsgr   r   r   r   Úpy_anext&   s    
ÿ
 r&   c                   @   sB   e Zd ZdZddœdd„Zeee  ee ee e	dœdd„Z
dS )	ÚNoLockz@Dummy lock that provides the proper interface but no protection.Nr   c                 Ã   s   dS )zDo nothing.Nr   ©Úselfr   r   r   Ú
__aenter__X   s    zNoLock.__aenter__©Úexc_typeÚexc_valÚexc_tbr   c                 Ã   s   dS )z'Return False, exception not suppressed.Fr   ©r)   r,   r-   r.   r   r   r   Ú	__aexit__[   s    zNoLock.__aexit__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r*   r   r    ÚBaseExceptionr
   Úboolr0   r   r   r   r   r'   U   s   
ûr'   )r   ÚbufferÚpeersÚlockr   c                 C  sÌ  �z8|s¨|4 I dH š~ |r.W d  ƒI dH  qz|   ¡ I dH }W n( tyh   Y W d  ƒI dH  q´Y n0 |D ]}| |¡ qnW d  ƒI dH  q¨1 I dH sž0    Y  | ¡ V  qW |4 I dH š` t|ƒD ]\}}||u rÌ| |¡  qìqÌ|�st| dƒ�r|  ¡ I dH  W d  ƒI dH  �qÈ1 I dH �s00    Y  nŒ|4 I dH šf t|ƒD ]$\}}||u �rR| |¡  �qx�qR|�s˜t| dƒ�r˜|  ¡ I dH  W d  ƒI dH  �qÆ1 I dH �s¼0    Y  0 dS )a  An individual iterator of a :py:func:`~.tee`.

    This function is a generator that yields items from the shared iterator
    ``iterator``. It buffers items until the least advanced iterator has
    yielded them as well. The buffer is shared with all other peers.

    Args:
        iterator: The shared iterator.
        buffer: The buffer for this peer.
        peers: The buffers of all peers.
        lock: The lock to synchronise access to the shared buffers.

    Yields:
        The next item from the shared iterator.
    NÚaclose)r   r   ÚappendÚpopleftÚ	enumerateÚpopÚhasattrr:   )r   r7   r8   r9   ÚitemZpeer_bufferÚidxr   r   r   Útee_peere   s4    6
>ø


rB   c                   @   s  e Zd ZdZdddœee eeee	  dœdd„Z
edœd	d
„Zeeee dœdd„ƒZeeeee df dœdd„ƒZeeef eee eee df f dœdd„Zeee  dœdd„Zddœdd„Zeee  ee ee edœdd„Zddœdd„ZdS )ÚTeeaY  Create ``n`` separate asynchronous iterators over ``iterable``.

    This splits a single ``iterable`` into multiple iterators, each providing
    the same items in the same order.
    All child iterators may advance separately but share the same items
    from ``iterable`` -- when the most advanced iterator retrieves an item,
    it is buffered until the least advanced iterator has yielded it as well.
    A ``tee`` works lazily and can handle an infinite ``iterable``, provided
    that all iterators advance.

    .. code-block:: python

        async def derivative(sensor_data):
            previous, current = a.tee(sensor_data, n=2)
            await a.anext(previous)  # advance one iterator
            return a.map(operator.sub, previous, current)

    Unlike :py:func:`itertools.tee`, :py:func:`~.tee` returns a custom type instead
    of a :py:class:`tuple`. Like a tuple, it can be indexed, iterated and unpacked
    to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method
    immediately closes all children, and it can be used in an ``async with`` context
    for the same effect.

    If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
    provide these items. Also, ``tee`` must internally buffer each item until the
    last iterator has yielded it; if the most and least advanced iterator differ
    by most data, using a :py:class:`list` is more efficient (but not lazy).

    If the underlying iterable is concurrency safe (``anext`` may be awaited
    concurrently) the resulting iterators are concurrency safe as well. Otherwise,
    the iterators are safe if there is only ever one single "most advanced" iterator.
    To enforce sequential use of ``anext``, provide a ``lock``
    - e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -
    and access is automatically synchronised.

    é   N)r9   )ÚiterableÚnr9   c                   s>   |  ¡ ˆ_dd„ t|ƒD ƒˆ_t‡ ‡fdd„ˆjD ƒƒˆ_dS )a  Create a ``tee``.

        Args:
            iterable: The iterable to split.
            n: The number of iterators to create. Defaults to 2.
            lock: The lock to synchronise access to the shared buffers.
                Defaults to None.
        c                 S   s   g | ]
}t ƒ ‘qS r   r   )Ú.0Ú_r   r   r   Ú
<listcomp>Ó   ó    z Tee.__init__.<locals>.<listcomp>c                 3   s0   | ](}t ˆj|ˆjˆ d urˆ ntƒ d�V  qd S )N)r   r7   r8   r9   )rB   Ú	_iteratorÚ_buffersr'   )rG   r7   ©r9   r)   r   r   Ú	<genexpr>Ô   s   úüzTee.__init__.<locals>.<genexpr>N)Ú	__aiter__rK   ÚrangerL   ÚtupleÚ	_children)r)   rE   rF   r9   r   rM   r   Ú__init__Ã   s
    
ùzTee.__init__r   c                 C   s
   t | jƒS )z%Return the number of child iterators.)ÚlenrR   r(   r   r   r   Ú__len__Þ   s    zTee.__len__)r@   r   c                 C   s   d S r   r   ©r)   r@   r   r   r   Ú__getitem__â   s    zTee.__getitem__.c                 C   s   d S r   r   rV   r   r   r   rW   å   s    c                 C   s
   | j | S )z:Return the child iterator(s) for the given index or slice.©rR   rV   r   r   r   rW   è   s    c                 c   s   | j E dH  dS )z\Iterate over the child iterators.

        Yields:
            The child iterators.
        NrX   r(   r   r   r   Ú__iter__î   s    zTee.__iter__zTee[T]c                 Ã   s   | S )zReturn the tee instance.r   r(   r   r   r   r*   ö   s    zTee.__aenter__r+   c                 Ã   s   |   ¡ I dH  dS )zcClose all child iterators.

        Returns:
            False, exceptions not suppressed.
        NF)r:   r/   r   r   r   r0   ú   s    zTee.__aexit__c                 Ã   s   | j D ]}| ¡ I dH  qdS )z Async close all child iterators.N)rR   r:   )r)   Úchildr   r   r   r:     s    
z
Tee.aclose)rD   )r1   r2   r3   r4   r   r   Úintr   r	   r   rS   rU   r   rW   ÚslicerQ   r   r   rY   r*   r    r5   r
   r6   r0   r:   r   r   r   r   rC   �   s2   ( ýû
û
þ
ûrC   c                   @   s‚   e Zd ZdZeeeef ee f ddœdd„Ze	eeeef ee f dœdd„ƒZ
e	eee  ee ee dd	œd
d„ƒZdS )Úaclosinga“  Async context manager to wrap an AsyncGenerator that has a ``aclose()`` method.

    Code like this:

    .. code-block:: python

        async with aclosing(<module>.fetch(<arguments>)) as agen:
            <block>

    is equivalent to this:

    .. code-block:: python

        agen = <module>.fetch(<arguments>)
        try:
            <block>
        finally:
            await agen.aclose()

    N)Úthingr   c                 C   s
   || _ dS )z\Create the context manager.

        Args:
            thing: The resource to wrap.
        N©r^   )r)   r^   r   r   r   rS   '  s    zaclosing.__init__r   c                 Ã   s   | j S r   r_   r(   r   r   r   r*   1  s    zaclosing.__aenter__)r,   Ú	exc_valueÚ	tracebackr   c                 Ã   s    t | jdƒr| j ¡ I d H  d S )Nr:   )r?   r^   r:   )r)   r,   r`   ra   r   r   r   r0   5  s    zaclosing.__aexit__)r1   r2   r3   r4   r   r   r   r   rS   r   r*   r   r    r5   r
   r0   r   r   r   r   r]     s   þ
$
ûr]   )ÚsizerE   r   c                 C  sR   g }|2 z83 dH W }t |ƒ| k r*| |¡ t |ƒ| kr|V  g }q6 |rN|V  dS )z´Utility batching function for async iterables.

    Args:
        size: The size of the batch.
        iterable: The async iterable to batch.

    Yields:
        The batches.
    N)rT   r;   )rb   rE   ÚbatchÚelementr   r   r   Úabatch_iterate@  s    
re   )$r4   Úcollectionsr   Úcollections.abcr   r   r   r   r   Ú
contextlibr	   Útypesr
   Útypingr   r   r   r   r   r   r   r   Ztyping_extensionsr   r   Úobjectr#   r&   r'   ÚlistrB   rC   Zateer]   r[   re   r   r   r   r   Ú<module>   s4   (ÿþ/

ù8q0
þ