
    NgI/                        d Z ddl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mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ  ed          Z e            Zefdee         deeef         deeedef                  fd	Z G d
 d          Zdee         dee         deee                  de	e         de
edf         f
dZ  G d dee                   Z!e!Z"d Z#deeef         defdZ$dddee%         deeddef                  de&de
edf         fdZ'dedef         de(fdZ)dddeej*                 fdZ+ ej,        d !          d"             Z-dS )#zzAdapted.

Original source:
https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
MIT License
    Ndeque)AnyAsyncContextManagerAsyncGeneratorAsyncIterableAsyncIterator	AwaitableCallable	CoroutineDequeGenericIterableIteratorListOptionalTupleTypeVarUnioncastoverloadTiteratordefaultreturnc                 j    	 t          t          t          t                   gt          t                   f         t                     j                  n # t          $ r t           d          w xY wt          u r            S dt          t          t          f         f fd} |            S )a0  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.
    z is not an async iteratorr   c                  P   K   	              d {V S # t           $ r cY S w xY wN)StopAsyncIteration)	__anext__r   r   s   V/var/www/html/ai-engine/env/lib/python3.11/site-packages/langsmith/_internal/_aiter.py
anext_implzpy_anext.<locals>.anext_impl>   sT      	 #8,,,,,,,,,! 	 	 	NNN	s    %%)r   r   r	   r   r
   typer    AttributeError	TypeError_no_defaultr   r   )r   r   r"   r    s   `` @r!   py_anextr'   *   s    BmA&'156X8P
 
		  B B B8@@@AAAB +y"""	eAsFm 	 	 	 	 	 	 	 	 :<<s   AA A3c                   2    e Zd ZdZd	dZdedededefdZdS )
NoLockz@Dummy lock that provides the proper interface but no protection.r   Nc                 
   K   d S r    selfs    r!   
__aenter__zNoLock.__aenter__O   s          exc_typeexc_valexc_tbc                 
   K   dS NFr+   r-   r0   r1   r2   s       r!   	__aexit__zNoLock.__aexit__R   s      ur/   r   N)__name__
__module____qualname____doc__r.   r   boolr6   r+   r/   r!   r)   r)   L   s^        JJ    c 3 4      r/   r)   bufferpeerslockc                  K   	 	 |s|4 d{V  |r	 ddd          d{V  !	 |                                   d{V }|D ]}|                    |           n!# t          $ r Y ddd          d{V  n@w xY w	 ddd          d{V  n# 1 d{V swxY w Y   |                                W V  	 |4 d{V  t	          |          D ] \  }}||u r|                    |            n!|s*t          | d          r|                                  d{V  ddd          d{V  dS # 1 d{V swxY w Y   dS # |4 d{V  t	          |          D ] \  }}||u r|                    |            n!|s*t          | d          r|                                  d{V  ddd          d{V  w # 1 d{V swxY w Y   w xY w)zIterate over :py:func:`~.tee`.TNaclose)r    appendr   popleft	enumeratepophasattrrA   )r   r=   r>   r?   itempeer_bufferidxs          r!   tee_peerrJ   V   sx     (	# 5 5 5 5 5 5 5 5 5  ! 	5 5 5 5 5 5 5 5 5 5 5 5 5
5%-%7%7%9%9999999 ,1 5 5K'..t44445 .   5 5 5 5 5 5 5 5 5 5 5 5 555 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5" ..""""""'	#5&  	( 	( 	( 	( 	( 	( 	( 	($-e$4$4   [&((IIcNNNE )  (WXx88 (oo'''''''''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(4 	( 	( 	( 	( 	( 	( 	( 	($-e$4$4   [&((IIcNNNE )  (WXx88 (oo'''''''''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s   E BE A B
A9%B&E 8A99B=E 
BE BE AD11
D;>D;	GAF<*G<
GG	G
Gc            
       l   e Zd ZdZ	 ddddee         dedeee	                  fdZ
d	efd
Zeded	ee         fd            Zeded	eee         df         fd            Zdeeef         d	eee         eee         df         f         fdZd	eee                  fdZddZde	de	de	d	efdZddZdS )TeeaX  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 pare 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:: python3

        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)r?   iterablenr?   c                     |                                  _        d t          |          D              _        t	           fd j        D                        _        d S )Nc                 *    g | ]}t                      S r+   r   ).0_s     r!   
<listcomp>z Tee.__init__.<locals>.<listcomp>   s    (C(C(CQ(C(C(Cr/   c              3   r   K   | ]1}t          j        |j        nt                                V  2d S )N)r   r=   r>   r?   )rJ   	_iterator_buffersr)   )rR   r=   r?   r-   s     r!   	<genexpr>zTee.__init__.<locals>.<genexpr>   se       
 
  m!-TT688	  
 
 
 
 
 
r/   )	__aiter__rV   rangerW   tuple	_children)r-   rN   rO   r?   s   `  `r!   __init__zTee.__init__   sx     "++--(C(C%(((C(C(C 
 
 
 
 
 -
 
 
 
 
r/   r   c                 *    t          | j                  S r   )lenr\   r,   s    r!   __len__zTee.__len__   s    4>"""r/   rG   c                     d S r   r+   r-   rG   s     r!   __getitem__zTee.__getitem__   s    :=#r/   .c                     d S r   r+   rb   s     r!   rc   zTee.__getitem__   s    HKr/   c                     | j         |         S r   r\   rb   s     r!   rc   zTee.__getitem__   s     ~d##r/   c              #   $   K   | j         E d {V  d S r   rf   r,   s    r!   __iter__zTee.__iter__   s&      >!!!!!!!!!r/   Tee[T]c                 
   K   | S r   r+   r,   s    r!   r.   zTee.__aenter__   s      r/   r0   r1   r2   c                 >   K   |                                   d {V  dS r4   )rA   r5   s       r!   r6   zTee.__aexit__   s+      kkmmur/   c                 R   K   | j         D ]}|                                 d {V  d S r   )r\   rA   )r-   childs     r!   rA   z
