o
    +if^g                  
   @  sZ  d Z ddlmZ ddlZddlZddl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 ddlm Z m!Z!m"Z" erdddl#m$Z$ e%e&Z'ej(ee!j)  ddd	Z*ej(ee+  d
dd	Z,ej(eee+   ddd	Z-ej(eee+ef   ddd	Z.d_ddZ/d`ddZ0d`ddZ1d`ddZ2dad d!Z3G d"d# d#ed$d%Z4G d&d' d'ed$d%Z5		dbdcd-d.Z6ddd2d3Z7								dedfd@dAZ8edBdCdDZ9eG dEdF dFeee9 Z:edgdHdIZ;e	JdhddddddddKdidQdIZ;djdSdIZ;ej<ddddddddTdkdYdZZ=dld]d^Z>dS )mz1Decorator for creating a run tree from functions.    )annotationsN)futures)TYPE_CHECKINGAnyAsyncGenerator	AwaitableCallableDict	GeneratorGenericListMappingOptionalProtocol	TypedDictTypeVarUnioncastoverloadruntime_checkable)client	run_treesutils)Runnable_PARENT_RUN_TREE)default_PROJECT_NAME_TAGS	_METADATAreturnOptional[run_trees.RunTree]c                   C  s   t  S )z!Get the current run tree context.)r   get r"   r"   N/var/www/html/corbot_env/lib/python3.10/site-packages/langsmith/run_helpers.pyget_run_tree_context/   s   r$   funcr   boolc                 C  s   t | ddS )N__langsmith_traceable__F)getattrr%   r"   r"   r#   _is_traceable_function4   s   r*   c                 C  s2   t | pt| tjot | jpt| dot | jS )z,Check if a function is @traceable decorated.__call__)r*   
isinstance	functoolspartialr%   hasattrr+   r)   r"   r"   r#   is_traceable_function8   s
   r0   c                 C  s    t | pt| dot | jS )z;Inspect function or wrapped function to see if it is async.__wrapped__)inspectiscoroutinefunctionr/   r1   r)   r"   r"   r#   is_asyncA   s   
r4   	signatureinspect.Signatureargsr   kwargsDict[str, Any]c                 O  s   | j |i |}|  t|j}|dd |dd | j D ]\}}|jtj	j
kr=||v r=|||  || q"|S )z:Return a dictionary of inputs from the function signature.selfNcls)bind_partialapply_defaultsdict	argumentspop
parametersitemskindr2   	ParameterVAR_KEYWORDupdate)r5   r7   r8   boundr?   
param_nameparamr"   r"   r#   _get_inputsH   s   

rJ   c                   @  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 )LangSmithExtraz<Any additional info to be injected into the run dynamically.zOptional[client.ID_TYPE]reference_example_idOptional[Dict]	run_extrar    run_treeOptional[str]project_nameOptional[Dict[str, Any]]metadataOptional[List[str]]tagsrun_idOptional[client.Client]r   N__name__
__module____qualname____doc____annotations__r"   r"   r"   r#   rK   \   s   
 rK   F)totalc                   @  s:   e Zd ZU dZded< ded< ded< ded< d	ed
< dS )_TraceableContainerz3Typed response when initializing a run a traceable.r    new_runrP   rQ   outer_projectrR   outer_metadatarT   
outer_tagsNrX   r"   r"   r"   r#   r_   i   s   
 r_   	containeroutputsOptional[Any]errorrP   c                 C  sF   |  d}|du rdS t|tr|nd|i}|j||d |  dS )zEnd the run.r`   Noutput)re   rg   )r!   r,   r>   endpatch)rd   re   rg   rO   outputs_r"   r"   r#   _container_ends   s   
