a
    ”˜ëjIO  ã                	   @  s¬  U d Z ddlm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 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mZmZmZmZmZmZm Z  dd
l!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0 e�r*ddl1m2Z2m3Z3 ddl'm4Z4m5Z5 neee6ef  Z3G dd„ de&dd�Z7G dd„ de&dd�Z8g d¢Z9g d¢Z:dZ;eddd�Z<de=d< dddœd d!„Z>edd"dœd#d$„ƒZ?dZd%ddœd&d'„Z@d(d)d*d+œd,d-„ZAdddddd.œd%d/d0d0d1d2dd3œd4d5„ZBd%dd6œd7d8„ZCd[d9d:dd;d<d=d>œd?d@„ZDd\dAd:ddBd<dCd>œdDdE„ZEddFdœdGdH„ZFddIdœdJdK„ZGe%dLƒZHedMƒZIG dNdO„ dOeƒZJed%dPdœdQdR„ƒZKdSdTdUdVdMdWœdXdY„ZLdS )]z&Configuration utilities for Runnables.é    )ÚannotationsN)Ú	AwaitableÚ	GeneratorÚIterableÚIteratorÚSequence)ÚExecutorÚFutureÚThreadPoolExecutor)Úcontextmanager)ÚContextÚ
ContextVarÚTokenÚcopy_context)Úpartial)ÚTYPE_CHECKINGÚAnyÚCallableÚOptionalÚTypeVarÚUnionÚcast)Ú_set_tracing_contextÚget_tracing_context)Ú	ParamSpecÚ	TypedDict)ÚAsyncCallbackManagerÚCallbackManager)ÚInputÚOutputÚaccepts_configÚaccepts_run_manager)ÚLangChainTracer)ÚBaseCallbackManagerÚ	Callbacks)ÚAsyncCallbackManagerForChainRunÚCallbackManagerForChainRunc                   @  s   e Zd ZdZdS )Ú	EmptyDictzEmpty dict type.N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r,   r,   ú^/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/runnables/config.pyr'   '   s   r'   F)Útotalc                   @  sR   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S )ÚRunnableConfigzConfiguration for a Runnable.z	list[str]Útagszdict[str, Any]Úmetadatar$   Ú	callbacksÚstrÚrun_nameúOptional[int]Úmax_concurrencyÚintÚrecursion_limitÚconfigurablezOptional[uuid.UUID]Úrun_idN)r(   r)   r*   r+   Ú__annotations__r,   r,   r,   r-   r/   +   s   
r/   )r0   r1   r2   r4   r6   r8   r9   r:   )r0   r1   r2   r9   é   Zchild_runnable_config)Údefaultz!ContextVar[RunnableConfig | None]Úvar_child_runnable_configz@tuple[Token[Optional[RunnableConfig]], Optional[dict[str, Any]]])ÚconfigÚreturnc                 C  sz   t  | ¡}d}|  d¡ }rrt|ddƒ }rrtdd„ t|dg ƒD ƒdƒ }rr|j t|ƒ¡ }rrtƒ }td|iƒ ||fS )zÊSet the child Runnable config + tracing context.

    Args:
        config (RunnableConfig): The config to set.

    Returns:
        The token to reset the config and the previous tracing context.
    Nr2   Úparent_run_idc                 s  s   | ]}t |tƒr|V  qd S ©N)Ú
isinstancer"   )Ú.0Úhandlerr,   r,   r-   Ú	<genexpr>Ž   s   
þz&_set_config_context.<locals>.<genexpr>ÚhandlersÚparent)	r>   ÚsetÚgetÚgetattrÚnextZrun_mapr3   r   r   )r?   Úconfig_tokenZcurrent_contextr2   rA   ZtracerÚrunr,   r,   r-   Ú_set_config_contextz   s$    
ÿý
þúúñrO   zGenerator[Context, None, None]c                 c  sx   t ƒ }| t| ¡\}}z2|V  W | tj|¡ | tdddddddœ¡ n*| tj|¡ | tdddddddœ¡ 0 dS )z�Set the child Runnable config + tracing context.

    Args:
        config (RunnableConfig): The config to set.

    Yields:
        The config context.
    N)rH   Úproject_namer0   r1   ZenabledÚclient)r   rN   rO   r>   Úresetr   )r?   ÚctxrM   Ú_r,   r,   r-   Úset_config_context�   s4    
