
    ghO                       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&m'Z'm(Z( erddl)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0 neee1ef                  Z+ G d de#d          Z2 G d de#d          Z3g dZ4g dZ5dZ6 edd          Z7de8d<   dTdZ9edUd             Z:dVdWd"Z;dXd'Z<dddddd(dYd2Z=dZd4Z>	 dVd[d>Z?	 dVd\dBZ@d]dDZAd^dFZB e"dG          ZC edH          ZD G dI dJe          ZEed_dL            ZFd`dSZGdS )az&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)	ParamSpec	TypedDict)InputOutputaccepts_configaccepts_run_manager)BaseCallbackManager	Callbacks)AsyncCallbackManagerAsyncCallbackManagerForChainRunCallbackManagerCallbackManagerForChainRunc                      e Zd ZdZdS )	EmptyDictzEmpty dict type.N)__name__
__module____qualname____doc__     \/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_core/runnables/config.pyr&   r&   &   s        r,   r&   F)totalc                  r    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-   r0   r0   *   s         ''OOO
 
 
 MMM #"""
  !      r,   r0   )r1   r2   r3   r5   r7   r9   r:   r;   )r1   r2   r3   r:      child_runnable_config)defaultz!ContextVar[RunnableConfig | None]var_child_runnable_configconfigreturn@tuple[Token[Optional[RunnableConfig]], Optional[dict[str, Any]]]c                  	 ddl m	 t                              |           }d}|                     d          x}rt          |dd          x}rut          	fdt          |dg           D             d          x}rH|j                            t          |                    x}rddl	m
}m}  |            } |d	|i           ||fS )
tSet the child Runnable config + tracing context.

    Args:
        config (RunnableConfig): The config to set.
    r   )LangChainTracerNr3   parent_run_idc              3  <   K   | ]}t          |          |V  d S N)
isinstance).0handlerrF   s     r-   	<genexpr>z&_set_config_context.<locals>.<genexpr>   sG        !'?;;     r,   handlers)_set_tracing_contextget_tracing_contextparent) langchain_core.tracers.langchainrF   r@   setgetgetattrnextrun_mapr4   langsmith.run_helpersrO   rP   )
rA   config_tokencurrent_contextr3   rG   tracerrunrO   rP   rF   s
            @r-   _set_config_contextr]   y   s&    A@@@@@,0088LOjj--	-. %YFFFM.    #*9j"#E#E  
   F. N&&s='9'9:::S." 	TSSSSSSS--//h_---((r,   Generator[Context, None, None]c              #  v  K   ddl m} t                      }|                    t          |           \  }}	 |V  |                    t
          j        |           |                    |ddddddd           dS # |                    t
          j        |           |                    |ddddddd           w xY w)rE   r   )rO   N)rQ   project_namer1   r2   enabledclient)rX   rO   r   r\   r]   r@   reset)rA   rO   ctxrY   _s        r-   set_config_contextrf      s       ;:::::
..Cgg16::OL!
			)/>>>  $  
	
 
	
 
	
 
	
 
	
 	)/>>>  $  
	
 
	
 
	
 
	
s   A9 9?B8Optional[RunnableConfig]c                   t          g i dt          i           }t                                          x}r?|                    t          dd |                                D                                  | ?|                    t          dd |                                 D                                  | 0|                                 D ]\  }}|t          vr|||d         |<   |                    di                                           D ]W\  }}|                    d          s=t          |t          t          t          t          f          r||d         vr||d         |<   X|S )	zEnsure 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)r1   r2   r3   r9   r:   r0   c                X    i | ]'\  }}|||t           v r|                                n|(S rI   )COPIABLE_KEYScopyrK   kvs      r-   
<dictcomp>z!ensure_config.<locals>.<dictcomp>   sA       1} 1#5#5qvvxxx1$}}r,   c                j    i | ]0\  }}||t           v ||t          v r|                                n|1S rI   )CONFIG_KEYSrj   rk   rl   s      r-   ro   z!ensure_config.<locals>.<dictcomp>   sM       1}k)9)9 1#5#5qvvxxx1)9)9)9r,   r:   __r2   )r0   DEFAULT_RECURSION_LIMITr@   rT   updater   itemsrq   
startswithrJ   r4   r8   floatbool)rA   empty
var_configrm   rn   keyvalues          r-   ensure_configr}      s    /  E /22444z 

   * 0 0 2 2   		
 		
 		
    &   		
 		
 		
 LLNN 	- 	-DAq##+,n%a(ii3399;; + +
Ut$$	+53UD"9::	+ 5,,,%*E*c"Lr,   9Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]lengthr8   list[RunnableConfig]c                    |dk     rd| }t          |          t           t                    r8t                     |k    r%dt                      d| d}t          |          t           t                    r"t	          t          t                               S |dk    rt           t                    ry                     d          dt          j
        d	t          d
           t          dd                                  D                        fdt          |          D             S  f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
stacklevelr0   c                &    i | ]\  }}|d k    ||S )r;   r+   rl   s      r-   ro   z#get_config_list.<locals>.<dictcomp>  s#    PPP1!x--q!---r,   c                P    g | ]"}|rt                    nt                    #S r+   r}   )rK   irA   
subsequents     r-   
<listcomp>z#get_config_list.<locals>.<listcomp>  sC     
 
 
 *+EM*%%%f0E0E
 
 