rl   extra_outerr>   langsmith_extrac                 C  s(   | dd }|ri | |}|S | }|S )NrN   )r!   )rm   rn   rN   extra_innerr"   r"   r#   _collect_extra   s   rp   run_typestrOptional[LangSmithExtra]nameexecutor$Optional[futures.ThreadPoolExecutor]rS   Optional[Mapping[str, Any]]rU   rT   r   rW   c                 C  s  t  pt }|pt }|dpt }|s,t s,ttj	d t
d ||d d dS |d|}t| }|p;| j}| j}t||}t }i |dpOi |pSi }t| ||p_i  d|d< ||d< zt|g|	R i |
}W n" ty } ztd| d	|  |	|
d
}W Y d }~nd }~ww t }|dpg |pg  }t| ||pg 7 }|dt }|d|}|d ur|j|||t||d||||d}ntj|||t||d|||d|||||d}|  t
|||||d}t |d  t|d  |S )NrO   z;LangSmith tracing is disabled, returning original function.)r`   rQ   ra   rb   rc   rQ   rS   	traceable	ls_methodzFailed to infer inputs for z: )r7   r8   rU   rV   r   )rt   r5   doc)rt   rq   
serializedinputsrU   extrarV   rL   )idrt   r{   r|   rq   rL   rQ   r}   rU   ru   r   r`   )r   r!   r   get_tracer_projectrK   r   tracing_is_enabledlog_onceloggingDEBUGr_   r2   r5   rY   r\   rp   r   setrF   rJ   	TypeErrorloggerdebugr   uuiduuid4create_childrr   r   RunTreepost)r%   rq   rm   rn   rt   ru   rS   rU   r   r7   r8   ra   parent_run_project_name_r5   name_	docstringro   rb   	metadata_r|   erc   tags_id_client_r`   response_containerr"   r"   r#   
_setup_run   s   
	




r   RT)	covariantc                   @  s   e Zd Zdddd
dZdS )SupportsLangsmithExtraNrn   r7   r   rn   rR   r8   r   r   c                O     d S Nr"   )r:   rn   r7   r8   r"   r"   r#   r+      s   zSupportsLangsmithExtra.__call__)r7   r   rn   rR   r8   r   r   r   )rY   rZ   r[   r+   r"   r"   r"   r#   r      s    r   Callable[..., R]c                 C  r   r   r"   r)   r"   r"   r#   rx      s   rx   chain)rt   ru   rS   rU   r   r}   	reduce_fnr}   rM   r   Optional[Callable]7Callable[[Callable[..., R]], SupportsLangsmithExtra[R]]c                C  r   r   r"   )rq   rt   ru   rS   rU   r   r}   r   r"   r"   r#   rx     s   /Union[Callable, Callable[[Callable], Callable]]c               	     s   | rt | d tr| d n|dpd|dpi |d|d|d|d|d	 |d
d fdd}t| dkr[t| d r[|s[|| d S |S )a$  Decorator for creating or adding a run to a run tree.

    Args:
        run_type: The type of run to create. Examples: llm, chain, tool, prompt,
            retriever, etc. Defaults to "chain".
        name: The name of the run. Defaults to the function name.
        executor: The thread pool executor to use for the run. Defaults to None,
            which will use the default executor.
        metadata: The metadata to add to the run. Defaults to None.
        tags: The tags to add to the run. Defaults to None.
        client: The client to use for logging the run to LangSmith. Defaults to
            None, which will use the default client.
        reduce_fn: A function to reduce the output of the function if the function
            returns a generator. Defaults to None, which means the values will be
                logged as a list. Note: if the iterator is never exhausted (e.g.
                the function returns an infinite generator), this will never be
                called, and the run itself will be stuck in a pending state.

    r   rq   r   r}   rt   ru   rS   rU   r   r   r%   r   c                   s  t  d dd fdd	}t  d dd f	dd}t  d dd fdd}t  d dd f	dd}t rb|}nt rnrk|}n|}nsut rx|}n|}t|dd |S )Nr   r7   r   rn   rs   r8   r   c           	        s,  t  }t|  ||d}tjdddu}zRz|r3|d|d i|I dH }n
|i |I dH }W n tyV } zt }t	||d |d}~ww W t 
| t
|d  t
|d  t
|d  nt 
| t
|d  t
|d  t
|d  w t	||d	 |S )
z!Async version of wrapper function
rq   rn   rm   rt   ru   rS   rU   r   r7   r8   rO   Nr`   rg   ra   rc   rb   re   )r   r!   r   r2   r5   rA   	Exception	traceback
format_excrl   r   r   r   r   	rn   r7   r8   context_runrun_containerfunc_accepts_parent_runfunction_resultr   
stacktracer   ru   rm   r%   rS   rt   rq   rU   r"   r#   async_wrapper8  sZ   