úþÿúþrU   zOptional[RunnableConfig]c                 C  sò   t g i dti d�}t ¡  }r<| tddd„ | ¡ D ƒƒ¡ | durb| tddd„ |  ¡ D ƒƒ¡ | dur˜|  ¡ D ]$\}}|tvrr|durr||d |< qr| di ¡ ¡ D ]D\}}| d¡s¨t	|t
tttfƒr¨||d	 vr¨|d
kr¨||d	 |< q¨|S )zæEnsure that a config is a dict with all keys present.

    Args:
        config (Optional[RunnableConfig], optional): The config to ensure.
          Defaults to None.

    Returns:
        RunnableConfig: The ensured config.
    N)r0   r1   r2   r8   r9   r/   c                 S  s.   i | ]&\}}|d ur||t v r&| ¡ n|“qS rB   )ÚCOPIABLE_KEYSÚcopy©rD   ÚkÚvr,   r,   r-   Ú
<dictcomp>Ï   s   þz!ensure_config.<locals>.<dictcomp>c                 S  s6   i | ].\}}|d ur|t v r||tv r.| ¡ n|“qS rB   )ÚCONFIG_KEYSrV   rW   rX   r,   r,   r-   r[   Ú   s   þr9   Ú__r1   Zapi_key)r/   ÚDEFAULT_RECURSION_LIMITr>   rJ   Úupdater   Úitemsr\   Ú
startswithrC   r3   r7   ÚfloatÚbool)r?   ÚemptyZ
var_configrY   rZ   ÚkeyÚvaluer,   r,   r-   Úensure_configº   sP    
ûþþÿ
þþÿ
ÿþ
ýürg   z9Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]r7   zlist[RunnableConfig])r?   Úlengthr@   c                   sÜ   |dk rd|› �}t |ƒ‚tˆ tƒrNtˆ ƒ|krNdtˆ ƒ› d|› d�}t |ƒ‚tˆ tƒrftttˆ ƒƒS |dkrÆtˆ tƒrÆˆ  d¡durÆt	j
d	td
d� tddd„ ˆ  ¡ D ƒƒ‰‡ ‡fdd„t|ƒD ƒS ‡ fdd„t|ƒD ƒS )aØ  Get a list of configs from a single config or a list of configs.

     It is useful for subclasses overriding batch() or abatch().

    Args:
        config (Optional[Union[RunnableConfig, list[RunnableConfig]]]):
          The config or list of configs.
        length (int): The length of the list.

    Returns:
        list[RunnableConfig]: The list of configs.

    Raises:
        ValueError: If the length of the list is not equal to the length of the inputs.

    r   zlength must be >= 0, but got z<config must be a list of the same length as inputs, but got z configs for z inputsé   r:   Nz@Provided run_id be used only for the first element of the batch.é   )ÚcategoryÚ