r,   c                .    g | ]}t                    S r+   r   )rK   r   rA   s     r-   r   z#get_config_list.<locals>.<listcomp>  s!    999aM&!!999r,   )
ValueErrorrJ   r   lenlistmapr}   dictrT   warningswarnRuntimeWarningr   ru   range)rA   r   msgr   s   `  @r-   get_config_listr      s   & zz6f66oo&(## Fv(=(=A6{{A A17A A A 	 oo&(## 0Cv..///zzj..z6::h3G3G3SN#	
 	
 	
 	

 PPPPP
 


 
 
 
 
6]]
 
 
 	
 :9995==9999r,   )r3   r9   r7   r5   r:   r3   Optional[BaseCallbackManager]r9   r6   r7   r5   Optional[str]r:   Optional[dict[str, Any]]c                   t          |           } ||| d<   d| v r| d= d| v r| d= ||| d<   ||| d<   ||| d<   |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.
    Nr3   r5   r;   r9   r7   r:   )r}   rT   )rA   r3   r9   r7   r5   r:   s         r-   patch_configr     s    4 6""F ({z"vx "$3 !"$3 !%z!SFJJ~r$B$B!Sl!S~Mr,   configsc            
        i }d | D             D ]o}|D ]h}|dk    r3i |                     di           |                     d          pi |d<   <|dk    rLt          t          |                     dg           |                     d          pg z                       |d<   |dk    r3i |                     di           |                     d          pi |d<   |dk    r&|                     d          }|d         }t          |t                    rq||                                |d<   t          |t                    r
||z   |d<   :|                                }|D ]}|                    |d           ||d<   q|||                                |d<   t          |t                    r7|                                }|D ]}|                    |d           ||d<   |                    |          |d<   |d	k    r|d	         t          k    r|d	         |d	<   |t          v r'||         ||                                         ||<   H||         p|                     |          ||<   jq|S )
zMerge multiple configs into one.

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

    Returns:
        RunnableConfig: The merged config.
    c              3  8   K   | ]}|t          |          V  d S rI   r   )rK   cs     r-   rM   z merge_configs.<locals>.<genexpr>W  s*      FF=##FFr,   r2   r1   r:   r3   NT)inheritr9   )
rT   sortedrS   rJ   r   rk   add_handlermergers   rj   )r   baserA   r{   base_callbacksthese_callbacksmngrcallbacks           r-   merge_configsr   K  s    D GFWFFF 29 29 1	9 1	9Cj  $hhz2..$zz*--3$Z   %,,

60B0B0HbIJJ   V &&(hh~r22(zz.117R(^$$ ##!%+!6!6"("5 ot44 R%-,;,@,@,B,B[))#ND99 1,:_,L[))  .2244(7 E EH ,,Xt,DDDD,0[))$0%-,;,@,@,B,B[))#ND99 R.3355(6 E EH ,,Xt,DDDD,0[)) -;,@,@,Q,Q[))))+,0GGG.45F.GD*+%%&+*A"3K,,..S		"3K8488C==S		c1	9d Kr,   funcUnion[Callable[[Input], Output], Callable[[Input, RunnableConfig], Output], Callable[[Input, CallbackManagerForChainRun], Output], Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]inputr   run_manager$Optional[CallbackManagerForChainRun]kwargsr   r   c                    t          |           r.|'t          ||                                          |d<   n||d<   |t          |           r||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r3   rA   r   r   r   	get_childr   r   r   rA   r   r   s        r-   call_func_with_variable_argsr     s    0 d &"+Fk>S>S>U>UVVVF8%F8#6t#<#< +}4     r,   Union[Callable[[Input], Awaitable[Output]], Callable[[Input, RunnableConfig], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]], Callable[[Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]])Optional[AsyncCallbackManagerForChainRun]Awaitable[Output]c                    t          |           r.|'t          ||                                          |d<   n||d<   |t          |           r||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   rA   r   r   r   s        r-   acall_func_with_variable_argsr     s    6 d &"+Fk>S>S>U>UVVVF8%F8#6t#<#< +}4     r,   r#   c                    ddl m}  |j        |                     d          |                     d          |                     d                    S )zGet a callback manager for a config.

    Args:
        config (RunnableConfig): The config.

    Returns:
        CallbackManager: The callback manager.
    r   )r#   r3   r1   r2   inheritable_callbacksinheritable_tagsinheritable_metadata) langchain_core.callbacks.managerr#   	configurerT   )rA   r#   s     r-   get_callback_manager_for_configr     s`     A@@@@@$?$$jj55F++#ZZ
33   r,   r!   c                    ddl m}  |j        |                     d          |                     d          |                     d                    S )zGet an async callback manager for a config.

    Args:
        config (RunnableConfig): The config.

    Returns:
        AsyncCallbackManager: The async callback manager.
    r   )r!   r3   r1   r2   r   )r   r!   r   rT   )rA   r!   s     r-   %get_async_callback_manager_for_configr     sa     FEEEEE))$jj55F++#ZZ