z3traceable.<locals>.decorator.<locals>.async_wrapperr   c                  s  t  }t|  ||d}tjdd d u}g }zzM|r2|d|d i|}n|i |}t | t|d  t|d  t	|d  t
|r]|I d H }|2 z3 d H W }|| |V  q_6 W n ty }	 zt }
t||
d |	d }	~	ww W t | t|d  t|d  t	|d  nt | t|d  t|d  t	|d  w |rrz|}W n ty }	 zt|	 |}W Y d }	~	n
d }	~	ww |}nd }t||d d S )	Nr   rO   r`   ra   rc   rb   r   r   )r   r!   r   r2   r5   rA   r   r   r   r   iscoroutineappendBaseExceptionr   r   rl   r   r   rg   )rn   r7   r8   r   r   r   resultsasync_gen_resultitemr   r   r   	r   ru   rm   r%   rS   rt   r   rq   rU   r"   r#   async_generator_wrapperc  s   






z=traceable.<locals>.decorator.<locals>.async_generator_wrapperc           	        s  t  }t|  ||d}tjdddu}zLz|r/|d|d i|}n|i |}W n tyO } zt }t	||d |d}~ww W t 
| t
|d  t
|d  t
|d  nt 
| t
|d  t
|d  t
|d  w t	||d	 |S )
z>Create a new run or create_child() if run is passed in kwargs.r   rO   Nr`   r   ra   rc   rb   r   )r   r!   r   r2   r5   rA   r   r   r   rl   r   r   r   r   r   r   r"   r#   wrapper  sX   

z-traceable.<locals>.decorator.<locals>.wrapperc                 ?  s   t  }t|  ||d}tjdd d u}g }zYz$|r2|d|d i|}n|i |}|D ]
}|| |V  q;W n ty_ }	 zt	 }
t
||
d |	d }	~	ww W t | t|d  t|d  t|d  nt | t|d  t|d  t|d  w |rrz|}W n ty }	 zt|	 |}W Y d }	~	n
d }	~	ww |}nd }t
||d d S )	Nr   rO   r`   r   ra   rc   rb   r   )r   r!   r   r2   r5   rA   r   r   r   r   rl   r   r   r   r   r   r   rg   )rn   r7   r8   r   r   r   r   generator_resultr   r   r   r   r   r"   r#   generator_wrapper  sv   



z7traceable.<locals>.decorator.<locals>.generator_wrapperr'   T)r7   r   rn   rs   r8   r   r   r   )r7   r   rn   rs   r8   r   r   r   )r-   wrapsr2   isasyncgenfunctionr4   isgeneratorfunctionsetattr)r%   r   r   r   r   selected_wrapperr   ru   rm   rS   rt   r   rq   rU   r)   r#   	decorator7  s.   "*$?"*$
9ztraceable.<locals>.decorator   N)r%   r   )r,   rr   r!   lencallable)r7   r8   r   r"   r   r#   rx     s$   






 b)r|   r}   ru   rQ   rO   rU   rS   r|   rQ   rO   (Generator[run_trees.RunTree, None, None]c             
   c  s   t  }	t }
t pt }|du rt n|}tt|p g |	p#g  }t | i |p0i |
p4i ddi}t| |pBi }||d< |pJ|}|durZ|j	| ||||d}nt
j| |||||pdi |d}|  t| t| z;z|V  W n tttfy } zt }|j|d |  |d}~ww W t| t| t |	 t|
 nt| t| t |	 t|
 w |jdu r|  |  dS )z(Context manager for creating a run tree.Nry   tracerS   )rt   rq   r}   r|   rU   )rt   rq   r}   ru   rQ   r|   rU   r   )r   r!   r   r   r   r   r   sortedr   r   r   r   r   r   KeyboardInterruptr   r   r   ri   rj   end_time)rt   rq   r|   r}   ru   rQ   rO   rU   rS   rc   rb   ra   r   r   rm   r   r`   r   tbr"   r"   r#   r     sj   

	









r   traceable_fnr   c              
     s   z ddl m m ddlm ddlmm} ddlm	m
 W n ty1 } ztd|d }~ww t| sSzt| }W n tyH   d}Y nw td|  d	| G  fd