Tee.aclose   sD      ^ 	! 	!E,,..        	! 	!r/   )rM   )r   ri   r7   )r8   r9   r:   r;   r	   r   intr   r   r   r]   r`   r   rc   slicer   r   r   rh   r.   r<   r6   rA   r+   r/   r!   rL   rL      s       " "N 

 48
 
 
"
 

 *3/0
 
 
 
&# # # # # ==a(8=== X=KK%a0@#0E*FKKK XK$#u*%$	}Q}Q'7'<!==	>$ $ $ $
"(=#34 " " " "    c 3 4    ! ! ! ! ! !r/   rL   c                    K   d | D             }	 	 t          j        d |D               d{V }t          |          W V  n# t          $ r Y dS w xY wD)zAsync version of zip.c                 6    g | ]}|                                 S r+   )rY   )rR   rN   s     r!   rT   zasync_zip.<locals>.<listcomp>   s$    FFF(##%%FFFr/   Tc              3   4   K   | ]}t          |          V  d S r   )r'   )rR   r   s     r!   rX   zasync_zip.<locals>.<genexpr>   s*      ??(8$$??????r/   N)asynciogatherr[   r   )async_iterables	iteratorsitemss      r!   	async_ziprx      s       GFoFFFI	!.??Y???      E ,,! 	 	 	EE	s   0A 
AArN   c                     t          | d          rt          t          |           S t          | d          r't          t          |                                           S  G d d          } ||           S )Nr    rY   c                   &    e Zd ZdefdZd Zd ZdS )3ensure_async_iterator.<locals>.AsyncIteratorWrapperrN   c                 .    t          |          | _        d S r   )iterrV   )r-   rN   s     r!   r]   z<ensure_async_iterator.<locals>.AsyncIteratorWrapper.__init__   s    !%hr/   c                 Z   K   	 t          | j                  S # t          $ r t          w xY wr   )nextrV   StopIterationr   r,   s    r!   r    z=ensure_async_iterator.<locals>.AsyncIteratorWrapper.__anext__   s<      -///$ - - -,,-s    *c                     | S r   r+   r,   s    r!   rY   z=ensure_async_iterator.<locals>.AsyncIteratorWrapper.__aiter__   s    r/   N)r8   r9   r:   r   r]   r    rY   r+   r/   r!   AsyncIteratorWrapperr{      sM        0 0 0 0 0- - -    r/   r   )rF   r   r	   rY   )rN   r   s     r!   ensure_async_iteratorr      s     x%% .M8,,,	;	'	' .M8#5#5#7#7888	 	 	 	 	 	 	 	 $#H---r/   )_eager_consumption_timeoutrO   	generatorr   c                      dk    rfd} |            S t          t          j         t          j                   nt                                dt          ffd fd} |            S )a  Process async generator with max parallelism.

    Args:
        n: The number of tasks to run concurrently.
        generator: The async generator to process.
        _eager_consumption_timeout: If set, check for completed tasks after
            each iteration and yield their results. This can be used to
            consume the generator eagerly while still respecting the concurrency
            limit.

    Yields:
        The processed items yielded by the async generator.
    r   c                 8   K   2 3 d {V } |  d {V W V  6 d S r   r+   )rG   r   s    r!   consumez'aiter_with_concurrency.<locals>.consume  sV      ' ! ! ! ! ! ! !d jjjjjj      (iis   Nixc                 |   K   4 d {V  | d {V }| |fcd d d           d {V  S # 1 d {V swxY w Y   d S r   r+   )r   rG   res	semaphores      r!   process_itemz,aiter_with_concurrency.<locals>.process_item  s       	 	 	 	 	 	 	 	******C9	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   +
55c                   K   i } t                      }d}2 3 d {V }|r4t          j                    }t          j         ||          |          }nt          j         ||                    }|| |<   |dz  }dk    rU	 t          j        |                                           D ]}| d {V \  }}|W V  | |= n# t          j        $ r Y nw xY wrt          |           k    r_t          j	        |                                 t          j
                   d {V \  }	}
|	D ]!}|                                \  }}|W V  | |= "66 t          j        |                                           D ]}| d {V \  }
}|W V  d S )Nr   )context   )timeout)return_when)asyncio_accepts_contextcontextvarscopy_contextrs   create_taskas_completedvaluesTimeoutErrorr_   waitFIRST_COMPLETEDresult)tasksaccepts_contextr   rG   r   task_futtask_idxr   donerS   r   r   rO   r   s              r!   process_generatorz1aiter_with_concurrency.<locals>.process_generator"  s'     133# 	( 	( 	( 	( 	( 	( 	($ C%244*<<D+A+A7SSS*<<D+A+ABBE"I!GB)A--	 ' 4 :! ! ! , , /3





#!				!(OO, +   D}Uq 'LLNN0G! ! !      a ! ( (D$(KKMMMHcIIIIh5 $8 (88 	 	DZZZZZZFAsIIIII	 	s   E>CCC)r   rs   	Semaphorer)   rn   )rO   r   r   r   r   r   r   s   ```  @@r!   aiter_with_concurrencyr      s    & 	Avv	! 	! 	! 	! 	! wyy1=7,Q///fhh Is      
" " " " " " " "H r/   callable.c                     	 t          j        |           j                            d          duS # t          $ r Y dS w xY w)z/Check if a callable accepts a context argument.r   NF)inspect	signature
parametersget
ValueError)r   s    r!   r   r   I  sP     **599)DDDPP   uus   -0 
>>)__ctxr   c                  K   t          j                    }|pt          j                    }t	          j        |j        | g|R i |}|                    d|           d{V S )a  Asynchronously run function *func* in a separate thread.

    Any *args and **kwargs supplied for this function are directly passed
    to *func*. Also, the current :class:`contextvars.Context` is propagated,
    allowing context variables from the main thread to be accessed in the
    separate thread.

    Return a coroutine that can be awaited to get the eventual result of *func*.
    N)rs   get_running_loopr   r   	functoolspartialrunrun_in_executor)funcr   argskwargsloopctx	func_calls          r!   aio_to_threadr   R  su       #%%D

-;+--C!#'4A$AAA&AAI%%dI666666666r/   r   )maxsizec                  4    t          t          j                  S )zCCheck if the current asyncio event loop accepts a context argument.)r   rs   r   r+   r/   r!   r   r   d  s     7.///r/   ).r;   rs   r   r   r   collectionsr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   objectr&   r'   r)   rJ   rL   ateerx   r   rn   floatr   r<   r   Contextr   	lru_cacher   r+   r/   r!   <module>r      s                                                            , GCLLfhh :E A).q#vuQc\"#   D       '(A'( !H'(
 a>'( c
"'( AtG'( '( '( '(TR! R! R! R! R!'!* R! R! R!j   .Hm+,.. . . .: )*	G G G}GYtT1}56G !&	G
 AtGG G G GThsCx0 T     <@7 7 7#K$787 7 7 7$ Q0 0  0 0 0r/   