33   r,   PTc                  8     e Zd ZdZd fd
Zdddd fdZ xZS )ContextThreadPoolExecutorz?ThreadPoolExecutor that copies the context to the child thread.r   Callable[P, T]argsP.argsr   P.kwargsrB   	Future[T]c           
         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   r\   )selfr   r   r   	__class__s       r-   r   z ContextThreadPoolExecutor.submit  sO      ww~~#W\^^-?%W%W%W%WPV%W%WXX
 
 	
r,   Nr   timeout	chunksizefnr   	iterablesIterable[Any]r   float | Noner   r8   Iterator[T]c                   d t          t          |d                             D             d	f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                *    g | ]}t                      S r+   )r   )rK   re   s     r-   r   z1ContextThreadPoolExecutor.map.<locals>.<listcomp>(  s    EEEqLNNEEEr,   r   r   r   rB   r   c                 D                                      j        g| R  S rI   )popr\   )r   contextsr   s    r-   _wrapped_fnz2ContextThreadPoolExecutor.map.<locals>._wrapped_fn*  s&    %8<<>>%b040000r,   r   )r   r   rB   r   )r   r   r   r   )r   r   r   r   r   r   r   r   s    `    @r-   r   zContextThreadPoolExecutor.map  s    & FEE#il2C2C,D,DEEE	1 	1 	1 	1 	1 	1 	1 uww{

 
 	
 
 
 	
r,   )r   r   r   r   r   r   rB   r   )
r   r   r   r   r   r   r   r8   rB   r   )r'   r(   r)   r*   r   r   __classcell__)r   s   @r-   r   r     ss        II
 
 
 
 
 
0 !%
 
 
 
 
 
 
 
 
 
 
 
r,   r   Generator[Executor, None, None]c              #     K   | pi } t          |                     d                    5 }|V  ddd           dS # 1 swxY w Y   dS )zGet an executor for a config.

    Args:
        config (RunnableConfig): The config.

    Yields:
        Generator[Executor, None, None]: The executor.
    r7   )max_workersN)r   rT   )rA   executors     r-   get_executor_for_configr   5  s       \rF	"JJ011
 
 
 	                 s   <A A executor_or_config)Optional[Union[Executor, RunnableConfig]]r   r   r   r   c           
     X  K   dfd}| t          | t                    rZt          j                                        dt          dt          t                      j        |                               d{V S t          j                                        | |           d{V S )a  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.

    Raises:
        RuntimeError: If the function raises a StopIteration.
    rB   r   c                 J    	  i S # t           $ r} t          | d } ~ ww xY wrI   )StopIterationRuntimeError)excr   r   r   s    r-   wrapperz run_in_executor.<locals>.wrapper]  sF    	(4(((( 	( 	( 	( C'		(s    
""Nr   )rB   r   )	rJ   r   asyncioget_running_looprun_in_executorr   r   r   r\   )r   r   r   r   r   s    ``` r-   r   r   H  s      *( ( ( ( ( ( ( ( !Z0BD%I%I!-//??#W\^^-?%I%IJJ
 
 
 
 
 
 
 
 	

 )++;;<NPWXXXXXXXXXr,   )rA   r0   rB   rC   )rA   r0   rB   r^   rI   )rA   rg   rB   r0   )rA   r~   r   r8   rB   r   )rA   rg   r3   r   r9   r6   r7   r6   r5   r   r:   r   rB   r0   )r   rg   rB   r0   )r   r   r   r   rA   r0   r   r   r   r   rB   r   )r   r   r   r   rA   r0   r   r   r   r   rB   r   )rA   r0   rB   r#   )rA   r0   rB   r!   )rA   rg   rB   r   )
r   r   r   r   r   r   r   r   rB   r   )Hr*   
__future__r   r   uuidr   collections.abcr   r   r   r   r   concurrent.futuresr	   r
   r   
contextlibr   contextvarsr   r   r   r   	functoolsr   typingr   r   r   r   r   r   r   typing_extensionsr   r   langchain_core.runnables.utilsr   r   r   r   langchain_core.callbacks.baser   r    r   r!   r"   r#   r$   r   r&   r0   rq   rj   rs   r@   r<   r]   rf   r}   r   r   r   r   r   r   r   r   r   r   r   r   r+   r,   r-   <module>r      s-   , , , " " " " " "    N N N N N N N N N N N N N N C C C C C C C C C C % % % % % % @ @ @ @ @ @ @ @ @ @ @ @       O O O O O O O O O O O O O O O O O O 2 2 2 2 2 2 2 2             +LLLLLLLL             tSy)*I    	    1 1 1 1 1Ye 1 1 1 1h	 	 	     @JzT@ @ @     !) !) !) !)H 
 
 
 
62 2 2 2 2j,: ,: ,: ,:d 04%)%)"-1+ + + + + +\? ? ? ?V 9=! ! ! ! !\ >B"! "! "! "! "!J   $   ( IcNNGCLL4
 4
 4
 4
 4
 2 4
 4
 4
n    $%Y %Y %Y %Y %Y %Yr,   