dd|| S )Nr   )AsyncCallbackManagerCallbackManagerLangChainTracer)RunnableConfigRunnableLambda)InputOutputz`as_runnable requires langchain to be installed. You can install it with `pip install langchain`.z<source unavailable>zRas_runnable expects a function wrapped by the LangSmith @traceable decorator. Got z defined as:
c                      sp   e Zd ZdZ	dd fd	d
ZedfddZedfddZedfddZ  Z	S )z&as_runnable.<locals>.RunnableTraceablezRunnableTraceable converts a @traceable decorated function
        to a Runnable in a way that hands off the LangSmith tracing context.
        Nr%   r   afunc*Optional[Callable[..., Awaitable[Output]]]r   Nonec              	     s   d }|  |}t|r!|d urtdtt gf |  |}nt|r2tt gf | |}|d u rAt| jj	 d| t
 |ttt gt f  | d S )NzFunc was provided as a coroutine function, but afunc was also provided. If providing both, func should be a regular function to avoid ambiguity.zG expects a function wrapped by the LangSmith @traceable decorator. Got )_wrap_asyncr4   r   r   r   r0   
_wrap_sync
ValueError	__class__rY   super__init__r   r   )r:   r%   r   wrappedawrapped)r   r   r   r"   r#   r     s.   

z/as_runnable.<locals>.RunnableTraceable.__init__callback_managerr   r    c              	     sZ   d }t |  fr+fdd| jD }|r+|d }tj| j|jddi | jd| jid}|S )Nc                   s   g | ]	}t | r|qS r"   )r,   ).0handlerr   r"   r#   
<listcomp>  s    zNas_runnable.<locals>.RunnableTraceable._configure_run_tree.<locals>.<listcomp>r   Wrappingr   rS   )r~   session_namert   rq   r|   rU   r}   )r,   handlersr   r   parent_run_idrQ   rU   rS   )r   rO   
lc_tracers	lc_tracer)r   r   r   r"   r#   _configure_run_tree  s"   
	z:as_runnable.<locals>.RunnableTraceable._configure_run_treeCallable[..., Output])Callable[[Input, RunnableConfig], Output]c                   s&   d
 fdd}t tgf |S )z4Wrap a synchronous function to make it asynchronous.r|   r>   configr   r   r   c                   s*     |d}di | dd|iiS N	callbacksrn   rO   r"   r   r!   r|   r   rO   )RunnableTraceabler%   r"   r#   wrap_traceable  s   zIas_runnable.<locals>.RunnableTraceable._wrap_sync.<locals>.wrap_traceableNr|   r>   r   r   r   r   )r   r   )r%   r   r   r   r   r   r)   r#   r     s   z1as_runnable.<locals>.RunnableTraceable._wrap_sync>Optional[Callable[[Input, RunnableConfig], Awaitable[Output]]]c                   sb   | du rdS t | std|  ttdt f |  d fd
d}ttgt f |S )z.Wrap an async function to make it synchronous.NzXRunnableTraceable expects a function wrapped by the LangSmith @traceable decorator. Got .r|   r>   r   r   r   r   c                   s2     |d}di | dd|iiI d H S r   r   r   )r   afunc_r"   r#   awrap_traceable  s
    zKas_runnable.<locals>.RunnableTraceable._wrap_async.<locals>.awrap_traceabler   )r0   r   r   r   r   )r   r   r   )r   r#   r     s   z2as_runnable.<locals>.RunnableTraceable._wrap_asyncr   )r%   r   r   r   r   r   )r   r   r   r    )r%   r   r   r   )r   r   r   r   )
rY   rZ   r[   r\   r   staticmethodr   r   r   __classcell__r"   r   r   r   r   r   r   r   )r   r#   r   z  s     r   )langchain.callbacks.managerr   r   %langchain.callbacks.tracers.langchainr   langchain.schema.runnabler   r   langchain.schema.runnable.utilsr   r   ImportErrorr0   r2   	getsourcer   r   )r   r   r   fn_srcr"   r   r#   as_runnableb  s8    cr  )r   r    )r%   r   r   r&   )r5   r6   r7   r   r8   r   r   r9   )NN)rd   r_   re   rf   rg   rP   )rm   r>   rn   rK   r   r>   )NNNNNNNN)r%   r   rq   rr   rm   r>   rn   rs   rt   rP   ru   rv   rS   rw   rU   rT   r   rW   r7   r   r8   r   r   r_   )r%   r   r   r   )r   )rq   rr   rt   rP   ru   rv   rS   rw   rU   rT   r   rW   r}   rM   r   r   r   r   )r7   r   r8   r   r   r   )rt   rr   rq   rr   r|   rM   r}   rM   ru   rv   rQ   rP   rO   r    rU   rT   rS   rw   r   r   )r   r   r   r   )?r\   
__future__r   
contextlibcontextvarsr-   r2   r   r   r   
concurrentr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   	langsmithr   r   r   r   r   	getLoggerrY   r   
ContextVarr   r   rr   r   r   r   r$   r*   r0   r4   rJ   rK   r_   rl   rp   r   r   r   rx   contextmanagerr   r  r"   r"   r"   r#   <module>   s    P




	

d

  C