stacklevelr/   c                 S  s   i | ]\}}|d kr||“qS )r:   r,   rX   r,   r,   r-   r[     ó    z#get_config_list.<locals>.<dictcomp>c                   s    g | ]}|rt ˆƒnt ˆ ƒ‘qS r,   ©rg   ©rD   Úi©r?   Z
subsequentr,   r-   Ú
<listcomp>  s   ÿz#get_config_list.<locals>.<listcomp>c                   s   g | ]}t ˆ ƒ‘qS r,   rn   ro   ©r?   r,   r-   rr     rm   )Ú
ValueErrorrC   r   ÚlenÚlistÚmaprg   ÚdictrJ   ÚwarningsÚwarnÚRuntimeWarningr   r`   Úrange)r?   rh   Úmsgr,   rq   r-   Úget_config_listð   s4    
ÿÿÿ
 ýÿþr~   )r2   r8   r6   r4   r9   zOptional[BaseCallbackManager]r5   zOptional[str]zOptional[dict[str, Any]])r?   r2   r8   r6   r4   r9   r@   c                C  sˆ   t | ƒ} |dur4|| d< d| v r&| d= d| v r4| d= |durD|| d< |durT|| d< |durd|| d< |dur„i |  di ¡¥|¥| d< | S )a±  Patch a config with new values.

    Args:
        config (Optional[RunnableConfig]): The config to patch.
        callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.
          Defaults to None.
        recursion_limit (Optional[int], optional): The recursion limit to set.
          Defaults to None.
        max_concurrency (Optional[int], optional): The max concurrency to set.
          Defaults to None.
        run_name (Optional[str], optional): The run name to set. Defaults to None.
        configurable (Optional[dict[str, Any]], optional): The configurable to set.
          Defaults to None.

    Returns:
        RunnableConfig: The patched config.
    Nr2   r4   r:   r8   r6   r9   )rg   rJ   )r?   r2   r8   r6   r4   r9   r,   r,   r-   Úpatch_config  s     r   )Úconfigsr@   c                  G  s  i }dd„ | D ƒD �]î}|D �]â}|dkrNi |  di ¡¥|  d¡pDi ¥|d< q|dkr~tt|  dg ¡|  d¡ppg  ƒƒ|d< q|dkrªi |  di ¡¥|  d¡p i ¥|d< q|dk�r˜|  d¡}|d }t|tƒ�r.|du rè| ¡ |d< nDt|tƒ�r|| |d< n*| ¡ }|D ]}|j|dd	� �q||d< nh|du�r |du �rP| ¡ |d< nFt|tƒ�rˆ| ¡ }|D ]}|j|dd	� �qh||d< n| |¡|d< q|d
k�r¾|d
 tk�r |d
 |d
< q|t	v �rè|| du�rè||  ¡ ||< q|| �pú|  |¡||< qq|S )z¬Merge multiple configs into one.

    Args:
        *configs (Optional[RunnableConfig]): The configs to merge.

    Returns:
        RunnableConfig: The merged config.
    c                 s  s   | ]}|d urt |ƒV  qd S rB   rn   )rD   Úcr,   r,   r-   rF   Y  rm   z merge_configs.<locals>.<genexpr>r1   r0   r9   r2   NT)Zinheritr8   )
rJ   ÚsortedrI   rC   rv   rW   Úadd_handlerÚmerger^   rV   )r€   Úbaser?   re   Zbase_callbacksZthese_callbacksZmngrÚcallbackr,   r,   r-   Úmerge_configsM  s^    	

ÿþ
ÿ

ÿþ







r‡   zÉUnion[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]r   z$Optional[CallbackManagerForChainRun]r   r   )ÚfuncÚinputr?   Úrun_managerÚkwargsr@   c                 K  sV   t | ƒr.|dur&t|| ¡ d�|d< n||d< |durFt| ƒrF||d< | |fi |¤ŽS )aš  Call function that may optionally accept a run_manager and/or config.

    Args:
        func: The function to call.
        input: The input to the function.
        config: The config to pass to the function.
        run_manager: The run manager to pass to the function. Defaults to None.
        **kwargs: The keyword arguments to pass to the function.

    Returns:
        The output of the function.
    N©r2   r?   rŠ   ©r    r   Z	get_childr!   ©rˆ   r‰   r?   rŠ   r‹   r,   r,   r-   Úcall_func_with_variable_args�  s    r�   zÿUnion[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]z)Optional[AsyncCallbackManagerForChainRun]zAwaitable[Output]c                 K  sV   t | ƒr.|dur&t|| ¡ d�|d< n||d< |durFt| ƒrF||d< | |fi |¤ŽS )a   Async call function that may optionally accept a run_manager and/or config.

    Args:
        func: The function to call.
        input: The input to the function.
        config: The config to pass to the function.
        run_manager: The run manager to pass to the function. Defaults to None.
        **kwargs: The keyword arguments to pass to the function.

    Returns:
        The output of the function.
    NrŒ   r?   rŠ   r�   rŽ   r,   r,   r-   Úacall_func_with_variable_args±  s    r�   r   c                 C  s"   t j|  d¡|  d¡|  d¡d�S )zžGet a callback manager for a config.

    Args:
        config (RunnableConfig): The config.

    Returns:
        CallbackManager: The callback manager.
    r2   r0   r1   ©Zinheritable_callbacksZinheritable_tagsZinheritable_metadata)r   Ú	configurerJ   rs   r,   r,   r-   Úget_callback_manager_for_configÖ  s
    	ýr“   r   c                 C  s"   t j|  d¡|  d¡|  d¡d�S )z°Get an async callback manager for a config.

    Args:
        config (RunnableConfig): The config.

    Returns:
        AsyncCallbackManager: The async callback manager.
    r2   r0   r1   r‘   )r   r’   rJ   rs   r,   r,   r-   Ú%get_async_callback_manager_for_configæ  s
    ýr”   ÚPÚTc                      sN   e Zd ZdZdddddœ‡ fdd„Zd	d
dœddddddœ‡ fdd„Z‡  ZS )ÚContextThreadPoolExecutorz?ThreadPoolExecutor that copies the context to the child thread.úCallable[P, T]úP.argsúP.kwargsz	Future[T])rˆ   Úargsr‹   r@   c                   s*   t ƒ  tdttƒ j|g|¢R i |¤Žƒ¡S )aC  Submit a function to the executor.

        Args:
            func (Callable[..., T]): The function to submit.
            *args (Any): The positional arguments to the function.
            **kwargs (Any): The keyword arguments to the function.

        Returns:
            Future[T]: The future for the function.
        úCallable[..., T])ÚsuperÚsubmitr   r   r   rN   )Úselfrˆ   r›   r‹   ©Ú	__class__r,   r-   rž   ÿ  s     ÿz ContextThreadPoolExecutor.submitNri   ©ÚtimeoutÚ	chunksizerœ   zIterable[Any]zfloat | Noner7   zIterator[T])ÚfnÚ	iterablesr£   r¤   r@   c                  sL   dd„ t t|d ƒƒD ƒ‰ dddœ‡ ‡fdd„}tƒ j|g|¢R ||d	œŽS )
aÃ  Map a function to multiple iterables.

        Args:
            fn (Callable[..., T]): The function to map.
            *iterables (Iterable[Any]): The iterables to map over.
            timeout (float | None, optional): The timeout for the map.
                Defaults to None.
            chunksize (int, optional): The chunksize for the map. Defaults to 1.

        Returns:
            Iterator[T]: The iterator for the mapped function.
        c                 S  s   g | ]
}t ƒ ‘qS r,   )r   )rD   rT   r,   r,   r-   rr   &  rm   z1ContextThreadPoolExecutor.map.<locals>.<listcomp>r   r   r–   )r›   r@   c                    s   ˆ   ¡ jˆg| ¢R Ž S rB   )ÚpoprN   )r›   ©Zcontextsr¥   r,   r-   Ú_wrapped_fn(  s    z2ContextThreadPoolExecutor.map.<locals>._wrapped_fnr¢   )r|   ru   r�   rw   )rŸ   r¥   r£   r¤   r¦   r©   r    r¨   r-   rw     s    ÿþüzContextThreadPoolExecutor.map)r(   r)   r*   r+   rž   rw   Ú__classcell__r,   r,   r    r-   r—   ü  s
   ûr—   zGenerator[Executor, None, None]c                 c  sB   | pi } t |  d¡d��}|V  W d  ƒ n1 s40    Y  dS )zžGet an executor for a config.

    Args:
        config (RunnableConfig): The config.

    Yields:
        Generator[Executor, None, None]: The executor.
    r6   )Úmax_workersN)r—   rJ   )r?   Úexecutorr,   r,   r-   Úget_executor_for_config3  s    ÿr­   z)Optional[Union[Executor, RunnableConfig]]r˜   r™   rš   )Úexecutor_or_configrˆ   r›   r‹   r@   c                 �  sd   ddœ‡ ‡‡fdd„}| du s(t | tƒrNt ¡  dtdttƒ j|ƒƒ¡I dH S t ¡  | |¡I dH S )aV  Run a function in an executor.

    Args:
        executor_or_config: The executor or config to run in.
        func (Callable[P, Output]): The function.
        *args (Any): The positional arguments to the function.
        **kwargs (Any): The keyword arguments to the function.

    Returns:
        Output: The output of the function.
    r–   )r@   c               
     s@   zˆˆ i ˆ¤ŽW S  t y: }  zt| ‚W Y d } ~ n
d } ~ 0 0 d S rB   )ÚStopIterationÚRuntimeError)Úexc©r›   rˆ   r‹   r,   r-   ÚwrapperX  s    z run_in_executor.<locals>.wrapperNrœ   )	rC   rx   ÚasyncioZget_running_loopÚrun_in_executorr   r   r   rN   )r®   rˆ   r›   r‹   r³   r,   r²   r-   rµ   F  s    	þ
rµ   )N)N)N)Mr+   Ú
__future__r   r´   Úuuidry   Úcollections.abcr   r   r   r   r   Úconcurrent.futuresr   r	   r
   Ú
contextlibr   Zcontextvarsr   r   r   r   Ú	functoolsr   Útypingr   r   r   r   r   r   r   Zlangsmith.run_helpersr   r   Ztyping_extensionsr   r   Z langchain_core.callbacks.managerr   r   Zlangchain_core.runnables.utilsr   r   r    r!   Z langchain_core.tracers.langchainr"   Zlangchain_core.callbacks.baser#   r$   r%   r&   rv   r'   r/   r\   rV   r^   r>   r;   rO   rU   rg   r~   r   r‡   r�   r�   r“   r”   r•   r–   r—   r­   rµ   r,   r,   r,   r-   Ú<module>   sf   $4ÿ#62ù.K ÷. ô%7